Вы находитесь на странице: 1из 7

recepcion de datos por puerto serial visual c++ | Programando con Huguito http://uitoarellanojosehugoarellanoperez.wordpress.com/category/rece...

Recepcinde datos en C++ a travs del puerto serial

1 de 7

14/07/2013 6:43

recepcion de datos por puerto serial visual c++ | Programando con Huguito http://uitoarellanojosehugoarellanoperez.wordpress.com/category/rece...

publicrefclass Form1 : publicSystem::Windows::Forms::Form { public: intnumimpresiones;

Form1(void) { InitializeComponent(); // //TODO:agregar cdigo de constructor aqu // numimpresiones=0;

if(!PuertoSerial->IsOpen) { try { //se abre el puerto serial PuertoSerial->Open(); } catch (Exception ^ex) { //manda un mensaje si no hay puerto detectado MessageBox::Show(No hay puertos abiertos); } } Ahora programamos elevento DataReceived del SerialPort:

Antes de ello declaramos un delegado: delegatevoidDelegado(String ^ s); Ahora s programamos el evento DataReceived //programacindeleventoDataReceived private: System::VoidPuertoSerial_DataReceived_1(System::Object^ sender, System::IO::Ports::SerialDataReceivedEventArgs^ e) { //sedeclara una variable s de tipo string String ^ s; if(PuertoSerial->BytesToRead>0){// Si hay datos a leer s=PuertoSerial->ReadExisting(); // Leemosdatos.Delegado ^ Escribir=gcnew Delegado(this,&Form1::vCargaDatos);// Invocamos a funcin que escribe en TextBox this->Invoke(Escribir,s); } }

2 de 7

14/07/2013 6:43

recepcion de datos por puerto serial visual c++ | Programando con Huguito http://uitoarellanojosehugoarellanoperez.wordpress.com/category/rece...

//metodopara imprimir en el TextBoxDatosRecepcion voidvCargaDatos(String ^Data){ if(numimpresiones<30) { //agregaal textboxDatosRecepcion el valor de data DatosRecepcion->Text+=Data; //incrementode la variable numimpresiones numimpresiones=numimpresiones+1; } else { //limpiatextboxDatosRecepcion DatosRecepcion->Text=L; //agregaal textboxDatosRecepcion el valor de data DatosRecepcion->Text+=Data; //inicializanuevamente la variable numimpresiones en cero numimpresiones=0; } }

#pragmaonce namespacemyserialport usingnamespace usingnamespace usingnamespace usingnamespace usingnamespace usingnamespace

{ System; System::ComponentModel; System::Collections; System::Windows::Forms; System::Data; System::Drawing;

/// <summary> /// Resumen de Form1 /// </summary> publicrefclass Form1 : publicSystem::Windows::Forms::Form { public: //variableglobal para contar las veces //quese imprime en el textboxDatosRecepcion intnumimpresiones; Form1(void) { InitializeComponent(); // //TODO:agregar cdigo de constructor aqu // //seinicializa la variable numimpresiones numimpresiones=0; if(!PuertoSerial->IsOpen) { try { //abre el SerialPort PuertoSerial->Open(); } catch (Exception ^ex) { //manda un mensaje si no hay puerto detectado MessageBox::Show(No se encontr el puerto); } } } protected: /// <summary> ///Limpiar los recursos que se estn utilizando. /// </summary> ~Form1() { if (components) { delete components; } } private: System::IO::Ports::SerialPort^ PuertoSerial; private: System::Windows::Forms::TextBox^ DatosRecepcion; protected: private: System::Windows::Forms::Label^ lbdatosrecibidos; private: System::ComponentModel::IContainer^ components; private: /// <summary> ///Variable del diseador requerida.

3 de 7

14/07/2013 6:43

recepcion de datos por puerto serial visual c++ | Programando con Huguito http://uitoarellanojosehugoarellanoperez.wordpress.com/category/rece...

/// </summary> #pragmaregion Windows Form Designer generated code /// <summary> ///Mtodo necesario para admitir el Diseador. No se puede modificar /// elcontenido del mtodo con el editor de cdigo. /// </summary> voidInitializeComponent(void) { this->components = (gcnewSystem::ComponentModel::Container()); this->PuertoSerial = (gcnewSystem::IO::Ports::SerialPort(this->components)); this->DatosRecepcion = (gcnewSystem::Windows::Forms::TextBox()); this->lbdatosrecibidos = (gcnewSystem::Windows::Forms::Label()); this->SuspendLayout(); // // PuertoSerial // this->PuertoSerial->PortName = LCOM10; this->PuertoSerial->StopBits =System::IO::Ports::StopBits::Two; this->PuertoSerial->DataReceived += gcnewSystem::IO::Ports::SerialDataReceivedEventHandler(this,&Form1::PuertoSerial_DataReceived_1); // // DatosRecepcion // this->DatosRecepcion->Location =System::Drawing::Point(12, 34); this->DatosRecepcion->Multiline = true; this->DatosRecepcion->Name = LDatosRecepcion; this->DatosRecepcion->Size = System::Drawing::Size(362,255); this->DatosRecepcion->TabIndex = 0; // //lbdatosrecibidos // this->lbdatosrecibidos->AutoSize= true; this->lbdatosrecibidos->BackColor =System::Drawing::Color::Silver; this->lbdatosrecibidos->Font = (gcnew System::Drawing::Font(LMicrosoftSans Serif, 9.75F, System::Drawing::FontStyle::Bold,System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->lbdatosrecibidos->Location =System::Drawing::Point(12, 9); this->lbdatosrecibidos->Name = Llbdatosrecibidos; this->lbdatosrecibidos->Size =System::Drawing::Size(122, 16); this->lbdatosrecibidos->TabIndex = 1; this->lbdatosrecibidos->Text= LDatos recibidos:; // // Form1 // this->AutoScaleDimensions =System::Drawing::SizeF(6, 13); this->AutoScaleMode =System::Windows::Forms::AutoScaleMode::Font; this->BackColor =System::Drawing::Color::LightGray; this->ClientSize = System::Drawing::Size(386,298); this->Controls->Add(this->lbdatosrecibidos); this->Controls->Add(this->DatosRecepcion); this->Name = LForm1; this->Text = LLeerpuertoserie; this->Load += gcnewSystem::EventHandler(this,&Form1::Form1_Load); this->ResumeLayout(false); this->PerformLayout(); } #pragmaendregion /*************************************************************************************************************************************/ delegatevoidDelegado(String ^ s); private: System::VoidPuertoSerial_DataReceived_1(System::Object^ sender, System::IO::Ports::SerialDataReceivedEventArgs^ e) { String ^ s; if(PuertoSerial->BytesToRead>0){ // Si haydatos a leer s=PuertoSerial->ReadExisting(); // Leemosdatos.Delegado ^ Escribir=gcnew Delegado(this,&Form1::vCargaDatos);// Invocamos a funcin que escribe en TextBox this->Invoke(Escribir,s); } } //metodopara imprimir en el TextBoxDatosRecepcion voidvCargaDatos(String^ Data){ if(numimpresiones<30) { //agregaal textboxDatosRecepcion el valor de data DatosRecepcion->Text+=Data; //incrementode la variable numimpresiones numimpresiones=numimpresiones+1; } else { //limpiatextboxDatosRecepcion

4 de 7

14/07/2013 6:43

recepcion de datos por puerto serial visual c++ | Programando con Huguito http://uitoarellanojosehugoarellanoperez.wordpress.com/category/rece...

DatosRecepcion->Text=L; //agregaal textboxDatosRecepcion el valor de data DatosRecepcion->Text+=Data; //inicializanuevamente la variable numimpresiones en cero numimpresiones=0; } } }; }

Circuito montado en Proteus:

Cdigo del programa para el pic en PIC C

5 de 7

14/07/2013 6:43

recepcion de datos por puerto serial visual c++ | Programando con Huguito http://uitoarellanojosehugoarellanoperez.wordpress.com/category/rece...

Cuando no encuentre puerto serie mostrar un MessageBox:

6 de 7

14/07/2013 6:43

recepcion de datos por puerto serial visual c++ | Programando con Huguito http://uitoarellanojosehugoarellanoperez.wordpress.com/category/rece...

7 de 7

14/07/2013 6:43

Вам также может понравиться