summaryrefslogtreecommitdiff
path: root/examples/arduino/arduino.ino
blob: 88cbcaacb4a75c9b6fd25ec38ae93a854a8585e9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <modbus.h>
// #include <SoftwareSerial.h>

/* Baud rate for UART */
#define BAUD 9600

/* 
 * To match the parameters of HardwareSerial Rx/Tx functions with the Modbus 
 * functions, wrappers around the ::read() and ::write() functions are 
 * required 
*/
MB_StatusTypeDef ArduinoSerial_Tx(void* serial, uint16_t* buf,
				  uint8_t* len, uint8_t* timeout);
MB_StatusTypeDef ArduinoSerial_Rx(void* serial, uint16_t* buf,
				  uint8_t* len, uint8_t* timeout);

MB_StatusTypeDef (*MB_UART_Tx)(void*, uint16_t*, uint8_t*, uint8_t*) =
    &ArduinoSerial_Tx;
MB_StatusTypeDef (*MB_UART_Rx)(void*, uint16_t*, uint8_t*, uint8_t*) =
    &ArduinoSerial_Rx;

/* Single modbus device node */
modbus_slave_device modbus_dev_single;
/* Multiple modbus device nodes.. after all, what is the point of using Modbus 
 * in a single point-to-point connection? */
/* Not illustrated beyond the definition, but should be clear enough */
modbus_slave_device modbus_dev_multiple[10];
// SoftwareSerial myserial(5, 6);

uint16_t reg;

void setup()
{
    Serial.begin(BAUD);
    // myserial.begin(BAUD);
    /* Set the slave ID to 1 */
    modbus_dev_single.slave_id = 3;
    /* Attach the default HardwareSerial class instance to this node */
    modbus_dev_single.modbus_uart = &Serial;
    
    /* Continuously read this input register in superloop */
    reg = 30001;
}

void loop()
{
    MB_StatusTypeDef status = ReadInputRegisters(&modbus_dev_single, reg, 1);
    if (status == MB_OK) {
	/* Do something with data in the response buffer */
	/* ... */
	// Serial.write((uint8_t)modbus_dev_single.response_buffer);
	ClearResponseBuffer(&modbus_dev_single);
    }    
}

MB_StatusTypeDef ArduinoSerial_Tx(void* serial, uint16_t* buf, uint8_t* len, uint8_t* timeout)
{
    // SoftwareSerial *_serial = static_cast<SoftwareSerial*>(serial);
    Stream *_serial = static_cast<Stream*>(serial);
    // HardwareSerial* _serial = static_cast<HardwareSerial*>(serial);
    _serial->write((uint8_t)*buf);
    // if (_serial->availableForWrite()) {
    // 	_serial->write((uint8_t)*buf);
    // }
    // _serial->flush();
    /* HardwareSerial class funcs do not return any UART errors, sadly */
    return MB_OK;
}

MB_StatusTypeDef ArduinoSerial_Rx(void* serial, uint16_t* buf, uint8_t* len, uint8_t* timeout)
{
    // HardwareSerial* _serial = static_cast<HardwareSerial*>(serial);
    // SoftwareSerial *_serial = static_cast<SoftwareSerial*>(serial);
    Stream *_serial = static_cast<Stream*>(serial);
    buf = _serial->read();
    
    /* HardwareSerial class funcs do not return any UART errors, sadly */
    return MB_OK;
}