abdolah
abdolah

Reputation: 564

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. 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?

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();
        }
    }

Upvotes: 0

Views: 706

Answers (1)

Scott Lemmon
Scott Lemmon

Reputation: 724

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#. Using your examples, 0x21 is 33 in decimal and 0x83 is 131 in decimal.

If you change the line Console.Out.WriteLine(b); to display in hex format like this Console.Out.WriteLine("{0:x}", b); you should find they are, in fact, the same.

Upvotes: 6

Related Questions