AdvancedClimateSystems / uModbus

Python implementation of the Modbus protocol.
Mozilla Public License 2.0
211 stars 82 forks source link

Possibility to use GPIO driving DE/RE Pin #52

Closed hallard closed 6 years ago

hallard commented 6 years ago

Hi There, On some RS485 hardware, sometimes, the DE/RE pins are tied together to a GPIO pin. In this case we need to drive the GPIO pin in the driver when sending/receiving.

Plenty of example here: https://github.com/madleech/Auto485 https://github.com/swarkn/MAX485 https://github.com/andresarmento/modbus-arduino

Sample Code of libraries are really simple, they check if we defined pin for RE/DE, and if so, setup the pin to High before each write on serial. After write, we flush serial, then wait protocol delay (t35 or t15 depending on speed) and then set back pin to Low.

Do you think it's do able simply in your library ?

Simple driver example works like that

bool ModbusSerial::config(HardwareSerial* port, long baud,  SerialConfig format, int txPin) 
{
    this->_port = port;
    this->_txPin = txPin;

    if (txPin >= 0) {
        pinMode(txPin, OUTPUT);
        digitalWrite(txPin, LOW);
    }

    if (baud > 19200) {
        _t15 = 750;
        _t35 = 1750;
    } else {
        _t15 = 15000000/baud; // 1T * 1.5 = T1.5
        _t35 = 35000000/baud; // 1T * 3.5 = T3.5
    }
    return true;
}

bool ModbusSerial::send(byte* frame) {
    byte i;

    if (this->_txPin >= 0) {
        digitalWrite(this->_txPin, HIGH);
        delayMicroseconds(1000);
    }

    for (i = 0 ; i < _len ; i++) {
        (*_port).write(frame[i]);
    }

    (*_port).flush();
    delayMicroseconds(_t35);

    if (this->_txPin >= 0) {
        digitalWrite(this->_txPin, LOW);
    }
}

Thanks

OrangeTux commented 6 years ago

I think that should be possible.

In case you need this in a Modbus RTU server you could extend umodbus.server.serial.RTUServer and override serve_once() with an implementation that toggles a GPIO pin.

For a Modbus RTU client you could reimplement send_message() yourself and add the GPIO handling.

hallard commented 6 years ago

Thanks for your quick answer, I'll check that needed