Serial connection between Esp32 and PC using C# interface gives wrong numbers

Hello,
I'm currently working on a 6DoF robotic arm controlled by an Esp32 Dev Module and and interface written in C#. I want to be able to control the robot from a C# WPF interface and therefore use a wired serial connection. For test purposes I created a simple sketch, which print out the input to the serial port when the first two characters are "J1". My interface writes a new line to the serial port when a button is pressed and writes "J1 " + (a value in a TextBox, which increased by ten each time the button is pressed). When I run my codes the Esp32 doesn't print out the right string and numbers in to the serial ports.
For reference:
Baudrate : 125200
ReadTimeout : 200ms
Writetimeout : 200ms

Here's the simple Esp32 sketch written in the official Arduino IDE:

String inData;
void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  Serial.setTimeout(200);
  // set the data rate for the SoftwareSerial port
}

void loop() { // run over and over
  while (Serial.available() > 0)
  {
    char recieved = Serial.read();
    inData += recieved;
    // Process message when new line character is recieved
    if (recieved == '\n')
    {
      String function = inData.substring(0, 2);
      if(function == "J1"){
        Serial.println(inData);
      }
    }
  }
}

Here's the section in my C# codebehind:

        private void joint1IncreaseBtn_Click(object sender, RoutedEventArgs e)
        {
            if (incrementalJogCBox.IsChecked == true && (joint1Angle + jogValue) <= joint1MaxAngle)
            {
                joint1Angle += jogValue;
                joint1Refresh();

                string message = "J1 " + joint1Angle.ToString("0.000");
                serialPort.WriteLine(message);

                Thread.Sleep(200);
                string serialReceive = serialPort.ReadLine();
                gripperCloseBtn.FontSize = 8;                  //just a random button to write the received data to
                gripperCloseBtn.Content = serialReceive;
            }
        }

        public void joint1Refresh()
        {
            joint1Angle = Math.Round(joint1Angle, 6);
            joint1Slider.Value = joint1Angle;
            joint1Box.Text = joint1Angle.ToString("0.000");
        }

Here's the XAML markup with the increase button (when pressed the textBox increases by 10 or a given value:

<Border Grid.Column="1" Grid.Row="0" x:Name="joint1ControlsBorder"BorderBrush="LightGray" BorderThickness="1">
     <Grid x:Name="joint1Grid">
            <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition Width="4*"/>
                    <ColumnDefinition/>
              </Grid.ColumnDefinitions>
              <Grid.RowDefinitions>
                     <RowDefinition/>
                      <RowDefinition Height="0.8*"/>
                       <RowDefinition Height="1.8*"/>
                </Grid.RowDefinitions>

               <Label Content="Joint 1" x:Name="joint1Label" Grid.Column="0" Grid.Row="0"                                Grid.ColumnSpan="3" FontSize="30"/> 
                <StackPanel Orientation="Horizontal" Grid.Column="1" Grid.Row="1" HorizontalAlignment="Center">
                 <TextBox x:Name="joint1Box" Text="{Binding ElementName=join1Slider , Path=Value}" MinWidth="80" Margin="0,0,15,0"KeyDown="joint1Box_KeyDown" LostFocus="joint1Box_LostFocus" PreviewTextInput="OnlyAllowNumbers"/>
                   <Button x:Name="joint1ResetBtn" Click="joint1ResetBtn_Click" HorizontalAlignment="Center"Content="&#x1F5D8;" Margin="0" Height="{Binding Width, RelativeSource={RelativeSource Self}}" Style="{StaticResource resetBtn}"/>
                     </StackPanel>
                            <Slider x:Name="joint1Slider" Grid.Column="1" Grid.Row="2"    TickFrequency="0.100"IsSnapToTickEnabled="True"
