My code from slave side:
#include <Wire.h>
const int analogInPin = A0;
const int led = 9;
int sensorValue = 0;
int outputValue = 0;
void setup()
{
Wire.begin(2);
Wire.onRequest(requestEvent);
pinMode(led, OUTPUT);
Serial.begin(9600);
}
void loop()
{
sensorValue = analogRead(analogInPin);
outputValue = map(sensorValue, 0, 1023, -100, 100);
// analogWrite(led, outputValue+100);
// print the results to the serial monitor:
Serial.print("sensor = " );
Serial.print(sensorValue);
Serial.print("\t output = ");
Serial.println(outputValue);
digitalWrite(led, LOW); // turn the LED on (HIGH is the voltage level)
delay(500); // wait for a second
digitalWrite(led, HIGH); // turn the LED off by making the voltage LOW
delay(500); // wait for a second
}
void requestEvent()
{
Wire.write(highByte(outputValue));
Serial.println(highByte(outputValue));
Wire.write(lowByte(outputValue));
Serial.println(lowByte(outputValue));
}
I see in terminal:
sensor = 1023 output = 100
0
100
0
100
Or if i turn pot close to zero:
sensor = 0 output = -100
255
156
255
156
I don,t understand, why i see 4 byte, not two in control section....
I2C Master code is:
#include <Wire.h>
#include <LiquidCrystal.h>
int data = 0;
LiquidCrystal lcd(10, 4, 5, 6, 7, 8);
void setup()
{
lcd.begin(16, 4);
lcd.print("hello, world!");
Wire.begin();
Serial.begin(9600);
}
void loop() {
lcd.setCursor(0, 1);
lcd.print(millis()/1000);
Wire.requestFrom(2, 2);
byte i = 0;
byte buffer[2] = {0, 0};
while(Wire.available())
{
i++;
Serial.print("i=");
Serial.println(i);
buffer[i] =Wire.read();
data = 0;
data |=buffer[1] & 0xFF;
data =data << 8;
data |=buffer[2] & 0xFF;
Serial.print("Data=");
Serial.println (data);
}
lcd.setCursor(-4,3);
lcd.print(data);
delay(500);
}
I see in terminal:
Data=-25345
i=1
Data=-25345
i=2
But -25345 not equal - 100 !
Whats wrong with my code?