read from serial port fails when called twice - c

Resolved Bellow: Wrong number of characters in read/write
I am attempting to read and write to a serial port, and I don't have much experience in C/C++.
My port is connected to a motion controller/driver that requires the following settings:
Baudrate: 57600
Data bits: 8
Parity: None
Stop bits: 1
Flow control: Xon/Xoff
Terminator CRLF
Problem: The code will write and read my first command,but it hangs on the second read call. I am currently blocking until I receive at least one character, but each written command should generate a return.
Additional information: I can only run the first write/read if I first unplug the remote and plug it back in. Alternatively, I can open a cool term window, setup my serial port and run a few commands. When I close the cool term window I will be able to write/read once.
Current Code:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <time.h>
#include <iostream>
using namespace std;
int open_port(void)
{
int fd;
// open file descriptor
fd = open("/dev/cu.USA19H41P1.1", O_RDWR | O_NOCTTY);
// if unsucessful
if (fd == -1)
{
printf("open_port: unable to open port. \n");
}
else
{
// remains open across executables
fcntl(fd, F_SETFL, 0);
printf("port is open. \n");
}
return (fd);
}
int configure_port(int fd)
{
// store terminal port settings
struct termios port_settings;
memset(&port_settings, 0, sizeof port_settings);
if(tcgetattr(fd, &port_settings) !=0)
{
printf("error tcgetattr \n");
cout << errno;
}
port_settings.c_iflag = 0;
port_settings.c_oflag = 0;
port_settings.c_lflag = 0;
port_settings.c_cflag = 0;
// flush
tcflush(fd, TCIOFLUSH);
// set baud rate
cfsetispeed(&port_settings, B57600);
cfsetospeed(&port_settings, B57600);
// xon/xoff requirment
port_settings.c_iflag |= IXON;
port_settings.c_iflag |= IXOFF;
// no parity requirement
port_settings.c_cflag &= ~PARENB;
// one stop bin requirement
port_settings.c_cflag &= ~CSTOPB;
// turn on read
port_settings.c_cflag |= CREAD;
port_settings.c_cflag |= CLOCAL;
// no character processing and 8 bit input
port_settings.c_cflag &= ~CSIZE;
port_settings.c_cflag |= CS8;
// one character blocking
port_settings.c_cc[VMIN] = 1;
port_settings.c_cc[VTIME] = 5;
// apply above settings
if(tcsetattr(fd,TCSANOW, &port_settings) != 0)
{
printf("error tcsetattr \n");
cout << errno;
}
// flush buffers one more time
tcflush(fd, TCIOFLUSH);
return(fd);
}
int read_write(int fd)
{
// write to serial port
ssize_t size=write(fd, "1va?\r\n", 8);
// wait until output is transmitted
tcdrain(fd);
// read from serial port
char buf[100];
memset(buf, '\0', sizeof buf);
ssize_t size2=read(fd, &buf, sizeof(buf));
cout << buf << endl;
return(fd);
}
int main(void)
{
// open port
int fd = open_port();
// store old settings
struct termios old_settings;
memset(&old_settings, 0, sizeof old_settings);
tcgetattr(fd,&old_settings);
// configure port
configure_port(fd);
// write/read first command ("1va?\r\n")
read_write(fd);
// write read second command ("1pa?\r\n")
ssize_t size=write(fd, "1pa?\r\n", 8);
tcdrain(fd);
char buf[100];
memset(buf, '\0', sizeof buf);
ssize_t size3=read(fd, &buf, sizeof(buf));
cout << buf;
//close serial port
close(fd);
tcsetattr(fd, TCSANOW, &old_settings);
return 0;
}

Here is some example code on working with Serial ports setting the correct flags and the baud rate:
Provide your code and and more thorough explanation for us to resolve your issue. What do you mean by write and read my first command? Is your device still responsive after this command? Isn't the second command sent?

Related

Serial Communication read() Error

