我试图向串行设备(arduino)发送命令并接收响应,该命令通过了,但是我没有从目标设备获得响应。
我希望C
程序通过发送和接收数据来控制串行设备。
Arduino
代码:
void setup() {
// initialize serial communication:
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0) {
int inByte = Serial.read();
switch (inByte) {
case 'H':
Serial.print("75864d63001bebaa");
break;
}
}
}
C
代码:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdint.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#include <sys/ioctl.h>
int main(int argc, char *argv[]) {
int fd, n, i;
char buf[64] = "temp text";
struct termios toptions;
/* open serial port */
fd = open("/dev/ttyACM0", O_RDWR | O_NOCTTY);
printf("fd opened as %i\n", fd);
/* wait for the Arduino to reboot */
usleep(3500000);
/* get current serial port settings */
tcgetattr(fd, &toptions);
/* set 9600 baud both ways */
cfsetispeed(&toptions, B9600);
cfsetospeed(&toptions, B9600);
/* 8 bits, no parity, no stop bits */
toptions.c_cflag &= ~PARENB;
toptions.c_cflag &= ~CSTOPB;
toptions.c_cflag &= ~CSIZE;
toptions.c_cflag |= CS8;
/* Canonical mode */
toptions.c_lflag |= ICANON;
/* commit the serial port settings */
tcsetattr(fd, TCSANOW, &toptions);
/* Send byte to trigger Arduino to send string back */
write(fd, "H", 1);
/* Receive string from Arduino */
n = read(fd, buf, 64);
/* insert terminating zero in the string */
buf[n] = 0;
printf("%i bytes read, buffer contains: %s\n", n, buf);
return 0;
}