Driving a Relay from Arduino
Combine the transistor-driven relay build from Lesson cb-11 with code, so a sketch can safely switch a higher-power load.
You'll need: the full transistor-and-relay circuit from Lesson cb-11 (including the flyback diode — non-negotiable), with the transistor's base resistor now connected to an Uno digital pin instead of a manual control signal.
An Uno pin can only safely supply a few tens of milliamps — nowhere near enough to drive a relay coil directly. This lesson doesn't change that wiring at all; it simply replaces the "control signal" from Lesson cb-11 with a digital pin, so the same safe isolation (Uno pin → base resistor → transistor → relay coil → flyback diode) still applies.
const int relayPin = 7;
void setup() {
pinMode(relayPin, OUTPUT);
}
void loop() {
digitalWrite(relayPin, HIGH);
delay(2000);
digitalWrite(relayPin, LOW);
delay(2000);
}
This introduces const int relayPin = 7; — a named constant, declared once outside both setup() and loop(), used throughout the rest of the sketch instead of writing the number 7 repeatedly. If you later rewire to a different pin, you change this one line instead of hunting through the whole sketch.
Keep whatever the relay's contacts control to low DC voltage for practice builds — as covered in Lesson cb-11, real mains-voltage switching is a job for a qualified electrician, not a breadboard learning exercise.