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
main.cpp
- Committer:
- gabrielrivas
- Date:
- 2015-01-21
- Revision:
- 1:544f5f721159
- Parent:
- 0:220ae68e7dd4
File content as of revision 1:544f5f721159:
#include "mbed.h" #include "rtos.h" #include "ModbusSlaveRTU.h" #include "MessageQueue.h" #include "SerialPortHandler.h" DigitalOut led(LED1); Serial pc(SERIAL_TX, SERIAL_RX); 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}; uint8_t hRegs[] = {1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0}; ThreadSafeArray_t hR; ThreadSafeArray_t cR; ThreadSafeArray_t iR; void rx_interrupt(void); void modbus_process (void const *args) { while (true) { mbus->FSM(); Thread::wait(10); } } void data_send_process(void const *args) { while (true) { if (!txQueue.isEmpty()) { sph.transmitPacket(); txQueue.reset(); } Thread::wait(500); } } 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); hR.length = 20; hR.data = hRegs; cR.length = 20; cR.data = cRegs; iR.length = 20; iR.data = inRegs; 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; } } void rx_interrupt(void) { if (!isReceiveTimerInitialized) { isReceiveTimerInitialized = true; receiveTimer.start(); } else { receiveTimer.reset(); } sph.receivePacket(); return; }