110 lines
2.4 KiB
C++
110 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(2705 , 2);
|
|
|
|
// Check if the read was successful
|
|
if (result == node.ku8MBSuccess)
|
|
{
|
|
Serial.print("Read successful: ");
|
|
|
|
uint16_t highWord = node.getResponseBuffer(0);
|
|
uint16_t lowWord = node.getResponseBuffer(1);
|
|
uint32_t floatRaw = ((uint32_t)highWord << 16) | lowWord; // Combine registers
|
|
float floatValue;
|
|
|
|
// Convert raw 32-bit value to float
|
|
memcpy(&floatValue, &floatRaw, sizeof(float));
|
|
|
|
Serial.print("Float value: ");
|
|
Serial.println(floatValue);
|
|
// 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);
|
|
}
|
|
|
|
}
|
|
|
|
}
|