Teaching event-based programming – a traffic light

Recently as I was looking through my blogroll, I read Mark Guzdial’s review of the K12CS.org Framework. I wished I had been able to review the framework with a group – I didn’t feel that I generated great ideas about it on my own, but I did like reading Mark’s. Reading my social media feed sometimes impacts what I’m going to teach. In this case, Mark made a point about models of computing:

Great research by people like John Pane at CMU has shown that novices think of programs as responding to events, being reactive (e.g., think apps, games, GUI interfaces). Thinking of computing as input-processing-output is an older model, difficult to understand, and less common today.


Huh. I had been teaching programming as input –> do stuff –> output and wondering to myself what to do when this model broke down. I never really thought about how I teach event-based programming differently. I decided I would give it a try, though. In my 7th-8th grade CS class, my kids had learned about variables, conditionals, and functions. Normally I would plow right into iteration but I decided to take a detour and do some activities with the kids on event-based programming. We did a couple of examples working in Processing with draw() and mouseClicked() and keyPressed(). I decided to introduce an activity involving a state machine to teach the difference between linear programming and event-based programming.

I talked with the kids about how many of us think a traffic light works. We see it as a linear set of steps.



But in reality, we know the traffic light has a set of sensors. And when a sensor is tripped and other conditions are met, then the traffic light advances to the next state. You can model the state with a variable. In this case, I used “lc” for light color. We can model the sensors with button clicks and key presses.


We wrote this program together, imagining that the mouse click simulates a timer expiring, and the space bar simulates the sensor that detects your car. I did this as a teacher-led launch. Kids followed along and ran their programs. Easy.



The kids asked about how you simulate a real timer. In Processing, there isn’t an easy implementation of a “delay” function, so you have to poll for a timer. There is a built-in function millis() that returns the number of milliseconds since the program had started. The kids played with the millis() function and had fun writing the time to the screen. So for the next class, I decided a program that used timers would be a good extension and problem-solving activity.

In the second class, we looked at this state machine model.


My amateurish drawing shows looping arrows where you are polling the timer. As long as the “ready” variable, for example, is 0, then the light stays the same. As soon as the “ready” variable changes to 1, then you can advance to the next state. You can check for “ready” by doing some math on variables that store the value of millis(). One variable stores millis() over and over again. Another variable only stores millis() when the state has just changed.

I put the kids with a partner and made this a pair programming assignment.  We reviewed the norms of pair programming. I gave them a starter program that just showed a red screen and used the millis() function to display the elapsed time. I had some variables in the program but did not tell the kids how to use them. Their task was: turn the program into a timed traffic light. It should turn the red light on for a certain time, then the green light for a longer time, then the yellow light for a very short time, and then go back to red.

This is the starter program.

// 0 is red, 1 is yellow, 2 is green 
int lc = 0; 
int ready = 0; 
int oldms; 
int newms; 
int elapsedms; 
int interval; 

void setup() 
  ready = 0; 
  oldms = millis();
  newms = millis(); 
  elapsedms = newms - oldms; 
  interval = 5000; 
void draw() 
  if(lc == 0) 
  else if(lc == 1) 
  else if(lc == 2) 
  newms = millis(); 
  elapsedms = newms - oldms; 
  text(elapsedms, 150,150); 

The kids split into pairs and started working. After a while, a few groups were close – they could check for a certain elapsed time and then change the light’s state variable so it switched colors. They didn’t know how to reset the timer, so after about 20-30 minutes, most of the kids could change red-green-yellow and then didn’t know how to get back to red.

So I did a catch-and-release where we talked about the polling loop.  I showed boxes that represented the values of “oldms”, “newms”, and “elapsedms” each time through the draw() function. Some kids figured out on their own that the way to reset the timer is by assigning “oldms” to millis() when you change the light’s color. Others figured out different solutions  and it was interesting to see what they came up with.