ValueChanged="joint1Slider_ValueChanged" Value="0"/>
                      <Button x:Name="joint1DecreaseBtn" Click="joint1DecreaseBtn_Click"  Content="-"Grid.Column="0" Grid.Row="2" Style="{StaticResource inc-decBtnStyle}" FontSize="50"PreviewMouseDown="joint1DecreaseBtn_PreviewMouseDown" PreviewMouseUp="joint1DecreaseBtn_PreviewMouseUp"/>
                       <Button x:Name="joint1IncreaseBtn" Click="joint1IncreaseBtn_Click" Content="+"Grid.Column="2" Grid.Row="2" Style="{StaticResource inc-decBtnStyle}" FontSize="50"PreviewMouseDown="joint1IncreaseBtn_PreviewMouseDown" PreviewMouseUp="joint1IncreaseBtn_PreviewMouseUp"/>

             </Grid>
</Border>

What happens:
When I click the increase button the textBox:text increases by a given amount (10) and a variable changes. Then the code write a new Line to the serial port : "J1 " + joint1Anlge ( = textBox.Text) and then in the button the content should change to "J1 " + TextBox.Value". However this just happend sometimes and sometimes when the value in the TextBox is 60 for example it outputs 40 and increses by ten every click. When I change the increse Value (from ten to one) for example it still outputs numbers incresing by ten and sometimes it outputs an empty string.

I'd be very grateful if someone can explain why this is and how I can fix it. Thanks for your help

Ignore what the user interface displays. Instead use the C# debugger with breakpoints to see exactly what data is being sent and received.

Thanks, I'll try that, but why are some wrong values shown?

I've tried debugging now and by the first click the value is correct. However as i clicked it twice the value of the serialReceive string is "\r". When I restarted the C# program and tried my code the out put were the ones of the former run. Can you help me further?

In your C# program create a log file that records the data you send and receive.

Also, currently your Arduino code appends to inData, which presumably gets bigger forever. You should probably clear it after doing
Serial.println(inData)

During my first run I implemented, that each time I click the button a new line, containing the received data, is written into a text file. the value should increase by one. :

J1 35.000
J1 75.000
J1 125.000
J1 15.000
J1 30.000
J1 1.000
J1 1.000

J1 35.000
J1 75.000
J1 125.000
J1 15.000
J1 30.000
J1 1.000
J1 1.000
J1 2.000

J1 35.000
J1 75.000
J1 125.000

I then re-uploaded the sketch and got these results:

J1 1.000

J1 1.000
J1 2.000

J1 1.000
J1 2.000
J1 3.000

J1 1.000
J1 2.000
J1 3.000
J1 4.000

J1 1.000
J1 2.000
J1 3.000
J1 4.000
J1 5.000

During my third test set inData = "" (as you suggested). I clicked the button 20 times and by an increment of 1:

J1 1.000

J1 2.000

J1 3.000

J1 4.000

J1 5.000

J1 6.000

J1 7.000

J1 8.000

J1 9.000

J1 10.000

The empty lines are probably the "\r" I saw during debugging. Am I right?

Is this the sent and received data?

Close the C# program and use the Arduino IDE terminal window to send simulated data to the Arduino serial port and see what is returned.

No, it's just the received data.

I simulated the input of the C# application by entering: J1 1.000, J1, 2.000, J1 3.000, J1 4.000, J1 5.000 into the Serial Monitor. Here are the outputs:

J1 1.000

J1 2.000

J1 3.000

J1 4.000

J1 5.000

I wrote the string into the file, that's being send through the serial port. The send strings are the one with the "--" in the front:

-- J1 1.000
J1 1.000
-- J1 2.000

-- J1 3.000
J1 2.000
-- J1 4.000

-- J1 5.000
J1 3.000
-- J1 6.000

-- J1 7.000
J1 4.000
-- J1 8.000

-- J1 9.000
J1 5.000
-- J1 10.000

The inData contains a '\n'.
Using println adds another '\n' to the transmitted data.

Thank you, how can I change it?

Serial.print(inData);

1 Like

Thank you very much. It finally works!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.