Reading arduino serial in linux using C - c

I want to read serial from arduino. I use this code :
#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 */
#include <sys/ioctl.h>
int main(){
char data[1024];
char dev[] = "/dev/ttyACM1";
int fd = open(dev, O_RDWR | O_NOCTTY | O_NDELAY);
fcntl(fd, F_SETFL, FNDELAY);
struct termios options;
tcgetattr(fd, &options);
cfsetispeed(&options, B9600);
cfsetospeed(&options, B9600);
options.c_cflag |= CS8;
options.c_cflag |= CS8;
options.c_cflag &= ~CRTSCTS;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
tcsetattr(fd, TCSANOW, &options);
ioctl(fd, TCFLSH, 2);
while(1){
read(fd, data, sizeof(data));
printf(data);
}
//write(fd, data, sizeof(data));
}
My arduino runs very simple sketch :
int x;
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println("DO YOU HEAR ME ??");
delay(1000);
}
and output of this combinatin is that :
??OU HEAR ME ??
DO YOU HEAR ME ??
DO YOU HEAR ME ??
A¹­þ
??OU HEAR ME ??
DO YOU HEAR ME ??
DO YOU HEAR ME ??
A¹­þ
??OU HEAR ME ??
DO YOU HEAR ME ??
DO YOU HEAR ME ??
My question is how to make order out of chaos. I found that this issue occurs when buffer ends and new one begins(bigger buffer less junk data) but I can't have a infinite buffer. Also there is a lot of junk when it reads for the first time.. Is there a way to sync it or something ?
(Also I am not native English sorry for any mistakes.)

I found answer to my own problem. I used this time c++ to organize it in class (very poor one because it doesn't handle any errors and doesn't use c++ in the most..) Here is the code :
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <strings.h>
#include <cstring>
#include <iostream>
//Here I define some vars
#define BAUDRATE B9600
#define MODEMDEVICE "/dev/ttyACM0"
#define _POSIX_SOURCE 1
class serial{
public:
serial(){
fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY );
if (fd <0) {perror(MODEMDEVICE); exit(-1); }
// Improvement No. 1 I save old setting and clean the new one
tcgetattr(fd,&oldtio);
bzero(&newtio, sizeof(newtio));
// Here I set all the flags to vars at once
newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;
newtio.c_iflag = IGNPAR | ICRNL;
newtio.c_oflag = 0;
newtio.c_lflag = ICANON;
//here I set some new flags..
newtio.c_cc[VINTR] = 0; /* Ctrl-c */
newtio.c_cc[VQUIT] = 0; /* Ctrl-\ */
newtio.c_cc[VERASE] = 0; /* del */
newtio.c_cc[VKILL] = 0; /* # */
newtio.c_cc[VEOF] = 4; /* Ctrl-d */
newtio.c_cc[VTIME] = 0; /* inter-character timer unused */
newtio.c_cc[VMIN] = 1; /* blocking read until 1 character arrives */
newtio.c_cc[VSWTC] = 0; /* '\0' */
newtio.c_cc[VSTART] = 0; /* Ctrl-q */
newtio.c_cc[VSTOP] = 0; /* Ctrl-s */
newtio.c_cc[VSUSP] = 0; /* Ctrl-z */
newtio.c_cc[VEOL] = 0; /* '\0' */
newtio.c_cc[VREPRINT] = 0; /* Ctrl-r */
newtio.c_cc[VDISCARD] = 0; /* Ctrl-u */
newtio.c_cc[VWERASE] = 0; /* Ctrl-w */
newtio.c_cc[VLNEXT] = 0; /* Ctrl-v */
newtio.c_cc[VEOL2] = 0; /* '\0' */
// and I finally save the settings
tcflush(fd, TCIFLUSH);
tcsetattr(fd,TCSANOW,&newtio);
}
~serial(){
close(fd);
}
std::string sread(){
res = read(fd,buf,255);
buf[res]=0;
return buf;
}
void swrite(const char* input){
write(fd,input,std::strlen(input));
}
private:
int fd,c,res;
struct termios oldtio,newtio;
char buf[255];
};
int main(){
serial s;
s.swrite("Light");
std::string buf = s.sread();
std::cout << buf;
}
This is more of a ripoff from "Serial programming HOW TO" : http://tldp.org/HOWTO/Serial-Programming-HOWTO/ (form the example code..)
And here is the new poor arduino code :
int x;
String buff;
int lpin = A0;
int tpin = A1;
int data;
void setup() {
Serial.begin(9600);
pinMode(lpin,INPUT);
pinMode(tpin,INPUT);
}
void loop() {
if(Serial.available() == 1)
{
buff = Serial.readString();
if(buff == "Light"){
data = analogRead(lpin);
Serial.print(data);
Serial.print("\n");
}else if(buff == "Temp"){
data = analogRead(tpin);
Serial.print(data);
Serial.print("\n");
}else{
Serial.print("Something went wrong !");
Serial.print("\n");
}
}
delay(1);
}