The activity took most kids until the end of the class. On the third class, I asked all of the pairs to copy and paste their programs into OneNote. I then called up several groups to do a walkthrough of their solution. They did a really good job presenting. I like OneNote for this kind of sharing because the rest of the class could copy the code and run it to understand what the presenting group did.

Here are some of the solutions! I liked how each group approached it a little differently. Some used my variables and some made up their own. Some used nested “if” statements and some used complicated boolean expressions. Some reset the timer after each state change and some waited until after a complete cycle of the traffic light.

Luke and Andrew’s Method

Anna and Kay’s method

Ryan and Parker’s method

I enjoy seeing the students have their lightbulb moments, and it’s also fun to have the overachieving students that can’t resist being a little creative with their programs.

Maya’s Traffic Light

Ben and Anthony’s Traffic Light with car (it stops on red, goes on green, and speeds up on yellow)

I liked this workshop model with the teacher-led launch, the worktime in pairs, and then the student-presented summary. I think it was a good problem-solving activity for the kids, and for me it was a nice departure from the input-stuff-output model of programming.




Tags: , , , ,

About dupriestmath

I'm a former software engineer who has taught middle school math and computer science for the past 6 years. I believe every kid has the right to be a thinker. I started this blog to save resources for integrating programming in the Common Core math classroom. I also use it to save my lessons and reflections from teaching budding computer scientists! Coding has transformed how I teach and think. You'll love what it does for you. You should try it.

7 responses to “Teaching event-based programming – a traffic light”

  1. gflint says :

    To make this really interesting throwing in the crosswalk buttons. A new timer is now involved. The picture I drew on the board was very colorful with lots of arrows. I was happily trudging along with this massive mass of code when one of my students said “Done”. His code was very short and clean. Smart assed kid.

    • dupriestmath says :

      I was thinking about that too. The state machine gets more complicated when you add in the cross streets, crosswalk buttons, left turn arrows etc. It would make a fun simulation to code the whole thing.
      And you’d think we would learn that there is always going to be a kid smarter than we are 🙂 I re-learn that lesson every single day.

    • dupriestmath says :

      Actually I think your blog post here https://gflint.wordpress.com/2015/08/09/flipped-programming/ gave me the original idea that I might like to do a project around a traffic light. The students really liked it and I think it’s really satisfying to code something that seems to have real-world relevance. Thanks much for your work on it.I liked your ideas around “here’s the problem we want to address, let’s learn to code around the project” – but I did give the students some structure.

  2. alfredtwo says :

    I’m playing around with a couple of ways to do this. With .NET languages (I use Visual Basic with my freshmen and C# with my sophomores) I have a timer object to work with. I have created a light class which is used by a traffic signal class. Maybe more complicated then I need but I needed to try some stuff.

    I have the timer control call Signal.NestState where Signal is an object of type Traffic Light. The Traffic Light class has a NextState method which checks the current state and changes the light and returns a new timer interval.

    I’m thinking I can use the traffic light class more or less as I have it now with my freshmen so they can learn about the timer. I may have my sophomores create the Traffic Light class.

    • dupriestmath says :

      Your implementation sounds really sensible and I bet it’s useful for a lot of teaching purposes. I hope my kiddos end up decently prepared for a CS course like yours sometime.

  3. danschellenberg says :

    Very nice, Dawn! I used this idea in my class today, as we were just working on state variables. My starter code was a tad different, but the execution was similar. I wrote a little post about it here: http://dan.schellenbergs.ca/2016/02/29/traffic-light-remix/

  4. Carl says :

    Interesting, if some of your students want to take this a bit farther, they might look at the approaches where whole systems are modeled. There are examples of traffic systems, etc. posted at Supercomputer Challenge. http://www.challenge.nm.org/

    Past projects and program codes are available online. Modeling complex systems versus complicated. So there are traffic systems, infection models, etc. Most of the examples are done by high school students, some by middle school.

    Program languages are Java, Netlogo, and Starlogo.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: