我正在尝试让 Arduino 和 Raspberry 进行交流。我在 Raspberry 上有一个使用 sysfs 库和一个 C-Arduino 程序的 C 程序。
我做什么: Arduino 已经有他自己编译的(在同一个 Raspberry 上)程序,而不是我在 raspberry 上编译程序并启动它。
问题:我在 Raspberry 上获取数据时延迟了一个 Raspberry 输入,正如您从下面的代码中看到的那样。
Type: a
OFFXX
Type: s
ONFXX
Type: a
OFFXX
Type: s
ONFXX
Type: s
OFFXX
Type: a
OFFXX
我第一次总是OFFXX
Arduino代码:
int led = 13;
void setup() {
pinMode(led, OUTPUT);
Serial.begin(57600);
}
void loop() {
if (Serial.available() > 0) {
char comando = toLowerCase(Serial.read());
if (comando == 'a') {
digitalWrite(led, HIGH);
Serial.print("ON");
}
else {
digitalWrite(led, LOW);
Serial.print("OFF");
}
}
}
和覆盆子代码:
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(){
int fd = open("/dev/ttyS0", O_RDWR);
if (fd == -1) {
perror("/dev/ttyS0");
return 1;
}
char msg[] = "a";
char rx[] = "XXXXX";
struct termios tios;
tcgetattr(fd, &tios);
// disable flow control and all that, and ignore break and parity errors
tios.c_iflag = IGNBRK | IGNPAR;
tios.c_oflag = 0;
tios.c_lflag = 0;
cfsetspeed(&tios, B57600);
tcsetattr(fd, TCSAFLUSH, &tios);
// the serial port has a brief glitch once we turn it on which generates a
// start bit; sleep for 1ms to let it settle
usleep(1000);
// output to serial port
while(1){
printf("Type: ");
scanf("%s", msg);
write(fd, msg, strlen(msg));
read(fd, rx, strlen(rx));
printf("%s\n", rx);
}
}
我的 USB 电缆和 GPIO 都有这个问题
编辑:另一个问题:为什么 OUTPUT 记得之前初始化的最后一个字符?