Modbus RS484 and Teensy 3.2 implementation

Status
Not open for further replies.
Hello everyone,

I am trying to get communication functioning between a MAX485/Teensy 3.2 and a modbus device operating over RS485 half-duplex. I am fairly new to this and in the process of learning so I may be overlooking something very simple. The only response I get back in the serial monitor is an error 255 for 'no response'.

I have the Teensy wired as such:

Teensy to MAX485 respectively.

RX1 to R0
TX1 to DI
Pin 2 to DE/RE (DE/RE Tied together)
Vin to Vcc
GND to GND


Any help or pointers would be much appreciated.

I am using the Arduino IDE with the teensyduino software.

Source Code:

Code:
#include <ModbusRtu.h>

// data array for modbus network sharing
uint16_t au16data[16];
uint8_t u8state;

/**
 *  Modbus object declaration
 *  u8id : node id = 0 for master, = 1..247 for slave
 *  u8serno : serial port (use 0 for Serial or 1 for Serial1)
 *  u8txenpin : 0 for RS-232 and USB-FTDI 
 *               or any pin number > 1 for RS-485
 */
Modbus master(0,1,2); // this is master and RS-232 or USB-FTDI

/**
 * This is an structe which contains a query to an slave device
 */
modbus_t telegram;

unsigned long u32wait;

void setup() {
  Serial.begin(38400);
  master.begin(38400); // baud-rate at 19200
  master.setTimeOut(2000); // if there is no answer in 2000 ms, roll over 
  u32wait = millis() + 1000;
  u8state = 0; 
}

void loop() {
  switch( u8state ) {
  case 0: 
    if (millis() > u32wait) u8state++; // wait state
    break;
  case 1: 
    telegram.u8id = 9; // slave address
    telegram.u8fct = 3; // function code (this one is registers read)
    telegram.u16RegAdd = 74; // start address in slave
    telegram.u16CoilsNo = 1; // number of elements (coils or registers) to read
    telegram.au16reg = au16data; // pointer to a memory array in the Arduino
    master.query( telegram ); // send query (only once)
    u8state++;
    break;
  case 2:
    master.poll(); // check incoming messages
    if (master.getState() == COM_IDLE) {
      Serial.print("STATE:");
      Serial.println(master.getState());
      Serial.print("ERROR:");
      Serial.println(master.getLastError());
      Serial.print("READ DATA:");
      Serial.println(au16data[0]);
      u8state = 0;
      u32wait = millis() + 100;
    }
    break;
  }
}
 
If this is your first experience with RS485 I recommend digging up an old CIrcuit Cellar article titled "The Art and Science of RS485". Google usually turns up a pdf.

One thing to watch out for is the state of your serial data in pin while in transmit mode. The MAX485 floats the receiver output so you should have something to put it into a known (high) state.

Assuming I dug up the same library, the 255 return code indicates a time out. So the first thing to do is to verify that your data is coming out of the transmit side of the MAX485.
 
Status
Not open for further replies.
Back
Top