CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: RS-232 Problem

  1. #1
    Join Date
    Mar 2002
    Posts
    9

    Question RS-232 Problem

    Hey!

    I have a little problem. I need to read and write to serial port but i'm doing something wrong in port initialization (setting up baudrate etc.)??? because after that SetCommState(...) function returns error. Can anyone help me?

    Here's my code:

    HANDLE hPort;
    DCB dcbPort;
    BOOL b_State;
    DWORD dwError;

    hPort = CreateFile("COM1",GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL ); //Opening serial port

    b_State = GetCommState(hPort,&dcbPort);
    if(!b_State)
    {
    dwError = GetLastError();
    CloseHandle(hPort);
    return 0;
    }
    else
    {

    dcbPort.DCBlength = sizeof(DCB);
    dcbPort.BaudRate = CBR_9600; // Baudrate
    dcbPort.ByteSize = 8; // Size of one byte data
    dcbPort.Parity = NOPARITY; // Parity-control
    dcbPort.StopBits = 1; // Stopbits
    }

    b_State = SetCommState(hPort,&dcbPort); //This returns false
    if(!b_State)
    {
    dwError = GetLastError(); //Error number is 87
    MessageBox(NULL,"Not working","!!!!",MB_OK);
    CloseHandle(hPort);
    return 0;
    }

    while(m_bListenThreadContinue)
    {

    }

    CloseHandle(hPort);

  2. #2
    Join Date
    Jun 2002
    Location
    Letchworth, UK
    Posts
    1,020
    It is probably the FILE_ATTRIBUTE_NORMAL which is throwing it. FILE_ATTRIBUTE_NORMAL should not be specified with any other flags. Try removing FILE_ATTRIBUTE_NORMAL.
    Succinct is verbose for terse

  3. #3
    Join Date
    Jan 2000
    Location
    Belgium
    Posts
    24
    you can use serial.cpp and serial.h from

    http://www.codeguru.com/network/serial.shtml

    this article and samples are contributed by Tom Archer and Rick Leinecker. The serial communication became very easy by using this class. take a look you 'll be very satisfied


    [URL=http://www.codeguru.com/network/serial.shtml]

  4. #4
    Join Date
    Aug 2001
    Posts
    77

    Smile Eureka!

    I fought this same problem for two days, and I can tell you what I found was my problem. Setting the dcbPort.StopBits value to '1' is apparently a bad value. Use the literal value ONESTOPBIT instead. That fixed it for me!

    I realize that this post is about two years too late for the original questioner, but hopefully this will help someone else later!

    JESUS REIGNS!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured