简体   繁体   English

用C#读取串口信号,接收到错误数据

[英]Serial port signal reading in C#, receives wrong data

A micro sends me a 10 bit frame which in it the first bit is Startbit and the last bit is also Stopbit . 一个微型给我发送一个10位的帧,其中的第一个是Startbit ,最后一个也是Stopbit I used the following program to take the data but the data is false; 我使用以下程序获取数据,但数据为假; for example when it sends me 21 I receive 33 and when sends me 83 I receive 131. What is going wrong? 例如,当它发送给我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();
        }
    }

Your values are actually correct. 您的价值观实际上是正确的。 What is happening is your are seeing the values in hex on the micro-controller, but they are being displayed in decimal when you print them out in c#. 发生的事情是您在微控制器上看到的十六进制值,但是当您在c#中打印出来时,它们以十进制显示。 Using your examples, 0x21 is 33 in decimal and 0x83 is 131 in decimal. 在您的示例中,0x21是十进制的33,0x83是十进制的131。

If you change the line Console.Out.WriteLine(b); 如果更改行Console.Out.WriteLine(b); to display in hex format like this Console.Out.WriteLine("{0:x}", b); 以十六进制格式显示,例如Console.Out.WriteLine("{0:x}", b); you should find they are, in fact, the same. 您应该发现它们实际上是相同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM