Linux 串口应用简单开发

Linux 串口配置,简单写操作: 

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

#define UART_PATH       "/dev/ttyS0"

int openPort()
{
    int temp_fd;
    int speed = B115200;              //115200

    /open serial port
    temp_fd = open(UART_PATH, O_RDWR | O_NOCTTY);
    if (temp_fd < 0) {
        ALOGE("Open %s error !", UART_PATH);
        return temp_fd;
    }

    struct termios tio;
    if (tcgetattr(temp_fd, &tio)){
        memset(&tio, 0, sizeof(tio));
    }
    tio.c_cflag =  speed | CS8 | CLOCAL | CREAD;
    tio.c_oflag &= ~OPOST;
    tio.c_iflag = IGNPAR;
    tio.c_lflag = 0;
    tio.c_cc[VTIME] = 0;
    tio.c_cc[VMIN] = 1;
    tcsetattr(temp_fd, TCSANOW, &tio);
    tcflush(temp_fd, TCIFLUSH);

    return temp_fd;
}

void writeUartFunc(int fd)
{
    int i, temp;
    char closeData[10] = {0x21, 0x23, 0x41, 0x4F, 0x09, 0x00, 0x43, 0x30, 0x00, 0x0D};

    temp = closeData[0];
    for (i=1; i<8; i++)
    {
        temp ^= closeData[i];
    }
    closeData[8] = temp;       // checksum

    //send heart beat packet data
    write(fd, closeData, 10);
}

int main(int argc, char* const argv[])
{
    int fd;
    fd = openPort();
    if (fd < 0)
    {
        ALOGE("Open uart error, exit now !");
        return -1;
    }

    writeUartFunc(fd);
    close(fd);
}

参考:

https://www.cnblogs.com/chengmin/p/3818133.html

https://blog.csdn.net/morixinguan/article/details/80898172

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值