This chapter is from the book
Wireless Doorbell Code
Upload the following code to your Arduinos. If you’re having difficulty figuring out how to upload your sketches, see Chapter 5 to learn how. As before, you can download the code from https://github.com/n1/Arduino-For-Beginners.
Button Unit Code
The Button Unit sketch consists of a loop that waits for the button to be pressed, then transmits a wireless alert.
#include <Wire.h> const int buttonPin = 8; int buttonState = 0; void setup() { Serial.begin(9600); pinMode(buttonPin, INPUT_PULLUP); } void loop() { if (Serial.available() >= 2) { char start = Serial.read(); if (start != '*') { return; } char cmd = Serial.read(); } buttonState = digitalRead(buttonPin); if (buttonState == HIGH) { Serial.write('*'); Serial.write(1); } else { Serial.write('*'); Serial.write(0); } delay(50); //limit how fast we update }
Buzzer Unit Code
The Buzzer Unit code is similarly plain. The loop monitors serial traffic, then sounds the buzzer when it detects the command from the Button Unit.
#include <Wire.h> const int buzzerPin = 13; void setup() { Serial.begin(9600); pinMode(buzzerPin, OUTPUT); } void process_incoming_command(char cmd) { int speed = 0; switch (cmd) { case 1: digitalWrite(buzzerPin, LOW); break; case 0: digitalWrite(buzzerPin, HIGH); break; } } void loop() { if (Serial.available() >= 2) { char start = Serial.read(); if (start != '*') { return; } char cmd = Serial.read(); process_incoming_command(cmd); } delay(50); //limit how fast we update }