Unit 8: On the Wire

 

 

 

Code for Sketch One: 


const int BUZZER_PIN = 9; // Buzzer pin

const int WIRE1_PIN = 2;  // Wire 1 pin (trigger alarm)

const int WIRE2_PIN = 3;  // Wire 2 pin (no effect)

 

void setup() {

  pinMode(BUZZER_PIN, OUTPUT);

  pinMode(WIRE1_PIN, INPUT_PULLUP); // Use internal pull-up resistor

  pinMode(WIRE2_PIN, INPUT_PULLUP); // Use internal pull-up resistor

}

 

void loop() {

  bool wire1State = digitalRead(WIRE1_PIN);

  bool wire2State = digitalRead(WIRE2_PIN);

 

  if (wire1State == HIGH) {

    tone(BUZZER_PIN, 1000); // Play a 1kHz tone

  } else {

    noTone(BUZZER_PIN);

  }

 

  delay(500); // Delay to debounce the wire cut detection

}

 

 

Code for Sketch Two:

const int BUZZER_PIN = 9; // Buzzer pin

const int WIRE1_PIN = 2;  // Wire 1 pin

const int WIRE2_PIN = 3;  // Wire 2 pin

const int WIRE3_PIN = 4;  // Wire 3 pin

const int WIRE4_PIN = 5;  // Wire 4 pin

int safeWire;             // The wire that does not trigger the alarm

 

void setup() {

  pinMode(BUZZER_PIN, OUTPUT);

  pinMode(WIRE1_PIN, INPUT_PULLUP); // Use internal pull-up resistor

  pinMode(WIRE2_PIN, INPUT_PULLUP); // Use internal pull-up resistor

  pinMode(WIRE3_PIN, INPUT_PULLUP); // Use internal pull-up resistor

  pinMode(WIRE4_PIN, INPUT_PULLUP); // Use internal pull-up resistor

 

  randomSeed(analogRead(0));        // Seed the random number generator

  safeWire = random(2, 6);          // Randomly choose pin 2, 3, 4, or 5 as the safe wire

}

 

void loop() {

  bool wire1State = digitalRead(WIRE1_PIN);

  bool wire2State = digitalRead(WIRE2_PIN);

  bool wire3State = digitalRead(WIRE3_PIN);

  bool wire4State = digitalRead(WIRE4_PIN);

 

  if ((safeWire != WIRE1_PIN && wire1State == HIGH) ||

      (safeWire != WIRE2_PIN && wire2State == HIGH) ||

      (safeWire != WIRE3_PIN && wire3State == HIGH) ||

      (safeWire != WIRE4_PIN && wire4State == HIGH)) {

    tone(BUZZER_PIN, 1000); // Play a 1kHz tone if the unsafe wire is cut

  } else {

    noTone(BUZZER_PIN);

  }

 

  delay(500); // Delay to debounce the wire cut detection

}

 

 

Notes: