Search code examples
c#asp.netserial-portrfid

Reading from a serialport and displaying the result


here's the code I've come-up with so far:

protected void Page_Load(object sender, EventArgs e)
{
    try {
    serialPort1.PortName = "COM4";
    serialPort1.BaudRate = 9600;
    serialPort1.Open();
    this.serialPort1.DataReceived += new      
        System.IO.Ports.SerialDataReceivedEventHandler(this.serialPort1_DataReceived);
    Label1.Text = "Connected";
    UpdatePanel1.Update();
    }
    catch (Exception ex) {

    }
}

string x = "";
private void serialPort1_DataReceived(object sender, 
      System.IO.Ports.SerialDataReceivedEventArgs e){

    x = serialPort1.ReadExisting();
    TextBox1.Text = x;
    UpdatePanel1.Update();
}

the problem is after the code runs the text box remains empty... (Im using AJAX update panel to refresh the textbox text) the thing is when I set breakpoints during debug, the data received from the serial port is in the variable and is set as the new textbox text but when the code finishes nothing is displayed.... I'm pretty sure the updatepanel works because I've tested it.

PS The serialport is connected to an rfid reader and im trying to read tags. I have successfully coded a windows form app to do what I want but I need to migrate it to ASP.NET


Solution

  • Reading data from serial port in ASP.NET application will only work if the reader is connected to the server (not the machine that is running the browser). It seems to be working only because you are testing it locally.

    The serialPort1 object will be destroyed after the initial page render is complete. The ASP.NET page only lives until the page is rendered. Then it is destroyed. The next request again recreates all objects. So the serial port would be opened again and again every time the browser goes to the server.

    UpdatePanel only changes the classic browser requests into AJAX - it does not change how ASP.NET server processing works. It is still request-response actions triggered by the client browser. In your case the UpdatePanel would have to query the server on a timer.

    Your best bet is to create a ActiveX control based on your Windows Forms code and embed that in your website.