Unit 27: Passive control
Code for Sketch One:
#include
const int tiltPin = 10; // Tilt sensor connected to pin 10
const int potentiometerPin = A0; // Potentiometer connected to analog pin A0
const int buzzerPin = 11; // Buzzer connected to pin 11
Servo myServo; // Create a Servo object
void setup() {
myServo.attach(9); // Attach servo to pin 9
pinMode(tiltPin, INPUT); // Set tilt pin as input
pinMode(buzzerPin, OUTPUT); // Set buzzer pin as output
Serial.begin(9600); // Initialize serial communication
}
void loop() {
// Read the potentiometer value (0-1023)
int potValue = analogRead(potentiometerPin);
// Map the potentiometer value to the servo angle (0-180)
int servoAngle = map(potValue, 0, 1023, 0, 180);
// Set the servo to the mapped angle
myServo.write(servoAngle);
// Read the tilt sensor state
int tiltState = digitalRead(tiltPin);
// Determine buzzer state
bool buzzerState = (tiltState == LOW); // Buzzer ON if tilted (LOW), OFF if upright (HIGH)
// Debugging output
Serial.print("Potentiometer Value: ");
Serial.print(potValue);
Serial.print(" | Servo Angle: ");
Serial.print(servoAngle);
Serial.print(" | Tilt State: ");
Serial.print(tiltState == LOW ? "Tilted (LOW)" : "Upright (HIGH)");
Serial.print(" | Buzzer: ");
Serial.println(buzzerState ? "ON" : "OFF");
// Control the buzzer based on the tilt state
digitalWrite(buzzerPin, buzzerState ? HIGH : LOW); // Turn buzzer on or off
delay(100); // Stability delay
}