Stijn Sontrop
/
ibutton
Function to get the ID of iButtons via the 1-wire bus
main.cpp
- Committer:
- StijnS
- Date:
- 2011-02-12
- Revision:
- 0:39cce56e485b
File content as of revision 0:39cce56e485b:
#include "mbed.h" #define ibuttonpin p20 Serial pc(USBTX, USBRX); DigitalInOut ibuttondata(ibuttonpin); 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 ibuttondata.output(); ibuttondata = 0; wait_us(500); ibuttondata.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) { ibuttondata.output(); ibuttondata = 0; wait_us(5); ibuttondata.input(); wait_us(60); } else { ibuttondata.output(); wait_us(60); ibuttondata.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++) { ibuttondata.output(); ibuttondata = 0; wait_us(5); ibuttondata.input(); wait_us(5); b = ibuttondata; 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; } int main() { ibuttonvalue detected; while(1) { detected = DetectiButton(); if (detected.valid == 1) { //Test valid flag pc.printf("iButton Family: %X Serial: ", detected.family); for (int i = 0; i < 6; i++) { pc.printf("%X", detected.serial[i]); } pc.printf(" CRC: %X\n", detected.crc); } } }