Share this post

Submit to DeliciousSubmit to DiggSubmit to FacebookSubmit to Google BookmarksSubmit to StumbleuponSubmit to TechnoratiSubmit to TwitterSubmit to LinkedIn
   

In this project I used my USB to serial converter and Visual C++ to send and receive data to and from an AVR microcontroller.

I used the C++ Serial Communication library called CSerial. You can find the library files and the instructions about how to use them in your project here.  

I've used this library in a Windows Forms program.

In this section I explain the code that receives some data from the microcontroller. 

 

here is the first part of the code I wrote inside Form.h file:

 

private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {

CSerial serial;

serial.Open(_T("COM4"));

 

As you can see if button1 is pressed the object "serial" is defined from the class "CSerial".

After that I've tried to open the port "COM4" (in this case would be the virtual serial port defined by my FTDI chip)

 

serial.Setup(CSerial::EBaud9600,CSerial::EData8,CSerial::EParNone,CSerial::EStop1);
serial.SetupHandshaking(CSerial::EHandshakeHardware);

 

serial.WaitEvent();

 

Ok in this part I've set the standard parameters for serial communication which would be Baud Rate,Data,Parity,Stop Bit & Hardware Handshake.

All of these parameters are in default mode and I didn't change anything.

After that you can see the serial wait event. This part just tells the comuter to wait for a serial data to be sent from the microcontroller.

 

serial.Read(szBuffer,sizeof(szBuffer)-1,&dwBytesRead);

 

When a serial data comes from the microcontroller serial.Read takes that data and saves in the array szBuffer.

dwBytesRead saves the number of bytes which have been read from the port.

 

a=Char::ToString(szBuffer[0]);

for (i=1;i<=dwBytesRead;i++)
{
b=Char::ToString(szBuffer[i]);
a=String::Concat(a,b);
}

textBox1->Text=a;

 

Here is the most difficult part and surprisingly it has nothing to do with the serial library itself.

It took me several days to figure out how to show the received data in a text box in Windows Forms.

The reason is clear: textbox only accepts strings to show but the data we get from serial.Read is char.

I found an strange solution: We convert every character in the szbuffer array to string and then we  concatenate them all together to form the final string.

This string now can be shown in a text box. With this technique you can receive a number or a character from a micro and show it easily in a windows application. 

Ok after your work is done you can just close the serial port:

  serial.Close();

 

Enjoy!

   
  
© geek brothers