Example code for modbus serial

Dependencies:   mbed

Revision:
1:0007712e84a8
Parent:
0:f306cb0263a6
diff -r f306cb0263a6 -r 0007712e84a8 main.cpp
--- a/main.cpp	Wed Mar 14 06:17:48 2018 +0000
+++ b/main.cpp	Fri Mar 16 04:34:08 2018 +0000
@@ -1,29 +1,84 @@
 #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);
+    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) {
-        // loop code
-        myled = 1; // LED is ON
-        wait(0.2); // 200 ms
-        myled = 0; // LED is OFF
-        wait(1.0); // 1 sec
+        // blinking LED
+        myled = !myled; 
+        wait(2.5);
+        printf("Detection: %d - %d\r\n", pressedTick, releasedTick);
+        modbus_response(0x01);
+        modbus_response(0x02);
+        modbus_response(0x03);
     }
 }