I'm a beginner in Visual C++ and I'm trying to established a serial communication.I am using VS 2010 and windows forms application to create my program.
I've made a devise that measures distance and sending the value to the PC.The Value of the measurement is changing continuously. So I need from my program to read the serial port continuously.
As you can see I'm using the ReadByte() method to read from the port and there is a loop to read from the port while the port is opened. I'm using ReadByte because the device sending to the PC 1 byte each time in hex.
But when I'm running the program and try to read from the port the following message shown:
-An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll
-Additional information: Cross-thread operation not valid: Control 'textBox1' accessed from a thread other -than the thread it was created on.
It seems to be an error in the ReadData event. What I am doing wrong?
Thanks in advance.
private: System::Void ConnectBtn_Click(System::Object^ sender, System::EventArgs^ e)
{
if (!serialPort1->IsOpen)
{
serialPort1->Open();
serialPort1->DtrEnable=true;
serialPort1->RtsEnable=true;
ComStatusLabel->Text="Status:CONNECTED";
}
else
{
ComStatusLabel->Text="Status:DISCONNECTED";
}
try
{
serialPort1->ReadByte();
}
catch(TimeoutException^)
{
MessageBox::Show(" Σφάλμα Σύνδεσης ");
serialPort1->Close();
PortList->Enabled=true;
serialPort1->DtrEnable=false;
serialPort1->RtsEnable=false;
ComStatusLabel->Text="Status:DISCONNECTED";
}
}
private: System::Void DisconnectBtn_Click(System::Object^ sender, System::EventArgs^ e)
{
serialPort1->Close();
serialPort1->DtrEnable=false;
serialPort1->RtsEnable=false;
PortList->Enabled=true;
ComStatusLabel->Text="Status:DISCONNECTED";
}
private: System::Void PortList_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e)
{
//setting the Port name to read from the port we want to.
String^ comname;
comname=Convert::ToString(PortList->Text);
serialPort1->PortName=(comname);
PortList->Enabled=false;
}
private: System::Void FindPort_Click(System::Object^ sender, System::EventArgs^ e)
{
PortList->Items->Clear();// Cleaning the existing List.
//Creating the new list.
array<String^>^ serialPorts = nullptr;//variable for storage the serial port names.
try
{
serialPorts = SerialPort::GetPortNames();// Get a list of serial port names.
}
catch (Win32Exception^)
{
MessageBox::Show("Δεν βρέθηκαν θύρες");//message in case of errror.
}
for each(String^ port in serialPorts)
{
PortList->Items->Add(port );//store the port names to the ComboBox PortList.
}
}
private: System::Void DataRead(System::Object^ sender, System::IO::Ports::SerialDataReceivedEventArgs^ e)
{
Byte data;
do
{
textBox1->Text="";
data=serialPort1->ReadByte();
textBox1->Text=":"+data;
serialPort1->DiscardInBuffer();
}while(serialPort1->IsOpen);
}

New Topic/Question
Reply




MultiQuote





|