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;
}
相关推荐
John.Lewis1 小时前
数据结构初阶(13)排序算法-选择排序(选择排序、堆排序)(动图演示)
c语言·数据结构·排序算法
丑小鸭是白天鹅4 小时前
嵌入式C语言学习笔记之枚举、联合体
c语言·笔记·学习
GUET_一路向前5 小时前
【C语言防御性编程】if条件常量在前,变量在后
c语言·开发语言·if-else·防御性编程
pusue_the_sun6 小时前
数据结构——栈和队列oj练习
c语言·数据结构·算法··队列
Dontla6 小时前
Makefile介绍(Makefile教程)(C/C++编译构建、自动化构建工具)
c语言·c++·自动化
奶黄小甜包6 小时前
C语言零基础第18讲:自定义类型—结构体
c语言·数据结构·笔记·学习
一支闲人7 小时前
C语言相关简单数据结构:双向链表
c语言·数据结构·链表·基础知识·适用于新手小白
John.Lewis7 小时前
数据结构初阶(19)外排序·文件归并排序的实现
c语言·数据结构·排序算法
John.Lewis7 小时前
数据结构初阶(16)排序算法——归并排序
c语言·数据结构·排序算法
wearegogog1238 小时前
C语言中的输入输出函数:构建程序交互的基石
c语言·开发语言·交互