Please help me. I’m trying to create a power meter data logger using an Arduino Mega 2560, but when I try, the values are always unreadable, and the connection always fails. I tried using Modbus Poll, and the connection works, and the values are readable, but when I try using the Mega 2560, the values are always unreadable.
Wiring diagram:
- VCC --> Vin 5V Mega2560
- Tx --> Pin 18 Tx1
- Rx --> Pin 19 Rx1
- GND --> GND Mega2560
- A+ --> A(D1) PM1200
- B- --> B(D0) PM1200
I am using an RS485 to TTL, Slave ID 1, Baud rate 9600, Parity Even.
#include "SimpleModbusMaster.h"
/*
The example will use packet1 to read a register from address 0 (the adc ch0 value)
from the arduino slave (id=1). It will then use this value to adjust the brightness
of an led on pin 9 using PWM.
It will then use packet2 to write a register (its own adc ch0 value) to address 1
on the arduino slave (id=1) adjusting the brightness of an led on pin 9 using PWM.
*/
//////////////////// Port information ///////////////////
#define baud 9600
#define timeout 1000
#define polling 200 // the scan rate
#define retry_count 10
// used to toggle the receive/transmit pin on the driver
#define TxEnablePin 0
#define LED 9
// The total amount of available memory on the master to store data
#define TOTAL_NO_OF_REGISTERS 2
// This is the easiest way to create new packets
// Add as many as you want. TOTAL_NO_OF_PACKETS
// is automatically updated.
enum
{
PACKET1,
// PACKET2,
TOTAL_NO_OF_PACKETS // leave this last entry
};
// Create an array of Packets to be configured
Packet packets[TOTAL_NO_OF_PACKETS];
// Masters register array
unsigned int regs[TOTAL_NO_OF_REGISTERS];
void setup()
{
Serial.begin(9600);
// Initialize each packet
modbus_construct(&packets[PACKET1], 1, READ_HOLDING_REGISTERS, 3911, 2, 0);
// modbus_construct(&packets[PACKET2], 1, PRESET_MULTIPLE_REGISTERS, 1, 1, 0);
// Initialize the Modbus Finite State Machine
modbus_configure(&Serial1, baud, SERIAL_8E1, timeout, polling, retry_count, TxEnablePin, packets, TOTAL_NO_OF_PACKETS, regs);
pinMode(LED, OUTPUT);
}
void loop()
{
if (Serial.available()){
int inByte =Serial1.read();
Serial.write(inByte);
}
modbus_update();
Serial.println("==================================");
Serial.print("successful_requests \t : ");
Serial.println(packets[PACKET1].successful_requests);
Serial.print("failed_requests \t : ");
Serial.println(packets[PACKET1].failed_requests);
Serial.print("exception_errors \t : ");
Serial.println(packets[PACKET1].exception_errors);
Serial.print("connection \t\t : ");
Serial.println(packets[PACKET1].connection);
Serial.println("==================================");
delay(1000);
float A = *(float*)®s[0]; Serial.print (" F : "); Serial.println (A);
}