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)
2022-1-17 23:19 上傳
點擊文件名下載附件
下載積分: 黑幣 -5
|