This should be fairly straightforward for someone in the know, but I have been struggling for a bit and would appreciate some thoughts. I am writing an application that reads from a serial comm port.
My Setup:
I have a windows machine with putty open and connected to my comm port of interest.
I have a linux (ubuntu) machine in which I am writing this software (in C).
I am typing into putty on the windows machine and trying to read it with my application on the linux machine.
What I have:
So far, using the code below I can successfully write to the putty display on the windows machine from my application on the linux computer, but I cannot read the buffer on my linux machine when I type on the windows machine.
Code:
#include <stdio.h> // standard input / output functions
#include <stdlib.h>
#include <string.h> // string function definitions
#include <unistd.h> // UNIX standard function definitions
#include <fcntl.h> // File control definitions
#include <errno.h> // Error number definitions
#include <termios.h>
int openport()
{
int USB = open( "/dev/ttyUSB0", O_RDWR| O_NOCTTY | O_NONBLOCK );
struct termios tty;
struct termios tty_old;
memset(&tty, 0, sizeof tty);
/* Error Handling */
if ( tcgetattr( USB, &tty ) != 0 )
{
printf("Error 1, or something");
}
/* Save old tty parameters */
tty_old = tty;
/* Set Baud Rate */
cfsetospeed (&tty, (speed_t)B9600);
cfsetispeed (&tty, (speed_t)B9600);
/* Setting other Port Stuff */
tty.c_cflag &= ~PARENB; // Make 8n1
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8;
tty.c_cflag &= ~CRTSCTS; // no flow control
tty.c_cc[VMIN] = 1; // read doesn't block
tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
tty.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines
/* Make raw */
cfmakeraw(&tty);
/* Flush Port, then applies attributes */
tcflush( USB, TCIFLUSH );
if ( tcsetattr ( USB, TCSANOW, &tty ) != 0)
{
printf("Error, or something");
}
return USB;
}
int main()
{
int n = 0;
int j = 0;
unsigned char buf[10] = {0,0,0,0,0,0,0,0,0,0};
printf("Hello world!\n");
int USB = openport();
unsigned char cmd[] = "INIT Hey SHanahas \r";
int n_written = 0;
do
{
n_written += write( USB, &cmd[n_written], 1 );
}
while (cmd[n_written-1] != '\r' && n_written > 0);
printf("Here\n\n");
do
{
n = read( USB, &buf, 1 );
printf("%s \n",buf);
printf("%d",n);
}
while( buf != '\r' && n > 0);
printf("Herr2");
return 0;
}
Does anyone have any thoughts on what might be happening? the read() command returns a -1 error.
Thanks!

Reading from serial port on Linux and OSX

I am writing simple CLI application for reading data from serial port. I have USB to serial converter with CP2102 and every few seconds, I am receiving 200 B long string.
Edit: I made a mistake. It is not a CP2102, but Profilic PL2303. I also found strange behavior when I use stty -- I cannot change baud rate and it's randomly changing:
$ stty -F /dev/ttyUSB5 57600 # Set baudrate
$ stty -F /dev/ttyUSB5 # Read configuration
speed 1200 baud;
.....
$$ stty -F /dev/ttyUSB5 # Read configuration
speed 9600 baud;
.....
End-of-edit
When I compile my application under Mac OS X, it works without any problem. But when I compile this code for Linux (cheap Android tablet with ARM CPU, I use Android NDK for compilation) I receive some data, then garbage:
~|?>?lq?43??d??2~??O?$?$??c??Hello World, good data.
???5??l??!???????x?????????????fx???~????????????x??????`???????~???f?x???~????`f??f???~?????x??????#ף???????x?????????????fx???~????????????x??????`???????~???f?x???~????`f??f???~??3?
It looks like I set wrong baud rate, but I am 100% sure the baud rate is 57600 bauds.
Is the problem in my code (differences in POSIX, Unix, Linux, etc.) or should I look for problems in hardware (CP2102, etc)?
This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // string function definitions
#include <errno.h> // Error number definitions
#include <unistd.h> // UNIX standard function definitions
#include <fcntl.h> // File control definitions
#include <termios.h> // POSIX terminal control definitions
int main(int argc, char *argv[]) {
printf("Opening device... ");
int USB = open("/dev/ttyUSB5", O_RDONLY | O_NOCTTY | O_NONBLOCK);
printf("opened.\n");
struct termios tty;
struct termios tty_old;
memset (&tty, 0, sizeof tty);
/* Error Handling */
if (tcgetattr(USB, &tty) != 0) {
printf("Error %d from tcgetattr: %s!\n", errno, strerror(errno));
}
/* Save old tty parameters */
tty_old = tty;
/* Set Baud Rate */
cfsetospeed (&tty, (speed_t)B57600);
cfsetispeed (&tty, (speed_t)B57600);
/* Setting other Port Stuff */
tty.c_cflag &= ~PARENB; // Make 8n1
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8;
tty.c_cflag &= ~CRTSCTS; // no flow control
tty.c_cc[VMIN] = 1;
tty.c_cc[VTIME] = 5;
tty.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines
/* Make raw */
cfmakeraw(&tty);
/* Flush Port, then applies attributes */
tcflush(USB, TCIFLUSH);
if ( tcsetattr ( USB, TCSANOW, &tty ) != 0) {
printf("Error %d from tcgetattr: %s!\n", errno, strerror(errno));
}
int n = 0;
char buf [256];
printf("Starting to read data...\n");
do {
n = read( USB, &buf, sizeof buf);
if (n > 0) {
printf("%s", buf);
memset(&buf, '\0', sizeof buf);
}
usleep(100000); /* sleep for 100 milliSeconds */
} while(1);
}

