Solved

|How to read input from serial port?

Posted on 2004-04-14
7
97,749 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Technology Partners: 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!

 

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

Simplifying Server Workload Migrations

This use case outlines the migration challenges that organizations face and how the Acronis AnyData Engine supports physical-to-physical (P2P), physical-to-virtual (P2V), virtual to physical (V2P), and cross-virtual (V2V) migration scenarios to address these challenges.

Question has a verified solution.

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

A list of useful business intelligence software.
Skype is a P2P (Peer to Peer) instant messaging and VOIP (Voice over IP) service – as well as a whole lot more.
This video demonstrates how to use each tool, their shortcuts, where and when to use them, and how to use the keyboard to improve workflow.
Viewers will learn how to use the Hootsuite Dashboard.

615 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