在Delphi中實現串口通信,可以使用Windows API函數來進行操作。
uses
Windows;
const
ReadBufferSize = 1024;
var
hComm: THandle; // 串口句柄
CommPort: string; // 串口號
BaudRate: DWORD; // 波特率
DataBits: DWORD; // 數據位
Parity: DWORD; // 校驗位
StopBits: DWORD; // 停止位
ReadBuffer: array[0..ReadBufferSize] of Byte; // 讀取緩沖區
function InitSerialPort: Boolean;
var
DCB: TDCB;
Timeouts: TCommTimeouts;
begin
Result := False;
hComm := CreateFile(PChar(CommPort), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if hComm = INVALID_HANDLE_VALUE then
Exit;
if not GetCommState(hComm, DCB) then
Exit;
DCB.BaudRate := BaudRate;
DCB.ByteSize := DataBits;
DCB.Parity := Parity;
DCB.StopBits := StopBits;
if not SetCommState(hComm, DCB) then
Exit;
if not GetCommTimeouts(hComm, Timeouts) then
Exit;
Timeouts.ReadIntervalTimeout := MAXDWORD;
Timeouts.ReadTotalTimeoutMultiplier := 0;
Timeouts.ReadTotalTimeoutConstant := 0;
Timeouts.WriteTotalTimeoutMultiplier := 0;
Timeouts.WriteTotalTimeoutConstant := 0;
if not SetCommTimeouts(hComm, Timeouts) then
Exit;
Result := True;
end;
function ReadSerialPort(var Buffer: array of Byte; Count: Integer): Integer;
begin
Result := 0;
if not ReadFile(hComm, Buffer, Count, DWORD(Result), nil) then
Result := 0;
end;
function WriteSerialPort(const Buffer: array of Byte; Count: Integer): Boolean;
var
BytesWritten: DWORD;
begin
Result := False;
if not WriteFile(hComm, Buffer, Count, BytesWritten, nil) then
Exit;
Result := BytesWritten = DWORD(Count);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
ReadCount: Integer;
begin
if not InitSerialPort then
ShowMessage('Failed to initialize serial port!')
else
begin
ReadCount := ReadSerialPort(ReadBuffer, ReadBufferSize);
if ReadCount > 0 then
begin
// 處理讀取到的數據
end;
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
DataToSend: array[0..3] of Byte; // 要發送的數據
begin
DataToSend[0] := 0; // 設置發送數據內容
if not WriteSerialPort(DataToSend, SizeOf(DataToSend)) then
ShowMessage('Failed to send data!');
end;
以上是一個簡單的Delphi串口通信示例,你可以根據實際需求進行修改和完善。