RS36

Dependencies:   mbed

Revision:
0:5da6d25de6c5
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Thu Mar 17 12:06:42 2022 +0000
@@ -0,0 +1,81 @@
+#include "mbed.h"
+Serial pc(SERIAL_TX, SERIAL_RX);
+Serial modbus(PC_10, PC_11);
+uint8_t get[13];
+float tem[29];
+
+uint16_t CRC16(uint8_t *bpMsgStartAddress, uint8_t bDataLen)
+{
+    uint16_t crc = 0xffff;
+    uint8_t u8tmp;
+    for (int i=0; i<bDataLen; i++) {
+        crc ^= *bpMsgStartAddress++;
+        for (int n=0; n<8; n++) {
+            u8tmp = crc & 1;
+            crc >>= 1;
+            crc &= 0x7fff;
+            if (u8tmp == 1) {
+                crc ^= 0xa001;
+            }
+        }
+    }
+    return crc;
+}
+
+void get_data(int len)
+{
+    int i=0;
+    while(i<len) {
+        if(modbus.readable() ) {
+            get[i]=modbus.getc();
+            i=i+1;
+        }
+    }
+}
+
+void put_data(int address,int len)
+{
+    uint8_t put[8];   //   读取4路温度
+    put[0]=address;
+    put[1]=0x03;
+    put[2]=0x00;
+    put[3]=0x28;
+    put[4]=0x00;
+    put[5]=0x04;
+    uint16_t crc=CRC16(put,6);
+    //pc.printf("crc:%x,%x,%x",crc,crc&0xFF,(crc&0xFF00)>>8);
+    put[6]=crc&0xFF;
+    put[7]=(crc&0xFF00)>>8;
+    for(int i=0; i<len; i++)
+        modbus.putc(put[i]);
+}
+
+void read_tem()
+{
+    for(int i=0; i<7; i++) {
+        put_data(i+1,8);
+        get_data(13);
+        tem[1+4*i]=(get[3]*256.0+get[4])/10.0f;//一通道
+        tem[2+4*i]=(get[5]*256.0+get[6])/10.0f;//二通道
+        tem[3+4*i]=(get[7]*256.0+get[8])/10.0f;//三通道
+        tem[4+4*i]=(get[9]*256.0+get[10])/10.0f;//四通道
+        wait_ms(5);
+    }
+}
+
+int main()
+{
+    pc.baud(115200);
+    modbus.baud(9600);
+    pc.printf("PC connected!\n");
+    while(1) {
+        read_tem();
+        pc.printf("d0:");
+        for(int i=1; i<28; i++) {
+            pc.printf("%.1f,",tem[i]);
+        }
+        pc.printf("%.1f",tem[28]);
+        pc.printf("\n");
+        wait(0.1);
+    }
+}
\ No newline at end of file