Solved

Windows XP Serial Port

Posted on 2002-05-27
28
927 Views
Last Modified: 2013-11-15
Hello,
Can someone please provide some simple sample code to open a serial port, set all needed values, and then write a simple string to that port (like "hello" or somthing). It is a necessity that this code work on all modern versions of Windows (98/2K/XP). I've tried some solutions but they didn't work with Windows XP. I need this to work with Windows XP.

This is not a homework problem. I am trying to send a command to a serial port device, but i can't find any code that has worked with Windows XP.
0
Comment
Question by:axia
  • 11
  • 7
  • 3
  • +4
28 Comments
 
LVL 32

Expert Comment

by:jhance
ID: 7036862
If you have code that works on Win2000, it will work on XP also.  The same is NOT true for code that works on Win9x/ME.  On 9x/ME you can "cheat" the Win32 protections and go directly to the hardware.  

On NT/2K/XP you cannot and must use the CreateFile() API to get a handle to the COM port and then use ReadFile() or WriteFile() to receive/send data.

Please post your code that works on Win2000.
0
 
LVL 86

Expert Comment

by:jkr
ID: 7036995
See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnwbgen/html/msdn_serial.asp ("Serial Communications in Win32") - it comes with a full-featured sample...
0
 

Author Comment

by:axia
ID: 7037560
i've only gotten it to work on 9x. not 2K or XP (i simply used XP as an example because do not have access to a 2K machine but I assumed that if it worked with XP it would work with 2K)

I am using CreateFile and then WriteFile. I've looked at the link posted by jkr. I've tried my code in the application i'm working on, and by it self in an application i developed just to test it. I really can't think of what's wrong.

I started out using those functions until I found (on a free code website) a class called CSerialPort (by PJ Naughter). It also uses CreateFile and WriteFile. It works fine on 9x. Why not on NT (2K/XP) with the same code. I don't think I, or this class, are taking any shortcuts.
0
 
LVL 86

Expert Comment

by:jkr
ID: 7037611
Have you tried to just run the sample that comes with the article?
0
 

Author Comment

by:axia
ID: 7037787
that doesn't seem to compile for me. It generates 5 linker errors. I have a hunch that it might be the serial port on my Windows XP computer. Do you know of a diagnostic program that would let me write a test string to the serial port and see if the device responds?
0
 
LVL 49

Expert Comment

by:DanRollins
ID: 7037957
You can (and should) use the program named HyperTerminal that comes with Windows
[Start]>Programs>Accessories>Communications

When you are prompted "Connect To" please drop-down the "Connect Using" combo and select the COMn port.  This lets you send text directly to the port (just type it into the screen and press Enter).

You may want to use
File>Properties>Settings>ASCII Setup > Echo typed characters locally
so that you are not typing blindly.

-- Dan
0
 

Author Comment

by:axia
ID: 7037985
hmm, my hyperterminal has very bad "lagg". It takes 5-6 seconds to send 1 character. When I try the send file option, the connection times out. Is this the nature of hyperterminal or is my serial port broken?
0
 
LVL 32

Expert Comment

by:jhance
ID: 7037999
>>It generates 5 linker errors. I have a hunch that it
>>might be the serial port on my Windows XP computer.

That's ridiculous!  The linker doesn't even KNOW ABOUT the serial port.  

If you get linker errors then you most likely have a error in your linker options.

Post the specific errors.  My guess is that you are failing to include a required .lib file.
0
 

Author Comment

by:axia
ID: 7038035
you have mis-read my comment. Those are 2 different comments. I should have made a new paragraph. I said that there were linker errors. On a new topic, i don't think it's the code but my serial port that is causing the problem. Of cource the serial port has nothing to do with the linker!!!

Errors:
Linking...
INIT.OBJ : error LNK20001: unresolved external symbol __imp__InitCommonControls@0
TRANSFER.OBJ : error LNK20001: unresolved external symbol __imp__timeSetEvent@20
TRANSFER.OBJ : error LNK20001: unresolved external symbol __imp__timeKillEvent@4
LIBCD.lib(crt0.obj) : error LNK2001: unresolved external symbol _main
Debug/MITTY.exe : fatal error LNK1120: 4 unresolved externals
Error executing link.exe

MITTY.exe - 5 error(s), 0 warning(s)

Am i missing a file or library or somthing?
0
 
LVL 49

Expert Comment

by:DanRollins
ID: 7038588
If the serial port is responding that slowly, then probably one of two things is happening:

1) The device attached to the port is not responding as expected.  What kind of device is it?

2) Some other TAPI device (such as some fax software) is holding ownership of the port and giving it up reluctantly.  Disable all such software.

-- Dan
0
 
LVL 4

