Está en la página 1de 2

COMUNICACINPORELPUERTOSERIALUTILIZANDOC++BUILDER

N2.Septiembrede2008

AlterNEXT
SoftwareEngineering

COMUNICACIN POR EL PUERTO SERIAL


UTILIZANDO C++ BUILDER
1.PonerlaspropiedadesdelMemodelasiguienteforma:
Alignment = alClient
MaxLength = 0
ScrollBars = ssVertical
WantReturns = true
WantTabs = false
WordWrap = true

2. Aadir un nuevo objeto Thread (File > New...). Cuando


pregunteelnombreparalaclase,llamarloTRead.

Ahorasedeberatener2units,unaUnit1.cppparaelForm1,yuna
Unit2.cppparaelthread.

3.Aquhayunalistadeloseventosaimplementar:

Form1 OnCreate
Form1 OnClose
Memo1 OnKeyPress

xiste un gran nmero de casos en que el software 4.ElcdigodelaUnit1.cpp...


necesita emitir algn tipo de salida o resultado hacia el //
#include<vcl.h>
exterior del mismo hardware donde se ejecuta, o bien #pragmahdrstop
#include"Unit1.h"
necesita recibir algn tipo de entrada desde algn #include"Unit2.h"//CABECERADELAUNIT2(THREAD)
//VARIABLESGLOBALES
dispositivoexterno,yesbastantecomnqueestosdispositivos HANDLEhComm=NULL;
externos estn conectados al hardware de computo donde se TRead*ReadThread;
COMMTIMEOUTSctmoNew={0},ctmoOld;
ejecutaelprograma(CPU)atravsdeunaconexinporelPuerto
//
Serial,tambinconocidacomointerfazRS232.
#pragmapackage(smart_init)
En este artculo se expone una manera sencilla de conectarse al
puerto serial y enviar o recibir seales utilizando el lenguaje de
programacin C++ Builder de CodeGear. Evidentemente este
articulo est destinado a personas con conocimientos en
programacin de sistemas y familiarizados con el entorno de
desarrolloRADStudio.Tomarencuentalossiguientespuntospara
mejorcompresindelcdigoexpuesto:

Los comentarios dados en este color verde son para


entenderelfuncionamientodelejemplo.
Eltextoescritoencolorazul,eselquegeneraelIDEyno
debemosvolveracopiar.
Elcdigodecolorrojo,eselquedebemosintroducirpara
seguirelejemplo.

El ejemplo consiste en un Form con un objeto Memo (para la


entrada/salidadetexto)yunobjetoThread.
Se empieza con un nuevo proyecto, donde situaremos un Memo
enelForm1.
Pgina1
http://www.alternext.com.bo

#pragmaresource"*.dfm"
TForm1*Form1;

//
__fastcallTForm1::TForm1(TComponent*Owner)
:TForm(Owner)
{
}

//
void__fastcallTForm1::FormCreate(TObject*Sender)
{
Memo1>Clear();
DCBdcbCommPort;
//ABREELPUERTO
//REEMPLAZAR"COM2"POR"COM1","COM3",ETC.PARAABRIR
//OTROPUERTO
hComm=CreateFile("COM2",
GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,0,0);
//SIELPUERTONOPUEDEABRIRSE...
if(hComm==INVALID_HANDLE_VALUE)
Application>Terminate();
//ESTABLECEMOSLOSTIMEOUTS
GetCommTimeouts(hComm,&ctmoOld);
ctmoNew.ReadTotalTimeoutConstant=100;
ctmoNew.ReadTotalTimeoutMultiplier=0;
ctmoNew.WriteTotalTimeoutMultiplier=0;
ctmoNew.WriteTotalTimeoutConstant=0;
SetCommTimeouts(hComm,&ctmoNew);
//ESTABLECEMOSBAUDRATE,PARITY,WORDSIZE,YSTOPBITS.
//HAYOTROSMETODOSDEHACERESTO,PEROESTEESELMASFACIL
dcbCommPort.DCBlength=sizeof(DCB);
GetCommState(hComm,&dcbCommPort);
BuildCommDCB("9600,N,8,1",&dcbCommPort);
SetCommState(hComm,&dcbCommPort);
//ACTIVAMOSELTHREAD
ReadThread=newTRead(false);
}

