我正在开发一个涉及Arduino Uno和Raspberry Pi之间I2C通信的项目。我试图从Pi向Arduino发送字符串数据,反之亦然。
这是我的Arduino代码
#include <Wire.h>
#include <Arduino.h>
#define SLAVE_ADDRESS 0x12
int flag_int_to_send_to_PI = 0;
int flag_int_received_from_PI = 0;
char data_to_send_PI[] = "hello PI";
String data_recieved_from_pi = "";
void setup() {
Wire.begin(SLAVE_ADDRESS);
Wire.onReceive(receiveData);
Wire.onRequest(sendData);
Serial.begin(9600);
flag_int_to_send_to_PI = 1;
}
void loop() {
}
void receiveData(int byteCount) {
while(Wire.available())
{
flag_int_received_from_PI = Wire.read();
if(flag_int_received_from_PI == 1)
{
Serial.println("PI Wants data[].");
flag_int_to_send_to_PI= 3;
}
if(flag_int_received_from_PI == 3)
{
Serial.println("PI Wants To say its ok.");
//reading a string from pi: Here (How ?)
while( Wire.available())
{
data_recieved_from_pi += (char)Wire.read();
}
Serial.print("Data Received From PI:");
Serial.println(data_recieved_from_pi);
data_recieved_from_pi = "";
}
}
}
void sendData() {
if(flag_int_to_send_to_PI == 1)
{
Serial.println("Conversation begin : sending 1 to PI");
Wire.write(flag_int_to_send_to_PI);
}
if(flag_int_to_send_to_PI == 3) {
Wire.write(data_to_send_PI);
}
flag_int_to_send_to_PI = 0;
}
以下是Raspberry Pi代码:
from smbus import SMBus
import time
bus = SMBus(1)
slaveAddress = 0x12
data_received_from_Arduino = ""
data_to_send_to_Arduino = "Hello Uno"
def StringToBytes(val):
retVal = []
for c in val:
retVal.append(ord(c))
return retVal
while(1):
try:
x = bus.read_byte(slaveAddress)
if (x == 1):
print(x)
bus.write_byte(slaveAddress,1)
time.sleep(0.2)
data_received_from_Arduino = bus.read_i2c_block_data(slaveAddress, 0,12)
print(data_received_from_Arduino)
bus.write_byte(slaveAddress,3)
print(StringToBytes(data_to_send_to_Arduino))
bus.write_i2c_block_data(slaveAddress, 0x00,StringToBytes(data_to_send_to_Arduino))
这是串口和控制台输出。
Arduino串行输出:
Conversation begin : sending 1 to PI
PI Wants data[].
PI Wants To say its ok.
Data Received From PI:
Raspberry Pi控制台:
1
[0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]
[72, 101, 108, 108, 111, 32, 85, 110, 111]
它是如何工作的?
Arduino向Pi发送1以启动两次通信 Pi发回1确认它 Arduino将数据串发送给Pi Pi接收数据并向Arduino发回3号说它没问题。 (但没有好的) 然后Pi将数据字符串发送到Arduino,我不知道如何在Arduino端阅读,尽管我尝试过。
我的问题:
为什么Raspberry Pi在缓冲区的任何地方都接收255? Arduino如何获得从Pi发送的字节数组?