Expert Comment

by:havman56
ID: 7041980
axia
here is my code working fine!!
use it..
it uses createfile..

0
 
LVL 4

Expert Comment

by:havman56
ID: 7041983
-- ------------------------------------------------------------------------ --
--                                                                          --
--    Note to Visual C++ users:  Don't forget to compile with the           --
--     "Multithreaded" option in your project settings                      --
--                                                                          --
--         See   Project settings                                           --
--                   |                                                      --
--                   *--- C/C++                                             --
--                          |                                               --
--                          *--- Code generation                            --
--                                       |                                  --
--                                       *---- Use run-time library         --
--                                                     |                    --
--                                                     *---- Multithreaded  --
--                                                                          --
--                                                                          --
--                                                                          --
-- ------------------------------------------------------------------------ */




/* ---------------------------------------------------------------------- */

#define STRICT
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <process.h>
#include <conio.h>
#include <windows.h>


#include "Tserial_event.h"

#define SIG_POWER_DOWN     0
#define SIG_READER         1
#define SIG_READ_DONE      2    // data received has been read
#define SIG_WRITER         3
#define SIG_DATA_TO_TX     4    // data waiting to be sent
#define SIG_MODEM_EVENTS   5
#define SIG_MODEM_CHECKED  6

void Tserial_event_thread_start(void *arg);

typedef unsigned (WINAPI *PBEGINTHREADEX_THREADFUNC) (LPVOID lpThreadParameter);
typedef unsigned *PBEGINTHREADEX_THREADID;

/* ---------------------------------------------------------------------- */
/* ---------------------  Tserial_event_thread_start  ------------------- */
/* ---------------------------------------------------------------------- */
/**
    This function is not part of the Tserial_event object. It is simply used
    to start the thread from an external point of the object.
*/
void Tserial_event_thread_start(void *arg)
{
    class Tserial_event *serial_unit;

    serial_unit = (Tserial_event *) arg;
   
    if (serial_unit!=0)
        serial_unit->run();
}

/* -------------------------------------------------------------------- */
/* -------------------------    Tserial_event ------------------------- */
/* -------------------------------------------------------------------- */
Tserial_event::Tserial_event()
{
    int i;

    ready            = false;
    parityMode       = SERIAL_PARITY_NONE;
    port[0]          = 0;
    rate             = 0;
    threadid         = 0;
    serial_handle    = INVALID_HANDLE_VALUE;
    tx_in_progress   = 0;
    rx_in_progress   = 0;
    max_rx_size      = 1;
    tx_size          = 0;
    received_size    = 0;
    check_modem      = false;

    manager          = 0;

    /* -------------------------------------------------------------- */
    // creating Events for the different sources
    for (i=0; i<SERIAL_SIGNAL_NBR; i++)
    {
        if ((i==SIG_READER) || (i==SIG_WRITER) || (i==SIG_MODEM_EVENTS))
            serial_events[i] = CreateEvent(NULL, TRUE, FALSE, NULL);  // Manual Reset
        else
            serial_events[i] = CreateEvent(NULL, FALSE, FALSE, NULL); // Auto reset
    }
}

