zoukankan      html  css  js  c++  java
  • Linux下串口编程

    1、设置串口波特率

    stty -F /dev/ttyPS1  speed 115200
    dmesg | grep ttyS* //查串口设备
    echo 232 >> /dev/ttyPS1 //查看串口是否可用

    2、测试代码

    //可串口调试助手进行测试,可通过stty设置串口波特率

    #include <stdio.h> /*标准输入输出定义*/ #include <stdlib.h> /*标准函数库定义*/ #include <unistd.h> /*Unix 标准函数定义*/ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> /*文件控制定义*/ #include <termios.h> /*PPSIX 终端控制定义*/ #include <errno.h> /*错误号定义*/
    #include   <string.h>

    int main(void)
    {

    
    

    int fd;
    char buf[50]={0};
    char buf111[12]={0x01,0x09,0x30,0x34,0x35,0x44,0x42,0x35,0x33,0x41,0x46,0x0D};
    char buf123[200]={0};
    int len = 0;
    int len1 = 0;
    int i = 0;
    int count =0;
    struct termios termios_p;
    fd = open("/dev/ttyPS1", O_RDWR | O_NOCTTY);

    
    

    tcgetattr(fd, &termios_p);
    termios_p.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
    termios_p.c_oflag &= ~OPOST;
    termios_p.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
    termios_p.c_cflag &= ~(CSIZE | PARENB);
    termios_p.c_cflag |= CS8;
    tcsetattr(fd, TCSANOW, &termios_p);
    printf("Line %d ", __LINE__);

    while(1)
    {


    sleep(2);
    write(fd, buf111, 12);

    
    

    // goto out;
    memset(buf, 0, sizeof(buf));
    len =0;
    len1 = 0;
    while(len1 < 20)
    {
    len = read(fd, buf, 10);
    if (len <= 0)
    {

    printf("read failed %d 0x%02x ", len, buf[0]);
    //exit(-1);
    continue;
    }
    memcpy(buf123+len1, buf, len);
    len1 += len;
    for(i =0; i< len; i++)
    printf("%02x ", buf[i]);

    }

    printf("count %d ", count++);

    out:
    usleep(1000000);
    }

    }

    参考文档: POSIX操作系统的串行编程指南

          Linux 下串口编程入门

  • 相关阅读:
    CSS中的小知识
    网络基础 中的osi七层 协议
    pickle的使用
    max()的key的运用
    read,readline,readlines的区别
    print()控制台输出带颜色的方法
    写项目时bin目录下的start中的细节(路径问题的解决)
    使用hashlib密文存储实例
    固态硬盘使用f2fs作为根分区安装linux
    工厂方法(Factory Method)
  • 原文地址:https://www.cnblogs.com/listxue/p/13141038.html
Copyright © 2011-2022 走看看