Serial port (UART) c++ read

纵然是瞬间 提交于 2019-12-12 01:33:23

问题


I have a small problem with read-in function in the c++. I'm trying to read in data available on UART's RxD port.

when running this code I'm getting result (read <0) hence it displays me an error msg error in read. what should be done to be able read in and display the data from read. I'm sure that there's data available on RxD port I have checked it with oscilloscope.

#include <iostream>
#include <termios.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/signal.h>
#include <stdlib.h>
#include <sys/ioctl.h>

#define BAUDRATE B19200
#define PORT "/dev/ttyO4"
#define _POSIX_SOURCE 1

#define FALSE 0
#define TRUE 1
volatile int STOP=FALSE;

void signal_handler_IO(int status);
int wait_flag = TRUE;



main ()
{
    int fd=0, res=0, result=0;


    char SYNC  [] = {0x55};
    char PID [] = {0x6A};

    struct termios oldtio, newtio;
    struct sigaction saio;
    char buff[255];

    fd = open(PORT, O_RDWR | O_NOCTTY | O_NONBLOCK);
    if (fd<0) {perror(PORT); exit(-1);}

    saio.sa_handler=signal_handler_IO;
    saio.sa_flags=0;
    saio.sa_restorer = NULL;
    sigaction(SIGIO, &saio,NULL);
    fcntl(fd, F_SETFL, FASYNC);
    tcgetattr(fd, &oldtio);

    newtio.c_cflag = BAUDRATE | CS8 | CLOCAL | CREAD;
    newtio.c_iflag = IGNPAR;
    newtio.c_oflag = 0;
    newtio.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
    //newtio.c_lflag = 0;
    newtio.c_cc[VMIN]=1;
    newtio.c_cc[VTIME]=0;
    tcflush(fd, TCIFLUSH);
    tcsetattr(fd, TCSANOW, &newtio);

    ioctl(fd, TIOCSBRK);
    usleep(1300);

    ioctl(fd,TIOCCBRK);
    usleep(200);

    write(fd, SYNC, sizeof(SYNC));
    write(fd,PID, sizeof(PID));

    res = read(fd, buff,255);

    if (res < 0)
    {
        printf("read error\n");
    }
    else if (res ==0)
    {
        printf("read = 0 \n");
    }
   else
    {
        sprintf(result, "%x",res);
        buff[res]=0;
        printf(": %s :%d :%d\n", buff,result,res);

    }
    close (fd);

}

void signal_handler_IO(int status)
{
    printf("received the signal\n");
wait_flag=FALSE;
}

来源:https://stackoverflow.com/questions/23471724/serial-port-uart-c-read

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!