/* -------------------------------------------------------------------- */
/* --------------------------    ~Tserial_event ----------------------- */
/* -------------------------------------------------------------------- */
Tserial_event::~Tserial_event()
{
    int i;

    /* -------------------------------------------------------- */
    for (i=0; i<SERIAL_SIGNAL_NBR; i++)         // deleting the events
    {
        if (serial_events[i]!=INVALID_HANDLE_VALUE)
            CloseHandle(serial_events[i]);
        serial_events[i] = INVALID_HANDLE_VALUE;
    }

    if (serial_handle!=INVALID_HANDLE_VALUE)
        CloseHandle(serial_handle);
    serial_handle = INVALID_HANDLE_VALUE;
}
/* -------------------------------------------------------------------- */
/* --------------------------    disconnect   ------------------------- */
/* -------------------------------------------------------------------- */
void Tserial_event::disconnect(void)
{
    ready = false;
    SetEvent(serial_events[SIG_POWER_DOWN]);
}
/* -------------------------------------------------------------------- */
/* --------------------------    connect      ------------------------- */
/* -------------------------------------------------------------------- */
/**
     Serial port, file and overlapped structures initialization
*/
int  Tserial_event::connect (char *port_arg, int  rate_arg,  int parity_arg,
                             char ByteSize , bool modem_events)
{
    int  erreur;
    DCB  dcb;
    int  i;
    COMMTIMEOUTS cto = { 0, 0, 0, 0, 0 };

    /* --------------------------------------------- */
    if (serial_handle!=INVALID_HANDLE_VALUE)
        CloseHandle(serial_handle);
    serial_handle = INVALID_HANDLE_VALUE;

    if (port_arg!=0)
    {
        strncpy(port, port_arg, 10);
        rate        = rate_arg;
        parityMode  = parity_arg;
        check_modem = modem_events;

        erreur      = 0;
        ZeroMemory(&ovReader   ,sizeof(ovReader)   );  // clearing the overlapped
        ZeroMemory(&ovWriter   ,sizeof(ovWriter)   );
        ZeroMemory(&ovWaitEvent,sizeof(ovWaitEvent));
        memset(&dcb,0,sizeof(dcb));

        /* -------------------------------------------------------------------- */
        // set DCB to configure the serial port
        dcb.DCBlength       = sizeof(dcb);                  
       
        /* ---------- Serial Port Config ------- */
        dcb.BaudRate        = rate;

        switch(parityMode)
        {
            case SERIAL_PARITY_NONE:
                            dcb.Parity      = NOPARITY;
                            dcb.fParity     = 0;
                            break;
            case SERIAL_PARITY_EVEN:
                            dcb.Parity      = EVENPARITY;
                            dcb.fParity     = 1;
                            break;
            case SERIAL_PARITY_ODD:
                            dcb.Parity      = ODDPARITY;
                            dcb.fParity     = 1;
                            break;
        }


        dcb.StopBits        = ONESTOPBIT;
        dcb.ByteSize        = (BYTE) ByteSize;

        dcb.fOutxCtsFlow    = 0;
        dcb.fOutxDsrFlow    = 0;
        dcb.fDtrControl     = DTR_CONTROL_DISABLE;
        dcb.fDsrSensitivity = 0;
        dcb.fRtsControl     = RTS_CONTROL_DISABLE;
        dcb.fOutX           = 0;
        dcb.fInX            = 0;
       
        /* ----------------- misc parameters ----- */
        dcb.fErrorChar      = 0;
        dcb.fBinary         = 1;
        dcb.fNull           = 0;
        dcb.fAbortOnError   = 0;
        dcb.wReserved       = 0;
        dcb.XonLim          = 2;
        dcb.XoffLim         = 4;
        dcb.XonChar         = 0x13;
        dcb.XoffChar        = 0x19;
        dcb.EvtChar         = 0;
       
        /* -------------------------------------------------------------------- */
        serial_handle    = CreateFile(port, GENERIC_READ | GENERIC_WRITE,
                   0, NULL, OPEN_EXISTING,FILE_FLAG_OVERLAPPED,NULL);
                   // opening serial port

        ovReader.hEvent    = serial_events[SIG_READER];
        ovWriter.hEvent    = serial_events[SIG_WRITER];
        ovWaitEvent.hEvent = serial_events[SIG_MODEM_EVENTS];

        if (serial_handle    != INVALID_HANDLE_VALUE)
        {
            if (check_modem)
            {
                if(!SetCommMask(serial_handle, EV_RING | EV_RLSD))
                    erreur = 1;
            }
            else
            {
                if(!SetCommMask(serial_handle, 0))
                    erreur = 1;
            }

               
            // set timeouts
            if(!SetCommTimeouts(serial_handle,&cto))
                erreur = 2;

            // set DCB
            if(!SetCommState(serial_handle,&dcb))
                erreur = 4;
        }
        else
            erreur = 8;
    }
    else
        erreur = 16;


    /* --------------------------------------------- */
    for (i=0; i<SERIAL_SIGNAL_NBR; i++)
    {
        if (serial_events[i]==INVALID_HANDLE_VALUE)
            erreur = 32;
    }

    /* --------------------------------------------- */
    if (erreur!=0)
    {
        CloseHandle(serial_handle);
        serial_handle = INVALID_HANDLE_VALUE;
    }
    else
    {
        // start thread
        _beginthreadex(NULL,0,(PBEGINTHREADEX_THREADFUNC) Tserial_event_thread_start,
                  (void *) this, 0, &threadid);
    }

    /* --------------------------------------------- */
    return(erreur);
}
/* -------------------------------------------------------------------- */
/* ---------------------           setManager     --------------------- */
/* -------------------------------------------------------------------- */
void         Tserial_event::setManager(type_myCallBack manager_arg)
{
        manager = manager_arg;
}
/* -------------------------------------------------------------------- */
/* ---------------------           setRxSize      --------------------- */
/* -------------------------------------------------------------------- */
void         Tserial_event::setRxSize(int size)
{
        max_rx_size = size;
        if (max_rx_size>SERIAL_MAX_RX)
            max_rx_size = SERIAL_MAX_RX;
}
/* -------------------------------------------------------------------- */
/* ---------------------           setManager     --------------------- */
/* -------------------------------------------------------------------- */
char *      Tserial_event::getDataInBuffer(void)
{
    return(rxBuffer);
}
/* -------------------------------------------------------------------- */
/* ---------------------           setManager     --------------------- */
/* -------------------------------------------------------------------- */
int      Tserial_event::getDataInSize(void)
{
    return(received_size);
}
/* -------------------------------------------------------------------- */
/* ---------------------           setManager     --------------------- */
/* -------------------------------------------------------------------- */
void   Tserial_event::dataHasBeenRead(void)
{
    SetEvent(serial_events[SIG_READ_DONE]);
}
/* -------------------------------------------------------------------- */
/* -----------------------   getNbrOfBytes  --------------------------- */
/* -------------------------------------------------------------------- */
int Tserial_event::getNbrOfBytes    (void)
{
    struct _COMSTAT status;
    int             n;
    unsigned long   etat;

    n = 0;

    if (serial_handle!=INVALID_HANDLE_VALUE)
    {
        ClearCommError(serial_handle, &etat, &status);
        n = status.cbInQue;
    }
    return(n);
}
/* -------------------------------------------------------------------- */
/* --------------------------    sendData     ------------------------- */
/* -------------------------------------------------------------------- */
void Tserial_event::sendData (char *buffer, int size)
{
    if ((!tx_in_progress) && (size<SERIAL_MAX_TX) && (buffer!=0))
    {
        tx_in_progress = 1;
        memcpy(txBuffer, buffer, size);
        tx_size = size;
        SetEvent(serial_events[SIG_DATA_TO_TX]);
        // indicating data to be sent
    }
}
/* -------------------------------------------------------------------- */
/* --------------------------    OnEvent      ------------------------- */
/* -------------------------------------------------------------------- */
void Tserial_event::OnEvent (unsigned long events)
{
    unsigned long ModemStat;

    GetCommModemStatus(serial_handle, &ModemStat);

    if ((events & EV_RING)!=0)
    {
        if ((ModemStat &  MS_RING_ON)!= 0)
        {
            if (manager!=0)
                manager((uint32) this, SERIAL_RING);
        }
    }

    if ((events & EV_RLSD)!=0)
    {
        if ((ModemStat &  MS_RLSD_ON)!= 0)
        {
            if (manager!=0)
                manager((uint32) this, SERIAL_CD_ON);
        }
        else
        {
            if (manager!=0)
                manager((uint32) this, SERIAL_CD_OFF);
        }
    }
}
/* -------------------------------------------------------------------- */
/* --------------------------       run       ------------------------- */
/* -------------------------------------------------------------------- */

