#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;
}
Deepin系统,中盛科技温湿度模块读温度纯c程序(备份)
java 乐山2024-07-21 10:51
相关推荐
厂太_STAB_丝针1 小时前
【自学嵌入式(8)天气时钟:天气模块开发、主函数编写】charlie1145141913 小时前
从0开始使用面对对象C语言搭建一个基于OLED的图形显示框架(协议层封装)*TQK*3 小时前
ZZNUOJ(C/C++)基础练习1041——1050(详解版)*TQK*4 小时前
ZZNUOJ(C/C++)基础练习1031——1040(详解版)Terasic友晶科技6 小时前
第26篇 基于ARM A9处理器用C语言实现中断<二>linhhanpy10 小时前
自制虚拟机(C/C++)(二、分析引导扇区,虚拟机读二进制文件img软盘)qystca17 小时前
洛谷 P1734 最大约数和 C语言Oracle_6661 天前
C基础算法与实现Pakho love1 天前
Linux:文件与fd(被打开的文件)W说编程1 天前
C语言指针专题四 -- 多级指针