EventLoopDemo Arduino Sketch

This sketch is used by Exercise: Event-Loop Programming.

Full Source Code

The full code is all in one file EventLoopDemo.ino.

 1// EventLoopDemo.ino : demonstrate generation of two simultaneous square waves at different rates
 2
 3// The example program generates audio-frequency square waves at different
 4// pitches on pins 4 and 5 to demonstrate a simple event-loop control structure
 5// allowing parallel execution of two timed tasks.  The exercise asks the
 6// student to add an analog potentiometer input and use the input value to
 7// modulate the pitch by varying the waveform timing.
 8
 9// Define the pin numbers on which the outputs are generated.
10const int outputPin1 = 4;
11const int outputPin2 = 5;
12
13/****************************************************************/
14// This function is called once after reset to initialize the program.
15void setup()
16{
17  // Initialize the digital output pins to output drive mode.
18  pinMode( outputPin1, OUTPUT );
19  pinMode( outputPin2, OUTPUT );
20}
21
22/****************************************************************/
23// Global variables.
24long next_output_time_1 = 0;        // timestamp in microseconds for when next to update output 1
25long next_output_time_2 = 0;        // timestamp in microseconds for when next to update output 2
26
27long output_interval_1 = 500;       // interval in microseconds between output 1 updates
28long output_interval_2 = 700;       // interval in microseconds between output 2 updates
29
30int output_state_1 = LOW;           // current state of output 1
31int output_state_2 = LOW;           // current state of output 2
32
33/****************************************************************/
34// This function is called repeatedly as fast as possible from within the
35// built-in library to poll program events.
36
37void loop()
38{
39  // read the current time in microseconds
40  long now = micros();
41
42  // Polled task 1 for output 1.  Check if the next_output_time_1 timestamp has
43  // been reached; if so then update the output 1 state.
44  if (now > next_output_time_1) {
45
46    // reset the timer for the next polling point
47    next_output_time_1 = now + output_interval_1;
48
49    // toggle the output_state_1 variable
50    output_state_1 = !output_state_1;
51
52    // update output pin 1 with the new value
53    digitalWrite( outputPin1, output_state_1 );
54  }
55
56  // Polled task 2 for output 2.  Check if the next_output_time_2 timestamp has
57  // been reached; if so then update the output 2 state.
58  if (now > next_output_time_2) {
59
60    // reset the timer for the next polling point
61    next_output_time_2 = now + output_interval_2;
62
63    // toggle the output_state_2 variable
64    output_state_2 = !output_state_2;
65
66    // update output pin 2 with the new value
67    digitalWrite( outputPin2, output_state_2 );
68  }
69}
70/****************************************************************/