User Tools

Site Tools


servo-interactive-test

arduino code

// Controlling a servo position using serial input

#include <Servo.h> 
 
Servo myservo;  // create servo object to control a servo 
 
int val;    // variable to read the value from the analog pin 
char t;
String str;

void setup() 
{ 
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  Serial.begin(9600);
} 
 
void loop() 
{ 
  
  while (Serial.available()>0) {
    char d = Serial.read();
    if (d=='\n') {
      char t[str.length()+1];
      str.toCharArray(t, (sizeof(t)));
      int intdata = atoi(t);
      Serial.println(intdata);
      myservo.write(intdata);   
            str = String();
        }
        else {
            str.concat(d);
        }
  }

 } 

then in python:

import serial
ser=serial.Serial("/dev/ttyACM0", 9600)
ser.write("30\n")
servo-interactive-test.txt · Last modified: 2012/10/11 12:30 by 46.57.95.208