I connected the Max485 as following:
pin 1 of IC to Rx (pin 0 of Arduino)
pin 2 of IC - (RE_NEG) to pin 2 of Arduino
pin 3 of IC (DE) - to pin 3 of Arduino
pin 4 of IC (Tx) - to pin 1 of Arduino
I also modified the code:
//need to send the Modbus command "01 06 00 43 00 01 B9 DE"
#include <ModbusMaster.h>
#define MAX485_DE 3
#define MAX485_RE_NEG 2
// instantiate ModbusMaster object
ModbusMaster node;
uint16_t u16WriteAddress = 0x0043;
uint16_t u16WriteValue = 0x0001;
void preTransmission()
{
digitalWrite(MAX485_RE_NEG, HIGH);
digitalWrite(MAX485_DE, HIGH);
}
void postTransmission()
{
digitalWrite(MAX485_RE_NEG, LOW);
digitalWrite(MAX485_DE, LOW);
}
void setup()
{
pinMode(MAX485_RE_NEG, OUTPUT);
pinMode(MAX485_DE, OUTPUT);
// Init in receive mode
digitalWrite(MAX485_RE_NEG, HIGH);
digitalWrite(MAX485_DE, LOW);
// Modbus communication runs at 115200 baud
Serial.begin(115200);
// Modbus slave ID 1
node.begin(1, Serial);
// Callbacks allow us to configure the RS485 transceiver correctly
node.preTransmission(preTransmission); //since we are going to transmit
// node.postTransmission(postTransmission);
}
bool state = false;
void loop()
{
uint8_t result;
if (state == false) { //execute the function 'writeSingleRegister' only once
Serial.println("Starting transmission");
result = node.writeSingleRegister(u16WriteAddress, u16WriteValue);
state = !state;
if (result == 0) {
Serial.println("Transmission done");
}
else
Serial.println("Error; press 'reset' button or restart serial to try again");
}
}
What I am missing here? The sketch does not work - I am getting the error message, so the function does not return 0.