- Код: Выделить всё • Развернуть
#include <vcl.h>
#include <windows.h>
#include <stdio.h>
#pragma hdrstop
#include "Unit1.h"
unsigned char tx_buffer[3];
unsigned char rx_buffer[3];
unsigned char status_rx_buffer;
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void Open_Port (char name)
{
char port_name[8];
sprintf(port_name, "COM%d", name);
hCom = CreateFile(port_name ,GENERIC_READ | GENERIC_WRITE,0,NULL,
OPEN_EXISTING,0, NULL);
if( hCom == INVALID_HANDLE_VALUE )
{
ShowMessage("Com port error");
CloseHandle(hCom);
}
else
{
SetupComm(hCom,128,128);
GetCommState(hCom, &dcb);
dcb.fOutxCtsFlow = FALSE;
dcb.fDtrControl = DTR_CONTROL_DISABLE;
dcb.fRtsControl = RTS_CONTROL_DISABLE;
dcb.fInX = FALSE;
dcb.fOutX = FALSE;
dcb.BaudRate = CBR_9600;
dcb.fBinary = TRUE;
dcb.fAbortOnError = FALSE;
dcb.fNull = FALSE;
dcb.ByteSize = 8;
dcb.fParity = NOPARITY;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
if (!SetCommState(hCom, &dcb))
{
CloseHandle(hCom);
ShowMessage("Com port error");
}
comm_timeouts.ReadIntervalTimeout = 5000;
comm_timeouts.ReadTotalTimeoutMultiplier = 5000;
comm_timeouts.ReadTotalTimeoutConstant = 5000;
comm_timeouts.WriteTotalTimeoutMultiplier = 5000;
comm_timeouts.WriteTotalTimeoutConstant =5000;
SetCommTimeouts(hCom, &comm_timeouts);
PurgeComm(hCom, PURGE_RXCLEAR);
PurgeComm(hCom, PURGE_TXCLEAR);
}
}
//--------------------------------------------------------------------------
void Close_Port(void)
{
CloseHandle(hCom);
}
//----------------------------------------------------------------------------
char Write_Port (unsigned char *buf, size_t raz)
{
DWORD dwWritten;
WriteFile(hCom,buf,raz,&dwWritten,NULL);
if(raz==dwWritten)
{return 1;}
else
{return 0;}
}
//-----------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
if (ComboBox1->ItemIndex==0)
{
ShowMessage("Select COM Port");
return;
}
else
{
Open_Port(ComboBox1->ItemIndex);
}
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button2Click(TObject *Sender)
{
Close_Port();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button3Click(TObject *Sender)
{
if (!hCom)
{
ShowMessage("First COM port connect");
return;
}
tx_buffer[0]=1;
tx_buffer[1]=3;
tx_buffer[2]=150;
if(Write_Port(tx_buffer,3)==false)
{ShowMessage("error write_port");}
}