/**
 this function is the main loop of the Tserial object. There is a
 do while() loop executed until either an error or a PowerDown is
 received.
 this is not a busy wait since we use the WaitForMultipleObject function
*/

/* * /
#define DEBUG_EVENTS
/* */

void Tserial_event::run(void)
{
    bool          done;
    long          status;
    unsigned long read_nbr, result_nbr;
    char          success;

    ready                   = true;
    done                    = false;
    tx_in_progress          = 0;
    rx_in_progress          = 0;
    WaitCommEventInProgress = 0;

    if (manager!=0)
        manager((uint32) this, SERIAL_CONNECTED);

    GetLastError();               // just to clear any pending error
    SetEvent(serial_events[SIG_READ_DONE]);
    if (check_modem)
        SetEvent(serial_events[SIG_MODEM_CHECKED]);

    /* ----------------------------------------------------------- */
    while(!done)
    {
        /* ------------------------------------------------------------------ */
        /*                                                                    */
        /*                                                                    */
        /*                                                                    */
        /*                          Waiting  for signals                      */
        /*                                                                    */
        /*                                                                    */
        /*                                                                    */
        /* ------------------------------------------------------------------ */
        // Main wait function. Waiting for something to happen.
        // This may be either the completion of a Read or a Write or
        // the reception of modem events, Power Down, new Tx
        //
        status = WaitForMultipleObjects(SERIAL_SIGNAL_NBR, serial_events,
                                        FALSE, INFINITE);

        // processing answer to filter other failures
        status = status - WAIT_OBJECT_0;
        if ((status<0) || (status>=SERIAL_SIGNAL_NBR))
            done=true;   // error
        else
        {
            /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
            /* ++++++++++++++++++++ EVENT DISPATCHER ++++++++++++++++++ */
            /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
            switch(status)
            {
                /* ######################################################## */
                case SIG_POWER_DOWN:
                    // receiving a POWER down signal. Stopping the thread
                    done = true;
                    break;
                /* ######################################################## */
                /* #                                                      # */
                /* #                                                      # */
                /* #                       RX                             # */
                /* #                                                      # */
                /* #                                                      # */
                /* ######################################################## */
                case SIG_READ_DONE:
                    // previous reading is finished
                    // I start a new one here
                    if (!rx_in_progress)
                    {
                        // locking reading
                        rx_in_progress = 1;
                        // starting a new read
                        success = (char) ReadFile(serial_handle,&rxBuffer,
                                         max_rx_size,&read_nbr,&ovReader);
                        if (!success)
                        {
                            // failure
                            if(GetLastError() != ERROR_IO_PENDING )
                            {
                                // real failure => quiting
                                done = true;
                                #ifdef DEBUG_EVENTS
                                printf("Readfile error (not pending)\n");
                                #endif DEBUG_EVENTS
                            }
                            #ifdef DEBUG_EVENTS
                            else
                                printf("ReadFile pending\n");
                            #endif DEBUG_EVENTS
                        }
                        #ifdef DEBUG_EVENTS
                        else
                        {
                            // I make nothing here since the overlapped
                            // will be signaled anyway, so I'll make
                            // the processing there
                            printf("ReadFile immediate success\n");
                        }
                        #endif
                    }
                    break;
                /* ######################################################## */
                case SIG_READER:
                    // reading the result of the terminated read
                    //BOOL GetOverlappedResult(
                    //    HANDLE hFile,      // handle of file, pipe, or communications device
                    //    LPOVERLAPPED lpOverlapped,      // address of overlapped structure
                    //    LPDWORD lpNumberOfBytesTransferred,      // address of actual bytes count
                    //    BOOL bWait       // wait flag
                    //   );
                    //
                    if (GetOverlappedResult(serial_handle, &ovReader,
                        &result_nbr, FALSE))
                    {
                        #ifdef DEBUG_EVENTS
                            printf("ReadFile => GetOverlappedResult done\n");
                        #endif DEBUG_EVENTS
                        // no error => OK
                        // Read operation completed successfully
                        ResetEvent(serial_events[SIG_READER]);
                        // Write operation completed successfully
                        received_size  = result_nbr;
                        rx_in_progress = 0; // read has ended
                        // if incoming data, I process them
                        if ((result_nbr!=0) &&(manager!=0))
                            manager((uint32) this, SERIAL_DATA_ARRIVAL);
                        // I automatically restart a new read once the
                        // previous is completed.
                        SetEvent(serial_events[SIG_READ_DONE]);

                    }
                    else
                    {
                        // GetOverlapped didn't succeed !
                        // What's the reason ?
                        if(GetLastError()!= ERROR_IO_PENDING )
                            done = 1;  // failure
                    }
                    break;
                /* ######################################################## */
                /* #                                                      # */
                /* #                                                      # */
                /* #                       TX                             # */
                /* #                                                      # */
                /* #                                                      # */
                /* ######################################################## */
                case SIG_DATA_TO_TX:
                    // Signal asserted that there is a new valid message
                    // in the "txBuffer" variable
                    // sending data to the port
                    success = (char) WriteFile(serial_handle, txBuffer, tx_size,
                                        &result_nbr, &ovWriter);
                        if (!success)
                        {
                            // ouups, failure
                            if(GetLastError() != ERROR_IO_PENDING )
                            {
                                // real failure => quiting
                                done = true;
                                #ifdef DEBUG_EVENTS
                                printf("WriteFile error (not pending)\n");
                                #endif DEBUG_EVENTS
                            }
                            #ifdef DEBUG_EVENTS
                            else
                                printf("WriteFile pending\n");
                            #endif DEBUG_EVENTS
                        }
                        #ifdef DEBUG_EVENTS
                        else
                        {
                            // I make nothing here since the overlapped
                            // will be signaled anyway, so I'll make
                            // the processing there
                            printf("WriteFile immediate success\n");
                        }
                        #endif
                    break;
                /* ######################################################## */
                case SIG_WRITER:
                    // WriteFile has terminated
                    // checking the result of the operation
                    if (GetOverlappedResult(serial_handle, &ovWriter,
                        &result_nbr, FALSE))
                    {
                        // Write operation completed successfully
                        ResetEvent(serial_events[SIG_WRITER]);
                        // further write are now allowed
                        tx_in_progress = 0;
                        // telling it to the manager
                        if (manager!=0)
                            manager((uint32) this, SERIAL_DATA_SENT);
                    }
                    else
                    {
                        // GetOverlapped didn't succeed !
                        // What's the reason ?
                        if(GetLastError() != ERROR_IO_PENDING )
                            done = 1;  // failure
                    }
                    break;
                /* ######################################################## */
                /* #                                                      # */
                /* #                                                      # */
                /* #                    MODEM_EVENTS EVENTS                      # */
                /* #                                                      # */
                /* #                                                      # */
                /* ######################################################## */
                case SIG_MODEM_CHECKED:
                    if ((!WaitCommEventInProgress) && check_modem)
                    // if no wait is in progress I start a new one
                    {            
                        WaitCommEventInProgress=1;
                        success = (char) WaitCommEvent(serial_handle,&dwCommEvent,
                                                       &ovWaitEvent);
                        // reading one byte only to have immediate answer on each byte
                        if (!success)
                        {
                            // ouups, failure
                            if(GetLastError() != ERROR_IO_PENDING )
                            {
                                // real failure => quiting
                                done = true;
                                #ifdef DEBUG_EVENTS
                                printf("WaitCommEvent error (not pending)\n");
                                #endif DEBUG_EVENTS
                            }
                            #ifdef DEBUG_EVENTS
                            else
                                printf("WaitCommEvent pending\n");
                            #endif DEBUG_EVENTS
                        }
                        #ifdef DEBUG_EVENTS
                        else
                        {
                            // I make nothing here since the overlapped
                            // will be signaled anyway, so I'll make
                            // the processing there
                            printf("WaitCommEvent immediate success\n");
                        }
                        #endif
                    }
                    break;
                /* ######################################################## */
                case SIG_MODEM_EVENTS:
                    // reading the result of the terminated wait
                    if (GetOverlappedResult(serial_handle, &ovWaitEvent,
                        &result_nbr, FALSE))
                    {
                        // Wait operation completed successfully
                        ResetEvent(serial_events[SIG_MODEM_EVENTS]);
                        WaitCommEventInProgress = 0;
                        // if incoming data, I process them
                        OnEvent(dwCommEvent);
                        // automatically starting a new check
                        SetEvent(serial_events[SIG_MODEM_CHECKED]);
                    }
                    else
                    {
                        // GetOverlapped didn't succeed !
                        // What's the reason ?
                        if(GetLastError() != ERROR_IO_PENDING )
                            done = 1;  // failure
                    }
                    break;
                /* ######################################################## */
            }
            /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
            /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
            /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
        }
    };

    // --------------------- Disconnecting ----------------
    ready = false;
    if (serial_handle!=INVALID_HANDLE_VALUE)
        CloseHandle(serial_handle);
    serial_handle = INVALID_HANDLE_VALUE;

    if (manager!=0)
        manager((uint32) this, SERIAL_DISCONNECTED);
}
/* -------------------------------------------------------------------- */
/* -------------------------------------------------------------------- */

