Solved

|How to read input from serial port?

Posted on 2004-04-14
7
97,740 Views
Last Modified: 2013-11-15
I will have 2 machines hooked up via the COM1 ports.
1 machine running windows having a hyperterminal session opened and the other machine running Linux having my program running.
I want to able to type a character into the hyperterminal window and have the character displayed on the Linux machine.

Im very new to C programming but heres what i have for my program so far, just not sure how to read the input and display it:

#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 open_port(void)
{
      int fd; /* File descriptor for the port */

      fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
            if(fd == 0)
            {
                  perror("open_port: Unable to open       /dev/ttyS0 - ");
            }
            else
                  fcntl(fd, F_SETFL, 0);
            
            return (fd);
}

/*Configire port*/

struct termios options;

/*Get the current options for the port*/

tcgetattr(fd, &options);

/*Set the Baud rates to 19200*/

cfsetispeed(&options, B19200);
cfsetospeed(&options, B19200);

/*Enable received and set local mode*/

options.c_cflag |= (CLOCAL | CREAD);

/*Set new options for port*/

tcsetattr(fd, TCSANOW, &options);

/*Set data bits*/

options.c_cflag &= ~CSIZE;      /*Mask the character size bits*/
options.c_cflag |= CS8;            /*Select 8 data bits*/

/*Set RAW input*/

options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);

/*Set Raw output*/

options.c_oflag &= ~OPOST;

/*Set timeout to 1 sec*/

options.c_cc[VMIN] = 0;
options.c_cc{VTIME] = 10;

/*Code to read input goes here*/

close(fd);

Can anyone advise on this?

Thanks
0
Comment
Question by:aaronmcl
7 Comments
 
LVL 45

Assisted Solution

by:Kent Olsen
Kent Olsen earned 50 total points
ID: 10822752
Hi aaronmcl,

Use the read() and write() functions to perform the actual I/O.

Also, if the two PC serial ports are directly connected, you'll want what is called a "crossover" cable that reverses the input/output signals.  If the two PCs are connected via a hub, switch, or router you should be fine.


Good Luck,
Kent
0
 
LVL 14

Accepted Solution

by:
Daniel Junges earned 75 total points
ID: 10823767
/* A sample program to illustrate setting up a serial port. */

#include <windows.h>

int main(int argc, char *argv[])
{
   DCB dcb;
   HANDLE hCom;
   BOOL fSuccess;
   char *pcCommPort = "COM2";

   hCom = CreateFile( pcCommPort,
                    GENERIC_READ | GENERIC_WRITE,
                    0,    // must be opened with exclusive-access
                    NULL, // no security attributes
                    OPEN_EXISTING, // must use OPEN_EXISTING
                    0,    // not overlapped I/O
                    NULL  // hTemplate must be NULL for comm devices
                    );

   if (hCom == INVALID_HANDLE_VALUE)
   {
       // Handle the error.
       printf ("CreateFile failed with error %d.\n", GetLastError());
       return (1);
   }

   // Build on the current configuration, and skip setting the size
   // of the input and output buffers with SetupComm.

   fSuccess = GetCommState(hCom, &dcb);

   if (!fSuccess)
   {
      // Handle the error.
      printf ("GetCommState failed with error %d.\n", GetLastError());
      return (2);
   }

   // Fill in DCB: 57,600 bps, 8 data bits, no parity, and 1 stop bit.

   dcb.BaudRate = CBR_57600;     // set the baud rate
   dcb.ByteSize = 8;             // data size, xmit, and rcv
   dcb.Parity = NOPARITY;        // no parity bit
   dcb.StopBits = ONESTOPBIT;    // one stop bit

   fSuccess = SetCommState(hCom, &dcb);

   if (!fSuccess)
   {
      // Handle the error.
      printf ("SetCommState failed with error %d.\n", GetLastError());
      return (3);
   }

   printf ("Serial port %s successfully reconfigured.\n", pcCommPort);
   return (0);
}
0
 
LVL 14

Expert Comment

by:Daniel Junges
ID: 10823804

sorry, i forgot the read part:

unsigned long readed = 0;
char buff[128];
ReadFile(hCom, buff, 128, &readed, 0);
0
Enterprise Mobility and BYOD For Dummies

Like “For Dummies” books, you can read this in whatever order you choose and learn about mobility and BYOD; and how to put a competitive mobile infrastructure in place. Developed for SMBs and large enterprises alike, you will find helpful use cases, planning, and implementation.

 

Author Comment

by:aaronmcl
ID: 10823846
Its alright guys got it sorted myself.
Thanks for the help anyways

0
 

Expert Comment

by:gurup_k
ID: 10886138
Hi all,

I am trying to communicate with the serial port. when I try to open the port using open system call, open("/dev/ttys0", O_RDONLY)...I am getting the Iput/output error. What could be the reason for this?
0
 

Expert Comment

by:gurup_k
ID: 10992660
After opening the file using open system call,
fd = open("filename", O_RDWR );

 Is it possible to convert the fd, i.e... the file descriptor(int) to FILE* so that I can do a formatted read like fread, fscanf etc....
0
 
LVL 14

Expert Comment

by:Daniel Junges
ID: 10994505
Dear gurup_k, this question is already closed.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Workplace bullying has increased with the use of email and social media. Retain evidence of this with email archiving to protect your employees.
Healthcare organizations in the United States must adhere to the guidance of both the HIPAA (Health Insurance Portability and Accountability Act) and HITECH (Health Information Technology for Economic and Clinical Health Act) for securing and protec…
The viewer will learn how to create multiple layers to apply various filters and how to delete areas from each layer’s filter.
The viewer will learn how to successfully create a multiboot device using the SARDU utility on Windows 7. Start the SARDU utility: Change the image directory to wherever you store your ISOs, this will prevent you from having 2 copies of an ISO wit…

680 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question