ciao a tutti,
ho un problema con la porta seriale in c#.
In pratica ho creato il codice per leggere in continuo dalla porta seriale una serie di caratteri (provenienti da una bilancia elettronica) solo che mi ritorna sempre un valore vuoto.
Questo è il codice:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
namespace bilancia
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Thread threadDoorOpener;
SerialPort serialPort = new SerialPort();
private void Form1_Load(object sender, EventArgs e)
{
Thread.Sleep(1000);
string[] ports = SerialPort.GetPortNames();
serialPort.PortName = "COM4";
serialPort.BaudRate = 9600;
serialPort.DataBits = 8;
serialPort.StopBits = StopBits.One;
serialPort.Parity = Parity.None;
if (serialPort.IsOpen) serialPort.Close();
threadDoorOpener = new Thread((new ThreadStart(this.DoorOpener)));
threadDoorOpener.Name = "alfa";
threadDoorOpener.Start();
}
public void DoorOpener()
{
while (true)
{
serialPort.Open();
serialPort.DtrEnable = true;
string data = "";
while (serialPort.BytesToRead > 0)
{
data += Convert.ToChar(serialPort.ReadByte());
}
txt1.Text = data.ToString();
Thread.Sleep(1000);
serialPort.Close();
}
}
}
}
la variabile data è sempre vuota. Riuscite a dirmi se il codice è giusto?
Grazie a tutti