[英]I want to receive multiple data from arduino to raspberry pi using I2C
[英]Arduino-Uno receive 1 or 2 bytes from Raspberry Pi over I2C
我需要通過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-baudrate:
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
到目前為止沒有任何工作。 我嘗試了每一種低於50ms的速度,但是幾乎每一次都失敗了。 沒有Wire lib,有什么方法可以做到這一點,因為我讀到它很慢。
謝謝你的幫助
我想我找到了解決方案:
Serial.begin();
Serial.print(...);
花費了很多時間,或者使arduino忙碌起來,以至於他沒有足夠快地從i2c收集數據。 我注釋掉了所有連續撰寫的內容,然后將“ someTime”降低到了1,這很整潔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.