Supachai Vorapojpisut
/
TAIST_modbus
Example code for modbus serial
main.cpp
- Committer:
- vsupacha
- Date:
- 2018-03-16
- Revision:
- 1:0007712e84a8
- Parent:
- 0:f306cb0263a6
File content as of revision 1:0007712e84a8:
#include "mbed.h" #include "modbus.h" #include "RawSerial.h" DigitalOut myled(LED1); RawSerial pc(USBTX, USBRX); InterruptIn button(USER_BUTTON); Ticker timebase; uint32_t Tick = 0; uint32_t pressedTick = 0; uint32_t releasedTick = 0; void serial_callback() { uint8_t frame[6]; uint16_t offset, count; uint8_t reg_map; char ch = pc.getc(); if (modbus_parser(ch, frame)) { offset = (frame[2] << 8) | (frame[3]); count = (frame[4] << 8) | (frame[5]); reg_map = modbus_check(offset, count); modbus_response(reg_map); } } void pressed_callback() { uint16_t skipCount; if ((Tick > pressedTick) && (Tick > releasedTick)) { skipCount = Tick - releasedTick; modbus_update(0x0000, skipCount); pressedTick = Tick; // printf("Pressed: %d - %d - %d\r\n", pressedTick, releasedTick, skipCount); } } void released_callback() { uint16_t widthCount; if ((Tick > pressedTick) && (Tick > releasedTick)) { widthCount = Tick - pressedTick; modbus_update(0x0001, widthCount); releasedTick = Tick; // printf("Released: %d - %d - %d\r\n", pressedTick, releasedTick, widthCount); } } void ticker_callback() { Tick++; } int main() { // setup code pc.attach(&serial_callback); // 1. button code button.rise(&pressed_callback); button.fall(&released_callback); // 2. timer code timebase.attach(&ticker_callback, 0.1); printf("Starting\n"); printf("Test: %02X\r\n", modbus_check(0x0000, 0x0001)); printf("Test: %02X\r\n", modbus_check(0x0001, 0x0001)); printf("Test: %02X\r\n", modbus_check(0x0000, 0x0002)); printf("Test: %02X\r\n", modbus_check(0x0000, 0x0003)); printf("Test: %02X\r\n", modbus_check(0x0001, 0x0002)); printf("Test: %02X\r\n", modbus_check(0x0002, 0x0002)); while(1) { // blinking LED myled = !myled; wait(2.5); printf("Detection: %d - %d\r\n", pressedTick, releasedTick); modbus_response(0x01); modbus_response(0x02); modbus_response(0x03); } }