Monday, 15 June 2015

Half Duplex RS485 linux Serial USB Programing in C -



Half Duplex RS485 linux Serial USB Programing in C -

i'm trying setup half duplex communication in ubuntu 14.04 in program. have rs485 transceiver using rts line toggle , forth between transmit , receive. i'm using speak when spoken scheme , programme master. problem rts isn't toggling off when i'm done sending bundle can receive data. want turn rts high, send data, turn rts low, read data. help great.

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <termios.h> #include <sys/ioctl.h> #include <sys/stat.h> #include <sys/signal.h> #include <sys/types.h> #define baudrate b38400 #define comport "/dev/ttyusb0" #define _posix_source 1 #define false 0 #define true 1 #define stx_keypad 0xe1 #define payload_buff_size 256 #define crc_hi 0xd8 #define crc_low 0xc3 volatile int stop=false; int ser_port; int bus_address = 1; int message_length = 0; struct termios oldtio,newtio; unsigned char rxbuf[256]; unsigned char tx_flags = 0; void opencommport(); void sendserial(); int setrts(int level); int main(void) { printf("starting...\r\n"); opencommport(); setrts(1); printf("sending serial data\r\n"); sendserial(); setrts(0); //close(ser_port); printf("all done\r\n"); homecoming exit_success; } void opencommport() { ser_port = open(comport, o_rdwr | o_noctty | o_nonblock); if (ser_port == -1) { perror(comport); perror("unable open port"); exit(-1); } if(tcgetattr(ser_port,&oldtio) <0)// save current port settings { perror(comport); perror("couldn't old terminal attributes"); exit (-1); } bzero(&newtio, sizeof(newtio)); newtio.c_cflag = baudrate | cs8 | clocal | cread | crtscts; newtio.c_iflag = ignpar | icanon; newtio.c_oflag = 0; // set input mode (non-c, no echo,...) newtio.c_lflag = 0; newtio.c_cc[vtime] = 0; // inter-character timer unused newtio.c_cc[vmin] = 0; // blocking read until 5 chars received tcflush(ser_port, tciflush); tcsetattr(ser_port,tcsanow,&newtio); } void sendserial() { unsigned char tx_header[6]; tx_header[0] = stx_keypad; tx_header[1] = bus_address; tx_header[2] = tx_flags; tx_header[3] = message_length; tx_header[4] = crc_hi; tx_header[5] = crc_low; if((write(ser_port, tx_header, 6)) != 6) { printf("error sending data! not bytes sent\r\n"); } } int setrts(int level) { int status; if (ioctl(ser_port, tiocmget, &status) == -1) { perror("getrts(): tiocmset"); homecoming 0; } if(level) { status |= tiocm_rts; } else { status &= ~tiocm_rts; } if (ioctl(ser_port, tiocmset, &status) == -1) { perror("setrts(): tiocmset"); homecoming 0; } homecoming 1; }

c linux ubuntu serial-port rs485

No comments:

Post a Comment