Example of how to handle the Modbus Slave RTU protocol using the mbed RTOS. This example can also be used as reference to implement other slow serial protocols.
Dependencies: MessageQueue ModbusSlaveRTU SerialPortHandler mbed-rtos mbed
Diff: main.cpp
- Revision:
- 1:544f5f721159
- Parent:
- 0:220ae68e7dd4
--- a/main.cpp Mon Jan 19 04:07:15 2015 +0000 +++ b/main.cpp Wed Jan 21 03:00:29 2015 +0000 @@ -9,9 +9,12 @@ MessageQueue<uint8_t> txQueue(64); MessageQueue<uint8_t> rxQueue(64); SerialPortHandler sph(&pc, &txQueue, &rxQueue); +Timer receiveTimer; +bool isReceiveTimerInitialized = false; ModbusSlaveRTU* mbus; Thread* modbus_process_thread; Thread* data_send_thread; +Thread* receive_timer_check_thread; uint8_t cRegs[] = {1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0}; uint8_t inRegs[] = {1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0}; @@ -43,6 +46,20 @@ } } +void timer_check(void const *args) +{ + while(true) { + if (receiveTimer.read_ms() >= 1) { + mbus->trigger(); + isReceiveTimerInitialized = false; + receiveTimer.reset(); + receiveTimer.stop(); + } + /*Waits for 5 ms*/ + Thread::wait(5); + } +} + int main (void) { pc.attach(&rx_interrupt); @@ -58,16 +75,24 @@ mbus = new ModbusSlaveRTU(0x01, &txQueue, &rxQueue, &cR, &iR, &hR); modbus_process_thread = new Thread(modbus_process); data_send_thread= new Thread(data_send_process); - + receive_timer_check_thread = new Thread(timer_check); while(true) { Thread::wait(1000); led = !led; - mbus->trigger(); } } void rx_interrupt(void) { + if (!isReceiveTimerInitialized) + { + isReceiveTimerInitialized = true; + receiveTimer.start(); + } + else + { + receiveTimer.reset(); + } sph.receivePacket(); return; }