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;
}
相关推荐
2601_949146538 小时前
C语言语音通知接口接入教程:如何使用C语言直接调用语音预警API
c语言·开发语言
知南x10 小时前
【Ascend C系列课程(高级)】(1) 算子调试+调优
c语言·开发语言
2的n次方_12 小时前
Runtime 执行提交机制:NPU 硬件队列的管理与任务原子化下发
c语言·开发语言
凡人叶枫12 小时前
C++中智能指针详解(Linux实战版)| 彻底解决内存泄漏,新手也能吃透
java·linux·c语言·开发语言·c++·嵌入式开发
凡人叶枫14 小时前
C++中输入、输出和文件操作详解(Linux实战版)| 从基础到项目落地,避坑指南
linux·服务器·c语言·开发语言·c++
傻乐u兔15 小时前
C语言进阶————指针3
c语言·开发语言
CodeSheep程序羊16 小时前
拼多多春节加班工资曝光,没几个敢给这个数的。
java·c语言·开发语言·c++·python·程序人生·职场和发展
I'mChloe16 小时前
PTO-ISA 深度解析:PyPTO 范式生成的底层指令集与 NPU 算子执行的硬件映射
c语言·开发语言
2的n次方_17 小时前
Runtime 内存管理深化:推理批处理下的内存复用与生命周期精细控制
c语言·网络·架构
嵌入小生00717 小时前
标准IO---核心函数接口延续(嵌入式Linux)
c语言·vscode·vim·嵌入式·小白·标准io·函数接口