read() in c raspberry pi gsm-module

I am working on a project where i can send sms with my raspberry pi thats connected to a sim300s module thrue a usb to serial connection.
problem:
sim300 doesnt detect the simcard , harware malfunction, i have ordered a new one. Until then i want to check if the connection works between the 2.
Now i want to send at command and receive OK(or something like that) Here is my code:
the value that is stored in string buf is TATATATAT.... etc.. etc..
Can someone explain why i am not getting OK back? Am i doing something wrong?
#include <stdio.h> /* Standard input/output definitions */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
/*
* 'open_port()' - Open serial port 1.
*
* Returns the file descriptor on success or -1 on error.
*/
int main(int argc, char* argv[])
{
puts("start open_port");
open_port();
puts("open_port started ");
}
int
open_port(void)
{
char reply;//not shure if its gonna be used
struct termios options;
int n=0;
int fd; /* File descriptor for the port */
char buf[50];
int valueBytes;
int x = 0;
fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY ); //| O_NDELAY);
if (fd == -1)
{//could not open port
fprintf(stderr, "open_port: Unable to open /dev/ - %s\n",
strerror(errno));
}
printf("%d",fd);
tcgetattr(fd, &options); //get current options for port
puts("test1");
cfsetispeed(&options, B9600);//set baud rate
cfsetospeed(&options, B9600);//set baud rate
puts("\n2");
options.c_cflag |= (CLOCAL | CREAD | CRTSCTS);//enable the receiver and set local mode
puts("\n3");
options.c_cflag &= ~PARENB;//disable parity generation and detection
options.c_cflag &= ~CSTOPB;//Use one stop bit per character
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;//use 8 bits to send or receive characters
options.c_lflag &= ~(ICANON | /* Enable canonical input (else raw) */
ECHO | /*Enable echoing of input characters */
ECHOE | /*Echo erase character as BS-SP-BS*/
ISIG); /*Enable SIGINTR, SIGSUSP, SIGDSUSP, and SIGQUIT signals*/
tcsetattr(fd, TCSANOW, &options);//TCSANOW change values immediately
puts("4");
n = write(fd, "AT\r", 4); // n = write(fd, "AT+CMGF=1\r", 10);
if (n < 0){
puts("write() of 4 bytes failed!");}
if(read(fd, buf, 2) < 0){
puts("it doesnt work"); }
fcntl(fd, F_SETFL, FNDELAY);
valueBytes=read(fd, buf,50);
printf("%d",valueBytes);
if(valueBytes < 0){
printf(strerror(errno));}
puts("6.3");
for(x; x<50;x++){
printf("%c",buf[x]);
}
close(fd);
puts("7");
return (fd);
puts("8");
}

Can write to, but can't read from serial port ttyS0 in linux C program

