Flex Sensor and Servo
The following sketch is designed to actuate a servo based on the input from a flex sensor. Because the sketch uses serial communications a button push to start and stop the sketch has been introduced to allow upload on Arduino Uno and Mega boards. An LED has also been introduced to show when the sensor and servo have been enabled. A fair bit of the circuit and the coding was from the Sparkfun Inventor’s Guide - Circuit 13.
A higher resolution image can be picked up from here or by clicking on the image above.
A higher resolution image can be picked up from here or by clicking on the image above.
The sketch below can be downloaded from here: FlexSens_Servo_v2.ino
// Based on File > Examples > Servo > Knob
// Controlling a servo position using a flex-sensor (variable resistor)
// by Michal Rinott
// <http://people.interaction-ivrea.it/m.rinott>
// and also the instructions in the Sparkfun Inventor's Guide - Circuit 13.
// Modifications by Hamish Trolove add a button to start the sketch
// and an LED to indicate when it is activated.
#include <Servo.h>
Servo myservo; // create servo object to
// control a servo
int potpin = 0; // analog pin used to
// connect the potentiometer
int val;
// variable to read the value from the analog pin
const int LEDpin = 12; //LED is on Digital pin 12
const int Button = 2; //Button is on Digital pin 2
volatile boolean Toggle; //Introduce the controlling switch.
//which will change with the interrupt.
void setup()
{
// delay(10000); // This is a 10 sec delay before sketch proceeds.
// this is another safeguard to allow uploading
Serial.begin(9600);
myservo.attach(9);// attaches the servo
// servo on pin 9 to the servo object
pinMode(LEDpin, OUTPUT); //Sets the LEDpin to output
pinMode(Button,INPUT); //Sets the Button to input.
Toggle = false; //Sets the condition toggle
attachInterrupt(0,FFlag,FALLING); //Sets up the Interruptor
//on pin 2,and calls subroutine FFlag when the button value falls.
//using FALLING helps avoid the blink jittering if the button is held.
}
void loop()
{
//Look at the Toggle that tells the loop to run or not.
if (Toggle == true){
digitalWrite(LEDpin,HIGH); //If the Toggle is true then show sketch active.
DoStuff(); //Execute the DoStuff subroutine.
}
else {
digitalWrite(LEDpin,LOW);
delay(400);
}
}
void DoStuff()
{
val = analogRead(potpin);// reads the value
// of the potentiometer(value between 0 and 1023)
Serial.println(val);
val = map(val, 350, 550, 0, 179);
// scale it to use it with the servo
// (value between 0 and 180)
myservo.write(val); // sets the servo
// according to the scaled value
delay(15);
// waits for the servo to get there
}
void FFlag()
{
Toggle = !Toggle; //The should switch the value - "!" means NOT
}