#include <SoftwareSerial.h>
SoftwareSerial mySerial(6, 7); // RX, TX
unsigned long u32lastReadChars; // used for serial read timeout
// DLSM COSEM testing:
//byte cmd[] = {0xAF,0x3F,0x21,0x8D,0x0A}; // query the meter for data "/?!"+<13><10>
//byte cmd2[] = {0x06,0x30,0x30,0x30,0x8D,0x0A}; // query the meter for data <ack>"000"+<13><10>
// M-Bus testing:
byte cmd[] = {0x10,0x40,0x00,0x40,0x16}; //ping: start;command;address;checksum;end
byte cmd2[] = {0x10,0x5B,0x00,0x5B,0x16}; //req data: start;command;address;checksum;end
int state = 0;
int count = 0;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.println("Goodnight moon!");
// set the data rate for the SoftwareSerial port
//mySerial.begin(300);
mySerial.begin(2400);
}
void loop() { // run over and over
// Serial.println("");
// Serial.print("state: ");
// Serial.println(state);
switch(state) {
case 0:
mySerial.flush();
mySerial.write (cmd,5);
mySerial.flush();
delay(102);
u32lastReadChars = millis();
count = 0;
state++;
break;
case 1:
readSerial();
//Serial.println();
if(u32lastReadChars + 3000 < millis()) {
if(count > 0)
state++;
else
state = 0;
delay(2000);
}
break;
case 2:
mySerial.flush();
mySerial.write (cmd2,6);
mySerial.flush();
delay(102);
u32lastReadChars = millis();
count = 0;
state++;
break;
case 3:
readSerial();
if(u32lastReadChars + 3000 < millis()) {
if(count > 0)
state = 2;
else
state = 0;
Serial.println("State 3 end");
delay(2000);
}
break;
}
}
void readSerial() {
byte a;
int i = 0;
for(i = 0; i < 1; i++) {
while (mySerial.available() > 0)
{
a = mySerial.read() & 0x7F; // from 8N1 to 7E1
char b = a; // convert serial byte to ASCII character
int c = a;
Serial.print(b);
//Serial.print(c);
if(c != 127) // for some reason my optical header generates spaces.. reading some reflection of sent message?
count++;
u32lastReadChars = millis();
}
}
//Serial.print("Serial read done..");
//Serial.println();
}