1

I am trying to get an RFID tag number using a WinForms application. But whenever I click the Button the application stops responding. Please help regarding this.

Arduino code

void setup() {
  Serial.begin(9600);
  SPI.begin();
  rfid.init();
}

void loop() {
  if(rfid.isCard()) {
    if(rfid.readCardSerial()) {
      Serial.print(rfid.serNum[0], HEX);
      Serial.print(" ");
      Serial.print(rfid.serNum[1], HEX);
      Serial.print(" ");
      Serial.print(rfid.serNum[2], HEX);
      Serial.print(" ");
      Serial.print(rfid.serNum[3], HEX);
      Serial.print(" ");
      Serial.print(rfid.serNum[4], HEX);
      Serial.println("");
      delay(1000);
    }
  }
  rfid.halt();
}

C# code

private void button1_Click(object sender, EventArgs e) {
  try {
    serialPort1.Open();
    serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
    textBox2.Text = "connected";
    serialPort1.Close();
  }
  catch(Exception ex) {
    textBox2.Text = "Com port disconnected";
  }
}

private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) {
  SerialPort sp = (SerialPort)sender;
  string indata = sp.ReadExisting();
  textBox1.Text = indata;
}
  • 1
    Remove serialPort1.Close(); because that will close the serial port right after you open it. – Johnny Mopp May 1 '17 at 13:04
  • i tried this now I am getting exception in textbox1.Text=indata; exception is System.InvalidOperationException: 'Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on.' – Ravi May 2 '17 at 15:00
1

You are closing the port immediately after you open it. You need to keep it open while you are expecting data. Remove the line

serialPort1.Close();

Then, in the callback you try to access the GUI from the callback thread. That's not allowed. Use Invoke().

private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
     SerialPort sp = (SerialPort)sender;
     //string indata = sp.ReadExisting();
     string indata = sp.ReadLine();
     //textBox1.Text = indata;
     Invoke(new Action<string>(
         (s) => 
         {
             textBox1.Text = s;
         }
     ), indata);
}
  • now the error is removed but nothing is shown in textbox – Ravi May 2 '17 at 15:53
  • @Ravi First, I noticed I was missing a ) in the code. Second, since you are sending the data with Serial.println(""); you should probably use ReadLine() on the C# side. See updated answer. – Johnny Mopp May 2 '17 at 16:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.