Solved

|How to read input from serial port?

Posted on 2004-04-14
7
97,696 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:Kdo
Kdo earned 50 total points
Comment Utility
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
Comment Utility
/* 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
Comment Utility

sorry, i forgot the read part:

unsigned long readed = 0;
char buff[128];
ReadFile(hCom, buff, 128, &readed, 0);
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 

Author Comment

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

0
 

Expert Comment

by:gurup_k
Comment Utility
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
Comment Utility
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
Comment Utility
Dear gurup_k, this question is already closed.
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

This article shows how to convert a multi-page PDF file into multiple image files, with one image file created for each page of the PDF. It does this by utilizing an excellent, free software package called GraphicsMagick. The solution is amazingly s…
If your app took Google’s lash recently, here are the 5 most likely reasons.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.
This video demonstrates basic masking and how to edit the mask to reveal the desired image.

743 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now