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;
}

5894d05032234c78a313d4d0f05317cf.png

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值