各位大虾,最近我在做个单片机与PC机通信,用VB作上位机,然后想让上位机发送16个字节的字符串到51上,再从51发回PC机,操作如下:
上位机
 rivate Sub Command1_Click() //发送字符Dim pp As Variant, a As Variant, Cstring() As Variant, i As Variant, j As Variant
If Timer1.Enabled = True Then Timer1.Interval = Val(text_dingshi.Text)
If text_send = "" Then pp = MsgBox("发送字符区不为空!", vbCritical)
If MSComm1.PortOpen = False Then
pp = MsgBox("串口没有打开!", vbCritical)
Exit Sub
End If
a = Len(text_send.Text)
ReDim Cstring(a)
For i = 0 To a
Cstring(i) = Mid(text_send.Text, i + 1, 1)
Next
For j = 0 To a
MSComm1.Output = Cstring(j)
Sleep 20
Next
End Sub
下位机 //波特率9600
unsigned char getptr,putptr,buf[16]; //开辟16个字节的缓冲区,一个取数指针一个存数指针
void USART_Interrupt() interrupt 4
{
if(RI)
{
RI=0;
buf[putptr]=SBUF;
putptr++;
}
void main()
{
unsigned char i,mydat[16],j;
USART_INit();
getptr=0;
putptr=0;
while(1)
{
if(getptr!=putptr) //两个指针不同证明存数多余取数,可以取数
{
mydat=buf[getptr];
getptr++;
i++;
i%=8;
if(i==0)
{
for(j=0;j<16;j++)
{
send_byte(mydat[j]);
}
}
}
}
}
但问题出现了,我在调试的时候有时候能接收到正确数据,有时候却数据的顺序倒换了,例如我输入“12345678”,接收时却会出现“78123456”,“56781234”这些情况,敢问大虾门这是什么原因造成的呢,有什么办法解决呢
|