Unit 16: Line of Fire
Code for Sketch One:
// Define pin for laser
const int laserPin = 9;
void setup() {
// Initialize laser pin as an output
pinMode(laserPin, OUTPUT);
// Turn the laser on (no off or delay)
digitalWrite(laserPin, HIGH);
}
void loop() {
// Nothing needs to be done here since the laser stays on
}
Code for Sketch Two:
// Define pin for laser
const int laserPin = 9;
void setup() {
// Initialize laser pin as an output
pinMode(laserPin, OUTPUT);
}
void loop() {
// Turn the laser on
digitalWrite(laserPin, HIGH);
// Wait for 5 seconds (5000 milliseconds)
delay(5000);
// Turn the laser off
digitalWrite(laserPin, LOW);
// Wait for 5 seconds (5000 milliseconds)
delay(5000);
}
Code for Sketch Three:
// Define pin for laser
const int laserPin = 9;
void setup() {
// Initialize laser pin as an output
pinMode(laserPin, OUTPUT);
// Seed the random number generator
randomSeed(analogRead(0)); // Uses an analog pin to get a random seed value
}
void loop() {
// Generate random time between 1 and 10 seconds (1000 to 10000 milliseconds)
int randomTime = random(1000, 10001);
// Turn the laser on
digitalWrite(laserPin, HIGH);
// Keep it on for randomTime milliseconds
delay(randomTime);
// Generate another random time for turning the laser off
randomTime = random(1000, 10001);
// Turn the laser off
digitalWrite(laserPin, LOW);
// Keep it off for randomTime milliseconds
delay(randomTime);
}