0
 
LVL 4

Expert Comment

by:havman56
ID: 7041986
TO test the above code

serail test program is given down!!!
0
 
LVL 4

Expert Comment

by:havman56
ID: 7041992
//---------------------------------------------------------------------------
#include "conio.h"
#include "Tserial_event.h"

 extern char buf[20];
 extern void Testmsg();
 extern void TestBuf();


/* ======================================================== */
/* ===============  OnCharArrival     ===================== */
/* ======================================================== */
void OnDataArrival(int size, char *buffer)
{
    if ((size>0) && (buffer!=0))
    {
        buffer[size] = 0;
     //   printf("OnDataArrival: %s ",buffer);
          printf("%s",buffer);
    }
}

/* ======================================================== */
/* ===============  OnCharArrival     ===================== */
/* ======================================================== */
void SerialEventManager(uint32 object, uint32 event)
{
    char *buffer;
    int   size;
    Tserial_event *com;

    com = (Tserial_event *) object;
    if (com!=0)
    {
        switch(event)
        {
            case  SERIAL_CONNECTED  :
                                        printf("Connected ! \n");
                                        break;
            case  SERIAL_DISCONNECTED  :
                                        printf("Disonnected ! \n");
                                        break;
            case  SERIAL_DATA_SENT  :
                                        printf("Data sent ! \n");
                                        break;
            case  SERIAL_RING       :
                                        printf("DRING ! \n");
                                        break;
            case  SERIAL_CD_ON      :
                                        printf("Carrier Detected ! \n");
                                        break;
            case  SERIAL_CD_OFF     :
                                        printf("No more carrier ! \n");
                                        break;
            case  SERIAL_DATA_ARRIVAL  :
                                        size   = com->getDataInSize();
                                        buffer = com->getDataInBuffer();
                                        OnDataArrival(size, buffer);
                                        com->dataHasBeenRead();
                                        break;
        }
    }
}
/* ======================================================== */
/* ========================   main  ======================= */
/* ======================================================== */
int main(int argc, char* argv[])
{
    int            c;
    int            erreur;
    char           txt[32];
    Tserial_event *com;

    //Testmsg();
     TestBuf();
    com = new Tserial_event();
    if (com!=0)
    {
        com->setManager(SerialEventManager);
        erreur = com->connect("COM1", 38400, SERIAL_PARITY_NONE, 8, true);
        if (!erreur)
        {
               // com->sendData("Hello World",11);
               //com->sendData("10$8$",5);
               com->sendData(buf,sizeof(buf));
             
               com->setRxSize(1);


            // ------------------
            do
            {
                c = getch();
                printf("_%c",c);
                txt[0] = c;
               com->sendData(txt, 1);
                com->setRxSize(1);
            }
            while (c!=32);

        }
        else
            printf("ERROR : com->connect (%ld)\n",erreur);
        // ------------------
        com->disconnect();

        // ------------------
        delete com;
        com = 0;
    }
    return 0;
}

