Arduino-Uno通过I2C从树莓派接收1或2个字节
Arduino-Uno receive 1 or 2 bytes from Raspberry Pi over I2C
我需要通过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");
}
如果我将' sometimes '在我的raspi代码中设置为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 lib的情况下做到这一点,因为我读到它非常慢。
谢谢你的帮助
我想我找到解决办法了:
Serial.begin();
Serial.print(...);
花费太多时间,或者使arduino不知何故忙碌,以至于他不能足够快地从i2c收集数据。我注释了所有的连写,我可以把'someTime'降为1,所以这很简洁。
相关文章:
- 从文件中读取多个字节,并将它们存储在C++中进行比较
- 为什么 bool 和 _Bool 如果它们在内存中占用 1 个字节,它们只能存储 0 或 1
- 在 Linux 中,uint32_t从 4 个字节更改为 6 个字节
- 运行时错误:引用绑定到类型"int"的未对齐地址0xbebebebebebebec6,这需要 4 个字节对齐 (stl_vector.h)
- 向指针地址添加 20 个字节偏移量
- 将(N 个字节)无符号字符指针转换为浮点数和双 C++
- C++/地址空间:每个地址 2 个字节?
- 为什么这个结构需要 24 个字节
- 为什么带有 vptr 的对象长 12 个字节?
- 使用 valgrind 检查我的链表暗示中的内存泄漏,让我"肯定丢失:1 个块中有 40 个字节"
- 复制后删除原始数组指针将前 3 个字节设置为 0
- 在编译时而不是运行时创建一个由两个字节组成的值
- 为什么在我的实现中,所有数组都对齐到 16 个字节?
- 使用 Python 导出 4 个字节浮点数
- C++向指针地址添加 4 个字节
- 是否强制转换void**并将第一个字节设置为nullptr
- AES-128 CFB-8解密的前16个字节已损坏
- Qt TCP 套接字 - 写入超过 15 个字节
- 在"C++代码"部分中,可能会写入两个字节
- 视觉C++转换和写入值为 10 的无符号 int 给出 5 个字节