Deepin系统,中盛科技温湿度模块读温度纯c程序(备份)

复制代码
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <termios.h>

int main() {
    int fd;
    struct termios options;

    // 打开串口设备
    fd = open("/dev/ttyMP0", O_RDWR | O_NOCTTY|O_NDELAY); //O_NDELAY:打开设备不阻塞
                                                          //O_NOCTTY:防止串口成为终端设备
    if (fd == -1) {
        perror("Error opening serial port");
        return 1;
    }

    // 设置串口参数
    cfsetispeed(&options, B9600); // 设置输入波特率
    cfsetospeed(&options, B9600); // 设置输出波特率
    options.c_cflag |= (CLOCAL | CREAD); // 必要的控制标志
    options.c_cflag &= ~PARENB; // 禁用奇偶校验
    options.c_cflag &= ~CSTOPB; // 1个停止位
    options.c_cflag &= ~CSIZE;  // 清除当前字符大小位 与CS 连用 
    options.c_cflag |= CS8; // 8位数据位

    options.c_cflag &= ~CRTSCTS;  //禁用控制流  这句非常重要,如不加程序异常
    options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);  //原始模式
    options.c_iflag &= ~(IXON | IXOFF | IXANY);         //禁用软件流
    options.c_oflag &= ~OPOST;                          //原始输出

// 应用新的串口属性
    if (tcsetattr(fd, TCSANOW, &options) != 0) {
        perror("Error setting serial port attributes");
        close(fd);
        return 1;
    }

  //  写串口,读串口  
        unsigned char data[]={1,4,0,0,0,1,0x31,0xca};
	write(fd,data,8);
    	unsigned char o[20];
    	int rt=read(fd,o,20);

	while(rt<2){    //接收数据不正确就重发
		sleep(1);       //发和收必须有时间延时
		write(fd,data,8);
		rt=read(fd,o,20);
	}

    	for(int a=0;a<rt;a++){
	    printf("%x;",o[a]);
    	}
	puts("");
	printf("温度=%0.1f\n",(o[3]*256+o[4])*0.1);
    
       // 关闭串口设备
       close(fd);

       return 0;
}
相关推荐
RuoZoe11 小时前
重塑WPF辉煌?基于DirectX 12的现代.NET UI框架Jalium
c语言
祈安_4 天前
C语言内存函数
c语言·后端
norlan_jame5 天前
C-PHY与D-PHY差异
c语言·开发语言
czy87874755 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
m0_531237175 天前
C语言-数组练习进阶
c语言·开发语言·算法
Z9fish6 天前
sse哈工大C语言编程练习23
c语言·数据结构·算法
代码无bug抓狂人6 天前
C语言之单词方阵——深搜(很好的深搜例题)
c语言·开发语言·算法·深度优先
CodeJourney_J6 天前
从“Hello World“ 开始 C++
c语言·c++·学习
枫叶丹46 天前
【Qt开发】Qt界面优化(七)-> Qt样式表(QSS) 样式属性
c语言·开发语言·c++·qt
with-the-flow6 天前
从数学底层的底层原理来讲 random 的函数是怎么实现的
c语言·python·算法