このページはEtoJ逐語翻訳フィルタによって翻訳生成されました。

翻訳前ページへ


Delphi: RS-232, serial comms, COM1, COM2 HOME - - - - - - - TUTORIALS INDEX - - - - - - - - - - - - Other 構成要素 for programmers

Delphi: RS-232, serial comms, COM1, COM2

This has good (警察などへの)密告,告訴(状), and a search button at the 底(に届く) of the page

Please don't 解任する it because it isn't 十分な of graphics, scripts, cookies, etc!

Click here if you want to know more about the source and 判型 of these pages.


The RS-232 serial interface is a wondrous thing. It has many marvelous 能力s. It is also something I've put of 格闘するing with for a long time. Search the web for "How To"s and you may see why. It turns out that things are not as bad as you might think.

STOP PRESS: I wrote this tutorial in April of 2003. In April of 2010, I attacked the same 事業/計画(する) again, but by then the 外部の 装置 I 手配中の,お尋ね者 to work with was the wonderful 安価な, programmer friendly, Arduino microprocessor. I would advise you to go to the newer tutorial about talking to things over a serial cable from a Windows computer. If that doesn't tell you everything you want to know, or if it leaves you feeling that you've "nearly got it", perhaps then come 支援する here and skim what's below to see if reading a second explanation of, mostly, the same things helps.

FOLLOWING COMMENTS APPLY TO WHAT FOLLOWS here, NOT TO THE new-at-Apr-2010 tutorial DISCUSSED A MOMENT AGO

