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;
}
相关推荐
深夜吞食13 分钟前
项目实现:云备份③(配置文件加载模块、数据管理模块的实现)
linux·c语言·c++·json
螺蛳粉只吃炸蛋的走风37 分钟前
面试题总结(三) -- 内存管理篇
c语言·c++·面试·内存·堆栈·raii
爱是小小的癌40 分钟前
C语言自定义类型-联合与枚举
c语言·开发语言
轩源源1 小时前
C/C++内存管理
c语言·开发语言·数据结构·c++·算法·缓存·内存空间的开创
spiritualfood2 小时前
联合体与枚举以及结构体补充
c语言·开发语言·c++·算法·青少年编程
ZLRRLZ3 小时前
【初阶数据结构】排序
c语言·算法·排序算法
极客小张3 小时前
基于ESP32的管道检修机器人:MQTT协议、SLAM技术栈设计流程
c语言·单片机·物联网·网络协议·算法·机器人·语音识别
MrGaomq4 小时前
Linux权限
linux·运维·服务器·c语言·数据结构·c++·动态规划
ChoSeitaku5 小时前
单链表各种接口的实现(C)
c语言·开发语言·数据结构
Skrrapper5 小时前
【数据结构】排序算法系列——堆排序(附源码+图解)
c语言·数据结构·算法·排序算法