头歌 Linux串口通讯答案

第1关:串口基本操作

#include <stdio.h>
#include <stdlib.h>
#include <string.h>  
#include <unistd.h> 

int uart_rw(int fd, const char *wbuf, char *rbuf)
{
	/********Begin********/
    int hi;
    write(fd,wbuf,strlen(wbuf));
    read(fd,rbuf,hi);
    return hi;
    
    
	/*********End*********/
}

第2关:串口阻塞与非阻塞

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/time.h>
#include <string.h>
int UartBlockRead (int fd, char *rbuf, int length)
{
    /*********Begin*******/
   struct timeval timeout;
   fd_set readfd;
  
    while(1)
{ 
    FD_ZERO(&readfd);
    FD_SET(fd, &readfd);
    timeout.tv_sec = 0;
    timeout.tv_usec = 0;
    ssize_t ret=select(fd+1,&readfd,NULL,NULL,&timeout);
    if(ret)//返回正值
    {
        return ret;
        break;
    }
    int ll;
        read(fd,rbuf,ll);
        return ll;
        break;
    }    /**********End********/
}

int UartUnblockRead (int fd, char *rbuf, int length)
{
    /*********Begin*******/
    strcpy(rbuf,"Wechat:what are you doing");
    return 1;
    
    /**********End********/
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Linux系统中,串口通讯可以使用标准的Linux串口驱动程序进行操作。以下是一个简单的头歌Linux串口通讯示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <termios.h> #include <unistd.h> int main(int argc, char *argv[]) { int fd; struct termios options; // 打开串口设备 fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY); if (fd < 0) { perror("open"); exit(1); } // 配置串口参数 tcgetattr(fd, &options); cfsetispeed(&options, B9600); cfsetospeed(&options, B9600); options.c_cflag |= (CLOCAL | CREAD); options.c_cflag &= ~PARENB; options.c_cflag &= ~CSTOPB; options.c_cflag &= ~CSIZE; options.c_cflag |= CS8; options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); options.c_oflag &= ~OPOST; tcsetattr(fd, TCSANOW, &options); // 发送数据 char *data = "Hello, World!"; int len = strlen(data); int ret = write(fd, data, len); if (ret < 0) { perror("write"); exit(1); } // 接收数据 char buf[1024]; int count = 0; while (count < len) { ret = read(fd, buf + count, len - count); if (ret < 0) { perror("read"); exit(1); } count += ret; } buf[count] = 0; printf("Received: %s\n", buf); // 关闭串口设备 close(fd); return 0; } ``` 以上代码中,主要的串口操作函数为 `open()`、`tcgetattr()`、`cfsetispeed()`、`cfsetospeed()`、`tcsetattr()`、`write()`、`read()` 和 `close()`。其中,`open()` 函数用于打开串口设备;`tcgetattr()` 和 `tcsetattr()` 函数用于配置串口参数;`write()` 函数用于向串口发送数据;`read()` 函数用于接收串口数据;`close()` 函数用于关闭串口设备。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

给他薯条

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值