Go Down

Topic: Toggle switch and servo (Read 657 times) previous topic - next topic


Nov 22, 2019, 11:00 pm Last Edit: Nov 23, 2019, 12:46 am by Mata007
Hi guys so I'm pretty new to arduino and for my new project I need to know how to control the servo with control switch... So I'm trying to know how to do when the toggle switch value is low, the servo val should be 0.And when the toggle switch value is high , how do I make servo rotate 180 degrees?

Plz help me :(  lol...

P.S ignore the led variables, I wanted it to be later inputed


OP's code
Code: [Select]

#include <Servo.h>

Servo serv;
int button = 3;
int led = 4;
int ledval;
int butval;

void setup(){
  pinMode(button, INPUT);
  pinMode(led, OUTPUT);

void loop(){
  ledval = digitalRead(led);
  butval = digitalRead(button);

You don't seem to have got very far.

The Button example from the IDE will give you everything you need. Just replace the digitalWrites that switch the LED on or off with  serv.write(0) or serv.write(180).





Your code can be:
Code: [Select]
#include <Servo.h>

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

// constants won't change. They're used here to set pin numbers:
const int BUTTON_PIN = 7;       // the number of the pushbutton pin
const int SERVO_PIN = 9;       // the number of the pushbutton pin

void setup() {
  // initialize the pushbutton pin as an pull-up input
  // the pull-up input pin will be HIGH when the switch is open and LOW when the switch is closed.
  myservo.attach(SERVO_PIN);  // attaches the servo on pin 9 to the servo object

void loop() {
  // read the state of the switch/button:
  int buttonState = digitalRead(BUTTON_PIN);

  if(buttonState == LOW)

This is a combination of codes in two tutorials: Button and Servo motor

The code for the switch is the same as code for the button.

You can see line-by-line explanation in the above tutorials


Go Up