Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Diff: iButton.cpp
- Revision:
- 0:cabf3d9fad23
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/iButton.cpp Mon Aug 07 10:54:15 2017 +0000
@@ -0,0 +1,141 @@
+#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;
+}