Devices & Components
Arduino Nano
Momentarty touch sensor
TowerPro MG995 Digital Servo
Touch sensor TTP223 universal
Self latching touch sensor with LED backlight
Software & Tools
Arduino IDE
Project description
Code
Controlling servo with touch sensors
js
Using both momentary and self latching
1#include <Servo.h> 2 3Servo myServo; // Create a Servo object to control the servo 4 5int touchSensorPin = 2; // Touch sensor connected to pin D5 6int servoPin = 9; // Servo connected to pin D9 7 8int angle = 0; // Variable to store current angle of the servo 9int direction = 1; // Direction of servo, 1 for forward, -1 for reverse 10 11void setup() { 12 myServo.attach(servoPin); // Attach the servo to pin D9 13 pinMode(touchSensorPin, INPUT); // Set the button pin as input 14 myServo.write(angle); // Initialize the servo at 0 degrees 15} 16 17void loop() { 18 bool touchDetected = digitalRead(touchSensorPin);//Check if the button is pressed 19 20 if (touchDetected) { 21 // Move the servo by 2 degrees in the current direction 22 angle += direction * 2; 23 // If the servo reaches 0 or 180 degrees, reverse the direction 24 if (angle >= 180) { 25 angle = 180; // Limit the angle to 180 degrees 26 direction = -1; // Reverse direction 27 } else if (angle <= 0) { 28 angle = 0; // Limit the angle to 0 degrees 29 direction = 1; // Reverse direction 30 } 31 myServo.write(angle); 32 } 33 delay(20); 34}
Comments
Only logged in users can leave comments