Related

Send Commands to serial device and receiving response

Am trying to send a command to a serial device (arduino) and receive a response, the command goes through but I don't get a response from the target device.
I want the C program to control the serial device by sending & receiving data.
Arduino Code:
void setup() {
// initialize serial communication:
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0) {
int inByte = Serial.read();
switch (inByte) {
case 'H':
Serial.print("75864d63001bebaa");
break;
}
}
}
C Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdint.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#include <sys/ioctl.h>
int main(int argc, char *argv[]) {
int fd, n, i;
char buf[64] = "temp text";
struct termios toptions;
/* open serial port */
fd = open("/dev/ttyACM0", O_RDWR | O_NOCTTY);
printf("fd opened as %i\n", fd);
/* wait for the Arduino to reboot */
usleep(3500000);
/* get current serial port settings */
tcgetattr(fd, &toptions);
/* set 9600 baud both ways */
cfsetispeed(&toptions, B9600);
cfsetospeed(&toptions, B9600);
/* 8 bits, no parity, no stop bits */
toptions.c_cflag &= ~PARENB;
toptions.c_cflag &= ~CSTOPB;
toptions.c_cflag &= ~CSIZE;
toptions.c_cflag |= CS8;
/* Canonical mode */
toptions.c_lflag |= ICANON;
/* commit the serial port settings */
tcsetattr(fd, TCSANOW, &toptions);
/* Send byte to trigger Arduino to send string back */
write(fd, "H", 1);
/* Receive string from Arduino */
n = read(fd, buf, 64);
/* insert terminating zero in the string */
buf[n] = 0;
printf("%i bytes read, buffer contains: %s\n", n, buf);
return 0;
}

Read from serial port in C LINUX

