【问题标题】:Arduino-Uno receive 1 or 2 bytes from Raspberry Pi over I2CArduino-Uno 通过 I2C 从 Raspberry Pi 接收 1 或 2 个字节
【发布时间】:2015-10-22 23:02:34
【问题描述】:

我需要通过 I2C 将一些数据从我的 Raspberry Pi 发送到我的 Arduino Uno。我希望 Arduino 用 pwm 转动一些电机并从 Raspi 接收数据(哪个电机有多快)。

我把它连线,编码了一下,它工作了。但是如果我提高传输速度,因为我需要电机每毫秒改变一次速度,那么 arduino 就会把一切都搞砸了。

在我的 Pi 上,我在 cpp(简化)中运行了测试代码:

file = open(deviceName, O_RDWR);
uint8_t command[2] = {motorNum, pwm};
while(1) {
  write(file, command, 2);
  usleep(someTime);
}

Arduino 上的代码:

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

byte pwm[] = {3, 9, 10, 11};

void setup() {
  Serial.begin(9600); // start serial for output
  Wire.begin(SLAVE_ADDRESS);
  Wire.onReceive(receiveData);
  Serial.println("Ready!");
}

void loop() {
  delay(10);
}

void receiveData(int byteCount) {
  byte motor = Wire.read(); //should be between 0 and 4
  byte freq = Wire.read(); //should be between 150 and 220

  if(motor == 4) { //all motors same speed
    Serial.print("All Motors with pwm: ");
    Serial.println(freq);
    for(byte i=0; i<4; i++) analogWrite(pwm[i], freq);
  } else {
    Serial.print("Motor: ");
    Serial.print(motor);
    Serial.print(" with pwm: ");
    Serial.println(freq);
    analogWrite(pwm[motor], freq);
  }

  if(Wire.available())
    Serial.println("...more than 2 bytes received");

}

如果我将 raspi 代码中的“someTime”设置为 50000 (=50ms),一切正常,并且我在我的 arduino 上得到了这个输出:

Ready!
Motor: 0 with pwm: 100
Motor: 0 with pwm: 100
Motor: 0 with pwm: 100
Motor: 0 with pwm: 100
Motor: 0 with pwm: 100
Motor: 0 with pwm: 100
Motor: 0 with pwm: 100
Motor: 0 with pwm: 100
Motor: 0 with pwm: 100
Motor: 0 with pwm: 100
Motor: 0 with pwm: 100
Motor: 0 with pwm: 100

目前似乎没有必要,但这只是为了测试。问题出现了,如果我提高速度,意味着将我的 pi 上的“someTime”减少到 1000(=1ms),我得到这个:

Ready!
Motor: 0 with pwm: 100
Motor: 0 with pwm: 100
Motor: 0 with pwm: 100
Motor: 8 with pwm: 0
...more than 2 bytes received

我不知道这里出了什么问题,因为很明显 arduino 无法处理速度。我已经尝试通过以下方式增加 pi 和 arduino 上的 i2c 波特率:

 sudo nano /etc/modprobe.d/i2c.conf
 ->  options i2c_bcm2708 baudrate=400000

Wire.begin(SLAVE_ADDRESS);
TWBR = 12; //should be 400khz

甚至将 twi.h 更改为:

#define TWI_FREQ 400000L

到目前为止没有任何效果。我尝试了低于 50 毫秒的每个速度,但几乎每次都失败了。有没有办法在没有 Wire 库的情况下做到这一点,因为我读到它非常慢。

感谢您的帮助

【问题讨论】:

    标签: c++ raspberry-pi arduino-uno i2c


    【解决方案1】:

    我想我找到了解决办法:

    Serial.begin();
    Serial.print(...);
    

    花费了太多时间,或者让 arduino 不知何故忙碌,以至于他从 i2c 收集数据的速度不够快。我注释掉了所有连续的文章,我能够将“someTime”降到 1,所以这很整洁。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-16
      相关资源
      最近更新 更多