与串口通信

时间:2016-02-21 12:26:54

标签: visual-c++ serial-port serial-communication createfile

我正在尝试与visual studio 2012中的“COM4”串口进行通信。

#include "Header.h"
#include <Windows.h>
#include <string.h>
#include <stdio.h>
#include <conio.h>
#include <string>
#include <iostream>

void system_error(char *name) {
// Retrieve, format, and print out a message from the last error.  The 
// `name' that's passed should be in the form of a present tense noun 
// (phrase) such as "opening file".
//
    char *ptr = NULL;
    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM,
        0,
        GetLastError(),
        0,
        (char *)&ptr,
        1024,
        NULL);

    fprintf(stderr, "\nError %s: %s\n", name, ptr);
    LocalFree(ptr);
}

void main()
{
    HANDLE serialHandle;


serialHandle = CreateFile("\\\\.\\COM4", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);


// Do some basic settings
DCB serialParams = { 0 };
serialParams.DCBlength = sizeof(serialParams);


if (!GetCommState(serialHandle, &serialParams))
    system_error("Get COM State.");
serialParams.BaudRate = CBR_115200;
serialParams.ByteSize = DATABITS_8;
serialParams.StopBits = ONESTOPBIT;
serialParams.Parity = NOPARITY;

if (!SetCommState(serialHandle, &serialParams))
    system_error("Set COM State.");

// Set timeouts

// set short timeouts on the comm port.
COMMTIMEOUTS timeout = { 0 };
timeout.ReadIntervalTimeout = 1;
timeout.ReadTotalTimeoutMultiplier = 1;
timeout.ReadTotalTimeoutConstant = 1;
timeout.WriteTotalTimeoutMultiplier = 1;
timeout.WriteTotalTimeoutConstant = 1;
if (!SetCommTimeouts(serialHandle, &timeout))
    system_error("setting port time-outs.");

DWORD dwBytesWritten;
char data = 165;

if ( !WriteFile(serialHandle, &data, (DWORD) sizeof(data), &dwBytesWritten, NULL))
        system_error("writing data to port");

    if (dwBytesWritten != sizeof(data))
        system_error("not all data written to port");
data = 00;
int isWritten = WriteFile(serialHandle, &data, (DWORD) sizeof(data), &dwBytesWritten, NULL);
data = 165;
isWritten = WriteFile(serialHandle, &data, (DWORD) sizeof(data), &dwBytesWritten, NULL);

CloseHandle(serialHandle);
}

我正在尝试此代码并在使用system_error函数检查错误的所有行中收到错误。 serialHandle始终为“0xffff”,即INVALID_HANDLE。我也试过关闭UINICOCE字符。

任何建议?

0 个答案:

没有答案