STC12C5A60S2单片机接MAX485模块,读取485温湿度传感器的数据(MODBUS),并显示在OLED屏上
说明:主机发送数据帧:01 03 02 00 00 03 04 73

单片机源程序如下:
-
- /************************************************************************************
- 功能:单片机作为主机读取基于RS485的MODBUS协议的温湿度传感器数据测试
- **************************************************************************************/
- //头文件
- #include "main.h"
- int temp=2500;
- int humidity=3500;
- unsigned char code read_temp_hum_cmd[]={0x01,0x03,0x02,0x00,0x00,0x03,0x04,0x73};
- void main(void)
- {
- Timer0Init();
- UartInit();
- OLED_Init();
- OLED_Clear();
- EA = 1;
- printf("RS485 Modbus Test\r\n");
- while(1)
- {
- if (sec_flag)
- {
- sec_flag=0;
- uart_sendbuf(read_temp_hum_cmd,8);
- }
- if (rxd_flag)
- {
- rxd_flag=0;
- uart_sendbuf(rxd_buf,rxd_index);
- modbus_handle(rxd_buf,rxd_index);
- rxd_index=0;
- }
- display_temp_hum(temp,humidity);
- }
- }
- void display_temp_hum(int t,int h)
- {
- unsigned char tempstr[8];
- unsigned char humiditystr[8];
- if(t<0)
- {
- IntegerToStr(t,tempstr);
- OLED_ShowString(0,4,"TEMP:",16);
- OLED_ShowString(48,4,tempstr,16);
- }
- else
- {
- IntegerToStr(t,tempstr);
- OLED_ShowString(0,4,"TEMP:",16);
- OLED_ShowString(56,4,tempstr,16);
- }
- IntegerToStr(h,humiditystr);
- OLED_ShowString(0,6,"RH :",16);
- OLED_ShowString(56,6,humiditystr,16);
- OLED_ShowChar(96,6,'%',16);
- }
- void modbus_handle(unsigned char *buf,unsigned char len)
- {
- unsigned int crc;
- unsigned char crch,crcl;
- if (buf[0] != TEMP_HUM_ADDR)
- {
- return;
- }
- else if (buf[0] == TEMP_HUM_ADDR)
- {
- crc=GetCRC16(buf,len-2);
- crch=crc>>8;
- crcl=crc&0xff;
- if((buf[len-2]!=crch)||(buf[len-1]!=crcl))
- {
- return;
- }
- temp=((int)buf[3]<<8) + buf[4];
- humidity=((int)buf[5]<<8) + buf[6];
- }
- }
复制代码
Keil代码下载:
RS485型MODBUS协议的温湿度传感器.zip
(112.17 KB, 下载次数: 164)
|