Solved

|How to read input from serial port?

Posted on 2004-04-14
7
97,735 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
Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

 

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

U.S. Department of Agriculture and Acronis Access

With the new era of mobile computing, smartphones and tablets, wireless communications and cloud services, the USDA sought to take advantage of a mobilized workforce and the blurring lines between personal and corporate computing resources.

Question has a verified solution.

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

A list of useful business intelligence software.
Let’s list some of the technologies that enable smooth teleworking. 
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.
XMind Plus helps organize all details/aspects of any project from large to small in an orderly and concise manner. If you are working on a complex project, use this micro tutorial to show you how to make a basic flow chart. The software is free when…

792 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