zzz
iButton.cpp
- Committer:
- mauuuuul
- Date:
- 2020-08-26
- Revision:
- 14:2d0b5e0f0aed
- Parent:
- OneWire.cpp@ 12:27a1b359b95c
File content as of revision 14:2d0b5e0f0aed:
#include "iButton.h" extern Serial dbg; iButton::iButton(PinName IO) : io(IO) { } iButton::~iButton() { } void iButton::OneWireReset(void) { io.output(); io = 0; wait_us(500); io.input(); wait_us(500); } void iButton::OneWireOutByte(unsigned char data) { for (int n = 8;n!=0; n--) { if ((data & 0x01) == 1) { io.output(); io = 0; wait_us(5); io.input(); wait_us(60); } else { io.output(); wait_us(60); io.input(); } data = data >> 1; } } unsigned char iButton::OneWireReadByte(void) { unsigned char d = 0; unsigned char b; for (int n = 0; n<8; n++) { io.output(); io = 0; wait_us(5); io.input(); wait_us(5); b = io; wait_us(50); d = (d >> 1) | (b << 7); } return d; } void iButton::ResetData() { detect.family = 0; detect.serial.clear(); detect.crc = 0; detect.valid = false; } void iButton::DetectiButton(void) { unsigned char crc = 0; OneWireReset(); OneWireOutByte(0x33); ResetData(); detect.family = OneWireReadByte(); crc = crc8(crc, detect.family); if (detect.family == 0x00 || detect.family == 0xFF) { detect.valid = false; return; } for (int i = 0; i <6; i++) { // detect.serial[i] = OneWireReadByte(); detect.serial.push_back(OneWireReadByte()); crc = crc8(crc, detect.serial[i]); } detect.crc = OneWireReadByte(); if (crc == detect.crc) { detect.valid = true; } //dbg.printf("[Detect Ibutton]\r\n"); return; } std::string conv(const unsigned char &val) { char st[5]; sprintf(st,"%02X",val); return st; } bool iButton::IsTaping(void) { return detect.valid; } std::string iButton::GetData(void) { size_t sz = detect.serial.size(); string ret = ""; for(int i=sz-1; i>=0; i--) { ret += conv(detect.serial[i]); } return ret; } unsigned char iButton::crc8(unsigned char crc, unsigned char data) { crc = crc ^ data; for (int i = 0; i < 8; i++) { if (crc & 0x01) { crc = (crc >> 1) ^ 0x8C; } else { crc >>= 1; } } return crc; }