ibutton function for mbed working!

Dependencies:   OneWire mbed

Fork of ibutton by Stijn Sontrop

main.cpp

Committer:
Renato
Date:
2013-08-27
Revision:
1:d6732fa1e5f8
Parent:
0:39cce56e485b

File content as of revision 1:d6732fa1e5f8:

#include "mbed.h"
//#define ibuttonpin p21

Serial pc(USBTX, USBRX);

//DigitalInOut ibuttondata(ibuttonpin);
DigitalInOut sensor(p21);

typedef struct {
    unsigned char family;
    unsigned char serial[6];
    unsigned char crc;
    unsigned char valid;
} ibuttonvalue;


unsigned char crc8(unsigned char crc, unsigned char data) { //Calculate CRC8
    crc = crc ^ data;
    for (int i = 0; i < 8; i++) {
        if (crc & 0x01) {
            crc = (crc >> 1) ^ 0x8C; 
        } else {
            crc >>= 1; 
        }
    }
    return crc;
}

void OneWireReset(void) { //Generates reset on 1-wire bus
    sensor.output();
    sensor = 0;
    wait_us(500);
    sensor.input();
    wait_us(500);
}

void OneWireOutByte(unsigned char data) { //Write byte on 1-wire bus
    for (int n = 8;n!=0; n--) {
        if ((data & 0x01) == 1) {
            sensor.output();
            sensor = 0;
            wait_us(5);
            sensor.input();
            wait_us(60);
        } else {
            sensor.output();
            wait_us(60);
            sensor.input();
        }
        data = data >> 1;
    }
}

unsigned char OneWireReadByte(void) { //Read 1 byte from 1-wire bus
    unsigned char d = 0;
    unsigned char b;
    for (int n = 0; n<8; n++) {
        sensor.output();
        sensor = 0;
        wait_us(5);
        sensor.input();
        wait_us(5);
        b = sensor;
        wait_us(50);
        d = (d >> 1) | (b << 7);
    }
    return d;
}

ibuttonvalue DetectiButton(void) { //Function to detect an iButton en give back its contents
    ibuttonvalue detect;
    unsigned char crc = 0;
    OneWireReset();
    OneWireOutByte(0x33); //Read Rom cmd
    detect.family = OneWireReadByte();
    crc = crc8(crc, detect.family);
    if (detect.family == 0x00 || detect.family == 0xFF) {
        detect.valid = 0;
        return detect; //No iButton detected
    }
    for (int i = 0; i <6; i++) {
        detect.serial[i] = OneWireReadByte();
        crc = crc8(crc, detect.serial[i]);
    }
    detect.crc = OneWireReadByte();
    if (crc == detect.crc) { //If CRC is valid: set valid flag to 1
        detect.valid = 1;
    }
    return detect;
}

//LocalFileSystem local("local");

int main() {

//FILE *fp = fopen("/local/out.txt", "rw");

    ibuttonvalue detected; 
    int i;   
    while(1) {
        detected = DetectiButton();
        if (detected.valid == 1) { //Test valid flag
            pc.printf("iButton Family: %X Serial: ", detected.family);
            for (i=6-1; i>=0; i--) {
                pc.printf("%X", detected.serial[i]);
               // fprintf(fp, "Serial: %X", detected.serial[i]);
               
            }
            pc.printf(" CRC: %X\n", detected.crc);
       }//fclose(fp);
    }
}