I know There are lot of questions about this in Internet. But none of them works for me. I'm trying to read from serial port, which is connected to MODEM.To be more specific. I send AT command and save response(OK or ERROR) to variable. But when i try to read from serial port,response always changes. like AT, AT=, AT= O etc.
Here's code that send command:
#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 */
int main(int argc, char const *argv[])
{
int fd;
struct termios options;
/* open the port */
fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);
fcntl(fd, F_SETFL, FNDELAY);
/* get the current options */
tcgetattr(fd, &options);
/* set raw input, 1 second timeout */
options.c_cflag |= (CLOCAL | CREAD);
options.c_lflag &= (ICANON | ECHO | ECHOE | ISIG);
options.c_oflag &= ~OPOST;
options.c_cc[VMIN] = 0;
options.c_cc[VTIME] = 10;
init_modem();
/* set the options */
tcsetattr(fd, TCSANOW, &options);
return 0;
}
int /* O - 0 = MODEM ok, -1 = MODEM bad */
init_modem(int fd) /* I - Serial port file */
{
char buffer[255]; /* Input buffer */
char *bufptr; /* Current char in buffer */
int nbytes; /* Number of bytes read */
int tries; /* Number of tries so far */
write(fd, "AT\r", 3);
return (-1);
}
UPDATE:
Thanks for the replies.So i set canonical input and raw output. That helped me a lot and i found this code: And this outputs:AT OK But i want only OK. What should i change ?
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
/* baudrate settings are defined in <asm/termbits.h>, which is
included by <termios.h> */
#define BAUDRATE B38400
/* change this definition for the correct port */
#define MODEMDEVICE "/dev/ttyUSB0"
#define _POSIX_SOURCE 1 /* POSIX compliant source */
#define FALSE 0
#define TRUE 1
volatile int STOP=FALSE;
main()
{
int fd,c, res;
struct termios oldtio,newtio;
char buf[255];
/*
Open modem device for reading and writing and not as controlling tty
because we don't want to get killed if linenoise sends CTRL-C.
*/
fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY );
if (fd <0) {perror(MODEMDEVICE); exit(-1); }
tcgetattr(fd,&oldtio); /* save current serial port settings */
bzero(&newtio, sizeof(newtio)); /* clear struct for new port settings */
/*
BAUDRATE: Set bps rate. You could also use cfsetispeed and cfsetospeed.
CRTSCTS : output hardware flow control (only used if the cable has
all necessary lines. See sect. 7 of Serial-HOWTO)
CS8 : 8n1 (8bit,no parity,1 stopbit)
CLOCAL : local connection, no modem contol
CREAD : enable receiving characters
*/
newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;
/*
IGNPAR : ignore bytes with parity errors
ICRNL : map CR to NL (otherwise a CR input on the other computer
will not terminate input)
otherwise make device raw (no other input processing)
*/
newtio.c_iflag = IGNPAR | ICRNL;
/*
Raw output.
*/
newtio.c_oflag = 0;
/*
ICANON : enable canonical input
disable all echo functionality, and don't send signals to calling program
*/
newtio.c_lflag = ICANON;
/*
initialize all control characters
default values can be found in /usr/include/termios.h, and are given
in the comments, but we don't need them here
*/
newtio.c_cc[VINTR] = 0; /* Ctrl-c */
newtio.c_cc[VQUIT] = 0; /* Ctrl-\ */
newtio.c_cc[VERASE] = 0; /* del */
newtio.c_cc[VKILL] = 0; /* # */
newtio.c_cc[VEOF] = 4; /* Ctrl-d */
newtio.c_cc[VTIME] = 0; /* inter-character timer unused */
newtio.c_cc[VMIN] = 1; /* blocking read until 1 character arrives */
newtio.c_cc[VSWTC] = 0; /* '\0' */
newtio.c_cc[VSTART] = 0; /* Ctrl-q */
newtio.c_cc[VSTOP] = 0; /* Ctrl-s */
newtio.c_cc[VSUSP] = 0; /* Ctrl-z */
newtio.c_cc[VEOL] = 0; /* '\0' */
newtio.c_cc[VREPRINT] = 0; /* Ctrl-r */
newtio.c_cc[VDISCARD] = 0; /* Ctrl-u */
newtio.c_cc[VWERASE] = 0; /* Ctrl-w */
newtio.c_cc[VLNEXT] = 0; /* Ctrl-v */
newtio.c_cc[VEOL2] = 0; /* '\0' */
/*
now clean the modem line and activate the settings for the port
*/
tcflush(fd, TCIFLUSH);
tcsetattr(fd,TCSANOW,&newtio);
/*
terminal settings done, now handle input
In this example, inputting a 'z' at the beginning of a line will
exit the program.
*/
write(fd,"AT\r",3);
while (STOP==FALSE) { /* loop until we have a terminating condition */
/* read blocks program execution until a line terminating character is
input, even if more than 255 chars are input. If the number
of characters read is smaller than the number of chars available,
subsequent reads will return the remaining chars. res will be set
to the actual number of characters actually read */
res = read(fd,buf,255);
buf[res]=0; /* set end of string, so we can printf */
buf[res-1]=0;
printf("%s\n", buf);
if (buf[0]=='\r') STOP=TRUE;
}
/* restore the old port settings */
tcsetattr(fd,TCSANOW,&oldtio);
}

Initiation of the USB port for serial communication whiteout using the hyper terminal

