Before I begin, my skill level is pretty novice right now. I've gotten the Experimentation Kit and I'm starting to attempt to adjust code to make new things work, not just follow tutorials.
That said, I came up with a simple goal tonight: Use a pot to control both a servo and an LED at the same time. Pot = 0, the Servo and LED = 0. Pot = 1023, Servo = 179 and LED = 254.
This seemed like an easy enough goal and I felt like I could figure it out on my own by editing the "knob" example code.
Here's the code I'm presently working with:
- Code: Select all
// Controlling a servo position using a potentiometer (variable resistor)
// by Michal Rinott <http://people.interaction-ivrea.it/m.rinott>
int ledPin = 10; // Setting my LED to pin 10
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
int LEDval; // Empty value to control LED brightness
int brightness = 0; //LED brightness value 0 - 254
myservo.attach(9); // attaches the servo on pin 9 to the servo object
analogWrite(ledPin, brightness); // lights up the LED based on brightness value
val = analogRead(potpin); // reads the value of the potentiometer (value between 0 and 1023)
val = map(val, 0, 1023, 0, 179); // scale it to use it with the servo (value between 0 and 180)
LEDval = map(val, 0, 179, 0, 254); // rescale the input over to LED brightness values
brightness = LEDval; // Set the brightness value based on the Pot input
myservo.write(val); // sets the servo position according to the scaled value
delay(30); // waits for the servo to get there
The pot is correctly controlling the servo, but there are no signs of life to the LED.
I set up a "println" command in one variation to make sure the LEDval was getting written correctly and it was.
So I started tearing the code down bit by bit and found that if I remove the "myservo.attach" string from setup, the LED works as expected. But if I put the "myservo.attach" string back in, the servo works but the LED won't anymore.
So my question, after all this rambling: Why won't the LED and the Servo work at the same time? If someone could break it down a little, or lead me down the correct path to figuring it out myself I'd greatly appreciate it! I'm really trying my best to start understanding how to code on my own but, since this involves invoking a servo library and things stop working, I feel like it's already over my head.