Trying to read values via I2C
Posted: Mon Mar 07, 2016 11:01 am
I am having problems reading values via I2C from an Arduino nano slave.
Whilst testing I have the I2C slave put out constant values, but what the Pi reads do not agree with those constant values sometimes it read 9 instead of 19 ( 0x13) I put in sleeps of 1 second between register reads which helped but did not resolve the problem
Running the code - note when it reads 9 instead of 19
The code
The I2C slave code
Whilst testing I have the I2C slave put out constant values, but what the Pi reads do not agree with those constant values sometimes it read 9 instead of 19 ( 0x13) I put in sleeps of 1 second between register reads which helped but did not resolve the problem
Running the code - note when it reads 9 instead of 19
Code: Select all
python readReg.py
19
20
1234
19
20
1234
9
20
1234
9
20
1234
9
20
Code: Select all
import smbus
import time
bus = smbus.SMBus(1)
address = 25
def write(value):
bus.write_byte_data(address, 0, value)
return -1
def read_AN2():
an2 = bus.read_word_data(address, 2)
return an2
def read_AN3():
an3 = bus.read_word_data(address, 3)
return an3
def read_ID0():
id = bus.read_byte_data(address, 0)
return id
def read_ID1():
id = bus.read_byte_data(address, 1)
return id
while True:
print read_ID0()
time.sleep(1)
print read_ID1()
time.sleep(1)
print format(read_AN2(),'04x')
time.sleep(1)
Code: Select all
// Simple I2C protocol for Arduino
// Slave side program
// (c) 2014 Ignas Gramba
//
#include <Wire.h>
#define XSensorPin 2
#define YSensorPin 3
const byte SlaveDeviceId = 25;
byte Register = 0;
void setup(){
Wire.begin(SlaveDeviceId); // join i2c bus with Slave ID
Wire.onReceive(receiveCommand); // register talk event
Wire.onRequest(slavesRespond); // register callback event
pinMode(XSensorPin, INPUT);
pinMode(YSensorPin, INPUT);
}
void loop(){
delay(100);
}
void receiveCommand(int howMany){
Register = Wire.read(); // 1 byte (maximum 256 commands)
}
void slavesRespond(){
int returnValue = 0x12;
//Wire.write(returnValue+Register);
//return;
int buffer1;
switch(Register){
case 0: // No new command was received
//Wire.write("NA");
Wire.write(0x13);
break;
case 1:
Wire.write(0x14);
break;
case 2: // Return X sensor value
//returnValue = GetXSensorValue();
buffer1 = 0x1234;
Wire.write((char *) &buffer1,2);
break;
case 3: // Return Y sensor value
//returnValue = GetYSensorValue();
returnValue = 0x0500;
break;
}
return;
returnValue = Register;
byte buffer[2]; // split int value into two bytes buffer
buffer[0] = returnValue >> 8;
buffer[1] = returnValue & 255;
//buffer[0] = 6;
//buffer[1] = 0;
Wire.write((char * ) buffer, 2); // return response to last command
Register = 0; // null last Master's command
}
int GetXSensorValue(){
int val = analogRead(XSensorPin);
return val;
}
int GetYSensorValue(){
int val = analogRead(YSensorPin);
return val;
}