0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 4

Expert Comment

by:havman56
ID: 7041997
AXIA

it works perfectly ......on win2000 i dont have winXP

i hope it shoudl work on XP too bcoz file concept is used.
Any doubts i am here to help u ...
0
 
LVL 4

Expert Comment

by:havman56
ID: 7053495
axia

did u tried  it my program?

why no response from u...
0
 
LVL 4

Expert Comment

by:havman56
ID: 7066677
axia

kindly respond!!

my programm works fine why no response form u...?

any doubts post it here !! dont keep mum

0
 

Author Comment

by:axia
ID: 7163387
Sorry it's been so long. I've been very busy. But this is now my priority. There is no "Tserial_event.h" file to #include. Because i can't compile your code I have been using my own code. Here is the thing: My program works fine on the loffowing platforms: Win95, Win98, WinMe, Win2K, but not WinXP. I tried replaceing the commands i am sending over the serial port to modem commands and replaced my device with a modem and it got the proper commands under XP. So my code must work with XP.

However it doesn't work with my device. All the device does is record when it gets a signal from the serial port and generates an electrical pulse (it's plugged in to a 4 pin power connector in my PC). Why would this code work on Win9x and Win2K but not on XP. The device is just simple circuts so I don't think it could be incompatible with WinXP. Are there any known issues that would create this situation?

