Solved

Sending Data to the Serial Port

Posted on 2002-06-09
12
907 Views
Last Modified: 2013-12-14
have to computers hooked together thru a wire directly.  I am using MSVC++ 6.0 on a Win ME system.
 The problem is that the data will not write to the comm port.  I am trying to send a binary file thru
the comm port.  Here is my code:

// igisru.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <conio.h>
#include "igisru.h"
#include "Serial.h"
#include <fstream.h>
#include <fcntl.h>
#include <io.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// The one and only application object

CWinApp theApp;

using namespace std;

enum { EOF_Char = 27 };

int ShowError (LONG lError, LPCTSTR lptszMessage)
{
   // Generate a message text
   TCHAR tszMessage[256];
   wsprintf(tszMessage,_T("%s\n(error code %d)"), lptszMessage, lError);

   // Display message-box and return with an error-code
   ::MessageBox(0,tszMessage,_T("Listener"), MB_ICONSTOP|MB_OK);
   return 1;
}

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
   int nRetCode = 0;

   CFile sru, sru1;

   CSerial serial;
       
   // initialize MFC and print and error on failure

        LONG    lLastError = ERROR_SUCCESS;
       
        // Attempt to open the serial port (COM1)
        lLastError = serial.Open(_T("COM1"));
        if (lLastError != ERROR_SUCCESS)
             return ::ShowError(serial.GetLastError(), _T("Unable to open COM-port"));
       
        // Setup the serial port (9600,8N1, which is the default setting)
        lLastError = serial.Setup(CSerial::EBaud19200,CSerial::EData8,CSerial::EParNone,CSerial::EStop1);
       
        if (lLastError != ERROR_SUCCESS)
             return ::ShowError(serial.GetLastError(), _T("Unable to set COM-port setting"));
       
        // Setup handshaking (default is no handshaking)
        lLastError = serial.SetupHandshaking(CSerial::EHandshakeOff);
        if (lLastError != ERROR_SUCCESS)
             return ::ShowError(serial.GetLastError(), _T("Unable to set COM-port handshaking"));
       
//          lLastError = serial.SetupReadTimeouts(CSerial::EReadTimeoutNonblocking);
//          if (lLastError != ERROR_SUCCESS)
//               return ::ShowError(serial.GetLastError(), _T("Unable to set COM-port read timeout."));
       
        // Keep reading data, until an EOF (CTRL-Z) has been received
//          bool fContinue = true;
       
        CString m_infile, msg;
        BYTE readbin[93];

        m_infile = "d:\\_testdata\\aven1.bin";
        m_infile = "aven1.bin";
       
        if (!sru.Open(m_infile, CFile::modeRead| CFile::typeBinary) )
        {
             msg = "Could not open ";
             msg += m_infile;
             msg += " for reading.  Please check filename.";
             printf("%s \n\n", msg);
             return (0);
             
        } // end of      if (!logfile.Open(m_infile, CFile::typeText | CFile::modeRead | CFile::shareDenyWrite))

        printf("\n\n\t\tWorking, Sending data to the comm port!!!\n\n");
        printf("Press ctrl c to stop sending.....\n\n\n");
        DWORD readbytes = sru.GetLength();
        long xx = 0L;

        while (readbytes)
        {

             //read data from file
             UINT x = 0;
             x = sru.Read((char *) &readbin, sizeof(readbin));
             readbytes -= x;

             printf("%s", readbin);
             
             // write data to comm port
             xx = serial.Write(&readbin, sizeof(readbin));

             Sleep(94);

             xx=0;

        } // end of while (sru)

  // Close the file and serial port
  serial.Close();
   sru.Close();

   printf("\n\nEnd of File....\n\n");
   
   return nRetCode;
}
0
Comment
Question by:adatd
  • 5
  • 2
  • 2
  • +3
12 Comments
 
LVL 8

Expert Comment

by:fl0yd
ID: 7065445
| The problem is that the data will not write to the comm port.

And what exactly is the problem? Please, guys, if you have a question provide at least the most basic information. Does it raise an error? What is the return value? Does your application crash altogether? Are you sure you can't write or do you assume you can't since you don't receive anything at the other machine?

.f
0
 

Author Comment

by:adatd
ID: 7065826
I'm sorry.....

When I run the program it does not send any data to the comm port.
0
 
LVL 8

Expert Comment

by:fl0yd
ID: 7065920
That's exactly what you said before -- please be a bit more specific. If you don't know what 'specific' means go through the list of questions in my previous comment and use them as an inspiration.

One thing that certainly is wrong is your 't_main'-function which isn't standard-conforming, if that is supposed to be your application entry point. You will have to rename it to 'main' and changing the argument list to '( int argc, char* argv[] )' is probably a good idea although not mandatory.
0
 
LVL 4

Expert Comment

by:havman56
ID: 7066665
adatd

i am having a serial programm use it !!!
if it is helpful.but i aldready posted the answer in some thread i forgot the thread id.


0
 
LVL 4

Expert Comment

by:havman56
ID: 7066667
it is working fine for me..

-- ------------------------------------------------------------------------ --
--                                                                          --
--    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: 7066671
testing the serial program

/* ---------------------------------------------------------------------- */
#ifdef __BORLANDC__
#pragma hdrstop             // borland specific
#include <condefs.h>
#pragma argsused
USEUNIT("Tserial_event.cpp");
//---------------------------------------------------------------------------
#endif

//---------------------------------------------------------------------------
#include "conio.h"
#include "Tserial_event.h"
#include "TestMsg.h"

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




/* ======================================================== */
/* ===============  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;
      int size;

    //Testmsg(); /* Data in the form of structure */
      //TestBuf(); /* dtaa in the form of buffer */
      InputTestCase() ;/* entry point for test suite */

    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);
                  size=sizeof(sapmsg);

                  com->sendData(buf,sizeof(sapmsg));
                  
             
                  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
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 4

Expert Comment

by:havman56
ID: 7066673
header file here

#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


/* -------------------------------------------------------------------- */
/* -----------------------------  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
 

Expert Comment

by:duncanlatimer
ID: 7066728
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
was presumably supplied by the VC++ wizard when you asked for an application that supports MFC, so I wouldn't change it to main because there is probabbly a main somewhere else and you might break your program.

Is CSerial an part of MFC? I can't find it im my VC++6.0

I have found another CSerial class which looks a bit more simple to use (http://www.codeguru.com/network/serial.shtml) you could always try this one and see if it works any better.
0
 

Author Comment

by:adatd
ID: 7067718
The Problem is that when I write to the serial port I get a return of zero bytes written.  I think that I am using the serial.Write command right.  
0
 

Expert Comment

by:1cand01t
ID: 7072024
use Hyper Terminal to check if u can send data thru COM1 using the wire, this'll confirm that ur COM ports and wire is connected properly.

open hyper terminal on both PCs and select 'COM1' in the 'Connect using' option when the 'Connect To' dialog box appears. then what u type on one PC should appear on the other if it is connected properly.

good luck
0
 
LVL 4

Expert Comment

by:havman56
ID: 7072196
adatd
did u tried my program

it works fine i have tested lot!!
0
 
LVL 3

Accepted Solution

by:
jimbucci earned 300 total points
ID: 7107139
Since the program seems to be working for others, check your cable - make sure it is has pins 2 and 3 swapped.
For a 9 pin connector I think the pin outs are the same.  
Just make sure your TXMT and RECV lines are swapped.
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

The article will include the best Data Recovery Tools along with their Features, Capabilities, and their Download Links. Hope you’ll enjoy it and will choose the one as required by you.
Skype is a P2P (Peer to Peer) instant messaging and VOIP (Voice over IP) service – as well as a whole lot more.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
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…

746 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

13 Experts available now in Live!

Get 1:1 Help Now