Skip to content

Instantly share code, notes, and snippets.

@hanusek
Last active April 24, 2020 20:57
Show Gist options
  • Save hanusek/6886693811229605df42a00e661a7551 to your computer and use it in GitHub Desktop.
Save hanusek/6886693811229605df42a00e661a7551 to your computer and use it in GitHub Desktop.
Beaglebone Black RS485 Echo
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <linux/serial.h>
#include <termios.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <poll.h>
#include <unistd.h>
#include <getopt.h>
#include <time.h>
/* RS485 ioctls: */
#define TIOCGRS485 0x542E
#define TIOCSRS485 0x542F
int main( int argc, char **argv )
{
char buf[80];
if( argc < 2 ) {
printf("Usage: %s [port name]\n", argv[0]);
exit(0);
}
char *port = argv[1];
int fd = open(port, O_RDWR);
if (fd < 0) {
/* Error handling. See errno. */
fprintf( stderr, "Error opening port \"%s\" (%d): %s\n", port, errno, strerror( errno ));
exit(-1);
}
struct serial_rs485 rs485conf;
if (ioctl (fd, TIOCGRS485, &rs485conf) < 0) {
printf("Error: TIOCGRS485 ioctl not supported.\n");
}
struct termios newtio;
bzero(&newtio, sizeof(newtio)); /* clear struct for new port settings */
/* man termios get more info on below settings */
newtio.c_cflag = B115200 | CS8 | CLOCAL | CREAD;
newtio.c_iflag = 0;
newtio.c_oflag = 0;
newtio.c_lflag = 0;
// block for up till 128 characters
newtio.c_cc[VMIN] = 128;
// 0.5 seconds read timeout
newtio.c_cc[VTIME] = 5;
/* now clean the modem line and activate the settings for the port */
tcflush(fd, TCIOFLUSH);
tcsetattr(fd, TCSANOW, &newtio);
rs485conf.delay_rts_after_send = 0;
rs485conf.delay_rts_before_send = 0;
rs485conf.flags = 0;
rs485conf.flags |= SER_RS485_ENABLED;
/* If sending HI LEVEL */
rs485conf.flags &= ~(SER_RS485_RTS_ON_SEND);
/* If recv LO LEVEL */
rs485conf.flags |= SER_RS485_RTS_AFTER_SEND;
rs485conf.flags |= SER_RS485_RX_DURING_TX;
if (ioctl (fd, TIOCSRS485, &rs485conf) < 0) {
printf("Error: TIOCSRS485 ioctl not supported.\n");
}
int bytes_read = 0; /* Number of bytes read by the read() system call */
while(1 == 1)
{
bytes_read = read(fd, &buf, 32);
if (bytes_read != 0)
{
write(fd, buf, bytes_read);
}
}
/* Close the device when finished: */
if (close (fd) < 0) {
fprintf( stderr, "Error closing port (%d): %s\n", errno, strerror( errno ));
}
exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment