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;
}
相关推荐
T1mzhou6 小时前
ARM64 Linux 6.10内核启动流程7-ioremap和readl writel
linux·服务器·c语言
未来之窗软件服务11 小时前
计算机二级[英文]-C 字符串移动—东方仙盟
c语言·开发语言·仙盟创梦ide·东方仙盟
是隼人16 小时前
buuctf-pwn bypwn(ret2shellcode)题解(学习过程持续更新)
c语言·学习·安全·pwn入门·ctf入门
T1mzhou17 小时前
ARM64 Linux 6.10内核启动流程6-psci.c和ATF/U-Boot 的电源接口
linux·服务器·c语言
是隼人17 小时前
buuctf-pwn PWN2(整数溢出)题解(学习过程持续更新)
c语言·学习·安全·pwn入门·ctf入门
LuminousCPP18 小时前
数据结构 - 排序(二):快速排序从错误初版到优化版|双指针划分 + 三数取中 + 小区间插入优化
c语言·数据结构·笔记·算法·排序算法
竞赛考级题库18 小时前
202606 青少年等级考试C/C++真题一级 建议答题时长:60min
java·c语言·c++
迷茫、Peanut18 小时前
C语言混合链接
c语言
wdfk_prog19 小时前
RT-Thread Kconfig 配置明明是 y,为什么 rtconfig.h 就是不生成?一次 `_PATH` 后缀踩坑复盘
c语言
是隼人19 小时前
buuctf-pwn jarvisoj_level5(64位ret2libc)题解(学习过程持续更新)
c语言·学习·安全·pwn入门·ctf入门