chipKIT® Development Platform

Inspired by Arduino™

Serial.write

Created Tue, 11 Aug 2015 22:14:53 +0000 by nicemmicke


nicemmicke

Tue, 11 Aug 2015 22:14:53 +0000

HI,

I am trying to implement a simpel protocoll to send data from the chipkit to my computer. But i get realy strange behavior whit the Serial.Write method. So I did write this litle code to show you the problem.

long int position;

void setup() 
{
  Serial.begin(115200);
}

void loop() 
{
  
  delay(50);
  SendPosition();
}

void SendPosition()
{
  byte data[4];  
  memcpy(data,&position,sizeof(long int));
  
  Serial.write(data,4 );
  Serial.print(position, DEC);
  
  position += 10;
}

The data received in hex form was:

At line 14 the strange behavior starts and end att line 27 and starts again on line 40.

I want to send binary data, but whit this behavior it want work. What am I doing wrong?


majenko

Wed, 12 Aug 2015 10:17:52 +0000

My guess is that it actually has something to do with the reception rather than the transmission of the data.

The problem appears as soon as the high bit of a byte is set to 1, which if you are receiving into a signed variable, will indicate a negative value. My guess is that your PC based program is making a horrible mess of any bytes received with the high bit set and ending up with 0x3F instead of the real value.

What programming language are you working in on the PC? Can you share your receiving program, or the portion of it that does the reception and prints it, with us?


nicemmicke

Wed, 12 Aug 2015 20:40:23 +0000

Hi majenko

Thanks for the replay. I am using c#. Here is a part of the code I am using.

serialPort = new SerialPort(port, speed, Parity.None, 8, StopBits.One);
serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

serialPort.Open();

private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {

            string comData = serialPort.ReadExisting();

            byte[] ba = Encoding.Default.GetBytes(comData);
    
            string hexString = BitConverter.ToString(ba);

            tsw.WriteLine(hexString);
        }

I have now changed the DataReceivedHandler method to this and now its working.

private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
            byte comData;

            while (serialPort.BytesToRead > 0)
            {
                try
                {
                    comData = Convert.ToByte(serialPort.ReadByte());
                   }
                   catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
         }

Thanx again for the help of pointing out where the real problem where.