I'm trying to learn how to program the ttyS0 serial port in Linux using C. I have another machine connected to my serial port sending alternating hex values of 5f and 6f about every two seconds. I've verified with other port monitoring apps that these values are appearing at the port. In my code I'm using a blocking read() into a 10 char length buffer. Even though my other machine is still sending data, read() blocks forever. If I include the line fcntl(fd, F_SETFL, FNDELAY); which sets read() to non-blocking read() always returns with a value of -1, meaning no data was in the UART buffer, and my for loop code just prints out random values that are in the buffer. So in short my assumption is that my code is not reading ttyS0 and I have no idea why. Below is my code, hopefully someone will see what's causing my problem and set me straight. By the way, I'm using Scientific Linux, I believe ttyS0 is com port 1, as it is in RedHat and Fedora. Aslo below is the output when i run the code. It seems to be writing to the COM port with no problems, but for a read it says its unavailable. Also it's clear that the buffer I'm printing out is just random values not data that's been read in. Thanks
console output
hello world
hi again
write error: : Success
wrote 4 bytes
number of bytes read is -1
read error:: Resource temporarily unavailable
4 8 120 -99 -73 -65 41 -120 4 8
should of put something out
Code
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <unistd.h>
int main()
{
printf("hello world\n");
int n;
int fd;
char c;
int bytes;
char buffer[10];
char *bufptr;
int nbytes;
int tries;
int x;
struct termios options;
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
if(fd == -1)
{
perror("open_port: Unable to open:");
}
else
{
fcntl(fd, F_SETFL, 0);
printf("hi again\n");
}
tcgetattr(fd, &options);
cfsetispeed(&options, B115200);
cfsetospeed(&options, B115200);
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag &= ~( ICANON | ECHO | ECHOE |ISIG );
options.c_iflag &= ~(IXON | IXOFF | IXANY );
options.c_oflag &= ~OPOST;
tcsetattr(fd, TCSANOW, &options);
write(fd, "ATZ\r",4);
printf(" wrote\n");
bufptr = buffer;
fcntl(fd, F_SETFL, FNDELAY);
bytes = read(fd, bufptr, sizeof(buffer));
printf("number of bytes read is %d\n", bytes);
perror ("read error:");
for (x = 0; x < 10 ; x++)
{
c = buffer[x];
printf("%d ",c);
}
close(fd);
//puts(buffer[0]);
printf("\nshould of put something out \n");
return (0);
}
Try setting MIN and/or TIME values:
/*...*/
options.c_cc[VMIN] = 1; //read() will return after receiving 1 character
options.c_cc[VTIME] = 0; // == 0 - infinite timeout, != 0 - sets timeout in deciseconds
/*...*/
tcsetattr(fd, TCSANOW, &options);
The given example will set your read() to return after getting any symbol and to wait indefinitely for input. Naturally, you may play with these parameters as you see fit (e.g. set MIN to 10 if you want).
You may want to remove fcntl(fd, F_SETFL, FNDELAY); call for this to work though.
It is also wise to save previous termios settings and restore them before leaving your program.

Reading and writing from serial port,through loopback in c in linux

I am on a program to read and write from and to serial port using serial crosscable and loopback by soring 2nd and 3rd pin of cable. I am able to write but not able to read.
in read output it is showing 0 as the no. of bytes read by it. It is not showing error as -1 .
#include <stdio.h> // standard input / output functions
#include <string.h> // string function definitions
#include <unistd.h> // UNIX standard function definitions
#include <fcntl.h> // File control definitions
#include <errno.h> // Error number definitions
#include <termios.h> // POSIX terminal control definitionss
#include <time.h> // time calls
#include <sys/ioctl.h>
int open_port(void)
{
int fd; // file description for the serial port
fd = open("/dev/ttyS1", O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
if(fd == -1) // if open is unsucessful
{
perror("open_port: Unable to open /dev/ttyS0 - ");
}
else
{
fcntl(fd, F_SETFL, 0);
}
printf("%d",fd);
return(fd);
}
int configure_port(int fd) // configure the port
{
struct termios port_settings; // structure to store the port settings in
cfsetispeed(&port_settings, B9600); // set baud rates
cfsetospeed(&port_settings, B9600);
port_settings.c_cflag |= ( CLOCAL | CREAD );
port_settings.c_cflag &= ~PARENB; // set no parity, stop bits, data bits
port_settings.c_cflag &= ~CSTOPB;
port_settings.c_cflag &= ~CSIZE;
port_settings.c_cflag |= CS8;
tcflush( fd, TCIOFLUSH );
tcsetattr(fd, TCSANOW, &port_settings); // apply the settings to the port
return(fd);
}
int main()
{
int fd= open_port();
int d=configure_port(fd);
printf("%d",d);
int bytes;
char mk[10];
scanf("%s",&mk);
int w=write(fd,mk,strlen(mk));
int y=ioctl(fd,FIONREAD,&bytes);
printf("%d\n",w);
perror("write");
printf("%d",y);
char buffer[80];
char *data;
int nbytes;
data=buffer;
nbytes=read(fd,data,5);
printf("the outputis \n%d\n\n",nbytes);
perror("read");
while(nbytes > 0)
{printf("datmukun %d\n\n",nbytes);
data+=nbytes;
if (data[-1]=='\n'||data[-1]=='\r')
break;
}
return 0;
}
Depending on your TTY-driver the O_NDELAY and O_NONBLOCK can cause read to behave in a non-blocking manner. Therefore, it is very likely that the data has not been received by the time you call read. If you remove those flags, you should block in read until at least one character is available.
you must wait for a while for the data to become available. you can do this like the following:
very simply and just for test purpose by creating a small delay using a while loop and a sleep() function inside it and possibly a counter to try for a number of times.
you can use select() function on your file descriptor to let your process go to sleep for a while and get notified when the data is available or the timeout has reached.

Resources