Hi, i have problem to send float data from ds18b20 (temperature sensor) to another Arduino with I2C communication. This is my Source Code for Master and Slave. In Serial Monitor from Slave, i got the temperature in Celcius, but when from serial monitor in master there's nothing (blank). Can anybody help? thanks before
--Master Code--
#include <Wire.h>
void setup()
{
Wire.begin(); //join I2C BUS
Serial.begin(9600);
}
void loop()
{
Wire.requestFrom(2,3);
while(Wire.available())
{
int a=Wire.read();
char c=Wire.read();
int b=Wire.read();
Serial.print("Nilai 1");
Serial.println(a);
Serial.print("Nilai 2");
Serial.println(c);
Serial.print("Nilai 3");
Serial.println(b);
}
delay (500);
}
--Slave Code--
#include <OneWire.h>
#include <Wire.h>
#define TEMPERATURE_ERROR -1000
#define DS18S20_ID 0x10
#define DS18B20_ID 0x28
int DS18S20_Pin = 2; //DS18S20 Signal pin on digital 2
//Temperature chip i/o
OneWire ds(DS18S20_Pin); // on digital pin 2
void setup(void)
{
Serial.begin(9600);
Wire.begin(2); //join I2C bus dengan address #2
Wire.onRequest(requestEvent); //register Event
}
void loop(void)
{
tampilSerial();
}
float getTemperature()
{
//returns the temperature from one DS18S20 in DEG Celsius
byte data[12];
byte addr[8];
if ( !ds.search(addr))
{
ds.reset_search();
return TEMPERATURE_ERROR; // no more sensors on chain, reset search
}
if ( OneWire::crc8( addr, 7) != addr[7])
{
return TEMPERATURE_ERROR; //CRC is not valid!
}
if ( addr[0] != DS18S20_ID && addr[0] != DS18B20_ID)
{
return TEMPERATURE_ERROR; // Device is not recognized
}
ds.reset();
ds.select(addr);
ds.write(0x44,1); // start conversion
delay(850); // Wait some time...
ds.reset(); // byte present = ds.reset();
ds.select(addr);
ds.write(0xBE); // Read Scratchpad command
for (int i = 0; i < 9; i++) // Receive 9 bytes
{
data = ds.read();
-
}*
-
ds.reset_search();*
_ /* memory consuming but readable code:_
- byte MSB = data[1];*
- byte LSB = data[0];*
- float tempRead = ((MSB << 8) | LSB); //using two's compliment*
- float TemperatureSum = tempRead / 16; // 1/16 = 0.0625*
- return TemperatureSum;*
_ */_
_ return ( (data[1] << 8) + data[0] )*0.0625 ;_
}
void tampilSerial()
{
-
float temperature = getTemperature();*
-
if ( temperature != TEMPERATURE_ERROR )*
-
{*
-
Serial.println(temperature);*
-
}*
-
delay(1000); //just here to slow down the output so it is easier to read*
}
void requestEvent()
{ -
float temperature=getTemperature();*
-
if(temperature != TEMPERATURE_ERROR)*
-
{*
-
int whole = temperature;*
_ int fract = (temperature-whole)*10;_ -
Wire.write(whole);*
-
Wire.write('.');*
-
Wire.write(fract);*
-
}*
}