Click here to Skip to main content
Rate this: bad
Please Sign up or sign in to vote.
See more: C serialport
Hi guys!
I managed to come up with some code for making a Serial Port Device communicate with a computer wherein I send it some data and it sends the same data back to me (as a test program). However, the device sends back some different data.
THe code is as follows :
#include <stdafx.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>
#include <ctype.h>
#include <math.h>
#include <dos.h>
#define MAX 5000 //max length of delay time period
#define COM1 (unsigned short)0x3F8 // Serial Port COM1
#define COM2 (unsigned short)0x2F8 // Serial Port COM2

int TestSerial();
int Delay(int num);
int main(void)
  int rc=0;
    printf("Error in TestSerial()!\n");
    printf("Success with TestSerial!\n");
  return 0;
int TestSerial()
  int index, value, result=0;
  printf("Begin to execute outp() & inp() ... \n");
  for(index=0; index<10;index++)
     printf("Data sent to COM1 is : %d \n",index);
     printf("Data returned from COM1 is : %d \n",value);
       printf("Error in loop testing of COM1! \n");
       return result;
  return result;
int Delay(int num)
  int m,n,cycle=MAX;
  for(m=0;m<=num*cycle; m++)
  return 0;
The problem I am facing is that the device returns different data EVERY time (which is not the sent data of 1-9). Could you please help me out ?
Also, I thought of a way where in _outp() I send a comman that is specific to the device - say it is an instruction in C only .. but then that kind of limits the scope of my program's usage. Frown | :(
P.S. I have used #include <> only but the HTML preview prevents the appropriate usage.
[EDIT: Added tags to code block and restored include statements]
Posted 2-Apr-13 21:14pm
Edited 2-Apr-13 21:57pm
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

To get code that might work you should:
  • Initialize the serial port (baud rate, number of bits, parity, flow control).
  • Perform a dummy read to clear the status register bits.
  • Replace the delay loop by code that checks if new data are available by testing bit 0 (Data Ready) of the line status register.
A good reference about serial programming is[^].
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

thanks Jochen! Big Grin | :-D
I took your advice and link .. finished that software development!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Advertise | Privacy | Mobile
Web03 | 2.8.150327.1 | Last Updated 9 Apr 2013
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100