The implementation in Delphi is as follows. We use the tcomm Control for serial communication. This control calls Win32 API to implement the required functions. After the control is installed, you can see the following attributes: baudrate, comport, databits, datacount, dtrenabled, hwhandshaking, inputlen, parity, portopen, rthreshold, rtsenabled, stopbits, swhandshaking. It also provides three events, including onreceivedata, onreceiveerror, and fonmodemstatechange. Through the simple interface provided by the control, we can program it conveniently. We can directly select the values specified by the Protocol in the attribute, or modify their attributes during the process, and write our data processing code in the trigger event. Below is a sending Code Program:
Procedure tfrmtransient. timertotalsendtimer (Sender: tobject );
VaR
Bytesend: array of byte;
I: DWORD;
Stringsend: array [0 .. 7] of byte;
Begin
Commtotal. portopen: = false;
Stringsend [0]: = strtoint ('$' + 'bb ');
Stringsend [1]: = strtoint ('$' + 'be ');
Stringsend [2]: = strtoint ('$' + '10 ');
Stringsend [3]: = strtoint ('$' + '01 ');
Stringsend [4]: = strtoint ('$' + 'fd ');
Stringsend [5]: = strtoint ('$' + '70 ');
Stringsend [6]: = strtoint ('$' + '10 ');
Stringsend [7]: = strtoint ('$' + 'ee ');
Commtotal. portopen: = true;
Setlength (bytesend, 8 );
For I: = 0 to 7 do
Bytesend [I]: = stringsend [I];
Commtotal. outputbyte (bytesend );
Exit;
End;
Let's look at the receiving code again:
Procedure tfrmtransient. commtotalreceivedata (Sender: tobject );
VaR
Byterecieve: array of byte;
Coun, I: DWORD;
PT: pbyte;
Receivestring: string;
Begin
Receivestring: = '';
Coun: = commtotal. readinputbyte (PT );
Setlength (byterecieve, Coun );
For I: = 0 to coun do
Begin
Byterecieve [I]: = PT ^;
Receivestring: = receivestring + inttohex (byterecieve [I], 2 );
INC (PT );
End;
End;
In this way, data can be sent and received to complete the communication with the serial port.
Generally, the default access time is 100 ms. If you need faster access speed. You can add a timer to solve the problem.