Linux应用程序开发--串口通信

来源:互联网 发布:2017双十一成交数据 编辑:程序博客网 时间:2024/06/05 04:35

第一步:

参考“Linux应用程序开发--Hello”的第一步。

 

第二步:

示例程序如下:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#include <pthread.h>

int main(void)
{
    int fd;
    char rxBuffer[1024];
    int len = 1024;
    int rxByte;
    struct termios opt;

    fd = open("/dev/ttyS1",O_RDWR);
    if(fd==-1)
    {
        perror("error");
    }
    //set bps
    tcgetattr(fd,&opt);
    cfsetispeed(&opt,B9600);
    cfsetospeed(&opt,B9600);
    //set raw input and output
    opt.c_lflag &= ~(ICANON|ECHO|ECHOE|ISIG);
    opt.c_oflag &= ~OPOST;
    tcsetattr(fd,TCSANOW,&opt);
    //print tips
    printf("Please enter any data to the COM1, Enter key to confirm/n");
    write(fd,"READY!/n",7);
    //receive bytes and send back
    while(1)
    {
        rxByte = 0;
        rxByte = read(fd,rxBuffer,len);
        if(rxByte>0)
        {
           rxBuffer[rxByte]='/0';
            write(fd,"RE:",3);
            write(fd,rxBuffer,rxByte);
            write(fd,"/n",1);
           printf("%s/n",rxBuffer);
        }
    }
    close(fd);
    return 0;
}

 

第三步:

参考“Linux应用程序开发--Hello”的第三步。

 

第四步:

参考“Linux应用程序开发--Hello”的第四步。

 

第五步:

参考“Linux应用程序开发--Hello”的第五步。

 
原创粉丝点击