一个微向我发送一个 10 位帧,其中第一位是Startbit
,最后一位也是Stopbit
。我用下面的程序取数据但是数据是假的;例如,当它向我发送 21 时,我收到 33,当向我发送 83 时,我收到 131。出了什么问题?
class Program
{
static void Main(string[] args)
{
dataCollector dc = new dataCollector();
dc.Start("COM23");
}
public class dataCollector : IDisposable
{
private static dataCollector collector;
public dataCollector()
{
thread = new Thread(new ThreadStart(ThreadMain));
}
private Thread thread;
private SerialPort port;
private void ThreadMain()
{
try
{
if (port.IsOpen)
throw new Exception();
}
catch (Exception)
{
Console.Out.WriteLine("port is not open!!");
}
while (port.IsOpen)
{
try
{
var b = port.ReadByte();
Console.Out.WriteLine(b);
//System.Threading.Thread.Sleep(2000);
}
catch (Exception) { }
}
}
public void Start(string portName, int rate=2600)
{
port = new SerialPort("COM23");//baudrate is 2600;
port.BaudRate = 9600;
//port.DataBits = 8;
//port.StopBits = StopBits.One;
//port.Parity = Parity.None;
port.Open();
thread.Start();
}
public void Stop()
{
if (port != null)
{
if (port.IsOpen) port.Close();
if (thread.IsAlive) thread.Join();
port.Dispose();
}
}
public void Dispose()
{
Stop();
}
}