(But I must 収容する/認める, the last program below doesn't work yet! But online 資源s 保証する me it "should"! Read on?)

The programs 現在のd here will do 確かな 職業s, but they do not 器具/実施する everything 明示するd within RS-232. The big gap in my "解答" is that there is no handshaking.

I 手配中の,お尋ね者 to be able to communicate with a nice little PIC based microcontroller called the Pascalite. You can learn more about that (there's a 解放する/自由な compiler and 金物類/武器類 simulator) in my Pascalite pages.

My 追求(する),探索(する) for serial communications took a leap 今後 thanks to Robert Clemenzi's FAQ answers.

Much of the に引き続いて is taken from there, with alterations. He himself credited the old http://community.borland.com/article/0,1410,16400,00.html Borland's FAQ 16400 as the inspiration and source of what he 地位,任命するd.

I subsequently did a Google search on "commtimeouts delphi" and turned up a number of useful things, not least Peter Johnson's good essay. Peter has written a number of articles, 構成要素s and 使用/適用s, all of which can be 設立する on his web page. He also 演説(する)/住所s how you can 始める,決める the port's baud 率, etc, which I have not covered here. (Yet!)

If you need help with the low level electronics, cables, pinouts, connectors of RS-232, visit Arc Electronics' helpful page.

Still with me, I hope? First we'll 令状 a Delphi program which can send RS-232 data to the Pascalite (or other RS-232 receiving 装置!) The Pascalite will 陳列する,発揮する what is sent to it on the Pascalite's LCD 陳列する,発揮する.

The program in the Pascalite will be:
program Demo3RS232;
var bTmp,bFrmRS232:byte;

begin {main}
令状(LCD,255); {(疑いを)晴らすs LCD}
repeat
if RS232_New_Byte then begin
  read(RS232,bFrmRS232);
  令状(LCD,bFrmRS232);
 end;
until 4=5;
end.
If only Windows programming was so straightforward! (You may want to visit my Pascalite tutorial if the above isn't (疑いを)晴らす to you.)

The Pascalite 加える has a one byte RS-232 receive 衝撃を和らげるもの. If a second byte of data is received before the first has been 過程d, the first is lost. Happily, the filling of the 衝撃を和らげるもの is done by an interrupt-誘発する/引き起こすd 決まりきった仕事. The Pascalite can be doing something else at the moment the byte's bits begin to arrive. その上に, the RS232_New_Byte 許すs the PAscalite to know if there is an 未使用の byte waiting in the 衝撃を和らげるもの for 過程ing. (The 加える has a 32byte 衝撃を和らげるもの). In our simple approach to serial communication over the comm port, we're going to have to do in ソフトウェア what can be done in 金物類/武器類 with more sophisticated 解答s.

If you think about the code given above, and the fact that there's only a 選び出す/独身 byte 衝撃を和らげるもの, you will see that the machine sending (警察などへの)密告,告訴(状) to the Pascalite must send it a character at a time, slowly enough to 確実にする that the Pascalite has dealt with the previous byte before the next one is sent. There are lots of ways to 打ち勝つ the problems inherent in that 状況/情勢, which I'll try to discuss later, but for now: let's get the 必須のs working.

We're still not ready to start our Delphi program. RS-232 is fraught with many 関係 問題/発行するs. The cable between the machines has to be 権利. At each end, baud 率s and other things have to be 始める,決める. In 尊敬(する)・点 of connecting a Pascalite to a Windows machine, these 問題/発行するs are discussed at my Pascalite RS232 tutorial. For the 残り/休憩(する) of you, I will point out that the program I am going to develop here does not have parameter setting 決まりきった仕事s. 始める,決める up your Windows comm port 経由で the Settings | System Settings | 装置 経営者/支配人. 始める,決める up your remote 装置 however it has to be done. 公式文書,認める in particular that you should select no handshaking, not RTS/CTS, not XON/XOFF.

Before 乗る,着手するing on the Delphi program here, it would probably be best to see if you can send to your remote 装置 using Hyperterminal. (Again, my Pascalite RS232 tutorial discusses 面s of this.)

So! At last! The Delphi Program. I've 実験(する)d it with Delphi 2.

It is pretty simple! The form has one button. When you click the button, the machine the Delphi program is running in sends a phrase to the other machine 経由で the RS-232.

First I'll 名簿(に載せる)/表(にあげる) the whole program, then I'll explain 半端物s and ends. I used the 力/強力にする of Delphi to 追加する a button to the form, and to 生成する the 爆撃する of Button1Click. I've put (***** n *) after lines I had to type in by 手渡す.
部隊 DD28;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, 支配(する)/統制するs, Forms, Dialogs, StdCtrls;

type
  TDD28F1 = class(TForm)
    Button1: TButton;
    手続き Button1Click(Sender: TObject);
    手続き SendChar(sToSend:string);(***** 1 *)
  私的な
    { 私的な 宣言s }
  public
    { Public 宣言s }
  end;

var
  DD28F1: TDD28F1;
  NumberWritten:dword;           (***** 2 *)
  sPhraseToSend,CommPort:string; (***** 3 *)
  hCommFile:THandle;             (***** 3 *)
  c1:byte;                       (***** 3 *)

実施

{$R *.DFM}

手続き TDD28F1.SendChar(sToSend:string);
begin
CommPort := 'COM1';                      (***** 4 start *)
hCommFile := CreateFile(PChar(CommPort),
                          GENERIC_WRITE,
                          0,
                          nil,
                          OPEN_EXISTING,
                          FILE_ATTRIBUTE_NORMAL,
                          0);
WriteFile(hCommFile,
            PChar(sToSend)^,
            Length(sToSend),
            NumberWritten,
            nil);                        (***** 4 end *)
CloseHandle(hCommFile);                  (***** 5 *)
end;

手続き TDD28F1.Button1Click(Sender: TObject);
begin
sPhraseToSend:='実験(する)ing 1 2 3';           (***** 6 start *)
for c1:=1 to length(sPhraseToSend) do begin
  SendChar(copy(sPhraseToSend,c1,1));
  使用/適用.processmessages;            (***** 6 end *)
  sleep(10);                              (***** 7 *)
  end;
end;

end.
(I'll try to give you more in the way of comments another time. For now, two things to 公式文書,認める....

If your comm link is 経由で COM2, you need to alter the code in the line 示すd "(***** 4 start *)"

In the line 示すd "(***** 2 *)", I've 宣言するd NumberWritten to be of type dword. This 同意しないs with Borland's FAQ answer, but agrees with something in the other source I について言及するd... and it 作品!

=============
So much for sending things FROM the Delphi program. Now we'll move on to receiving things by the Delphi program.

Remember that it will be up to you to org anise things so that the machines in "conversation" don't interrupt each other, i.e. remember that 金物類/武器類 handshaking has been 取って代わるd with careful programming.

For the 演習 below, we are going to have the "main" computer (i.e. the one running the Delphi program" be in 告発(する),告訴(する)/料金. The "slave" (a Pascalite in my 事例/患者) will wait on the big machine, and speak after it is spoken to.

特に, the slave's program will be a 宙返り飛行 looking for a message from the main machine. If an "f" is sent, the slave will "reply" with "I saw an f". If something else is sent, the slave will reply with "I saw something other than an f". (The reply will be 陳列する,発揮するd as the caption of a label on the Delphi program's form.)

The Pascalite program... which can be 実験(する)d with the main machine running Hyperterminal.... is as follows....
program Demo3RS232;
var bTmp,bFrmRS232:byte;

begin {main}
repeat
bFrmRS232:=255;
if RS232_New_Byte then begin
  read(RS232,bFrmRS232);
  end;
if bFrmRS232<255 then begin
   {delay(200); see below}
   if bFrmRS232=102 {102 is code for "f"}
      then write(RS232,'I saw an f') {no ; here}
      else write(RS232,'I saw something other than f');
end;{not 255}
until 4=5;
end.
The に引き続いて SHOULD work!! with the above... but it doesn't yet, sigh. It RUNS... but it doesn't seem to 選ぶ up the message coming 支援する from the Pascalite. The Pascalite is working 罰金 with Hyperterminal. (And yes, I did remember to disconnect the Hyperterminal 関係 before trying to run the above.) I tried putting in the 延期する(200) remmed out in the Pascalite code above in 事例/患者 the 返答 from the Pascalite was appearing before the main PC was looking... but it didn't help.

The に引き続いて is the code behind a simple Delphi form with two buttons, two labels....
部隊 DD29u1;

(*DOESN'T WORK... but NEARLY does.... I think!*)

(*Yes! I know this could be more elegant! その上に, it is "不正に written"
in a number of 尊敬(する)・点s. In particular, it is not very 強健な and fails to
会社にする/組み込む sundry 利用できる error (犯罪,病気などの)発見 and 扱うing 準備/条項s of
Windows. 改善する it... without obscuring the basic things it is trying to
illustrate... and send me the 改善するd 見解/翻訳/版!!*)

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, 支配(する)/統制するs, Forms, Dialogs,
  StdCtrls;

type
  TDD29F1 = class(TForm)
    buSendf: TButton;
    buSendx: TButton;
    Label1: TLabel;
    Label2: TLabel;
    手続き buSendfClick(Sender: TObject);
    手続き buSendxClick(Sender: TObject);
    手続き SendChar(sToSend:string);
    手続き EstablishHandle;
    機能(する)/行事 ReadStringFrmRS232:string;
    手続き FormCreate(Sender: TObject);
  私的な
    { 私的な 宣言s }
  public
    { Public 宣言s }
  end;

var
  DD29F1: TDD29F1;
  sPhraseToSend:string;
  hCommFile:THandle;
  c1:byte;

const ver='18 Apr 03';
CommPort = 'COM1';

実施

{$R *.DFM}

機能(する)/行事 TDD29F1.ReadStringFrmRS232:string;
(*hCommFile must be valid before this is called*)
var sTmp:string;
    c1:integer;
    chBuffer:array[0..255] of char;
    NumberOfBytesRead : dword;

begin
if hCommFile=INVALID_HANDLE_VALUE then 出口;

if not ReadFile (hCommFile, chBuffer, sizeof(chBuffer),
              NumberOfBytesRead, Nil) then
               showmessage('Problem with ReadStringFrmRS232')
               { Better: Raise an exception } ; { <- semicolon IS needed here!}

{The program will go off and watch the RS-232 data source
 for 後継の data. It will continue to watch (and collect
 data as it appears) for a time 決定するd by the CommTimeouts
 settings... thus you dont need to know in 前進する how many
 bytes will be coming, nor does the connected 装置 need
 to send a 旗 場内取引員/株価 the last byte.... though that
 議定書 could be 会社にする/組み込むd on 最高の,を越す of the other
 準備/条項s for signalling the end of the data.}

label2.caption:='Bytes seen: '+inttostr(NumberOfBytesRead - 1);
for c1:= 0 to NumberOfBytesRead - 1 do
      sTmp:= sTmp+chBuffer[c1];

result:=sTmp;
end;

手続き TDD29F1.SendChar(sToSend:string);
(*hCommFile must be valid before this is called*)
var NumberWritten:dword;
begin
if hCommFile = INVALID_HANDLE_VALUE then
        showmessage('Problem with SendChar')
        {Better: raise an exception } ; (* <- 半分 結腸 IS needed here*)
WriteFile(hCommFile,
            PChar(sToSend)^,
            Length(sToSend),
            NumberWritten,
            nil);
end;

手続き TDD29F1.EstablishHandle;
var CommTimeouts : TCommTimeouts;
begin
hCommFile := CreateFile(PChar(CommPort),
                          GENERIC_READ or GENERIC_WRITE,
                          0,
                          nil,
                          OPEN_EXISTING,
                          FILE_ATTRIBUTE_NORMAL,
                          0); {Delphi 2 helpfile said use "NULL" here,
                                and program 収集するd, but raised error when
                                it was run. Two 言及/関連s said use 0}
{Ever been 失望させるd by something that would not work when it
"should"? I spent about an hour tinkering with this program
with "generic_write or generic_write" (WRITE twice instead of
one read, one 令状) in the parameters above.....
ARGHH!!, as Snoopy would say.}
with CommTimeouts do
begin
  {put cursor on 'CommTimeouts', 圧力(をかける) f1 to learn
  about what the に引き続いて 明示する. The numbers here
  are 天然のまま, and need consideration.... though they
  MAY work for yoyu in your 状況/情勢! The '権利'
  numbers depend on many things, 含むing the settings
  in the 装置 you are communicating with. If the
  numbers are too small, the Delphi program will not
  "see" the 大(公)使館員d 装置. If they are too large,
  the program will appear to hang while communicating....
  If too large, they may also 干渉する with Windows'
  proper 機能(する)/行事ing.... but may not.}
  ReadIntervalTimeout := 0;
  ReadTotalTimeoutMultiplier := 0;
  ReadTotalTimeoutConstant := 1500;
  WriteTotalTimeoutMultiplier := 0;
  WriteTotalTimeoutConstant := 500;
end; {with}

if not SetCommTimeouts(hCommFile, CommTimeouts) then
       showmessage('Problem with SetCommTimeouts')
       { Better: raise an exception }  ; (* <- 半分 結腸 IS needed here*)

end;

手続き TDD29F1.buSendfClick(Sender: TObject);
begin
sPhraseToSend:='f';
EstablishHandle;
for c1:=1 to length(sPhraseToSend) do begin
  SendChar(copy(sPhraseToSend,c1,1));
  使用/適用.processmessages;
  sleep(10);
  end;
label1.caption:='hardcoded f'{ReadStringFrmRS232};
CloseHandle(hCommFile);
end;

手続き TDD29F1.buSendxClick(Sender: TObject);
begin
sPhraseToSend:='x';
EstablishHandle;
for c1:=1 to length(sPhraseToSend) do begin
  SendChar(copy(sPhraseToSend,c1,1));
  使用/適用.processmessages;
  sleep(10);
  end;
CloseHandle(hCommFile);  {Probably not necessary.... but was trying....}
EstablishHandle;            {.... things in desperation!}
label1.caption:=ReadStringFrmRS232;
CloseHandle(hCommFile);
end;

手続き TDD29F1.FormCreate(Sender: TObject);
begin
caption:='DD29, sheepdogsoftware.co.uk, '+ver;
end;

end.


Sorry to have to leave this "half-baked". But! In 2010, I 人物/姿/数字d out what the problem was. Instead of re-令状ing the above, I did a new tutorial from scratch, which you may want to visit: How to do bi-directional communications from a Windows machine over a serial link.

If you want to wade through an untidy collection of さまざまな things I 収穫d from the web in the work 主要な up to this tutorial, you'll find it at my collection of serial i/o (警察などへの)密告,告訴(状).

REMINDER: (I know I said this at the start, but for anyone who 行方不明になるd that...) I wrote this tutorial in April of 2003. In April of 2010, I attacked the same 事業/計画(する) again. I would advise you to go to the newer tutorial about talking to things over a serial cable from a Windows computer
            力/強力にするd by FreeFind
  場所/位置 search Web search
場所/位置 地図/計画する    What's New    Search This search 単に looks for the words you enter. It won't answer "Where can I download InpOut32?"

Click here if you're feeling 肉親,親類d! (促進するs my 場所/位置 経由で "Top100Borland")


If you visit 1&1's 場所/位置 from here, it helps me. They host my website, and I wouldn't put this link up for them if I wasn't happy with their service. They 申し込む/申し出 things for the beginner and the 会社/団体.www.1and1.com icon

広告 from page's editor: Yes.. I do enjoy 収集するing these things for you... hope they are helpful. However.. this doesn't 支払う/賃金 my 法案s!!! If you find this stuff useful, (and you run an MS-DOS or Windows PC) please visit my freeware and shareware page, download something, and 循環させる it for me? Links on your page to this page would also be 高く評価する/(相場などが)上がるd!
Click here to visit editor's freeware, shareware page.

Link to Tutorials main page
How to email or 令状 this page's editor, Tom Boyd

Valid HTML 4.01 Transitional Page WILL BE 実験(する)d for 同意/服従 with INDUSTRY (not MS-only) 基準s, using the 解放する/自由な, 公然と accessible validator at validator.w3.org


If this page 原因(となる)s a script to run, why? Because of things like Google パネル盤s, and the code for the search button. Why do I について言及する scripts? Be sure you know all you need to about spyware.

....... P a g e . . . E n d s .....