Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

|How to read input from serial port?

Posted on 2004-04-14
7
Medium Priority
?
97,762 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 46

Assisted Solution

by:Kent Olsen
Kent Olsen earned 150 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 225 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
Back Up Your Microsoft Windows Server®

Back up all your Microsoft Windows Server – on-premises, in remote locations, in private and hybrid clouds. Your entire Windows Server will be backed up in one easy step with patented, block-level disk imaging. We achieve RTOs (recovery time objectives) as low as 15 seconds.

 

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

Independent Software Vendors: 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

If you're a modern-day technology professional, you may be wondering if certifications are really necessary. They are. Here's why.
The core idea of this article is to make you acquainted with the best way in which you can export Exchange mailbox to PST format.
The viewer will learn how to create multiple layers to apply various filters and how to delete areas from each layer’s filter.
This video will demonstrate how to find the puppet warp tool from the edit menu and where to put the points to edit.

688 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