Linux串口编程

前言

第一次用串口连接两台Linux设备进行通行,慢慢的还要在串口通信的基础上实现其他的通信协议,看别人的开源代码已经看得神魂颠倒,神志不清,差点在暴毙的边缘了,该好好整理一下串口编程的一些基本知识了,帮助自己疏通一下

设备说明:
Ubuntu 1404:使用USB转串口
	  树莓派:直接使用接杜邦线的物理串口

串口编程

俗话说Linux下一切设备皆文件,接触越多越是能切身体会到这一点,
termios结构体
串口编程参考博文

树莓派端

test.c如下:

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

int main()
{
   
        SerialPort                              self;
        int                                     portNo=0;//在结构体uart_dev[]数组中第一个元素才是树莓派的路径名
        int                                     rt=0;
        char                                    buf[512];
        char                                    *str="I am Raspberry!";

        self=SerialPort_create(portNo,115200,8,'N',1);
        rt=SerialPort_open(self,portNo);
        if(rt<0)
        {
   
                printf("at line %s open serial failture!\n",__LINE__);
                return -1;
        }
        while(1)
        {
   
        		memset(buf,0,sizeof(buf));
                rt=SerialPort_readByte(self->fd, buf,sizeof(buf));
                if(rt<0)
                {
   
                        printf("at line %s read port failture!\n",__LINE__);
                        close(self->fd);
                        return -2;
                }
                printf("read %d bytes from buf is:%s\n",rt,buf);
                
                sleep(3);
                memset(buf,0,sizeof(buf));
                memcpy(buf,str,strlen(str));
                rt=SerialPort_write(self->fd, buf,0,strlen(str));
                if(rt<0)
                {
   
                        printf("at line %s write port failture!\n",__LINE__);
                        return -3;
                }
                printf("send %d bytes to buf is:%s\n",rt,buf);
        }
        return 0;
}
Ubuntu 1404端

test.c

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

int main()
{
   
        SerialPort                              self;
        int                                     portNo=1;//在结构体uart_dev[]数组中第二个元素才是Ubuntu 1404 USB转串口的路径名
        int                                     rt=0;
        char                                    buf[512];
        char                                    *str="I am Ubuntu!";

        self=SerialPort_create(portNo,115200,8,'N',1)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值