C# 串口中断中接收缓冲区会在下次进入时突然变成几百个数据(断点调试看到的),按理说请求一次数据只会接收到19个字节的,请求数据放在一个100ms的定时器里进行
上位机程序:
public void port_DataRecived(object sender, SerialDataReceivedEventArgs e)
{
byte[] r = new byte[serialPort1.BytesToRead];
if (r.Length != 0){
serialPort1.Read(r, 0, r.Length);
PortReceivedList.AddRange(r);
}
while (true){
if (PortReceivedList.Count>19){
if (PortReceivedList[0] == 0x66 && PortReceivedList[1] == 0x66 && PortReceivedList[2] == 0x66){
int CalculateCRC = 0;
int CRC = ((int)PortReceivedList[17] << 8) | PortReceivedList[18];
for (int i = 3; i<17; i++) {
CalculateCRC += PortReceivedList[i];
}
if (CRC == CalculateCRC){
int ID = PortReceivedList[3];
O_DY[ID] = (ushort)(((ushort)(PortReceivedList[5] & 0x0f) << 8) | PortReceivedList[6]);
O_DL[ID] = (ushort)(((ushort)(PortReceivedList[7] & 0x0f) << 8) | PortReceivedList[8]);
DCDY[ID] = (ushort)(((ushort)(PortReceivedList[9] & 0x0f) << 8) | PortReceivedList[10]);
DCDL[ID] = (ushort)(((ushort)(PortReceivedList[11] & 0x0f) << 8) | PortReceivedList[12]);
SDDY[ID] = (ushort)(((ushort)(PortReceivedList[13] & 0x0f) << 8) | PortReceivedList[14]);
SDDL[ID] = (ushort)(((ushort)(PortReceivedList[15] & 0x0f) << 8) | PortReceivedList[16]);
SD[ID] = ((PortReceivedList[4] & 0x01) == 0) ? false : true;
YJ[ID] = ((PortReceivedList[4] & 0x02) == 0) ? false : true;
GZ[ID] = ((PortReceivedList[4] & 0x04) == 0) ? false : true;
myPan();
PortReceivedList.RemoveRange(0, 19);
Interac
tiveSuccessful[nowMachine] = true;
}else{
//SendCmd(LastCmd[nowMachine], nowMachine);
InteractiveSuccessful[nowMachine] = false;
}
}else{
PortReceivedList.RemoveRange(0,1);
}
}else{
break;
}
}
}
下位机程序:
void USART1_IRQHandler(void)
{
if (USART_GetFlagStatus(USART1, USART_FLAG_ORE) != RESET){
USART_ReceiveData(USART1);
}
if (USART_GetITStatus(USART1, USART_IT_RXNE) != RESET){
static u8 DataCount = 0;
r[DataCount] = USART_ReceiveData(USART1);
if(r[0] != 0x99){
DataCount = 0;
}else{
if( DataCount==1 && r[1]!=0x99 ){
DataCount = 0;
}
}
if(++DataCount>=5){
DataCount = 0;
if(r[0]==0x99 && r[1]==0x99){
u8 CalculateCRC = (r[2]+r[3])/2.0+0.5;
u8 Cmd = r[3];
if(CalculateCRC == r[4]){
if(r[2]==ID){
u16 Crc = 0,i;
if(Cmd&0x02){ ForceStop = 1; }else{ ForceStop = 0; }
if(Cmd&0x04){ ForceStart = 1; }else{ ForceStart = 0; }
txBuffer[4]++;
txBuffer[5] = O_DY>>8;
txBuffer[6] = O_DY&0xff;
txBuffer[7] = O_DL>>8;
txBuffer[8] = O_DL&0xff;
txBuffer[9] = DCDY>>8;
txBuffer[10] = DCDY&0xff;
txBuffer[11] = DCDL>>8;
txBuffer[12] = DCDL&0xff;
txBuffer[13] = SDDY>>8;
txBuffer[14] = SDDY&0xff;
txBuffer[15] = SDDL>>8;
txBuffer[16] = SDDL&0xff;
for(i=3;i<17;i++){
Crc += txBuffer[i];
}
txBuffer[17] = Crc>>8;
txBuffer[18] = Crc&0xff;
SendDatas();
}
}
}
}
}
USART_ClearITPendingBit(USART1, USART_IT_RXNE);
}
上位机发送格式:0x99 0x99 ID Cmd CRC(=(byte)(ID+Cmd)/2.0+0.5)
下位机发送格式:0x66 0x66 0x66 ID State(状态标志) Datas(数据12个) CRCh CRCl