用c#的serpoet类与51单片机通信 为什么收到的数据是错误的。
下位机代码#include
#include
#define uchar unsigned char
#define uint unsigned int
uint flag;
uchar a;
char receve[5],i=0;
uint num;
float angle;
char table[10]="0123456789";
sbit led=P2^0;
void chuankouinit()
{
TMOD=0x20;
TH1=0xfd;
TL1=0Xfd;
TR1=1;
REN=1;
SM0=1;
SM1=1;
EA=1;
ES=1;
}
/*---------------------------------------------------------------
主函数
----------------------------------------------------------------*/
void display(uint a,float b)
{
uint c;
uchar d;
d=' ' ;
c=(int)b;
LcdWriteData(table[a/10]); //lcd1602显示收到的第一个数 2位
delayms(5);
LcdWriteData(table[a%10]);
delayms(5);
LcdWriteData(d);
LcdWriteData(table[c/100]); //lcd1602显示收到的第2个数 3位
delayms(5);
c%=100;
LcdWriteData(table[c/10]);
delayms(5);
LcdWriteData(table[c%10]);
delayms(5);
}
void datareceive()
{
int j;
if(flag==1)
{
led=0;
flag=0;
angle=receve[0]; //第一个数
num=receve[1]; //第二个数
LcdWriteCom(0x80);
display(num,angle); //LCD显示
for(j=0;j<5;j++)
{
receve[j]=0;
}
}
}
void main()
{
chuankouinit();
LcdInit();
I2Cinit();
begin();
setPWMFreq();
setPWM(0,0, 0) ;
while(1)
{
datareceive();
}
}
void ser() interrupt 4
{
RI=0;
receve[i]=SBUF;
i++;
if(i==2)
{
i=0;
flag=1;
}
}
上位机代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
using System.Threading;
namespace 串口App1
{
public class PortChat
{
static SerialPort _serialPort;
public static void Main()
{
byte[] b = new byte[2];
b[0] = 100;
b[1] = 200;
Console.Write("b[1] {0}", b[1]);
// Create a new SerialPort object with default settings.
_serialPort = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
// Set the read/write timeouts
_serialPort.ReadTimeout = 500;
_serialPort.WriteTimeout = 500;
_serialPort.Open();
_serialPort.Write(b,0,2);
Console.Write(" message已发送 ");
_serialPort.Close();
Console.ReadKey();
}
}
}