RS485 Slave

From Nutwiki
Jump to: navigation, search

Test Environments

Hardware
Comments
Nut/OS
4.6.4
Nut/OS
4.7.4
Nut/OS
4.8.0
Ethernut 2.1 B Jumper Settings OK
Binaries
OK
Binaries
OK
Binaries
Compiler: ARM-GCC 4.2.2 ; AVR-GCC 4.3.0

Description

File:Duplexconf.png
Nut/OS Configurator

This is an example on how to communicate between 2 (or more) Ethernut 2 boards (Slave(s) and Master) by using the RS485 interface. This page holds the code for the slave Board(s).

Note that you have to configure the UART1 Driver settings, as shown on the right.

Do not forget to set the correct jumpers and connect the cables. [1]

Source Code

<source lang="c">

  1. include <dev/board.h>
  2. include <sys/timer.h>
  1. include <string.h>
  2. include <stdio.h>
  3. include <io.h>

int main(void) {

   u_long baud_dbg = 115200;
   u_long baud_485 = 1200;
   u_long flow_485 = USART_MF_HALFDUPLEX;
   u_long to_485 = 2000;
   FILE *rs485;
   char buffer[16];
   NutRegisterDevice(&DEV_DEBUG, 0, 0);
   freopen(DEV_DEBUG_NAME, "w", stdout);
   _ioctl(_fileno(stdout), UART_SETSPEED, &baud_dbg);
   puts("\nRS485 Slave Sample");
   if (NutRegisterDevice(&DEV_UART1, 0, 0)) {
       puts("Failed to register " DEV_UART1_NAME);
   }
   if ((rs485 = fopen(DEV_UART1_NAME, "r+b")) == NULL) {
       puts("Failed to open " DEV_UART1_NAME);
   }
   if (_ioctl(_fileno(rs485), UART_SETFLOWCONTROL, &flow_485)) {
       puts("Failed to set flow control");
   }
   if (_ioctl(_fileno(rs485), UART_SETSPEED, &baud_485)) {
       puts("Failed to set baudrate");
   }
   if (_ioctl(_fileno(rs485), UART_SETREADTIMEOUT, &to_485)) {
       puts("Failed to set read timeout");
   }
   sbi(PORTD, 2);
   for (;;) {
       if (fgets(buffer, sizeof(buffer), rs485)) {
           printf("Rx(%d):%s", strlen(buffer), buffer);
           NutSleep(10);
           fputs(buffer, rs485);
           fflush(rs485);
           printf("Tx(%d):%s", strlen(buffer), buffer);
       }
       else if (ferror(rs485)) {
           puts("Receive error!");
       }
       else {
           puts("Receive time out!");
       }
   }
   return 0;

} </source>

Output

RS485 Slave Sample
Rx(10):00000000
Tx(10):00000000
Rx(10):00000001
Tx(10):00000001
Rx(10):00000002
Tx(10):00000002
Rx(10):00000003
Tx(10):00000003
Rx(10):00000004
Tx(10):00000004
...

See also