1、读取串口个数并绑定到指定控件
procedure TForm1.FormCreate(Sender: TObject);
var
coms : TStringList;
bands : string;
index : integer;
begin
coms := TStringList.Create;
EnumComPorts(coms);
cbbPort1.Items.Assign(coms);
FreeAndNil(coms);
//update comnum
bands := com1.Port;
index := Self.cbbPort1.Items.IndexOf(bands);
Self.cbbPort1.ItemIndex := index;
//update bandrate
bands := BaudRateToStr(com1.BaudRate);
index := Self.cbbBand1.Items.IndexOf(bands);
Self.cbbBand1.ItemIndex := index;
//update data num
bands := DataBitsToStr(com1.DataBits);
index := Self.cbbData1.Items.IndexOf(bands);
Self.cbbData1.ItemIndex := index;
//update stopdata
bands := StopBitsToStr(com1.StopBits);
index := Self.cbbStop1.Items.IndexOf(bands);
Self.cbbStop1.ItemIndex := index;
end;
2、创建串口配置文件,并写入配置
procedure TForm1.Mbtnbtn1Click(Sender: TObject);
var
conf : string;
begin
com1.Port := Self.cbbPort1.Text;
com1.BaudRate := StrToBaudRate(Self.cbbBand1.Text);
com1.DataBits := StrToDataBits(Self.cbbData1.Text);
com1.StopBits := StrToStopBits(Self.cbbStop1.Text);
conf := ExtractFilePath(Application.ExeName) + 'config.ini';
com1.StoreSettings(stIniFile, conf); //把配置属性存到配置文件
ComPort.LoadSettings(stRegistry, 'HKEY_LOCAL_MACHINE\Software\Dejan');//把配置文件属性存到注册表中
Close;
end;
3、读取串口数据
procedure TForm1.com1RxChar(Sender: TObject; Count: Integer);
var
str:string;
begin
com1.ReadUnicodeString(str,Count);
end;
4、写入串口程序可以用WriteReadUnicodeString(str);
5、打开串口
com1.open;