//#include "pch.h"
#define _CRT_SECURE_NO_WARNINGS
//#include <iostream>
#include <stdio.h>
#include <windows.h>
#include <string.h>
#include <conio.h>
#include "tchar.h"
void main()
{
/*****************************打開串口***********************************/
HANDLE hCom;//全域變數,串口句柄
COMMTIMEOUTS TimeOuts;
DCB dcb;
DWORD dwWriteLen = 0;
int i;
// DWORD dwWriteLen = 0;
int data_in;
unsigned char sendData[8];//寫入串口快取區的資料
//int error = GetLastError();
hCom = CreateFile("COM4",
GENERIC_READ | GENERIC_WRITE,//讀寫
0,//獨占方式
NULL,
OPEN_EXISTING,
0,//同步方式
//FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERAPPLE,//重疊方式
NULL);
if (hCom==INVALID_HANDLE_VALUE )
{
printf("send open failed");
// printf("CreateFile() error:%d", GetLastError());
}
else
{
printf("send open successed\n");
}
/**************配置串口************/
// SetupComm(hCom, 20480, 20480);//緩沖區
// COMMTIMEOUTS TimeOuts;
TimeOuts.ReadIntervalTimeout = 1000;//讀超時
TimeOuts.ReadTotalTimeoutMultiplier = 500;
TimeOuts.ReadTotalTimeoutConstant = 5000;
TimeOuts.WriteTotalTimeoutMultiplier = 500;//寫超時
TimeOuts.WriteTotalTimeoutConstant = 2000;
SetCommTimeouts(hCom, &TimeOuts);//設定超時
//DCB dcb;
GetCommState(hCom, &dcb);
dcb.BaudRate = 115200;//波特率115200
dcb.ByteSize = 8;//8bit/byte
dcb.Parity = NOPARITY;//無奇偶校驗位
dcb.StopBits = ONESTOPBIT;//一個停止位
dcb.fParity = FALSE;
dcb.fNull = FALSE;
SetCommState(hCom, &dcb);
PurgeComm(hCom, PURGE_TXCLEAR|PURGE_RXCLEAR);//讀寫串口前清慷訓沖區
/*******同步讀寫串口********/
scanf("%x",&data_in);
for(i=0;i<8;i++)
{
sendData[i]=(data_in&0x00000080) && 1;//拆
data_in=data_in<<1;
}
if(!WriteFile(hCom,sendData,1,&dwWriteLen, NULL))
{
printf("send failed\n");
//GetLastError();
//return 0;
//printf("%d",&error);
}
else
{ printf("send successed\n");
printf("send data is\n");
for(i=0; i<8; i++)
{
printf("%01X ", sendData[i]);
}
// return 1;
}
//system("PAUSE");
/***********關閉串口***********/
CloseHandle(hCom);
//GetLastError();
system("pause");
}
用串口監聽精靈發現不管發送什么資料,寫入的要么是00,要么是01。
用串口助手能實作正確收發,因此問題出現在我的程式。不知道是哪里出現錯誤。
謝謝各位。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/210202.html
標籤:驅動開發/核心開發
下一篇:測驗題15(答案詳析)