lvaroPintoTorrejn
apinto@alternext.com.bo

N2.Septiembrede2008

COMUNICACINPORELPUERTOSERIALUTILIZANDOC++BUILDER

AlterNEXT
SoftwareEngineering

//
void__fastcallTForm1::FormClose(TObject*Sender,TCloseAction&Action)
{
//TERMINAMOSELTHREAD.
ReadThread>Terminate();
//ESPERAMOSQUETERMINEYCERRAMOSELPUERTO
Sleep(250);
PurgeComm(hComm,PURGE_RXABORT);
SetCommTimeouts(hComm,&ctmoOld);
CloseHandle(hComm);
}

//
void__fastcallTForm1::Memo1KeyPress(TObject*Sender,char&Key)
{
//TRANSMITECUALQUIERCOSAESCRITAENELMEMO
TransmitCommChar(hComm,Key);
//ESTOPREVEELAVISUALIZACIONDECARACTERESBASURAENLAPANTALLA
if(Key!=13&&(Key<''||Key>'z'))
Key=0;
}
//

6.ElarchivocabeceraUnit2.h...
//
#ifndefUnit2H
#defineUnit2H

//
#include<Classes.hpp>

//
classTRead:publicTThread
{
private:
protected:
void__fastcallDisplayIt(void);
void__fastcallExecute();
public:
__fastcallTRead(boolCreateSuspended);
};
//

#endif

5.ElcdigofuentedelaUnit2.cpp...
//
#include<vcl.h>
#pragmahdrstop
//SEDEBEINCLUIRLACABECERADELAUNIT1
#include"Unit1.h"
#include"Unit2.h"
externHANDLEhComm;
charInBuff[100];
#pragmapackage(smart_init)

//
//Important:MethodsandpropertiesofobjectsinVCLcanonlybe
//usedinamethodcalledusingSynchronize,forexample:
//
//Synchronize(UpdateCaption);
//
//whereUpdateCaptioncouldlooklike:
//
//void__fastcallTRead::UpdateCaption()
//{
//Form1>Caption="Updatedinathread";
//}

//
__fastcallTRead::TRead(boolCreateSuspended)
:TThread(CreateSuspended)
{
}

//
void__fastcallTRead::DisplayIt()
{
//ENESTEEJEMPLONOSETIENEENCUENTACUANTOTEXTOHAENTRADOENEL
//Memo1QUEPUEDESERSOLODE32K.
//TAMPOCOSEHACENADACONLOSCARACTERESNOIMPRIMIBLES
//MUESTRAELTEXTORECIBIDO
Form1>Memo1>SetSelTextBuf(InBuff);
}

//
void__fastcallTRead::Execute()
{
//Placethreadcodehere
DWORDdwBytesRead;
//HACEQUEELOBJETOTRHEADSEADESTRUIDOCUANDOELTHREADTERMINA
FreeOnTerminate=true;
while(1){
//INTENTALEERDELPUERTOSERIE
//YSIHAYALGOLOVISUALIZA
ReadFile(hComm,InBuff,50,&dwBytesRead,NULL);
if(dwBytesRead){
InBuff[dwBytesRead]=0;//ACABALACADENAEN
NULO
Synchronize(DisplayIt);
}
}
}
//

Para probar el ejemplo, se puede enlazar los pines 2 y 3 del RS


232, o bien, escribir algn comando Hayes hacia el puerto del
modem(unATZporejemplo).

Pgina2
http://www.alternext.com.bo

lvaroPintoTorrejn
apinto@alternext.com.bo

También podría gustarte