我是一位在校的学生,在编写串口程序时遇到些问题,半个月也没有解决,希望大家帮助解决一下。 问题是这样: 我要做一个pda与单片机的串口通信,pda部分是在visual studio 2005 的vb中写的,已经可以用串口调试助手于pc进行通信。 程序如下: Public Class Form1 Dim F As Long, T As Long, First As Long, TH0 As Byte, TL0 As Byte, i As Integer Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'SerialPort.CommPort = 1 'SerialPort.PortOpen = True 'SerialPort.Settings = "9600,N,8,1"
With SerialPort .PortName = "COM1" .BaudRate = 9600 .DataBits = 8 .StopBits = IO.Ports.StopBits.One .Parity = IO.Ports.Parity.None '.ReadTimeout = 1000 End With End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
F = Val(TextSend.Text) '确定发射频率 T = 11059200 \ (24 * F) '计算定时器定时时间 First = &HFFFF - T '计算定时器初值 TL0 = &HFF And First '计算定时器初值低八位 TH0 = (First - TL0) / &H100 '计算定时器初值高八位 Dim TH0Hex Dim TL0Hex
TH0Hex = Hex(TH0) ' 返回
TL0Hex = Hex(TL0) ' 返回
'SerialPort.PortName = 1 SerialPort.Open() '打开串口 'SerialPort.BaudRate = "9600" 'SerialPort.Parity = SerialPort.Parity.None 'SerialPort.Open() 'SerialPort.WriteLineTextSend.Text) SerialPort.Write(Val(TH0Hex)) '发送定时器初值高八位 TextBox2.Text = TH0Hex SerialPort.Close() '关闭串口 Dim i As Integer For i = 0 To 10000000 Next i SerialPort.Open() '打开串口 SerialPort.Write(Val(TL0Hex)) '发送定时器初值低八位 TextBox2.Text = TL0Hex 'SerialPort.WriteLine(TextSend.Text) SerialPort.Close() '关闭串口
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click Application.Exit() End Sub End Class 单片机部分就是要把接受到的高低八位给定时器,然后产生方波。用串口调试助手给单片机发数,已经可以工作程序如下: #include <howevero.h>
//逻辑 #define FALSE 0 #define TRUE 1 #define H 1 #define L 0
//管脚定义 sbit std_cnt2 = p1^2; sbit std_cnt1 = p0^1; sbit std_cnt0 = p0^0; sbit std_cnt3 = p0^3;
//函数声明 void serial_init(void);//串口初始化 void serial_send(void);
//全局变量声明 unsigned int idata send_letter; //unsigned long data tempnumber=0; unsigned char numberhigh,numberlow; int i=0; unsigned int data temp;
/************ 主函数**************************/ void main(void) { SP=0x60; // interupt_init(); serial_init(); std_cnt0=0; std_cnt1=0; std_cnt2=0; std_cnt3=0;
while(i==0);//等待中断
/*发射波形*/ TH0=numberhigh; TL0=numberlow; TF0=0; TR0=1; while(1) { while(TF0==0); TH0=numberhigh; TL0=numberlow; std_cnt3=!std_cnt3; TF0=0; TR0=1; }
}
/************ 串口初始化?*************************/ void serial_init() { SCON=0x50; //工作方式1,单机通讯,接收允许 TMOD=0x21; //方式1下波特率由SMOD和定时器1共同决定,定时器一工作在方式2下 TR0=0; // PCON=0x00; //PCON=0x00速度不加倍 TH1=0xFD; TL1=0xFD; //计数初值,晶振11.0592M,波特率9600, TR1=1; //启动定时器 ET0=0; EX0=1; ES=1; EA=1; EX1=0; PS=1; }
/************ 串口中断函数**************************/ void serial_receive(void) interrupt 4 using 1 {
RI=0; std_cnt3=0; //输出低电平(未发射方波时) for(temp=0;temp<2;temp++) //连续接收2个字节 { switch(temp) { case 0:numberhigh=SBUF;while(RI==0);RI=0;break;//给出定时器初值高八位,并等待下个串行中断 case 1:numberlow=SBUF;break; //给出定时器初值低八位,准备跳出中断 default:break; } }
RI=0; i++; } 可是,把pda与单片机连接到一起时,不管pda串口发什么频率数,单片机的频率是一定的,我半个多月都没想明白,希望高手帮忙指点一下! |