How to tell servo to follow a pendulum movement

I have a pendulum and arduino reading script. I was able to track simple movements, but I cannot make it follow pendulum curve and convert it into degrees.

#include <Servo.h> 

//load servo to control it
    Servo myservo;  
#define servoPin 9

int sangle=0;
//information comming into servo = numbers read from processing
int inByte=0;

void setup() { 
//attach a pin 9 to servo
  myservo.attach(servoPin); 
 Serial.begin(9600);
} 

void loop() { 

 if(0<Serial.available()){
  inByte=Serial.read();
 }
 sangle=inByte;
 myservo.write(sangle);
}

and processing script:

import processing.serial.*;
Serial port;

float x= (PI/2);
float pos=0; 
float pos1=PI/4;
byte sangle=0;
float angle_degrees=0;
float rotangle=0;

void setup() {
  size(800, 800);
 port=new Serial(this,"COM3",9600);
}

void draw() {
  background(255);

// float rotangle = atan2(height/4, width/2);
//my servo is 90 degrees to each side =180
  rotangle=constrain(rotangle,0,PI);
  angle_degrees=degrees(rotangle);
  println(angle_degrees);
//send information into arduino
  port.write(sangle);

  translate(width/2, height/4);
  rotate(pos1*cos(millis()/900.0));
  stroke(0);
  strokeWeight(3);
  line(0, 0, 0, 300);
  fill(#0074FF);
  noStroke();
  ellipse(0, 300, 40, 40);
  println(pos1);
  println(angle_degrees);
  }

Answers

  • edited January 2018 Answer ✓

    in the processing script:

    this

    port.write(sangle);

    should be

    port.write(angle_degrees); or something like this.

    Remark

    You can use map() to transfer the values of angle_degrees to the value that the servo needs, e.g.

    valueForServo = map(angle_degrees,0,360,-22,22);
    port.write( valueForServo ); 
    

    Chrisir

  • It sounds like you are tracking a physical pendulum with sensors. If you are interested in classes that model pendulums, you also might find this interesting:

    https://forum.processing.org/two/discussion/comment/108565/#Comment_108565

Sign In or Register to comment.