LinuxでCプログラムを作成して、シリアルポートを介してマイクロコントローラーとデータを送受信しようとしています。テストとして、送信されたすべての文字をすぐにエコーするようにマイクロコントローラーを構成しました。これがminicomで機能し、「cat」と「echo」を使用してデータを送受信することによっても機能することを確認しました。
ただし、Cプログラムで同じことを行おうとすると、読み取り呼び出しが永久にブロックされます。シリアルポートを非正規モードに設定しています。MINは「1」、TIMEは「0」です。私のミニコムテストは、マイクロコントローラーが入力時に文字を返すことを証明しているので、書き込み呼び出しが文字を送信した後に読み取りが戻ることを期待しています。私は自分のコードをいくつかのオンラインの例と比較しましたが、欠けているものは何も見つかりませんでした。私は運が悪かったので、以下のコードのいくつかの順列を試しました。誰かが問題を見つけることができますか?
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <termios.h>
#define UART_SPEED B115200
char buf[512];
void init_serial (int fd)
{
struct termios termios;
int res;
res = tcgetattr (fd, &termios);
if (res < 0) {
fprintf (stderr, "Termios get error: %s\n", strerror (errno));
exit (-1);
}
cfsetispeed (&termios, UART_SPEED);
cfsetospeed (&termios, UART_SPEED);
termios.c_iflag &= ~(IGNPAR | IXON | IXOFF);
termios.c_iflag |= IGNPAR;
termios.c_cflag &= ~(CSIZE | PARENB | CSTOPB | CREAD | CLOCAL);
termios.c_cflag |= CS8;
termios.c_cflag |= CREAD;
termios.c_cflag |= CLOCAL;
termios.c_lflag &= ~(ICANON | ECHO);
termios.c_cc[VMIN] = 1;
termios.c_cc[VTIME] = 0;
res = tcsetattr (fd, TCSANOW, &termios);
if (res < 0) {
fprintf (stderr, "Termios set error: %s\n", strerror (errno));
exit (-1);
}
}
int main (int argc, char **argv)
{
int fd;
int res;
int i;
if (argc < 2) {
fprintf (stderr, "Please enter device name\n");
return -1;
}
fd = open (argv[1], O_RDWR | O_NOCTTY);
if (fd < 0) {
fprintf (stderr, "Cannot open %s: %s\n", argv[1], strerror(errno));
return -1;
}
init_serial (fd);
res = write (fd, "P=20\r\n", 6);
if (res < 0) {
fprintf (stderr, "Write error: %s\n", strerror(errno));
return -1;
}
tcdrain (fd);
res = read (fd, buf, 512);
printf ("%d\n", res);
if (res < 0) {
fprintf (stderr, "Read error: %s\n", strerror(errno));
return -1;
}
for (i=0; i<res; i++) {
printf ("%c", buf[i]);
}
return 0;
}