PIC16 C Sample: 1-Wire

Environment: MPLAB X IDE + HI TECH Compiler for PIC16

#define OW_TRIS TRISA0      //Port mode register, 1=input,0=output
#define OW_PORT RA0         //Pin connected to 1-wire bus

int owReset(void)
{
    char state = 0;
    OW_TRIS = 0;        //Set as output
    OW_PORT = 0;        //Drive Low
    __delay_us(480);
    OW_TRIS = 1;        //Release, Set back as input
    __delay_us(70);
    state = !OW_PORT;   //If devices are present, it will keep the pin low
                        //! will invert 1=0, 0=1
    __delay_us(410);
    return state;       //Returns 1 if devices are present
}

int owReadByte(void)
{
    int loop, result = 0;
    for(loop = 0; loop < 8; loop++)
    {
        result >>= 1;
        if(owReadBit())
            result |= 0x80;
    }
    return result;
}
int owReadBit(void)
{
    unsigned int iReadState = 0;
    OW_TRIS = 0;        //Set as output
    OW_PORT = 0;        //Drive low
    __delay_us(4);
    OW_TRIS = 1;        //Release, set as input
    __delay_us(8);
    iReadState = OW_PORT;
    return iReadState;
}
void owWriteByte(unsigned int data)
{
    int loop;
    for(loop = 0; loop < 8; loop++)
    {
        owWriteBit(data &0x01);
        data >>= 1;
    }
}
void owWriteBit(unsigned int b)
{
    OW_TRIS = 0;        //Set as output
    OW_PORT = 0;        //Drive low

    if(b==1)
    {
        __delay_us(3);
        OW_TRIS = 1;    //Release, set as input
        __delay_us(62);
    }
    else
    {
        __delay_us(57);
        OW_TRIS = 1;    //Release, set as input
        __delay_us(7);
    }
}
void owMatchRom(unsigned int * id)
{
    owReset();
    owWriteByte(0x55);  //Send command Match ROM
    //Send adress
    for(int i = 0;i<8;i++)
    {
        owWriteByte(id[i]);
    }
}

Geef een antwoord

Het e-mailadres wordt niet gepubliceerd.

Deze site gebruikt Akismet om spam te verminderen. Bekijk hoe je reactie-gegevens worden verwerkt.