Главная страница
Top.Mail.Ru    Яндекс.Метрика
Текущий архив: 2006.04.02;
Скачать: CL | DM;

Вниз

Доступ к com1   Найти похожие ветки 

 
sicilla ©   (2006-01-16 19:13) [0]

Проблема такая: не могу открыть из программы порт com1. Исходный код такой:
procedure TForm1.Button2Click(Sender: TObject);
var
 CommPort: string;
 f, hCommFile: THandle;
 ModemStat: DWord;
begin
 CommPort := "Com1";
 hCommFile := CreateFile(PChar(CommPort), GENERIC_READ or GENERIC_WRITE, 0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
 if hCommFile = INVALID_HANDLE_VALUE then
    begin
         ShowMessage("Unable to open "+ CommPort);
         exit;
    end;
 if GetCommModemStatus(hCommFile, ModemStat) <> false then
 begin
      if ModemStat and MS_CTS_ON <> 0 then ShowMessage("The CTS (clear-to-send) is on.");
      if ModemStat and MS_DSR_ON <> 0 then ShowMessage("The DSR (data-set-ready) is on.");
      if ModemStat and MS_RING_ON <> 0 then ShowMessage("The ring indicator is on.");
      if ModemStat and MS_RLSD_ON <> 0 then ShowMessage("The RLSD (receive-line-signal-detect) is on.");
 end;
 CloseHandle(hCommFile);
end;

Может кто подскажет?


 
tesseract ©   (2006-01-16 19:19) [1]

Забыл настроить порт через DCB.  BaudRate, ByteSize  и др.
Порт желательно открывать как "COM1" или "/.//COM1"


 
VirEx ©   (2006-01-16 19:24) [2]

unit COM_PORT_IO;

interface

function OpenComm(ComPort:string;InQueue, OutQueue, Baud: LongInt): Boolean;
function SetCommTiming: Boolean;
function SetCommBuffer(InQueue, OutQueue: LongInt): Boolean;
function SetCommStatus(Baud: Integer): Boolean;
function SendCommStr(S:string): Integer;
function ReadCommStr(S:string): Integer;
function SendCommBytes(B:array of byte): Integer;
function ReadCommBytes(B:array of byte): Integer;
procedure CloseComm;

implementation

uses Windows, SysUtils;

var
Com: THandle = 0;

function OpenComm(ComPort:string;InQueue, OutQueue, Baud : LongInt): Boolean;
begin
 if Com > 0 then CloseComm;
 Com := CreateFile(PChar(ComPort),GENERIC_READ or GENERIC_WRITE,0, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
 Result := (Com > 0) and SetCommTiming and
 SetCommBuffer(InQueue,OutQueue) and
 SetCommStatus(Baud);
end;

function SetCommTiming: Boolean;
var
 Timeouts: TCommTimeOuts;
begin
 with TimeOuts do
 begin
   ReadIntervalTimeout := 1;
   ReadTotalTimeoutMultiplier := 0;
   ReadTotalTimeoutConstant := 1;
   WriteTotalTimeoutMultiplier := 2;
   WriteTotalTimeoutConstant := 2;
 end;
Result := SetCommTimeouts(Com,Timeouts);
end;

function SetCommBuffer(InQueue, OutQueue: LongInt): Boolean;
begin
 Result := SetupComm(Com, InQueue, OutQueue);
end;

function SetCommStatus(Baud: Integer): Boolean;
var
 DCB: TDCB;
begin
 with DCB do
 begin
   DCBlength:=SizeOf(Tdcb);
   BaudRate := Baud;       //битрэйт
   Flags:=12305;
   wReserved:=0;
   XonLim:=600;            
   XoffLim:=150;
   ByteSize:=8;
   Parity:=0;
   StopBits:=0;
   XonChar:=#17;
   XoffChar:=#19;
   ErrorChar:=#0;
   EofChar:=#0;
   EvtChar:=#0;
   wReserved1:=65;
 end;
Result := SetCommState(Com, DCB);
end;

function SendCommStr(S:string): Integer;
var
 TempArray : array[1..255] of Byte;
 Count, TX_Count : Cardinal;
begin
 for Count := 1 to Length(S) do TempArray[Count] := Ord(S[Count]);
 WriteFile(Com, s, Length(s), TX_Count, nil);
 Result := TX_Count;
end;

function ReadCommStr(S:string) : Integer;
var
 TempArray : array[1..255] of Byte;
 Count, RX_Count : Cardinal;
begin
 S := "";
 ReadFile(Com, s, 255, RX_Count, nil);
 for Count := 1 to RX_Count do S := S + Chr(TempArray[Count]);
 Result := RX_Count;
end;

function SendCommBytes(B:array of byte): Integer;
var
 Send_Count : Cardinal;
begin
 WriteFile(Com, B, Length(B), Send_Count, nil);
 Result := Send_Count;
end;

function ReadCommBytes(B:array of byte): Integer;
var
 Read_Count : Cardinal;
begin
 ReadFile(Com, B, Length(B), Read_Count, nil);
 Result := Read_Count;
end;

procedure CloseComm;
begin
 CloseHandle(Com);
 Com := Cardinal(-1);
end;

end.


 
tesseract ©   (2006-01-16 19:49) [3]


> B:array of byte

Лучше использовать статический массив


 
begin...end ©   (2006-01-16 20:16) [4]

> tesseract ©   (16.01.06 19:49) [3]

Что значит "лучше"? В качестве параметра B может выступать как статический, так и динамический массив.


 
tesseract ©   (2006-01-16 21:45) [5]


> В качестве параметра B может выступать как статический,
> так и динамический массив.

Не спорю, в качестве примера может. Но у меня бывали проблемы с отправкой в REadFile динамического массива. Туда же нужно указатель на буфер отправлять,

ИМХО или TbyteArray или сразу структурой читать.


 
Evgeny V ©   (2006-01-17 07:34) [6]

Я так понял выполняется код
if hCommFile = INVALID_HANDLE_VALUE then
   begin
        ShowMessage("Unable to open "+ CommPort);
        exit;
   end;

Добавте перед ShowMessage  вызов GetLastError, посмотрите что за ошибку дает при открытии порта.


 
begin...end ©   (2006-01-17 09:00) [7]

> tesseract ©   (16.01.06 21:45) [5]

> Не спорю, в качестве примера может.

И не в качестве примера -- тоже.

> Туда же нужно указатель на буфер отправлять

Вот в [2] туда и отправляется указатель на буфер -- независимо от того, был ли в качестве передан динамический или статический массив. Внутри подпрограммы с параметром - открытым массивом создаётся копия данных передаваемого массива, и в WriteFile передаётся указатель на эту копию.



Страницы: 1 вся ветка

Текущий архив: 2006.04.02;
Скачать: CL | DM;

Наверх




Память: 0.49 MB
Время: 0.027 c
15-1141924816
Kerk
2006-03-09 20:20
2006.04.02
Почему моя миранда его пингует?


15-1141754213
ArtemESC
2006-03-07 20:56
2006.04.02
JavaScript


4-1136860021
Beduir
2006-01-10 05:27
2006.04.02
Аналог TPanel


15-1142026025
Amerzone
2006-03-11 00:27
2006.04.02
Архангельский А.Я.


1-1141213505
Aleksandr.
2006-03-01 14:45
2006.04.02
Что случилось с GetHeapStatus?