Delphi用SPCOMM组件与串口交互的代码如何转换为C#

sdxlh007 2012-04-12 10:05:20
想用C#和serialPort实现
Delphi代码如下(代码有精简):
unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Menus, jpeg, ExtCtrls, DB, ADODB, SPComm, StdCtrls, Grids,
DBGrids, ComCtrls, ToolWin, Buttons;

type
TFormMain = class(TForm)
var
FormMain: TFormMain;
checkSumData:array[0..100] of byte;
procedure TFormMain.Button8Click(Sender: TObject);
var
checkSumValue : integer;
strCmd: string;
begin
checkSumData[0] := $A0;
checkSumData[1] := $03;
checkSumData[2] := strtoint(EditReaderID.text);
checkSumData[3] := $08;
checkSumValue := CheckSum(4);

strCmd:= 'A0 03 ' + inttoHex(checkSumData[2],2) + ' 08 ' + inttoHex(checkSumValue,2);
SendHex(strCmd);
end;

//计算校验和的值
function CheckSum(uBuffLen : Byte ): Byte;
var
uSum: Byte;
i: Byte;
begin
uSum := 0;
i := 0;
for i:=0 to (uBuffLen - 1) do
uSum := uSum + checkSumData[i];
uSum := (Not uSum) + 1;
result:= uSum;
end;

//将string转换成16进制数发送
function SendHex(S: String): integer;
var
s2:string;
buf1:array[0..50000] of char;
i:integer;
begin
s2:='';
for i:=1 to length(s) do
begin
if ((copy(s,i,1)>='0') and (copy(s,i,1)<='9'))or((copy(s,i,1)>='a') and (copy(s,i,1)<='f'))
or((copy(s,i,1)>='A') and (copy(s,i,1)<='F')) then
begin
s2:=s2+copy(s,i,1);
end;
end;
for i:=0 to (length(s2) div 2-1) do
buf1[i]:=char(strtoint('$'+copy(s2,i*2+1,2)));
FormMain.Comm.WriteCommData(buf1,(length(s2) div 2));
end;
...全文
169 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
sdxlh007 2012-04-12
  • 打赏
  • 举报
回复
C#中serialPort对象的WriteLine方法有三个重载:
void Write (String)
void Write (Byte[], Int32, Int32)
void Write (Char[], Int32, Int32)

我觉得对应Delphi中
Comm.WriteCommData(buf1,(length(s2) div 2))
的方法,应该是用这个方法吧:
void Write (Byte[], Int32, Int32)
但是,三个参数怎么对对应?

不好意思,我对串口编程完全是个菜鸟。。。
bdmh 2012-04-12
  • 打赏
  • 举报
回复
你要想翻译,无非就是数据类型,然后就是几个函数的替换
copy就是substring
strtoint就是convert.toint32
buf1:array[0..50000] of char就是char[]
sdxlh007 2012-04-12
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]

转什么转,c#有自己的串口组件 SerialPort
[/Quote]
我当然知道c#有serialPort,这不是不会用么。。。。
网上的例子都是传字符串的,可是我这个串口设备用的是接收16进制的,如何做?
Delphi里WriteCommData方法传入2个参数,我查过SerialPort的方法,要么传一个,要么传三个。。。
bdmh 2012-04-12
  • 打赏
  • 举报
回复
转什么转,c#有自己的串口组件 SerialPort
sdxlh007 2012-04-12
  • 打赏
  • 举报
回复
郁闷,分给你吧。。。没人来帮帮的。。。唉

111,126

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