我的arduino是Mega2560。我在计算机上用C++,用winAPI串口函数编了一个程序,用来和Mega2560通信。通信通过USB内的虚拟串口进行。这个串口在我的计算机上显示是com5。
调试过程中发现,上位机程序和单片机是可以通信,但是有一个前提,就是每次单片机上电以后,我必须在计算机上启动arduino IDE里边的串口监视器,然后再关闭它,然后我的上位机程序才能够和单片机通信。如果我不事先启动串口监视器,看起来上位机程序可以向单片机发数据(2560的RX灯会闪),但是单片机不向计算机发送数据(tx灯不闪,计算机程序也等不到数据)。不知是否有前辈曾经有过类似的经历?这一般是怎么回事?
附上计算机上的相关源码:
HANDLE hCom;
hCom=CreateFile(Edit3 -> Text.c_str(),
GENERIC_READ|GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
0,
NULL
);
if(hCom==(HANDLE)-1)
{
Edit3 -> Text = "打开串口失败";
return;
}
SetupComm(hCom,64,64);
COMMTIMEOUTS TimeOuts;
TimeOuts.ReadIntervalTimeout=2;
TimeOuts.ReadTotalTimeoutMultiplier=50;
TimeOuts.ReadTotalTimeoutConstant=100;
TimeOuts.WriteTotalTimeoutMultiplier=500;
TimeOuts.WriteTotalTimeoutConstant=1000;
SetCommTimeouts(hCom,&TimeOuts);
DCB dcb;
GetCommState(hCom,&dcb);
dcb.BaudRate = CBR_115200;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
dcb.fParity = FALSE;
SetCommState(hCom,&dcb);
PurgeComm(hCom,PURGE_TXCLEAR|PURGE_RXCLEAR);
Sleep(1000); //wait at least900ms to wait MCU to ready
complex Ring[200];
int R,I,tmp1,tmp2,tmp3,tmp4;
char lpOutBuffer[]="1200 1328 0 7 0 r";
char str[64];
// int i=0;
for(int i=0;i<5;i++)
{
DWORD dwBytesWrite=20;
COMSTAT ComStat;
DWORD dwErrorFlags;
ClearCommError(hCom,&dwErrorFlags,&ComStat);
WriteFile(hCom,lpOutBuffer,dwBytesWrite,&dwBytesWrite,NULL);
Sleep(50);
DWORD wCount;
ReadFile(hCom,str,64,&wCount,NULL);
Label6 -> Caption = str;
sscanf(str,"%d %d %d %d %d %d",&R,&I,&tmp1,&tmp2,&tmp3,&tmp4);
Ring[i].R=(float)R/16.0;
Ring[i].I=(float)I/16.0;
}
CloseHandle(hCom); //handle to object to close