I am trying to initiate serial communication from the code below. The problem however is that I have to open the hyper terminal with the same settings and then close it, Before running the code below inside another program written in C for the code to work as intended. I would very much like to skip the initial step with the hyper terminal but I haven't been able to figure out what it is that is causing this odd behavior.
I have posted the code for the initiation below as well as my code for kbhit() that possibly could be the reason for this behavior. I would be extremely thankful if someone could tell my how I could solve this.
int kbhit(){ //Detects if a key has been pressed, 1 if true else 0
struct termios oldt, newt;
int ch;
int oldf;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
oldf = fcntl(STDIN_FILENO, F_GETFL, 0;
fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
fcntl(STDIN_FILENO, F_SETFL, oldf);
if(ch != EOF){
ungetc(ch, stdin); //Puts back the pressed key to the stack
return 1;
}
return 0;
}
The initiation code for the serial communication through the USB port is displayed below:
#include "USB.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdlib.h>
#include <strings.h>
#include <stdio.h>
/* baudrate settings are defined in <asm/termbits.h>, which is
* included by <termios.h> */
#ifndef BAUDRATE
#define BAUDRATE B9600 //the desired baud rate
#endif
#define _POSIX_SOURCE 1 /* POSIX compliant source */
static int fd, c, res;
static struct termios oldtio, newtio;
static char *device;
int USB_init(char *modemdevice){
device = modemdevice;
fd = open (device, O_RDWR | O_NOCTTY|O_NONBLOCK );//|O_NONBLOCK has been added
if (fd < 0){
perror (device);
exit(-1);
}
tcgetattr (fd, &oldtio); /* save current settings */
bzero (&newtio, sizeof (newtio)); /* clear struct for new port settings */
/*
*BAUDRATE: Set bps rate.
*CS8 : 8n1 (8bit,no parity,1 stop bit)
*CLOCAL : local connection, no modem contol
*CREAD : enable receiving characters
**/
newtio.c_cflag = BAUDRATE | CS8 | CLOCAL | CREAD;
newtio.c_iflag = IGNPAR | ICRNL;
/*
* ICANON : enable canonical input
* disable all echo functionality, and don't send signals to calling program*/
#if 1
newtio.c_lflag = ICANON;
#else
newtio.c_lflag = 0;
#endif
/* initialize all control characters
* default values can be found in /usr/include/termios.h, and are given
* in the comments, but we don't need them here*/
newtio.c_cc[VINTR] = 0; /* Ctrl-c */
newtio.c_cc[VQUIT] = 0; /* Ctrl-\ */
newtio.c_cc[VERASE] = 0; /* del */
newtio.c_cc[VKILL] = 0; /* # */
newtio.c_cc[VEOF] = 4; /* Ctrl-d */
newtio.c_cc[VTIME] = 10; // 0 before
newtio.c_cc[VMIN] = 0; /* blocking read until 0 character arrives*/
newtio.c_cc[VSWTC] = 0; /* '\0' */
newtio.c_cc[VSTART] = 0; /* Ctrl-q */
newtio.c_cc[VSTOP] = 0; /* Ctrl-s */
newtio.c_cc[VSUSP] = 0; /* Ctrl-z */
newtio.c_cc[VEOL] = 0; /* '\0' */
newtio.c_cc[VREPRINT] = 0; /* Ctrl-r */
newtio.c_cc[VDISCARD] = 0; /* Ctrl-u */
newtio.c_cc[VWERASE] = 0; /* Ctrl-w */
newtio.c_cc[VLNEXT] = 0; /* Ctrl-v */
newtio.c_cc[VEOL2] = 0; /* '\0' */
tcflush (fd, TCIFLUSH);
tcsetattr (fd, TCSANOW, &newtio);
return fd;
}
void USB_cleanup(int ifd){
if(ifd != fd){
fprintf(stderr, "WARNING! file descriptor != the one returned by USB_init()\n");
}
/* restore the old port settings */
tcsetattr (ifd, TCSANOW, &oldtio);
}

example C code for reading from a serial port using Cygwin

I am trying to create a simple serial communications program on code blocks with a Cygwin environment under Windows 7.
The program is just meant to read bytes from the serial port which is connected to a gps using three pins on the com port (TX, RX, GND)
I have a program that works (taken from an example i found) but polls till there is data from serial.
{
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#define BAUDRATE B115200
#define MODEMDEVICE "/dev/ttyS0"
#define FALSE 0
#define TRUE 1
main()
{
int fd,c, res, x;
struct termios oldtio,newtio;
uint8_t buf[255];
fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY );
if (fd <0) {perror(MODEMDEVICE); exit(-1); }
tcgetattr(fd,&oldtio); /* save current port settings */
bzero(&newtio, sizeof(newtio));
newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;
newtio.c_iflag = IGNPAR;
newtio.c_oflag = 0;
fcntl(fd, F_SETOWN, getpid());
/* set input mode (non-canonical, no echo,...) */
newtio.c_lflag = 0;
newtio.c_cc[VTIME] = 1; /* inter-character timer unused */
newtio.c_cc[VMIN] = 1; /* blocking read until 10 chars received */
tcflush(fd, TCIFLUSH);
tcsetattr(fd,TCSANOW,&newtio);
while (1) { /* loop for input */
res = read(fd,buf,255); /* returns after 5 chars have been input */
for (x=0;x<res;x++)
{
printf("%x ", buf[x]);
}
printf(":%d\n",res);
}
tcsetattr(fd,TCSANOW,&oldtio);
}
}
I would like to rather have an interrupt that allows me to run things in the background till something comes to the serial port.
I found an example that uses signal.h but it doesn't work? Can some help me.
{
#include <termios.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/signal.h>
#include <sys/types.h>
#define BAUDRATE B115200
#define MODEMDEVICE "/dev/ttyS0"
#define _POSIX_SOURCE 1 /* POSIX compliant source */
#define FALSE 0
#define TRUE 1
volatile int STOP=FALSE;
void signal_handler_IO (int status); /* definition of signal handler */
int wait_flag=TRUE; /* TRUE while no signal received */
main()
{
int fd,c, res;
struct termios oldtio,newtio;
struct sigaction saio; /* definition of signal action */
char buf[255];
/* open the device to be non-blocking (read will return immediatly) */
fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY | O_NONBLOCK);
if (fd <0) {perror(MODEMDEVICE); exit(-1); }
/* install the signal handler before making the device asynchronous */
saio.sa_handler = signal_handler_IO;
saio.sa_mask = 0;
saio.sa_flags = 0;
// saio.sa_restorer = NULL;
sigaction(SIGIO,&saio,NULL);
/* allow the process to receive SIGIO */
fcntl(fd, F_SETOWN, getpid());
/* Make the file descriptor asynchronous (the manual page says only
O_APPEND and O_NONBLOCK, will work with F_SETFL...) */
fcntl(fd, F_SETFL, FASYNC);
tcgetattr(fd,&oldtio); /* save current port settings */
/* set new port settings for canonical input processing */
newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;
newtio.c_iflag = IGNPAR | ICRNL;
newtio.c_oflag = 0;
newtio.c_lflag = 0;
newtio.c_cc[VMIN]=1;
newtio.c_cc[VTIME]=0;
tcflush(fd, TCIFLUSH);
tcsetattr(fd,TCSANOW,&newtio);
/* loop while waiting for input. normally we would do something
useful here */
while (STOP==FALSE) {
printf(".\n");usleep(100000);
/* after receiving SIGIO, wait_flag = FALSE, input is available
and can be read */
if (wait_flag==FALSE) {
res = read(fd,buf,255);
buf[res]=0;
printf(":%s:%d\n", buf, res);
if (res==1) STOP=TRUE; /* stop loop if only a CR was input */
wait_flag = TRUE; /* wait for new input */
}
}
/* restore old port settings */
tcsetattr(fd,TCSANOW,&oldtio);
}
/***************************************************************************
* signal handler. sets wait_flag to FALSE, to indicate above loop that *
* characters have been received. *
***************************************************************************/
void signal_handler_IO (int status)
{
printf("received SIGIO signal.\n");
wait_flag = FALSE;
}
}

