Search code examples
c#arduinoarduino-unoservo

Control two servos from WinForms C# application with Arduino Uno


I'm trying to figure out, how to control two servos separately from WinForms C# desktop application.

In C# initialization:

 myport.PortName = "COM6";
 myport.BaudRate = 9600;
 myport.Open();

Controlled by trackBar1:

private void trackBar1_Scroll(object sender, EventArgs e)
{
     if (myport.IsOpen)
     {
         myport.WriteLine(trackBar1.Value.ToString());
     }
}

Arduino code moves servos with pin 9 and 11, one goes to left, anther to right side synchronously :

#include <Servo.h>
Servo servo1;
Servo servo2;
int val;

void setup() {
    Serial.begin(9600);
    servo1.attach(9);
    servo2.attach(11);
}

void loop() {
  val = Serial.parseInt();
  if(val != 0){
    servo1.write(val);
    servo2.write(val);
  }
}

to control direction, I can create separate function void for servo1 and servo2 with different angle value, but I can't figure out, how to get separate control for each servo from C# application. I'm not sure, what I have to add in Arduino uploaded code and C#, for example, if I want control servo2 from pin 11 with trackBar2 and servo1 from pin 9 with trackBar1:

private void trackBar2_Scroll(object sender, EventArgs e)
{
    if (myport.IsOpen)
    {
        myport.WriteLine(trackBar2.Value.ToString());
    }
}

Any advice, guide or example would be very helpful


Solution

  • One option would be, instead of just reading ints on your Arduino, wait for character 'A' or 'B', then read an int. If the character is 'A' move servo1, if the character is 'B' move servo2. In your .net app, Write 'A' or 'B' before sending the trackbar value

    Note: Untested

    // in Arduino
    void loop() {
      switch(Serial.read())
      {
        case 'A':
          servo1.write(Serial.parseInt());
          break;
        case 'B':
          servo2.write(Serial.parseInt());
          break;
      }
    }
    
    
    // in c#
    myport.Write('B')
    myport.WriteLine(trackBar2.Value.ToString());