串口编程实例

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <string.h>
#include <unistd.h>

int openCom(char *comBuf)
{
    char comName[64] = {0};
    snprintf(comName,sizeof(comName),"/dev/tty%s",comBuf);
    int fd = open(comName,O_RDWR); // 
    if(fd < 0)
    {
        perror("openm:");
        printf("open %s error\n",comName);
        return -1;
    }
    fcntl(fd, F_SETFL, 0); //重设为堵塞状态, 去掉O_NONBLOCK
    struct termios opts;
    tcgetattr(fd, &opts); //把原设置获取出来,存放在opts

    //设置波特率
    cfsetispeed(&opts, B9600);
    cfsetospeed(&opts, B9600);

    opts.c_cflag |= CLOCAL|CREAD; //忽略modem控制线, 启动接收器

    // 8N1
    opts.c_cflag &= ~PARENB; 
    opts.c_cflag &= ~CSTOPB;
    opts.c_cflag |= CS8;

    opts.c_cflag &= ~CRTSCTS; //关闭硬件流控

    opts.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); //raw input
    opts.c_oflag &= ~OPOST; // raw output          

    tcsetattr(fd, TCSANOW, &opts);

}


int main(int argc,char **argv)
{
    int fd;
    if(argc < 2)
    {
        fd = openCom("");
    }
    else
    {
        fd = openCom(argv[1]);
    }
    if(fd < 0)
    {
        return 0;
    }
    while(1)
    {
        sleep(1);
        write(fd,"123\n",4);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值