Unexpected behavior related to write() function

This program is intended to read a byte from the console (cygwin on windows XP) and write it to the serial port (in order to communicate from a PC to an AVR). Then it should read data from the serial port. The AVR is set up to send data periodically, which works as it should (confirmed with Hyper Terminal). The program below works as it should, but when the line that writes data to the serial port is commented out, the program does not read either. In fact, it does not execute the lines before the (commented out) "write (fd, datatemp, 1);" either.
Why does the program seemingly not execute as intended when the write operation is not included?
#include "serialport.h"
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdlib.h>
#include <strings.h>
#include <stdio.h>
/* baudrate settings are defined in <asm/termbits.h>, which is
* included by <termios.h> */
#ifndef BAUDRATE
#define BAUDRATE B2400
#endif
#define _POSIX_SOURCE 1 /* POSIX compliant source */
#define BUFLEN 4
static int fd, c, res;
static struct termios oldtio, newtio;
static char *device;
int serial_init(char *modemdevice)
{
/*
* Open modem device for reading and writing and not as controlling tty
* because we don't want to get killed if linenoise sends CTRL-C.
**/
device = modemdevice;
fd = open (device, O_RDWR | O_NOCTTY | O_NDELAY);
//fd = open (device, O_RDWR | O_NOCTTY );
//fcntl(fd, F_SETFL, 0);
if (fd < 0)
{
perror (device);
exit(-1);
}
tcgetattr (fd, &oldtio); /* save current serial port settings */
bzero (&newtio, sizeof (newtio)); /* clear struct for new port settings */
/*
*BAUDRATE: Set bps rate. You could also use cfsetispeed and cfsetospeed.
*CRTSCTS : output hardware flow control (only used if the cable has
*all necessary lines. )
*CS8 : 8n1 (8bit,no parity,1 stopbit)
*CLOCAL : local connection, no modem contol
*CREAD : enable receiving characters
**/
newtio.c_cflag = BAUDRATE | CS8 | CLOCAL | CREAD;
/*
*IGNPAR : ignore bytes with parity errors
*ICRNL : map CR to NL (otherwise a CR input on the other computer
* will not terminate input)
* otherwise make device raw (no other input processing)
**/
newtio.c_iflag = IGNPAR | ICRNL;
/*
* Map NL to CR NL in output.
* */
#if 0
newtio.c_oflag = ONLCR;
#else
newtio.c_oflag = 0;
#endif
/*
* ICANON : enable canonical input
* disable all echo functionality, and don't send signals to calling program
**/
#if 1
newtio.c_lflag = ICANON;
#else
newtio.c_lflag = 0;
#endif
/*
* initialize all control characters
* default values can be found in /usr/include/termios.h, and are given
* in the comments, but we don't need them here
* */
newtio.c_cc[VINTR] = 0; /* Ctrl-c */
newtio.c_cc[VQUIT] = 0; /* Ctrl-\ */
newtio.c_cc[VERASE] = 0; /* del */
newtio.c_cc[VKILL] = 0; /* # */
newtio.c_cc[VEOF] = 4; /* Ctrl-d */
newtio.c_cc[VTIME] = 0; /* inter-character timer unused */
newtio.c_cc[VMIN] = 1; /* blocking read until 1 character arrives */
newtio.c_cc[VSWTC] = 0; /* '\0' */
newtio.c_cc[VSTART] = 0; /* Ctrl-q */
newtio.c_cc[VSTOP] = 0; /* Ctrl-s */
newtio.c_cc[VSUSP] = 0; /* Ctrl-z */
newtio.c_cc[VEOL] = 0; /* '\0' */
newtio.c_cc[VREPRINT] = 0; /* Ctrl-r */
newtio.c_cc[VDISCARD] = 0; /* Ctrl-u */
newtio.c_cc[VWERASE] = 0; /* Ctrl-w */
newtio.c_cc[VLNEXT] = 0; /* Ctrl-v */
newtio.c_cc[VEOL2] = 0; /* '\0' */
/*
* now clean the modem line and activate the settings for the port
**/
tcflush (fd, TCIFLUSH);
tcsetattr (fd, TCSANOW, &newtio);
/*
* terminal settings done, return file descriptor
**/
return fd;
}
void serial_cleanup(int ifd){
if(ifd != fd) {
fprintf(stderr, "WARNING! file descriptor != the one returned by serial_init()\n");
}
/* restore the old port settings */
tcsetattr (ifd, TCSANOW, &oldtio);
}
void main(void) {
int fd = serial_init("/dev/ttyS0");
//while(1)
//{
printf("Enter a dutycycle: ");
unsigned char buffer[BUFLEN] = {0};
fgets(buffer, BUFLEN, stdin);
uint8_t data = atoi(buffer);
unsigned char datatemp[1] = {(unsigned char) data};
printf("hen");
write (fd, datatemp, 1);
int n = 0;
unsigned char inbuffer[2] = {0};
int temp = -1;
//printf("%ld", temp);
while (temp <= 0)
{
//printf("%ld", temp);
temp = read(fd, inbuffer, 1);
}
printf("%u", (uint8_t) inbuffer[0]);
//}
serial_cleanup(fd);
}
Try looking at fflush() function.
Maybe
fflush(NULL)
or even
fflush(stdout)
will help in your case. Its worth experimenting by flushing before and/or after outputting to console.

Resources