If you don't reply to this soon I will post a new question worth 500 points so that I can get this resolved. I will then straighten this question out. Thanks.
0
 
LVL 4

Expert Comment

by:havman56
ID: 7164097
Tserial event.h file


#ifndef TSERIAL_EVENT_H
#define TSERIAL_EVENT_H

#include <stdio.h>
#include <windows.h>


#define SERIAL_PARITY_NONE 0
#define SERIAL_PARITY_ODD  1
#define SERIAL_PARITY_EVEN 2

#define SERIAL_CONNECTED         0
#define SERIAL_DISCONNECTED      1
#define SERIAL_DATA_SENT         2
#define SERIAL_DATA_ARRIVAL      3
#define SERIAL_RING              4
#define SERIAL_CD_ON             5
#define SERIAL_CD_OFF            6

typedef unsigned long uint32;
typedef void (*type_myCallBack) (uint32 object, uint32 event);

#ifndef __BORLANDC__
#define bool  BOOL
#define true  TRUE
#define false FALSE
#endif


#define SERIAL_SIGNAL_NBR 7         // number of events in the thread
//#define SERIAL_MAX_RX     256       // Input buffer max size

#define SERIAL_MAX_RX  1024


//#define SERIAL_MAX_TX     256       // output buffer max size

#define SERIAL_MAX_TX     3000



/* -------------------------------------------------------------------- */
/* -----------------------------  Tserial  ---------------------------- */
/* -------------------------------------------------------------------- */
class Tserial_event
{
    // -------------------------------------------------------- //
protected:
    bool          ready;
    bool          check_modem;
    char          port[10];                          // port name "com1",...
    int           rate;                              // baudrate
    int           parityMode;

    HANDLE        serial_events[SERIAL_SIGNAL_NBR];  // events to wait on
    unsigned int  threadid;                          // ...
    HANDLE        serial_handle;                     // ...
    OVERLAPPED    ovReader;                          // Overlapped structure for ReadFile
    OVERLAPPED    ovWriter;                          // Overlapped structure for WriteFile
    OVERLAPPED    ovWaitEvent;                       // Overlapped structure for WaitCommEvent
    char          tx_in_progress;                    // BOOL indicating if a WriteFile is
                                                     // in progress
    char          rx_in_progress;                    // BOOL indicating if a ReadFile is
                                                     // in progress
    char          WaitCommEventInProgress;
    char          rxBuffer[SERIAL_MAX_RX];
    int           max_rx_size;
    int           received_size;
    char          txBuffer[SERIAL_MAX_TX];
    int           tx_size;
    DWORD         dwCommEvent;                       // to store the result of the wait

