通过linux中的rs232进行串行通信

时间:2013-01-22 12:41:16

标签: c linux

我是Linux新手。我在串行通信方面遇到问题。 我有两台计算机,一台运行超级终端,另一台我正在编写一个与超级终端通信的C程序。两台PC都通过RS232连接。 我已经编写了一些代码,我可以将数据发送到超级终端,但我不知道如何使用在Linux PC上用C语言编写的程序从超级终端读取数据。

有什么建议吗?

提前致谢。

以下是我的代码:

int main(int argc, char **argv)
{
    struct termios options;
    int fd;

    fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
    if(fd == -1)
    {
        printf("Could not open port /dev/ttyS0\n");
        return 1;
    }

    tcgetattr(fd, &options); //get port options

    cfsetispeed(&options, B9600); //set input baud rate
    cfsetospeed(&options, B9600); //set output baud rate

    options.c_cflag |= (CLOCAL | CREAD); //enable receiver and set local mode

    options.c_cflag &= ~PARENB;
    options.c_cflag &= ~CSTOPB;
    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;
    options.c_cflag &= ~CRTSCTS; //disable hardware flow control
    options.c_cflag &= ~(ICANON | ECHO | ISIG); //set raw input

    options.c_cflag |= IXOFF; //disable software flow control

    tcsetattr(fd, TCSANOW, &options); //set new port options

    sleep(1);
    int rc,count;
    int size = 8;
    unsigned char buf[10];
    FILE *fp = NULL;
    char ch;
    int i=0;
    printf("enter the data you want to send");

    while((ch=getchar())!='\n')
    {
        write(fd,&ch,1);
    }
    close(fd);

    printf("Finished.\n");

    return 0;
}

0 个答案:

没有答案
相关问题