나는이 질문이 인터넷에 흩어져 있다는 것을 알고있다. 나는 프로펠러 보드를 위해 C++ (리눅스)의 시리얼 포트에 데이터를 쓰고 싶다. 프로그램은 콘솔에서 입력을 가져올 때 잘 작동하지만 문자열을 쓸 때는 항상 장치에서 ERROR - Invalid command
을 반환합니다. 나는 16 진수 값을 가지고 char
배열을 만들려고 시도했다. 아래에 작업 코드가 있습니다. 하지만 어떻게 명령 문자열 변수를 제공하고 직렬 포트로 보낼 수 있습니까? 아마도, 유일한 방법이라면 어떻게 그것을 16 진수 값으로 변환합니까? 모두에게 감사합니다C++ 리눅스에서 직렬 포트에 문자열을 쓰는 것
참고 : 루프는 콘솔에서 사용자 입력을 사용합니다. 직렬 포트에 문자열 변수를 보내는 방법이 필요합니다.
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
int main(int argc,char** argv){
struct termios tio;
struct termios stdio;
int tty_fd;
fd_set rdset;
unsigned char c='D';
printf("Please start with %s /dev/ttyS1 (for example)\n",argv[0]);
memset(&stdio,0,sizeof(stdio));
stdio.c_iflag=0;
stdio.c_oflag=0;
stdio.c_cflag=0;
stdio.c_lflag=0;
stdio.c_cc[VMIN]=1;
stdio.c_cc[VTIME]=0;
tcsetattr(STDOUT_FILENO,TCSANOW,&stdio);
tcsetattr(STDOUT_FILENO,TCSAFLUSH,&stdio);
fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK); // make the reads non-blocking
memset(&tio,0,sizeof(tio));
tio.c_iflag=0;
tio.c_oflag=0;
tio.c_cflag=CS8|CREAD|CLOCAL; // 8n1, see termios.h for more information
tio.c_lflag=0;
tio.c_cc[VMIN]=1;
tio.c_cc[VTIME]=5;
tty_fd=open(argv[1], O_RDWR | O_NONBLOCK);
cfsetospeed(&tio,B115200); // 115200 baud
cfsetispeed(&tio,B115200); // 115200 baud
tcsetattr(tty_fd,TCSANOW,&tio);
//char str[] = {'V','E','R','\r'};
//the above str[] doesn't work although it's exactly the same as the following
char str[] = {0x56, 0x45, 0x52, 0x0D};
write(tty_fd,str,strlen(str));
if (read(tty_fd,&c,1)>0)
write(STDOUT_FILENO,&c,1);
while (c!='q')
{
if (read(tty_fd,&c,1)>0) write(STDOUT_FILENO,&c,1); // if new data is available on the serial port, print it out
if (read(STDIN_FILENO,&c,1)>0)
if(c!='q')
write(tty_fd,&c,1); // if new data is available on the console, send it to the serial port
}
close(tty_fd);
}
C 또는 C++입니까? C++의 경우'std :: string'을 사용하지 않으시겠습니까? –
@BasileStarynkevitch : 나는 그것을 시도했다 :'std :: string str = "VER \ r"; write (tty_fd, str.data(), str.size()); 여전히 오류가 반환됩니다. 나는 여러 가지 방법을 시도했지만 그 16 진수 만 작동합니다. 너는 어떤 생각이있어? 코드는 C에서 왔지만 내 프로그램은 실제로 C++입니다. –
오류가 실제로 무엇을 말하는지 나에게 말 했니? –