This circuit is designed to control a servo motor (MG996R) using an Arduino UNO based on the input from a flex sensor (Basic Flex Resistor). The servo motor's position is determined by the flex sensor's resistance, which changes when the sensor is bent. The Arduino UNO reads the analog value from the flex sensor, maps it to a corresponding servo angle, and then commands the servo to move to that position. The circuit also includes a pull-up resistor to ensure a reliable voltage level for the analog input.
#include <Servo.h>
const int flexPin = A0; // Analog pin for flex sensor
const int servoPin = 9; // PWM pin for servo motor
Servo myServo;
void setup() {
Serial.begin(9600);
myServo.attach(servoPin);
}
void loop() {
int flexValue = analogRead(flexPin); // Read the flex sensor value
int servoAngle = map(flexValue, 0, 1023, 0, 180); // Map the value to a servo angle
myServo.write(servoAngle); // Set the servo position
delay(15); // Small delay for the servo to reach the position
Serial.print("Flex Value: ");
Serial.print(flexValue);
Serial.print(" -> Servo Angle: ");
Serial.println(servoAngle);
delay(100); // Delay for stability
}
File Name: sketch.ino
Description: This code initializes a Servo object and attaches it to pin D9 of the Arduino UNO. In the main loop, the analog value from the flex sensor connected to pin A0 is read and mapped to a servo angle range. The servo is then commanded to move to this angle. The flex sensor value and corresponding servo angle are printed to the serial monitor for debugging purposes.