Hi all,
I am trying to read a word form the serial port. so I have connected two PC one running QNX with my C code and the other windows xp with hyperterminal. I am able to read characters, but not words. So here is the code I am trying.
#include <fcntl.h>
#include <stdio.h>
#include <termios.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#define SPEED B9600
#define PORT “/dev/ser1”
int main()
{
int fd;
struct termios options;
struct termios org_port_options;
int r,i=0;
char buff[255];
char sCmd[254];
int n;
int len;
//fd = open(PORT, O_RDWR | O_NOCTTY | O_NDELAY);
fd = open(PORT, O_RDWR);
if(fd == -1)
{
printf("Can not open the port");
return 0;
}
tcgetattr(fd, &org_port_options); // Get the current port settings
options = org_port_options; // save the port settings
printf("\norg_options = %d",options.c_cflag); //test
/* Initialize the Port */
cfsetispeed(&options, SPEED); // Input Baud Rate - 9600
cfsetospeed(&options, SPEED); // Output Baud Rate - 9600
options.c_cflag |= CLOCAL; // Local line - Do not change the owner
options.c_cflag |= CREAD; // Enable receiver
options.c_cflag |= PARENB; // parity - enabled
options.c_cflag &= ~PARODD; // Odd parity - even
options.c_cflag &= ~CSTOPB; // stop bit - 1
options.c_cflag &= ~CSIZE; // bit mask for data bits
//options.c_cflag &= ~CNEW_RTSCTS; // hardware flow control-disable
options.c_cflag |= CS7; // data bits - 7
/* Initialize the Terminal */
options.c_lflag &= ~ECHO; // Echo the Terminal screen - off
options.c_lflag &= ~ICANON; // Canonical Input else raw - disable
options.c_iflag &= ~INPCK; // Parity Check - disable
options.c_iflag &= ~IGNBRK; // Parity Errors - Ignore
options.c_iflag &= ~PARMRK; // Mark Parity Errors - disable
options.c_iflag &= ~ISTRIP; // Strip Parity bits - disable
options.c_iflag &= ~IXON; // Software outgoing flow control - disable
options.c_iflag &= ~IXOFF; // Software incoming flow control - disable
options.c_oflag &= ~OPOST; // Post process output (not set = raw output)
tcsetattr(fd, TCSANOW, &options); // make changes on the Port
printf(" options = %d",options.c_cflag);
fcntl(fd, F_SETFL, 0); //FNDELAY);
//printf(" buff = %s\n",buff);
sCmd[0] = 0x41;
sCmd[1] = 0x42;
sCmd[2] = 0x43;
sCmd[3] = 0x00;; // keystroke input from user.
len = strlen(sCmd);
sCmd[len] = 0x0d; // stick a <CR> after the command
sCmd[len+1] = 0x00; // terminate the string properly
while(i < 20)
{
r = read(fd, &buff, '\r');
buff[r] = '\0';
if(r > 0)
{
i++;
printf(" ");
printf(" String = %s\n", buff);
n = write(fd, sCmd, strlen(sCmd));
if (n < 0) {
fputs("write failed!\n", stderr);
return 0;
}
}
}
tcsetattr(fd,TCSANOW,&org_port_options);
close(fd);
return 0;
}
Please let me know any changes and improvements I have to make.
Thank you.