mercredi 6 février 2013

Controlling the steering servo with a mouse: the Arduino code


On the Arduino side, I also adapted the sketch to fits with my purpose:

#include <Servo.h>

Servo xservo; // xservo is the direction servo

int xpos= 0;

void setup(){
xservo.attach(9); //attach the servo to pin 9
Serial.begin(9600); // 9600 is the rate of communication
}

void loop() {
static int v = 0; // value to be sent to the servo (0-180)
if ( Serial.available()) {
char ch = Serial.read(); // read in a character from the serial port and assign to ch
switch(ch) { // switch based on the value of ch, it will be only x in this case
case '0'...'9': // if it's numeric
v = v * 10 + ch - '0';
/*
so if the chars sent are 45x (turn x servo to 45 degs)..
v is the value we want to send to the servo and it is currently 0
The first char (ch) is 4 so
0*10 = 0 + 4 - 0 = 4;
Second char is 4;
4*10 = 40 + 5 = 45 - 0 = 45;
Third char is not a number(0-9) so we drop through...
*/
break;
case 'x': // if it's x
/*
....and land here
where we send the value of v which is now 45 to the x servo
and then reset v to 0
*/
v = constrain(v, 60, 130); // constrain the value to be between 60 and 130
xservo.write(v); // send the value to the servo
delay(25);
v = 0; // reset this value to 0
break;
}
}
}

Aucun commentaire:

Enregistrer un commentaire