In this exercise we were learning how to control servos. We used one servo as is and another that had been hacked to disable it's internal potentiometer. We used a button to switch between them and an off state. Leds show which is enabled.
Here is the code used:
#include <Servo.h>
Servo constant;
Servo angle;
const int ledOff = 6;
const int ledServoCon = 10;
const int ledServoAngle = 3;
const int buttonPin = 2;
const int potPin = A0;
int potValue = 0;
int buttonState = 0;
int buttonPressed = 0;
int ledCount = 0;
int dir = 0;
void setup() {
Serial.begin(9600);
constant.attach(11);//pins 9 and 10 don't work with servos
angle.attach(5);
pinMode(ledOff,OUTPUT);
pinMode(ledServoCon, OUTPUT);
pinMode(ledServoAngle, OUTPUT);
pinMode(buttonPin, INPUT);
digitalWrite(buttonPin, HIGH);
}
void loop() {
buttonPressed = digitalRead(buttonPin);
buttonPressed = map(buttonPressed,0,1,1,0);//we want a 1 when it's pressed, so we used map to reverse the inputs
if(buttonPressed==1){
buttonState ++;//every time we push the button we increase the button state by 1
delay(500);//make sure we don't push the button to many times by keeping our finger there too long
}
if(buttonState>=3){
buttonState = 0;
}
if(buttonState==0){
digitalWrite(ledServoCon,LOW);
digitalWrite(ledServoAngle,LOW);
constant.detach();
angle.detach();
if(ledCount<=0){
dir = 2;//double time
}
else if(ledCount>=255){
dir = -2;
}
ledCount += dir;
analogWrite(ledOff,ledCount);//right now this variable will keep the led brightness next time this is activated.
Serial.println(ledCount);
}
else if(buttonState==1){
digitalWrite(ledOff, LOW);
digitalWrite(ledServoCon, HIGH);
digitalWrite(ledServoAngle, LOW);
constant.attach(11);//because we detach this in our other loops we have to reattach it here.
constant.write(1);
angle.detach();
}
else if(buttonState==2){
digitalWrite(ledOff, LOW);
digitalWrite(ledServoCon, LOW);
digitalWrite(ledServoAngle, HIGH);
constant.detach();
angle.attach(5);
potValue = analogRead(potPin); //get value from potentiometer
Serial.println(potValue);
// delay(500);
potValue = map(potValue,0,1023,0,179);
angle.write(potValue);
potValue = map(potValue, 0,179,0,255);
analogWrite(ledServoAngle, potValue);
Serial.println(potValue);
}
Serial.print(buttonPressed);
Serial.print(" ");
Serial.println(buttonState);
constant.write(179);
}
No comments:
Post a Comment