c# servo control

ok so i’m trying to control a servo via c#

heres my sketch

#include <Servo.h> 
Servo myservo;

void setup() {

  // set all the other pins you're using as outputs:

  //the serial connection allows you to read commands sent through usb (from my windows form in my case)

void loop() {

 if (Serial.available())
   int c = Serial.read();
   myservo.write( c );


in c# i have

SerialPort port ;
	public int Position = 90;
	// Use this for initialization
	void Start () {
		port = new SerialPort ("COM4", 9600);


then when i call to set the servo position

void SetPos() {
		if (Position>180) {
			Position = 180;
		if (Position<0) {
			Position = 0;

		port.WriteLine (Mathf.RoundToInt ( Position).ToString ());


When i plug my arduino in to the usb, the servo keeps changing position a little and my computer makes the sound of a device being plugged in and unplugged again. This is before the script is run.

When i run my program nothing happens. At all.

i altered both scripts to set the pin 13 LED to turn on and off when i send a letter through and it worked fine.

Any thoughts?

I suspect you are trying to power the servo from the Arduino and the servo is drawing too much current causing the Arduino to reset repeatedly.

Servos should have their own power supply - the Arduino can't supply enough current and may get damaged. The ground for the servo power supply should be connected to the Arduino ground.

A quick test would be to see what happens when the servo is disconnected from everything.


I had connected it tovin instead last night and it worked perfectly. I am however going to attach it to a seperate supply as per your suggestion.

If i attach it to a seperate battery, should the ground still be attached to the ground on arduino?

If i attach it to a seperate battery, should the ground still be attached to the ground on arduino?

Only if you want it to work.

        port.WriteLine (Mathf.RoundToInt ( Position).ToString ());

I know for a fact that I'd have more parentheses in that statement. Not that I understand why you need to use the RoundToInt method defined in the Mathf class to convert Position to an int. Position is defined as an int, and is only assigned integer values. It is NOT a float that needs rounding to an int.

This is only the start of the script. The position var is going to be a float thats why this is prepared this way

Just had a different thought.

How could i parse lines in an arduino sketch to 2 parts eg

int Servo= 9;
int position = 90;
port.WriteLine (Servo + ":" + position);

How would i seperate these in arduino?

How would i seperate these in arduino?

strtok() comes to mind.

of course yeah. excuse my stupidity