0% found this document useful (0 votes)
36 views2 pages

This Example Code Is in The Public Domain Sensor-Servo-Motor

This Arduino code uses a touch sensor and servo motor. It initializes the touch sensor pin and servo pin, and creates a servo object. In setup, it configures the pins and attaches the servo. In loop, it reads the touch sensor state and moves the servo to 90 degrees or 0 degrees depending on the last state, printing a message when the sensor is touched.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views2 pages

This Example Code Is in The Public Domain Sensor-Servo-Motor

This Arduino code uses a touch sensor and servo motor. It initializes the touch sensor pin and servo pin, and creates a servo object. In setup, it configures the pins and attaches the servo. In loop, it reads the touch sensor state and moves the servo to 90 degrees or 0 degrees depending on the last state, printing a message when the sensor is touched.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

/*

* Created by ArduinoGetStarted.com
*
* This example code is in the public domain
*
* Tutorial page: https://arduinogetstarted.com/tutorials/arduino-touch-
sensor-servo-motor
*/

#include <Servo.h>

// constants won't change


const int TOUCH_SENSOR_PIN = 7; // Arduino pin connected to touch sensor's
pin
const int SERVO_PIN = 9; // Arduino pin connected to servo motor's
pin

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

// variables will change:


int angle = 0; // the current angle of servo motor
int lastTouchState; // the previous state of touch sensor
int currentTouchState; // the current state of touch sensor

void setup() {
Serial.begin(9600); // initialize serial
pinMode(TOUCH_SENSOR_PIN, INPUT); // set arduino pin to input mode
servo.attach(SERVO_PIN); // attaches the servo on pin 9 to the
servo object

servo.write(angle);
currentTouchState = digitalRead(TOUCH_SENSOR_PIN);
}
void loop() {
lastTouchState = currentTouchState; // save the last
state
currentTouchState = digitalRead(TOUCH_SENSOR_PIN); // read new state

if(lastTouchState == LOW && currentTouchState == HIGH) {


Serial.println("The sensor is touched");

// change angle of servo motor


if(angle == 0)
angle = 90;
else
if(angle == 90)
angle = 0;

// control servo motor arccoding to the angle


servo.write(angle);
}
}

You might also like