    type_myCallBack manager;

    // ............................................................
    void          OnCharArrival    (char c);
    void          OnEvent          (unsigned long events);


    // ++++++++++++++++++++++++++++++++++++++++++++++
    // .................. EXTERNAL VIEW .............
    // ++++++++++++++++++++++++++++++++++++++++++++++
public:
    void          run          (void);
                  Tserial_event();
                 ~Tserial_event();
    int           connect          (char *port, int rate, int parity,
                                    char ByteSize, bool modem_events);

    void          setManager       (type_myCallBack manager);
    void          setRxSize        (int size);
    void          sendData         (char *buffer, int size);
    int           getNbrOfBytes    (void);
    int           getDataInSize    (void);
    char *        getDataInBuffer  (void);
    void          dataHasBeenRead  (void);
    void          disconnect       (void);
};
/* -------------------------------------------------------------------- */

/*mangal */


#endif TSERIAL_EVENT_H




0
 
LVL 4

Expert Comment

by:havman56
ID: 7164099
Tserial . h  file


#ifndef TSERIAL_H
#define TSERIAL_H

#include <stdio.h>
#include <windows.h>


enum serial_parity  { spNONE,    spODD, spEVEN };


/* -------------------------------------------------------------------- */
/* -----------------------------  Tserial  ---------------------------- */
/* -------------------------------------------------------------------- */
class Tserial
{
    // -------------------------------------------------------- //
protected:
    char              port[10];                      // port name "com1",...
    int               rate;                          // baudrate
    serial_parity     parityMode;
    HANDLE            serial_handle;                 // ...

    // ++++++++++++++++++++++++++++++++++++++++++++++
    // .................. EXTERNAL VIEW .............
    // ++++++++++++++++++++++++++++++++++++++++++++++
public:
                  Tserial();
                 ~Tserial();
    int           connect          (char *port_arg, int rate_arg,
                                    serial_parity parity_arg);
    void          sendChar         (char c);
    void          sendArray        (char *buffer, int len);
    char          getChar          (void);
    int           getArray         (char *buffer, int len);
    int           getNbrOfBytes    (void);
    void          disconnect       (void);
};
/* -------------------------------------------------------------------- */

#endif TSERIAL_H


0
 
LVL 4

Expert Comment

by:havman56
ID: 7164105
when u ahve max232 IC chip or reciving end ( board end)then it doesnot matter what OS u r uisng on PC.
0
 

Author Comment

by:axia
ID: 7164153
that's what i thought. I tested your code and it does the exact same thing as mine did. It sends data to a modem but not my device.
0
 
LVL 4

Expert Comment

by:havman56
ID: 7164185
what is ur device?
 whther u have written serial comm program on reciving side using UART.

u need to write program on board side to recive it...

do u need to know the procedure of writing serial comm program on board side?

0
 

Author Comment

by:axia
ID: 7168448
All I need is to get this working on XP. It works on 9x and 2K. Other software can communicate with it on XP. I just need to know what I am doing wrong.
0
 
LVL 11

Expert Comment

by:griessh
ID: 7260211
Dear axia

I think you forgot this question. I will ask Community Support to close it unless you finalize it within 7 days. You can always request to keep this question open. But remember, experts can only help you if you provide feedback to their questions.
Unless there is objection or further activity,  I will suggest to

     "refund the points and delete this question"

since nobody had a satisfying answer for you.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
======
Werner
0
 
LVL 49

Expert Comment

by:DanRollins
ID: 7260966
griessh, I try not to be picky but jkr's link is the best one I've seen on serial communications and havman56 provided some useful code in this thread -- I'd hate to delete it all.  

Can we save this as a 0-pt PAQ?
-- Dan
0
 
LVL 11

Expert Comment

by:griessh
ID: 7261223
Dan

That was late in the evening ... I posted the wrong comment. Actually I have the URL on my own list to be saved. So

"refund and PAQ"

would be the recommendation ...

Thanks for catching this one.

======
Werner
0
 
LVL 6

Accepted Solution

by:
Mindphaser earned 0 total points
ID: 7332856
Points refunded and moved to PAQ

** Mindphaser - Community Support Moderator **
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Workplace bullying has increased with the use of email and social media. Retain evidence of this with email archiving to protect your employees.
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
Video by: Tony
This video teaches viewers how to export a project from Adobe Premiere Pro and the various file types involved.
The viewer will learn how to successfully create a multiboot device using the SARDU utility on Windows 7. Start the SARDU utility: Change the image directory to wherever you store your ISOs, this will prevent you from having 2 copies of an ISO wit…

760 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

22 Experts available now in Live!

Get 1:1 Help Now