求教給為大佬,用windows api撰寫個串口程式,只能正確發送0-127,大于128的系統會去掉第8bit,如發送0x26正常,但是我發送0xA6(大于127了),接收到的還是0x26,請教各位大俠,哪個地方設錯了啊,例子是按照串口通信編程實踐書上寫的,
不勝感激!!
代碼如下:
BOOL bErrorFlag;
BYTE TX_DataBuffer[100];
DWORD dwBytesToTX;
BYTE RX_DataBuffer[101];
DWORD nLenOut;
DWORD dwBytesWritten = 0;
static const int g_nZhenMax = 500;
//設定串口配置資訊
DCB dcb;
COMMTIMEOUTS timeouts;
HANDLE g_hCom = CreateFile("COM3", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0);
if (g_hCom == INVALID_HANDLE_VALUE)
{
printf("ERR!\r\n\r\n");
goto end;
}
//設定串口
dcb.DCBlength = sizeof(DCB);
dcb.BaudRate = 9600;//波特率為9600
dcb.Parity = 0;//校驗方式為無校驗
dcb.ByteSize = 8;//資料位為8位
dcb.StopBits = ONESTOPBIT;//停止位為1位
dcb.fBinary = TRUE;
if (!GetCommState(g_hCom, &dcb))
{
printf("Get COM State Error!!!\r\n\r\n");
goto end;
}
if (!SetCommState(g_hCom, &dcb))
{
printf("Set COM Error!!!\r\n\r\n");
goto end;
}
//設定讀超時
GetCommTimeouts(g_hCom, &timeouts);
timeouts.ReadIntervalTimeout = 0;
timeouts.ReadTotalTimeoutMultiplier = 0;
timeouts.ReadTotalTimeoutConstant = 1000;
timeouts.WriteTotalTimeoutMultiplier = 0;
timeouts.WriteTotalTimeoutConstant = 0;
SetCommTimeouts(g_hCom, &timeouts);
//設定讀寫緩沖區大小
if (!SetupComm(g_hCom, g_nZhenMax, g_nZhenMax))
{
printf("Setup COM Buffer Error!!!\r\n\r\n");
goto end;
}
//清慷訓沖
PurgeComm(g_hCom, PURGE_RXCLEAR|PURGE_TXCLEAR);
//清除錯誤
DWORD dwError;
COMSTAT cs;
if (!ClearCommError(g_hCom, &dwError, &cs))
{
printf("Clear COM Error!!!\r\n\r\n");
goto end;
}
TX_DataBuffer[0]=0xA6;
bErrorFlag = FALSE;
dwBytesToTX = 5;//(DWORD)strlen(TX_DataBuffer);
dwBytesWritten = 0;
bErrorFlag = WriteFile(
g_hCom, // open file handle
TX_DataBuffer, // start of data to write
dwBytesToTX, // number of bytes to write
&dwBytesWritten, // number of bytes that were written
NULL); // no overlapped structure
if (FALSE == bErrorFlag)
{
printf(" send data!!!\r\n\r\n");
return;
}
else
{
if (dwBytesWritten != dwBytesToTX)
{
printf(" written bytes is not right!!!\r\n\r\n");
return;
}
}
//讀取串口資料
memset(RX_DataBuffer, 0, 101);
nLenOut = 0;
if(ReadFile(g_hCom, RX_DataBuffer, 100, &nLenOut, NULL))
{
if(nLenOut)//成功
{
printf("Received data:%2x\r\n\r\n",RX_DataBuffer[0]);
}
else//超時
{
printf("time out!!!\r\n\r\n");
return;
}
}
else
{
//失敗
printf("Read Error!!!\r\n\r\n");
return;
}
uj5u.com熱心網友回復:
用你的程式發送 串口助手接收看看是否正常?用串口助手發送 目標程式接收看看是否正常?
uj5u.com熱心網友回復:
我是把TX、RX短接到一塊的。用串口助手發是正常的,用我自己的發,接收不正常uj5u.com熱心網友回復:
我懷疑是哪個引數沒設好,只能發送0-127,不能發送128-255之間的,網上搜了半天也沒找到相關的情況
uj5u.com熱心網友回復:
將所有char改為unsigned char再試試?
uj5u.com熱心網友回復:
昨晚找到問題了,串口引數設定應放在讀引數之后~
不給還是非常感謝您~
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/125117.html
標籤:基礎類
