// This sample emulates a DS18B20 device (temperature sensor), so we start by defining the available commands
constbyteDS18B20_START_CONVERSION=0x44;
constbyteDS18B20_READ_SCRATCHPAD=0xBE;
constbyteDS18B20_WRITE_SCRATCHPAD=0x4E;
// This sample implements a simple protocol : sending match ROM, then the ROM, then 0x01 will turn the arduino light on. Sending 0x02 will turn it off. In each case, the byte 0x42 is sent as acknowledgement.
constbyteCMD_TurnOn=0x01;
constbyteCMD_TurnOff=0x02;
// TODO:
// - handle configuration (resolution, alarms)
// - send 0 bits while conversion is in progress, 1 bits when it's done (until reset)
enumDeviceState
{
DS_WaitingReset,
DS_WaitingCommand,
DS_ConvertingTemperature,
DS_TemperatureConverted,
};
volatileDeviceStatestate=DS_WaitingReset;
// scratchpad, with the CRC byte at the end
volatilebytescratchpad[9];
volatileunsignedlongconversionStartTime=0;
// This function will be called each time the OneWire library has an event to notify (reset, error, byte received)
// You can do anything you want here, the OneWire library works entirely in background, using interrupts.
delay(10);
cli();//disable interrupts
// Be sure to not block interrupts for too long, OneWire timing is very tight for some operations. 1 or 2 microseconds (yes, microseconds, not milliseconds) can be too much depending on your master controller, but then it's equally unlikely that you block exactly at the moment where it matters.
// This can be mitigated by using error checking and retry in your high-level communication protocol. A good thing to do anyway.
// in this simple example we just reply with one byte to say we've processed the command
// a real application should have a CRC system to ensure messages are not corrupt, for both directions
// you can use the static OneWireSlave::crc8 method to add CRC checks in your communication protocol (it conforms to standard one-wire CRC checks, that is used to compute the ROM last byte for example)
OWSlave.write(&acknowledge,1,NULL);
caseOneWireSlave::RE_Reset:
state=DS_WaitingCommand;
break;
default:
;// we could also react to reset and error notifications, but not in this sample