VC++ 如何開啟RS232通訊埠

請問大大我以前是用VB來製做通訊程式

納在VC中該如何製作

以VB的寫法來看

DATA = "@00" + "WR" + "0000" + "00" + "00"

fcsx$ = fcs$(DATA)

SXD = DATA + fcsx$ + "*" + Chr$(13)

MSComm1.PortOpen = True

MSComm1.Output = SXD

MSComm1.PortOpen = False

那在VC++要如何寫呢??

1 Answer

Rating
  • 1 decade ago
    Favorite Answer

    這是Microsoft提供的範例, 參考看看,

    如要更詳細, 請看Microsoft的MSDN

    /* A sample program to illustrate setting up a serial port. */

    #include <windows.h>

    int

    main(int argc, char *argv[])

    {

    DCB dcb;

    HANDLE hCom;

    BOOL fSuccess;

    char *pcCommPort = "COM2";

    hCom = CreateFile( pcCommPort,

    GENERIC_READ | GENERIC_WRITE,

    0, // comm devices must be opened w/exclusive-access

    NULL, // no security attributes

    OPEN_EXISTING, // comm devices must use OPEN_EXISTING

    0, // not overlapped I/O

    NULL // hTemplate must be NULL for comm devices

    );

    if (hCom == INVALID_HANDLE_VALUE) {

    // Handle the error.

    printf ("CreateFile failed with error %d.\n", GetLastError());

    return (1);

    }

    // We will build on the current configuration, and skip setting the size

    // of the input and output buffers with SetupComm.

    fSuccess = GetCommState(hCom, &dcb);

    if (!fSuccess) {

    // Handle the error.

    printf ("GetCommState failed with error %d.\n", GetLastError());

    return (2);

    }

    // Fill in the DCB: baud=57,600 bps, 8 data bits, no parity, and 1 stop bit.

    dcb.BaudRate = CBR_57600; // set the baud rate

    dcb.ByteSize = 8; // data size, xmit, and rcv

    dcb.Parity = NOPARITY; // no parity bit

    dcb.StopBits = ONESTOPBIT; // one stop bit

    fSuccess = SetCommState(hCom, &dcb);

    if (!fSuccess) {

    // Handle the error.

    printf ("SetCommState failed with error %d.\n", GetLastError());

    return (3);

    }

    printf ("Serial port %s successfully reconfigured.\n", pcCommPort);

    return (0);

    }

    設定好COM port的參數以後, 直接對hCom這個Handle寫資料就可以了. 用 WriteFile( hCom, ....)

Still have questions? Get your answers by asking now.