Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Fork of TAIST_modbus_copy by
modbus.cpp
00001 #include "mbed.h" 00002 #include "modbus.h" 00003 00004 uint8_t nodeId = 0; 00005 uint16_t regValue[ADDR_RANGE]; 00006 00007 enum state {IDLE, RECEPTION, END} protState = IDLE; 00008 00009 int process_buffer(char *buf, uint8_t *frame) 00010 { 00011 int status = 0; 00012 uint8_t sum = 0; 00013 uint8_t lrc, i; 00014 char tmpbuf[] = {0, 0, 0}; 00015 00016 if (strlen(buf) == 14) { 00017 for (i = 0; i < 6; i++) { 00018 tmpbuf[0] = buf[i*2]; 00019 tmpbuf[1] = buf[i*2 + 1]; 00020 frame[i] = strtoul(tmpbuf, NULL, 16); 00021 } 00022 tmpbuf[0] = buf[12]; tmpbuf[1] = buf[13]; 00023 lrc = strtoul(tmpbuf, NULL, 16); 00024 for (i = 0; i < 6; i++) { 00025 sum += frame[i]; 00026 } 00027 if ((sum + lrc) == 0) { 00028 status = 1; 00029 } 00030 } 00031 00032 return status; 00033 } 00034 00035 void modbus_init(uint8_t id) 00036 { 00037 nodeId = id; 00038 } 00039 00040 uint16_t modbus_read(uint16_t offset) 00041 { 00042 if (offset < ADDR_RANGE) { 00043 return regValue[offset]; 00044 } 00045 return 0xFFFF; 00046 } 00047 00048 uint16_t modbus_update(uint8_t offset, uint16_t val) 00049 { 00050 uint16_t tmp; 00051 00052 if (offset < ADDR_RANGE) { 00053 tmp = regValue[offset]; 00054 regValue[offset] = val; 00055 return tmp; 00056 } 00057 return 0xFFFF; 00058 } 00059 00060 int modbus_parser(char ch, uint8_t *frame) 00061 { 00062 static char buf[514]; 00063 static int idx = 0; 00064 static int status = 0; 00065 00066 switch(protState) { 00067 case IDLE: 00068 if (ch == ':') { 00069 protState = RECEPTION; 00070 idx = 0; 00071 status = 0; 00072 } 00073 break; 00074 case RECEPTION: 00075 if ((ch >= '0') && (ch <= '9')) { 00076 buf[idx++] = ch; 00077 } else if ((ch >= 'a') && (ch <= 'f')) { 00078 buf[idx++] = ch; 00079 } else if ((ch >= 'A') && (ch <= 'F')) { 00080 buf[idx++] = ch; 00081 } else if (ch == '\r') { 00082 buf[idx] = 0; 00083 protState = END; 00084 } else { 00085 protState = IDLE; 00086 } 00087 break; 00088 case END: 00089 if (ch == '\n') { 00090 if (process_buffer(buf, frame)) { 00091 if ((frame[0] == nodeId) && (frame[1] == FUNC_CODE)) { 00092 status = 1; 00093 } 00094 } 00095 } 00096 protState = IDLE; 00097 break; 00098 default: 00099 protState = IDLE; 00100 } 00101 00102 return status; 00103 }
Generated on Tue Jul 26 2022 04:50:13 by
 1.7.2
 1.7.2 
    