With reference from http://www.gammon.com.au/i2c I tried the example there. However I am getting the wrong response and readings. At startup the Master will request for slave address. I should get a reading of "8" but I don't get it. Subsequently, A0 on the slave is connected to a miniature solar panel, that I have tested and it is working, however I keep getting a value -1 from it. No doubt I did modify a little bit to suit my inputs not sure if what I did affected the program.
This is the master code:
#include <Wire.h>
const int slaveAddressA = 8;
enum {
cmd_slaveAddress = 1,
cmd_read_A0 = 2,
cmd_read_A1 = 3
};
void sendCommand_toSlaveA (const byte cmd, const int responseSize)
{
Wire.beginTransmission(slaveAddressA);
Wire.write(cmd);
Wire.endTransmission();
Wire.requestFrom(slaveAddressA, responseSize);
}
void setup() {
Wire.begin();
Serial.begin(9600);
sendCommand_toSlaveA(cmd_slaveAddress, 1);
if(Wire.available())
{
Serial.print ("Slave address is: ");
Serial.println (Wire.read (), DEC);
}
else
{
Serial.println ("No response to slave address request");
}
}
void startupTest() {
Wire.beginTransmission(slaveAddressA);
}
void loop() {
int val;
sendCommand_toSlaveA(cmd_read_A0, 2);
val = Wire.read();
val <<= 8;
val |= Wire.read();
Serial.print("Value of A0: ");
Serial.println(val, DEC);
delay(500);
}
This is the slave code:
#include <Wire.h>
const byte my_address = 8;
enum{
cmd_address = 1,
cmd_read_A0 = 2,
cmd_read_A1 = 3
};
char command;
void setup() {
command = 0;
pinMode (A0, INPUT);
digitalWrite (A0, LOW); // disable pull-up
pinMode (A1, INPUT);
digitalWrite (A1, LOW); // disable pull-up
Serial.begin(9600);
Wire.begin (my_address);
Wire.onReceive (receiveEvent); // interrupt handler for incoming messages
Wire.onRequest (requestEvent); // interrupt handler for when data is wanted
}
void loop(){
//everything is done using interrupts
}
void receiveEvent(int howMany)
{
command = Wire.read();
}
void sendSensor (const byte which)
{
int val = analogRead (which);
byte buf [2];
buf [0] = val >> 8;
buf [1] = val & 0xFF;
Wire.write (buf, 2);
}
void requestEvent ()
{
switch (command)
{
case cmd_address: Wire.write(0x55); break; // send slave address
case cmd_read_A0: sendSensor(A0); break; // send A0 value
case cmd_read_A1: sendSensor(A1); break; // send A1 value
}
}
Also I'm wondering if I have to add a "Wire.begin(8);" at the slave program setup. ---------------------------I would like to know what did I do wrongly?
UPDATE: The 2 boards are now communicating with one another. However, requested address gives a '85' instead of an '8'. As for input A0, for example it should show '700' with a little bit of variant, but now it shows a repeated pattern of e.g '0 0 0 400 500 800 1040 1040 1040 800 500 400 0 0 0'