|
菜農(nóng)HotPower@126.com 發(fā)表于 2006/12/28 22:55:20
//以下是創(chuàng)建窗體時(shí)的MSCOMM參數(shù)設(shè)置過(guò)程
//MSComm1.InputMode := comInputModeBinary;
//和MSComm1.InputMode := comInputModeText;
//實(shí)驗(yàn)結(jié)果基本對(duì)Delghi不太起作用
procedure TForm1.FormCreate(Sender: TObject);
var
str: string;
begin
//MSCOMM參數(shù)設(shè)置
MSComm1.CommPort := 1;//使用COM1
MSComm1.Settings := '9600,N,8,1';//設(shè)置通信口參數(shù)
MSComm1.InBufferSize := 32;//設(shè)置MSComm1接收緩沖區(qū)為32字節(jié)
MSComm1.OutBufferSize := 2;//設(shè)置MSComm1發(fā)送緩沖區(qū)為2字節(jié)
MSComm1.InputMode := comInputModeBinary;//設(shè)置接收數(shù)據(jù)模式為二進(jìn)制形式
MSComm1.InputLen := 1;//設(shè)置Input 一次從接收緩沖讀取字節(jié)數(shù)為1
MSComm1.SThreshold := 1;//設(shè)置Output 一次從發(fā)送緩沖讀取字節(jié)數(shù)為1
MSComm1.InBufferCount := 0;//清除接收緩沖區(qū)
MSComm1.OutBufferCount := 0;//清除發(fā)送緩沖區(qū)
MSComm1.RThreshold := 1;//設(shè)置接收一個(gè)字節(jié)產(chǎn)生OnComm事件
MSComm1.PortOpen := true;//打開(kāi)串口1
/////////////////////////////////////////////////////////////
Buffers := '';
CheckSum := 0;
//發(fā)送串口命令
Command := 34;
str := '$' + #2 + #$22 + #1;//讀MP3總曲目
str := str + Char(GetCheckSum(str));//計(jì)算校驗(yàn)和
MSComm1.Output := str;//發(fā)送串口命令
end;
//以下是接收事件處理過(guò)程,在MCU中相當(dāng)于串口中斷
//注意其中2個(gè)語(yǔ)句
//while MSComm1.InBufferCount > 0 do//輸入FiFO不為空
//if str = '' then str := #0; //0字符處理
//例接收的數(shù)據(jù)為#24#02#00#01#03
//此時(shí)InBufferCount=5.若設(shè)置Input 一次從接收緩沖讀取字節(jié)數(shù)不限
//即:MSComm1.InputLen := 0;則str := MSComm1.Input;后str好象為#24#02#00#01#03
//但實(shí)際為'??'#24#02.總得不到結(jié)果,至少0字符后的#01#03無(wú)法讀出.
//采用MSComm1.InputLen := 1;后,并配合while MSComm1.InBufferCount > 0 do
//當(dāng)讀到0字符時(shí),由于str=''(空),故訪問(wèn)str[1]將會(huì)引發(fā)異常的發(fā)生而導(dǎo)致程序的終止.
//故用if str = '' then str := #0; 來(lái)向str[1]內(nèi)認(rèn)為地填入字符#0且str的長(zhǎng)度也為1了.
//故此要點(diǎn)是用if str = '' then str := #0;語(yǔ)句渡過(guò)讀0字符的難關(guān)~~~
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個(gè)字符,因?yàn)镸SComm1.InputLen := 1
if str = '' then str := #0; //0字符處理
if (Buffers = '') and (str = '$') then//同步符測(cè)試
begin
Buffers := str;//存入同步符'$'
CheckSum := 0;//初始化校驗(yàn)和
end
else if (Buffers <> '') and (Buffers[1] = '$') then begin//必須用同步符起始
Buffers := Buffers + str;//加入數(shù)據(jù)串
CheckSum := CheckSum xor Byte(str[1]);//求校驗(yàn)和(除同步符'$'外)
if Length(Buffers) = Byte(Buffers[2]) + 3 then//結(jié)束符測(cè)試
begin
if CheckSum = 0 then//此時(shí)校驗(yàn)和必須為0表示校驗(yàn)和正確
begin
case Command of
$22: begin//取歌曲總數(shù)
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 := '';//接收完畢清空緩沖區(qū)
CheckSum := 0;//初始化校驗(yàn)和
end;
end
else
begin
Buffers := '';//接收錯(cuò)誤清空緩沖區(qū),放棄所有數(shù)據(jù)
CheckSum := 0;//初始化校驗(yàn)和
end;
end;
end;
end;
end; |
|