如何使用带有I2C的Raspberry Pi从Arduino读取数据

The*_*ter 10 arduino i2c python-2.7

我正在尝试使用python smbus模块从Arduino UNO读取数据到Raspberry Pi.我在smbus模块上找到的唯一文档就在这里.我不确定cmd在模块中的含义.我可以使用write将数据发送到Arduino.我写了两个简单的程序,一个用于读取,一个用于写入

写的那个

import smbus
b = smbus.SMBus(0)
while (0==0):
    var = input("Value to Write:")
    b.write_byte_data(0x10,0x00,int(var))
Run Code Online (Sandbox Code Playgroud)

阅读的那个

import smbus
bus = smbus.SMBus(0)
var = bus.read_byte_data(0x10,0x00)
print(var)
Run Code Online (Sandbox Code Playgroud)

Arduino代码是

#include <SoftwareSerial.h>
#include <LiquidCrystal.h>
#include <Wire.h>
LiquidCrystal lcd(8,9,4,5,6,7);

int a = 7;

void setup() 
{ 
  Serial.begin(9600);
  lcd.begin(16,2);
  // define slave address (0x2A = 42)
  #define SLAVE_ADDRESS 0x10

  // initialize i2c as slave
  Wire.begin(SLAVE_ADDRESS);

  // define callbacks for i2c communication
  Wire.onReceive(receiveData);
  Wire.onRequest(sendData); 
}
void loop(){
}

// callback for received data
void receiveData(int byteCount) 
{
 Serial.println(byteCount);
  for (int i=0;i <= byteCount;i++){
  char c = Wire.read();
  Serial.println(c);
 }
}

// callback for sending data
void sendData()
{ 
  Wire.write(67);
  lcd.println("Send Data");
}
Run Code Online (Sandbox Code Playgroud)

当我运行读取程序时,它每次都返回"33".Arduino返回调用sendData函数.

我使用的是Data Level Shifter,描述说它可能有点迟钝.

有没有人得到这个工作?

Ste*_*bQC 11

我设法启动了Arduino和Raspberry Pi之间的通信.两个使用两个5k上拉电阻连接(参见本页).arduino为每个请求在i2c总线上写一个字节.在Raspberry Pi上,hello每秒打印一次.

Arduino代码:

#include <Wire.h>
#define SLAVE_ADDRESS 0x2A

void setup() {
    // initialize i2c as slave
    Wire.begin(SLAVE_ADDRESS);
    Wire.onRequest(sendData); 
}

void loop() {
}

char data[] = "hello";
int index = 0;

// callback for sending data
void sendData() { 
    Wire.write(data[index]);
    ++index;
    if (index >= 5) {
         index = 0;
    }
 }
Run Code Online (Sandbox Code Playgroud)

Raspberry Pi上的Python代码:

#!/usr/bin/python

import smbus
import time
bus = smbus.SMBus(1)
address = 0x2a

while True:
    data = ""
    for i in range(0, 5):
            data += chr(bus.read_byte(address));
    print data
    time.sleep(1);
Run Code Online (Sandbox Code Playgroud)

在我的Raspberry Pi上,i2c总线是1.使用命令i2c-detect -y 0i2c-detect -y 1验证您的Raspberry Pi是否检测到您的Arduino.