我需要通过I2C从我的树莓派发送一些数据到我的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我不知道这里出了什么问题,因为阿杜伊诺显然不能处理速度。我已经尝试在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库的情况下做到这一点,因为我读到它非常慢。
谢谢你的帮忙
发布于 2015-10-23 23:44:03
我想我找到了一个解决方案:
Serial.begin();
Serial.print(...);他花费了太多的时间,或者让阿杜伊诺不知何故很忙,以至于他不能足够快地从i2c上收集数据。我注释掉了所有的连载文章,并且我能够将'someTime‘降到1,所以这是相当整洁的。
https://stackoverflow.com/questions/33292190
复制相似问题