Simon Ford
/
OneWireDriver
main.cpp
- Committer:
- simon
- Date:
- 2009-11-18
- Revision:
- 0:d0b35e0b4294
File content as of revision 0:d0b35e0b4294:
#include "mbed.h" // DS18B20 converted to run on mbed #define TEMP_PIN p20 Serial pc(USBTX, USBRX); // tx, rx DigitalInOut temperature_pin(TEMP_PIN); void OneWireReset() { // reset. Should improve to act as a presence pulse temperature_pin.output(); temperature_pin = 0; // bring low for 500 us wait_us(500); temperature_pin.input(); wait_us(500); } void OneWireOutByte(unsigned char d) { // output byte d (least sig bit first). for(int n=8; n!=0; n--) { if ((d & 0x01) == 1) { // test least sig bit temperature_pin.output(); temperature_pin = 0; wait_us(5); temperature_pin.input(); wait_us(60); } else { temperature_pin.output(); temperature_pin = 0; wait_us(60); temperature_pin.input(); } d=d>>1; // now the next bit is in the least sig bit position. } } unsigned char OneWireInByte() { // read byte, least sig byte first unsigned char d = 0, b; for (int n=0; n<8; n++) { temperature_pin.output(); temperature_pin = 0; wait_us(5); temperature_pin.input(); wait_us(5); b = temperature_pin; wait_us(50); d = (d >> 1) | (b << 7); // shift d to right and insert b in most sig bit position } return d; } int main() { int HighByte, LowByte, TReading, SignBit, Tc_100, Whole, Fract; pc.printf("mbed 1 wire interface simple test!\r\n"); temperature_pin.output(); temperature_pin = 0; temperature_pin.input(); // sets the digital pin as input (logic 1) make sure external pullup resistor 4K7 wait(1); pc.printf("temperature measurements:\r\n"); while (1) { OneWireReset(); OneWireOutByte( 0xcc); //Skip ROM command OneWireOutByte( 0x44); // perform temperature conversion, strong pullup for one sec OneWireReset(); OneWireOutByte( 0xcc); OneWireOutByte( 0xbe); //Read Scratchpad LowByte = OneWireInByte(); HighByte = OneWireInByte(); TReading = (HighByte << 8) + LowByte; SignBit = TReading & 0x8000; // test most sig bit if (SignBit) { // negative TReading = (TReading ^ 0xffff) + 1; // 2's comp } Tc_100 = (6 * TReading) + TReading / 4; // multiply by (100 * 0.0625) or 6.25 Whole = Tc_100 / 100; // separate off the whole and fractional portions Fract = Tc_100 % 100; if (SignBit) { // If its negative pc.printf("-"); } pc.printf("%d", Whole); pc.printf("."); if (Fract < 10) { pc.printf("0"); } pc.printf("%d", Fract); pc.printf("\r\n"); wait(5); // 5 second delay. Adjust as necessary } }