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: ds18b20.cpp
- Revision:
- 5:6226f3c566ef
- Parent:
- 4:e076884ef8bd
- Child:
- 6:be97d38e0b01
--- a/ds18b20.cpp Tue May 03 09:23:26 2016 +0000
+++ b/ds18b20.cpp Wed May 11 16:42:35 2016 +0000
@@ -12,6 +12,8 @@
static int sendlen = 0;
static int recvlen = 0;
+uint16_t DS18B20Value;
+
void DS18B20ReadRom()
{
sendlen = 1;
@@ -20,11 +22,12 @@
OneWireExchange(sendlen, recvlen, send, recv, 0);
}
void DS18B20ReadScratchpad()
-{
+{
sendlen = 2;
send[0] = 0xCC;
send[1] = 0xBE;
recvlen = 9;
+ for (int i = 0; i < recvlen; i++) recv[i] = 0;
OneWireExchange(sendlen, recvlen, send, recv, 0);
}
void DS18B20ConvertT()
@@ -33,17 +36,52 @@
send[0] = 0xCC;
send[1] = 0x44;
recvlen = 0;
+ for (int i = 0; i < recvlen; i++) recv[i] = 0;
OneWireExchange(sendlen, recvlen, send, recv, 750);
}
-int DS18B20Init()
+#define IDLE 0
+#define CONVERT_T 1
+#define READ_SCRATCH_PAD 2
+#define EXTRACT_TEMPERATURE 3
+static int state = IDLE;
+static int handlestate()
{
- ticker.attach(&DS18B20ReadScratchpad, 10.0);
+ if (OneWireBusy()) return 0;
+
+ switch (state)
+ {
+ case IDLE:
+ break;
+ case CONVERT_T:
+ DS18B20ConvertT();
+ state = READ_SCRATCH_PAD;
+ break;
+ case READ_SCRATCH_PAD:
+ DS18B20ReadScratchpad();
+ state = EXTRACT_TEMPERATURE;
+ break;
+ case EXTRACT_TEMPERATURE:
+ if (OneWireCrc())
+ {
+ DS18B20Value = 0xFFFF;
+ }
+ else
+ {
+ DS18B20Value = recv[1];
+ DS18B20Value <<= 8;
+ DS18B20Value |= recv[0];
+ }
+ state = IDLE;
+ break;
+ default:
+ LogF("Unknown DS18B20 state %d\r\n", state);
+ return -1;
+ }
return 0;
}
-int DS18B20Main()
+static void logcomms()
{
static int wasbusy = false;
-
if (!OneWireBusy() && wasbusy)
{
LogF("1-wire | send:");
@@ -52,7 +90,24 @@
for (int i = 0; i < recvlen; i++) LogF(" %02x", recv[i]);
LogF("\r\n");
}
-
wasbusy = OneWireBusy();
+}
+static void timed()
+{
+ state = CONVERT_T;
+}
+int DS18B20Init()
+{
+ ticker.attach(&timed, 10.0);
+ return 0;
+}
+int DS18B20Main()
+{
+ logcomms();
+
+ int r = handlestate();
+
+ if (r) return -1;
+
return 0;
}
\ No newline at end of file