4-20ma / ModbusMaster

Enlighten your Arduino to be a Modbus master
http://4-20ma.io/ModbusMaster/
Apache License 2.0
603 stars 353 forks source link

Example on Software Serial for 32u4 Leonardo. #97

Open shmrymbd opened 6 years ago

shmrymbd commented 6 years ago

include

include

define READ_INTERVAL 5000

const int DEREPin = 3; // The pin controlling Recieve Enable and Driver Enable // on the RS485 adapter, if applicable (else, -1) // Setting HIGH enables the driver (arduino) to send text // Setting LOW enables the receiver (sensor) to send text const int SSRxPin = 8; // Recieve pin for software serial (Rx on RS485 adapter) const int SSTxPin = 9; // Send pin for software serial (Tx on RS485 adapter)

// instantiate ModbusMaster object ModbusMaster node; SoftwareSerial modbusSerial(SSRxPin, SSTxPin);

void preTransmission() { digitalWrite(DEREPin, 1); }

void postTransmission() { digitalWrite(DEREPin, 0); }

void setup() { pinMode(DEREPin, OUTPUT); // Init in receive mode digitalWrite(DEREPin, 0);

// Modbus communication runs at 115200 baud Serial.begin(9600); modbusSerial.begin(9600);

// Modbus slave ID 1 node.begin(10, modbusSerial); // Callbacks allow us to configure the RS485 transceiver correctly node.preTransmission(preTransmission); node.postTransmission(postTransmission);

Serial.println("Starting....."); delay(2000);

serial_num(); baud_rate(); node_id(); }

bool state = true; unsigned long previous1Millis=0; unsigned long previous2Millis=0;

void loop() {

uint8_t result; uint16_t data[6]; uint8_t j;

if (millis()-previous1Millis > READ_INTERVAL){ //read data result = node.readHoldingRegisters(0, 2); if (result == node.ku8MBSuccess){ for (j = 0; j < 6; j++) { data[j] = node.getResponseBuffer(j); } unsigned long temp1 = (unsigned long)data[1] << 16 | data[0]; float num = (float)&temp1; Serial.print("Reading NTU: "); Serial.println(num); } previous1Millis=millis(); }

if (millis()-previous2Millis > 1500){ //read data //run code here previous2Millis=millis(); } }

icandura commented 6 years ago

Dose the Software Serial works by your example? I tried to use MODBUS by software serial but it didn't work.