在 Delphi 中使用串口控件 MSComm 的 0 字符接收例程祥解
//以下是创建窗体时的 MSCOMM 参数设置过程 //MSComm1.InputMode := comInputModeBinary; //和 MSComm1.InputMode := comInputModeText; //实验结果基本对 Delghi 不太起作用
procedure TForm1.FormCreate(Sender: TObject); var str: string; begin //MSCOMM 参数设置 MSComm1.CommPort := 1;//使用 COM1 MSComm1.Settings := ''9600,N,8,1'';//设置通信口参数 MSComm1.InBufferSize := 32;//设置 MSComm1 接收缓冲区为 32 字节 MSComm1.OutBufferSize := 2;//设置 MSComm1 发送缓冲区为 2 字节 MSComm1.InputMode := comInputModeBinary;//设置接收数据模式为二进制形 式 MSComm1.InputLen := 1;//设置 Input 一次从接收缓冲读取字节数为 1 MSComm1.SThreshold := 1;//设置 Output 一次从发送缓冲读取字节数为 1 MSComm1.InBufferCount := 0;//清除接收缓冲区 MSComm1.OutBufferCount := 0;//清除发送缓冲区 MSComm1.RThreshold := 1;//设置接收一个字节产生 OnComm 事件 MSComm1.PortOpen := true;//打开串口 1 ///////////////////////////////////////////////////////////// Buffers := ''''; CheckSum := 0; //发送串口命令 Command := 34; str := ''$'' + #2 + #$22 + #1;//读 MP3 总曲目 str := str + Char(GetCheckSum(str));//计算校验和 MSComm1.Output := str;//发送串口命令 end; //以下是接收事件处理过程,在 MCU 中相当于串口中断 //注意其中 2 个语句
//while MSComm1.InBufferCount > 0 do//输入 FiFO 不为空 //if str = '''' then str := #0; //0 字符处理 //例接收的数据为#24#02#00#01#03 //此时 InBufferCount=5.若设置 Input 一次从接收缓冲读取字节数不限 //即:MSComm1.InputLen := 0;则 str := MSComm1.Input;后 str 好象为 #24#02#00#01#03 //但实际为''??''#24#02.总得不到结果,至少 0 字符后的#01#03 无法读出. //采用 MSComm1.InputLen := 1;后,并配合 while MSComm1.InBufferCount > 0 do //当读到 0 字符时,由于 str=''''(空),故访问 str[1]将会引发异常的发生而导 致程序的终止. //故用 if str = '''' then str := #0; 来向 str[1]内认为地填入字符#0 且 str 的长度也为 1 了. //故此要点是用 if str = '''' then str := #0;语句渡过读 0 字符的难关~~~ procedure TForm1.MSComm1Comm(Sender: TObject); var str: string; i: integer; begin case MSComm1.CommEvent of comEvReceive://接收事件处理 begin while MSComm1.InBufferCount > 0 do//输入 FiFO 不为空 begin str := MSComm1.Input;//从 FIFO 中只取 1 个字符,因为 MSComm1.InputLen := 1 if str = '''' then str := #0; //0 字符处理 if (Buffers = '''') and (str = ''$'') then//同步符测试 begin Buffers := str;//存入同步符''$'' CheckSum := 0;//初始化校验和 end else if (Buffers <> '''') and (Buffers[1] = ''$'') then begin// 必须用同步符起始 Buffers := Buffers + str;//加入数据串 CheckSum := CheckSum xor Byte(str[1]);//求校验和(除同步符 ''$''外) if Length(Buffers) = Byte(Buffers[2]) + 3 then//结束符测试
begi
n if CheckSum = 0 then//此时校验和必须为 0 表示校验和正确 begin case Command of $22: begin//取歌曲总数 ComboBox1.Items.Clear; for i := 1 to Byte(Buffers[4]) do begin str := ''第'' + inttostr(i) + ''首歌曲''; ComboBox1.Items.Add(str);// end; Command := 0; end; 1: ; else ; end; end; Buffers := '''';//接收完毕清空缓冲区 CheckSum := 0;//初始化校验和 end; end else begin Buffers := '''';//接收错误清空缓冲区,放弃所有数据 CheckSum := 0;//初始化校验和 end; end; end; end; end; MSComm 控件通过串行端口传输和接收数据,为应用程序提供串行通讯功能。 MSComm 控件在串口编程时非常方便, 程序员不必去花时间去了解较为复杂的 API 函数,而且在 VC、
VB、
Delphi 等语言中均