| //以下是創(chuàng)建窗體時的MSCOMM參數(shù)設(shè)置過程 //MSComm1.InputMode := comInputModeBinary; //和MSComm1.InputMode := comInputModeText; //實驗結(jié)果基本對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ù)模式為二進制形式 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è)置接收一個字節(jié)產(chǎn)生OnComm事件 MSComm1.PortOpen := true;//打開串口1 ///////////////////////////////////////////////////////////// Buffers := ''''; CheckSum := 0; //發(fā)送串口命令 Command := 34; str := ''$'' + #2 + #$22 + #1;//讀MP3總曲目 str := str + Char(GetCheckSum(str));//計算校驗和 MSComm1.Output := str;//發(fā)送串口命令 end;
//以下是接收事件處理過程,在MCU中相當(dāng)于串口中斷 //注意其中2個語句 //while MSComm1.InBufferCount > 0 do//輸入FiFO不為空 //if str = '''' then str := #0; //0字符處理 //例接收的數(shù)據(jù)為#24#02#00#01#03 //此時InBufferCount=5.若設(shè)置Input 一次從接收緩沖讀取字節(jié)數(shù)不限 //即:MSComm1.InputLen := 0;則str := MSComm1.Input;后str好象為#24#02#00#01#03 //但實際為''??''#24#02.總得不到結(jié)果,至少0字符后的#01#03無法讀出. //采用MSComm1.InputLen := 1;后,并配合while MSComm1.InBufferCount > 0 do //當(dāng)讀到0字符時,由于str=''''(空),故訪問str[1]將會引發(fā)異常的發(fā)生而導(dǎo)致程序的終止. //故用if str = '''' then str := #0; 來向str[1]內(nèi)認為地填入字符#0且str的長度也為1了. //故此要點是用if str = '''' then str := #0;語句渡過讀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個字符,因為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;//加入數(shù)據(jù)串 |