Servo motor with LED

When potentiometer is rotated clockwise green led turns on and red remains off. When potentiometer is rotated anticlockwise the red led turns on and green remains off.
Is there any improvement that you can suggest with the circuit and program to accomplish the task?

Also why in the following code Serial.print values don't show in Serial Monitor of Tinkcard?

Code:

/*
 Controlling a servo position using a potentiometer (variable resistor)
 by Michal Rinott <http://people.interaction-ivrea.it/m.rinott>

 modified on 8 Nov 2013
 by Scott Fitzgerald
 http://www.arduino.cc/en/Tutorial/Knob
*/

#include <Servo.h>

Servo myservo;  // create servo object to control a servo

int potpin = A0;  // analog pin used to connect the potentiometer
int val;    // variable to read the value from the analog pin

int green_led = 0;
int red_led = 0;


void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
  
}

void loop() {
 
  
  val = analogRead(potpin);            // reads the value of the potentiometer (value between 0 and 1023)
  Serial.print(val);
 
  val = map(val, 0, 1023, 0, 180);     // scale it for use with the servo (value between 0 and 180)
  Serial.print(val);
  
  myservo.write(val);                  // sets the servo position according to the scaled value
  Serial.print(val);
  delay(15);                           // waits for the servo to get there

   if (val <= 90) {
    digitalWrite(11, HIGH);
    digitalWrite(12, LOW);
  }
  
  else {
    digitalWrite(12, HIGH);
    digitalWrite(11, LOW);
  }
}

Is "clockwise" increasing or decreasing the resistance value of analogRead()?

You need to add Serial.begin(your-baud-rate); in void setup() for Serial.print() to work.

1 Like

A few things...

#include <Servo.h>

Servo myservo;  // create servo object to control a servo

int potpin = A0;  // analog pin used to connect the potentiometer
int val;    // variable to read the value from the analog pin

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  pinMode(12, OUTPUT);
  pinMode(11, OUTPUT);
}

void loop() {
  val = analogRead(potpin);            // reads the value of the potentiometer (value between 0 and 1023)
  Serial.print(val);

  // do the LEDs before truncating the value
  if (val < 1024 / 2) {
    digitalWrite(11, HIGH);
    digitalWrite(12, LOW);
  }
  else {
    digitalWrite(12, HIGH);
    digitalWrite(11, LOW);
  }

  val = val * 180L / 1024;    // scale it for use with the servo (value between 0 and 180)
  Serial.print(val);
  myservo.write(val);                  // sets the servo position according to the scaled value
  delay(15);                           // waits for the servo to get there
}
1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.