【发布时间】:2017-06-22 00:19:42
【问题描述】:
我正在尝试从连接到 Arduino 的电位计写入模拟读数,并使用 RPi 上的 python 的 I2C 读取这些值。我已经让 Arduino 到 Arduino 使用下面的代码工作。我似乎无法正确做的是从 Arduino 写入两个字节并从 RPi 读取两个字节。
Arduino 主代码:
#include <Wire.h>
#define SLAVE_ADDRESS 0x2a
void setup()
{
Wire.begin(); // join i2c bus (address optional for master)
Serial.begin(9600); // start serial for output
}
void loop()
{
Wire.requestFrom(SLAVE_ADDRESS, 2); // request 2 bytes from slave
byte loByte;
byte hiByte;
if(Wire.available() >= 2) // slave may send less than requested
{
hiByte = Wire.read();
loByte = Wire.read();
}
int val = (hiByte << 8) + loByte;
Serial.print("read value:");
Serial.println(val);
delay(500);
}
Arduino Slave 代码:
#include <Wire.h>
#include <stdlib.h>
#define SLAVE_ADDRESS 0x2a
//#define potPin 0
int readVal;
byte hi;
byte lo;
void setup()
{
// Communication I2C
Wire.begin(SLAVE_ADDRESS);
Wire.onRequest(requestEvent); // register event
Serial.begin(9600);
}
void loop()
{
readVal = analogRead(A2);
Serial.println(readVal);
hi = highByte(readVal);
lo = lowByte(readVal);
}
void requestEvent()
{
byte buf [2];
buf [0] = hi;
buf [1] = lo;
Wire.write(buf, sizeof buf); // send 2-byte response
}
我从 RPi 中得到的最接近的读数是:
RPi 主代码:
import smbus
import time
bus = smbus.SMBus(1)
address = 0x2a
while True:
bus.write_byte(address, 1)
number = bus.read_byte(address)
print(number)
time.sleep(1)
Arduino从机代码:
#include <Wire.h>
#define SLAVE_ADDRESS 0x2a
int number = 0;
void setup() {
Wire.begin(SLAVE_ADDRESS);
Wire.onReceive(receiveData);
Wire.onRequest(sendData);
}
void loop() {
}
void receiveData(int byteCount){
while(Wire.available()) {
number = Wire.read();
number = analogRead(A2);
}
}
void sendData(){
Wire.write(number);
}
我似乎能够得到 0-255,但在 255 之后该值又开始了。毫无疑问,有一种更精确的方式可以说我只得到一个字节的数据或类似的东西。最终,我希望将 2 个电位器连接到 Arduino,将读数输入 RPi。
【问题讨论】:
-
请原谅这个愚蠢的问题,但是让从机将 int 拼接成两个字节有什么意义,只是通过 SPI?简单地发送 int 不就行了吗?
标签: python arduino raspberry-pi i2c