I have the code below that simply turns an LED on and off if the photo interrupter's signal is interrupted. I'm new to Arduino and don't know enough C++ to start writing code from scratch so I was wondering if I could simply replace the ledPin output and add in a servo instead? I imagine I have to include the servo library but I know it's probably not this simple. I just want to make the servo rotate a distance and then stop if the photosensor is activated.
int ledPin=13;
int sensorPin=3;
int val;
void setup() {
pinMode(ledPin,OUTPUT);
pinMode(sensorPin,INPUT);
}
void loop() {
val=digitalRead(sensorPin);
if(val==HIGH)
{
digitalWrite(ledPin,LOW);
}
else
{
digitalWrite(ledPin,HIGH);
}
}
Any help will be appreciated, thank you!
I was wondering if I could simply replace the ledPin output and add in a servo instead?
It is not quite that easy but it is not difficult. It is easier to show you than to describe it
#include <Servo.h>
int ledPin = 13;
int servoPin = 9; //choose your own pin for the servo
int sensorPin = 3;
int val;
Servo aServo; //create a Servo object
void setup()
{
pinMode(ledPin, OUTPUT);
pinMode(sensorPin, INPUT);
aServo.attach(servoPin); //associate the servo with a pin
}
void loop()
{
val = digitalRead(sensorPin);
if (val == HIGH)
{
digitalWrite(ledPin, LOW);
aServo.write(150); //move the servo to 150
}
else
{
digitalWrite(ledPin, HIGH);
aServo.write(60); //move the servo to 60
}
}
Amend the code to use a different pin and angles to suit yourself and take out the LED code if it is not needed
Thank you so much, you're right, it's a bit less complicated than I thought it would be. Just by looking at this code it helps me learn a lot about how Arduino works, thank you! I will try this code tonight.