109 lines
2.4 KiB
C++
109 lines
2.4 KiB
C++
#include <ModbusMaster.h>
|
|
#include <SoftwareSerial.h>
|
|
|
|
// Define software serial pins (use any digital pins if not using hardware serial)
|
|
#define RX_PIN 13
|
|
#define TX_PIN 12
|
|
#define DE_PIN 3
|
|
#define RE_PIN 4
|
|
|
|
SoftwareSerial s1(RX_PIN, TX_PIN);
|
|
ModbusMaster node;
|
|
uint16_t holdingRegisters[20];
|
|
|
|
void setup() {
|
|
// Start the software serial port
|
|
s1.begin(9600 );
|
|
|
|
//pinMode(RX_PIN, INPUT);
|
|
//pinMode(TX_PIN, OUTPUT);
|
|
pinMode(DE_PIN, OUTPUT);
|
|
pinMode(RE_PIN, OUTPUT);
|
|
|
|
digitalWrite(DE_PIN, LOW);
|
|
digitalWrite(RE_PIN, LOW);
|
|
|
|
//node.setTimeout(2000);
|
|
// Optionally, start the Serial monitor for debugging
|
|
Serial.begin(9600);
|
|
|
|
while (!s1) {
|
|
}
|
|
node.begin(101, s1);
|
|
node.preTransmission(preTransmission);
|
|
node.postTransmission(postTransmission);
|
|
|
|
}
|
|
|
|
void preTransmission()
|
|
{
|
|
digitalWrite(DE_PIN, HIGH); // Enable RS485 transmit
|
|
digitalWrite(RE_PIN, HIGH);
|
|
|
|
|
|
}
|
|
|
|
void postTransmission()
|
|
{
|
|
digitalWrite(DE_PIN, LOW); // Disable RS485 transmit
|
|
digitalWrite(RE_PIN, LOW);
|
|
}
|
|
|
|
static unsigned long lastRefreshTime = 0;
|
|
#define ReadSize 4
|
|
void loop() {
|
|
static uint16_t count = 0;
|
|
uint8_t result;
|
|
int16_t data[ReadSize];
|
|
|
|
|
|
//delay(100); // Wait a second before the next loop
|
|
|
|
// digitalWrite(RE_PIN, HIGH);
|
|
// s1.print("Hello");
|
|
// digitalWrite(RE_PIN, LOW);
|
|
|
|
if(millis() - lastRefreshTime >= 1000)
|
|
{
|
|
|
|
lastRefreshTime += 1000;
|
|
Serial.print("Cycle\n\n");
|
|
|
|
|
|
result = node.readHoldingRegisters(1836 , 8);
|
|
|
|
// Check if the read was successful
|
|
if (result == node.ku8MBSuccess)
|
|
{
|
|
Serial.print("Meter Date Time Read successful: ");
|
|
Serial.print("Y : ");
|
|
Serial.println(node.getResponseBuffer(0));
|
|
Serial.print("M : ");
|
|
Serial.println(node.getResponseBuffer(1));
|
|
Serial.print("D : ");
|
|
Serial.println(node.getResponseBuffer(2));
|
|
Serial.print("H : ");
|
|
Serial.println(node.getResponseBuffer(3));
|
|
Serial.print("M : ");
|
|
Serial.println(node.getResponseBuffer(4));
|
|
// for (uint8_t j = 0; j < ReadSize; j++)
|
|
// {
|
|
// int recv = node.getResponseBuffer(j);
|
|
// data[j] = recv;
|
|
// Serial.print(recv );
|
|
// }
|
|
// Serial.print("\nHEX:");
|
|
// for (uint8_t j = 0; j < ReadSize; j++)
|
|
// {
|
|
// Serial.print(data[j],"HEX");
|
|
// }
|
|
// Serial.println();
|
|
} else {
|
|
Serial.print("Read error: ");
|
|
Serial.println(result, HEX);
|
|
}
|
|
|
|
}
|
|
|
|
}
|