C语言 串口通信问题
打开两个串口,COM3和COM4,程序如下:#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <commdlg.h>
#include <windef.h>
int nread,nwrite;
void main()
{
HANDLE hSerial;
COMMTIMEOUTS timeouts;
COMMCONFIG dcbSerialParams;
char *buffRead;
char *buffWrite;
//BYTE data;
DWORD dwBytesWritten, dwBytesRead;
//int k;
_retry:
hSerial = CreateFile("COM4",
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,//FILE_FLAG_OVERLAPPED, // FILE_ATTRIBUTE_NORMAL
NULL);
if ( hSerial == INVALID_HANDLE_VALUE)
{
if (GetLastError() == ERROR_FILE_NOT_FOUND)
{
printf(" serial port does not exist \n");
}
printf(" some other error occured. Inform user.\n");
}
else
printf("port open successed!\n");
//DCB dcbSerialParams ;
//GetCommState( hSerial, &dcbSerialParams.dcb);
if (!GetCommState(hSerial, &dcbSerialParams.dcb))
{
printf("error getting state \n");
}
dcbSerialParams.dcb.DCBlength = sizeof(dcbSerialParams.dcb);
dcbSerialParams.dcb.BaudRate = 9600;
dcbSerialParams.dcb.ByteSize = 8;
dcbSerialParams.dcb.StopBits = TWOSTOPBITS;
dcbSerialParams.dcb.Parity = NOPARITY;
dcbSerialParams.dcb.fBinary = TRUE;
dcbSerialParams.dcb.fDtrControl = DTR_CONTROL_DISABLE;
dcbSerialParams.dcb.fRtsControl = RTS_CONTROL_DISABLE;
dcbSerialParams.dcb.fOutxCtsFlow = FALSE;
dcbSerialParams.dcb.fOutxDsrFlow = FALSE;
dcbSerialParams.dcb.fDsrSensitivity= FALSE;
dcbSerialParams.dcb.fAbortOnError = TRUE;
if (!SetCommState(hSerial, &dcbSerialParams.dcb))
{
printf(" error setting serial port state \n");
}
GetCommTimeouts(hSerial,&timeouts);
//COMMTIMEOUTS timeouts = {0};
timeouts.ReadIntervalTimeout = 50;
timeouts.ReadTotalTimeoutConstant = 50;
timeouts.ReadTotalTimeoutMultiplier = 10;
timeouts.WriteTotalTimeoutConstant = 50;
timeouts.WriteTotalTimeoutMultiplier= 10;
if(!SetCommTimeouts(hSerial, &timeouts))
{
printf("error setting port state \n");
}
//****************Write Operation*********************//
buffWrite=(char *)malloc(256);
printf("please input your data:");
scanf("%s",buffWrite);
nwrite=255;
//nwrite =1024;
//dwBytesWritten = 0;
if (!WriteFile(hSerial, buffWrite, nwrite, &dwBytesWritten, NULL))
{
printf("error writing to output buffer \n");
}
else
printf("written data:%s\n",buffWrite);
system("pause");
//***************Read Operation******************//
//buffRead=0;
//buffRead = (char *)malloc(256);
SetFilePointer(hSerial, 0, 0, FILE_BEGIN);
nread = GetFileSize(hSerial,NULL);
buffRead = (char *)malloc(nread+1);
//memset(buffRead, 0, 1024);
if (!ReadFile(hSerial,buffRead,nread, &dwBytesRead, NULL))
{
printf("error reading from input buffer \n");
}
else
printf("Data read from read buffer is:%s\n\n",buffRead);
CloseHandle(hSerial);
Sleep(2000);
goto _retry;
}
到Writefile为止都可以运行,但是在Readfile这一块"Data read from read buffer is:"后面不能读取数据,显示的都是乱码,该如何解决呢?