# 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.

http://www.openprocessing.org/sketch/311664

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() { size(400,400); ready = 0; oldms = millis(); newms = millis(); elapsedms = newms - oldms; interval = 5000; }

void draw() {

if(lc == 0) { background(255,0,0); } else if(lc == 1) { background(255,255,0); } else if(lc == 2) { background(0,255,0); } newms = millis(); elapsedms = newms - oldms; textSize(30); fill(0,0,0); 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.

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.

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.

# So was I an effective teacher?

We just finished with PARCC testing for the year. Oh my gosh, finally. It was a massive effort involving time and technology and a ton of flexibility and creative problem-solving. For eight school days, I had to teach my computer classes either with no computers or with only a half hour of class time. The tests were really long and tiring and we were fried at the end of each session. I spent a lot of money on cookies and gum to keep the kids’ spirits up. Eight full days of testing schedules. I wondered to myself if the information I’m going to get from PARCC tests is so amazing that it would be well worth the eight days of testing.

So I put forth a little experiment. In the past few years, we have given two standardized math assessments. We give NWEA MAP, which is an hour-long multiple-choice test you can administer anytime on a flexible schedule. It’s easy and you get results right away. I’ve always valued being able to show a kid just how many points she gained in one year, on the day we take the test.

The other assessment has been (up until we started with PARCC) our state assessment, aligned to the Colorado Academic Standards (now Common Core). The test is called TCAP and takes 5-6 hours to administer for math alone. I bet myself that the data from the 1-hour test was just as good as the data from the 6 hour test. I decided I would scatterplot my growth on MAP vs. the growth on TCAP. If the correlation was strong, we were getting good information from both tests, and maybe that’s evidence we could get by with just one of them. You with me?

Growth is ultimately what determines our school’s rating and my rating as a teacher. I’ve always been behind that model, because it doesn’t matter where your kids start at the beginning of the year. If they grow, you’ve taught them, and that’s good. My understanding is that my results from the two standardized tests – MAP and TCAP – are plugged into a formula to give me an Effectiveness Rating.

So. Growth on MAP versus growth on TCAP. For the MAP tests, I see the numbers right away, so I get a raw score in points and just subtract the two spring scores to find the growth. Typical growth is around 6 points. For TCAP, the state uses a “growth model” formula to determine growth from year to year, and then they tell us a child’s growth percentile. Thus, typical growth is in the 50th percentile.

The graph:

I used the correl() function in Excel to find the correlation coefficient. It’s 0.24. If there is a correlation, it’s really weak.

This is the data that was used to determine my effectiveness rating. Would you determine that I did an effective job?

I made a graph of the previous year’s data and found the same thing. Growth by one measure did not predict growth by another. I took my charts to my friend Kathy to show her. She just as nerdy as I am about data, and she gets just as intense about results, so I knew she’d be really interested in it.

Me: So I was curious if growth on MAP had anything to do with growth on TCAP, since they’re used for our effectiveness rating. So I scatterplotted MAP against TCAP growth model.

Kathy: They don’t correlate.

Me: Wha… how did you know?

Kathy: I’ve been plotting mine for four years. My students analyze it as a statistics activity. There is no correlation between their MAP growth and TCAP growth.

Me: I’m having a crisis over this. It always meant a lot to me to get my test results.

Kathy: Maybe it’s just you and me. We ought to look at it department-wide.

So I took my charts to one of my administrators and explained what I found.

Me: So there’s no correlation.

Admin: Really?

Me: Look, there’s the correlation coefficient.

Admin: They’re testing different things.

Me: They shouldn’t be testing different things. Right? They should be measuring your growth in math achievement.

Admin: If they’re testing different things, we have to make sure we’re not treating them as if they’re testing the same thing. I’ll show this to the assessment department head. Will you send it to me electronically?

I have always appreciated that the leadership at my school and my district wants to use data correctly as an improvement tool, and they always welcome a critical discussion. I love that we can have that conversation.

He’s right, the tests probably are measuring different things, but I honestly do not know what they each measure. There are some key differences in the tests. MAP is all multiple choice, TCAP is partly constructed response and graded with a rubric. MAP is computerized. TCAP has always been on paper. MAP is a general survey of math knowledge and problem-solving, TCAP is standards-based and specific to a grade level. But still, you would think if a student generally got smarter in math, they would consistently show growth by both measures, and it just isn’t true.

I am really wondering if everything I’ve ever thought about math achievement tests is a lie.

One possibility is that PARCC will add clarity to this confusing picture of student achievement growth.

The other possibility is that I’ll get one more data point that doesn’t make any sense, but this time I will have wasted 8 days getting that data point.

# Advice on a coding lesson! Credit Card debt and Loops

As my students were learning about loops, I really wanted to add tie-in to personal financial literacy. My students are still very new to programming and this was their first experience with “for” loops. I am struggling with the right amount of structure for this task and would love your help reflecting on it.

Relevant standards:

7th grade Expressions and Equations: Multi-step ratio and proportion problems

CCSS.MATH.CONTENT.7.EE.B.3

Solve multi-step real-life and mathematical problems posed with positive and negative rational numbers in any form (whole numbers, fractions, and decimals), using tools strategically. Apply properties of operations to calculate with numbers in any form; convert between forms as appropriate; and assess the reasonableness of answers using mental computation and estimation strategies.

High School Functions: Exponential Growth

CCSS.MATH.CONTENT.HSF.LE.A.3

Observe using graphs and tables that a quantity increasing exponentially eventually exceeds a quantity increasing linearly, quadratically, or (more generally) as a polynomial function.

Computer Science Teachers Association: Middle School

Implement problem solutions using a programming language, including: looping behavior, conditional statements, logic, expressions, variables, and functions.

I gave the students this problem situation.

Fresh out of college, you need to buy furniture for your new apartment. You’re able to get a credit card with a 15% Annual Percentage Rate (APR). You immediately charge $5000 to the credit card for your new accessories for the crib.

The minimum payment on the credit card is $25, which you pay faithfully every month.

The credit card company charges you 1/12 of the APR every month on whatever money is left on the card.

Write a program that will calculate how much you have left to pay after 36 months.

From here, I have choices.

1) I can give students the pseudocode, and have them write the code.

Use variables for: amount of debt, APR, monthly payment, number of months,

Repeat this loop for the number of months: Subtract the monthly payment from the debt. Add the fee to the debt (1/12 of the APR * the debt) At the end, show how much debt is left.

2) I can give them skeleton code to fill in.

var debt = 5000; var apr = 0.15; var payment = 25; var months = 36;

// complete println( );

for(var i = 0;i<months; i+=1) { // add code and finish println statement println( ); }

// complete println( );

3) I can have them enter the “canned” code and then modify it to answer the key questions.

var debt = 5000; var apr = 0.15; var payment = 25; var months = 36; println("In the beginning you owed: $" + debt); for(var i = 0;i<months; i+=1) { println("At the start of month " + i + " you have $" +debt + " in debt"); debt = debt - payment; debt = debt + (apr / 12 * debt); } println("At the end you have $" + debt + " in debt.");

Here are the questions.

How much will you have to pay each month to pay off the credit card in 36 months?

Modify the program so it prints a message when the card is paid off.

Create and answer other questions with this simulation. Note your questions and what the answers are.

Since this was a new programming structure, I went with option 3. I loved the conversation I had with the students and the interesting questions they asked – but I have been wondering if I should have gone with less scaffolding so they could problem-solve themselves. Always such a tough call when learning something new. What would you have done?

# Using conditionals to understand rates

Computer programs start to become more interesting, interactive, and powerful when you can create the ability for them to make decisions. The conditional is a key concept! The ability to take one of two paths, to make a yes/no decision, is crucial to computing and algorithmic problem solving.

This lesson weaves rates in with conditionals. Relevant standards:

CSTA:L2:CPP:5 Implement problem solutions using a programming language, including: looping behavior, conditional statements, logic, expressions, variables, and functions.

CCSS.MATH.CONTENT.7.RP.A.1

Compute unit rates associated with ratios of fractions, including ratios of lengths, areas and other quantities measured in like or different units. *For example, if a person walks 1/2 mile in each 1/4 hour, compute the unit rate as the complex fraction ^{1/2}/_{1/4} miles per hour, equivalently 2 miles per hour*.

CCSS.MATH.CONTENT.7.RP.A.2.C

Represent proportional relationships by equations. *For example, if total cost t is proportional to the number n of items purchased at a constant price p, the relationship between the total cost and the number of items can be expressed as t = pn*.

I created a video to introduce the “if” statement to students. It’s a JavaScript dependent video. Other programming languages don’t use the same syntax for the “if” statement. The spelling, punctuation and grammar are all important when you work in a computer language.

The students’ task, as explained in the video, is to write a program that can help solve a common dilemma for me as a teacher. If two classes are racing to complete a game, and the two classes take different amounts of time but also have different amounts of students, how do I determine who won? Variables and expressions could be used to calculate the rates, and then a conditional statement would determine which class won.

The students did pairs programming for this activity. Each group opened the starter program which has the task in the comments.

After the groups worked on the task, we discussed some of the solutions. There were two main approaches:

Approach 1: Calculate the time per student. Lowest amount of time per student wins.

Approach 2: Calculate the number of students per second. The greater number of students per second wins.

Some common misconceptions were: adding the seconds and minutes together and treating that as the total time (instead of converting the minutes to seconds and then adding), misunderstanding the rate of time per student vs. students per second, and failing to use parentheses in their rate calculation, so the order of operations would make division happen before addition. (example: rate = min * 60 + sec / students; rather than rate = (min * 60 + sec) / students;)

The students did a great job overall, and the level of challenge seemed appropriate for most. I truly think the mathematics and the programming were at a very appropriate level of challenge, but as we get deeper into programming, students need to be more metacognitive, they need to ask questions of each other, they need to be resourceful in finding answers – and many students lack those skills.

We will learn about boolean expressions next with these ideas in mind!

# Programming Math Puzzlers

I teach a 40-minute enrichment class at the end of the day called “Computer-Based Math”, which is an intro to programming, but with an eye toward the math that makes interesting things happen on the computer. A couple of the topics we’ve explored as a class include:

PROBABILITY

I started with this topic, because when your computer program behaves a little unpredictably, it becomes so addictive and really hooks the students. We wrote programs to generate random numbers, such as coordinates for images, and then to create lists (beginning with arrays in JavaScript) and pull an element randomly from the list.

Jack created this color-matching game. I used it as an example in another math class to explore the difference between experimental and theoretical probability. It looks like every color should show up as frequently as every other color, but as students played it and tallied results, the Green/Green combination was far more likely than any other. The reason why is interesting. Do you see it?

ANIMATION AND COLLISIONS

Animation is another feature of games that can be addictive to play with, and the basics are pretty easy to understand. Take an object’s (x,y) coordinates and change them at a steady rate, and the object moves faster or slower.

Nathan literally just played and experimented with the rule for changing an object’s (x,y) coordinates and “discovered” an algorithm for making an object move in a circle. It’s really cool. I feel as though I understood why this algorithm creates a circular path at some point in my life, but I don’t remember why anymore. What’s the relationship between Nathan’s rule and the equation for a circle, r-squared = x-squared + y-squared? Play with the initial values of x and y, and the denominators of the animation rule, and you see some pretty interesting stuff.

Gabby made a clever “Frogger” game which explored the math behind collisions. A circle is positioned according to its center, but a rectangle is positioned by its top-left corner. Finessing the details of checking whether the outside edge of a circle collided with the outside edge of a rectangle took some thought!

This class is not standards-based, is not graded, and so we can be more free to explore topics the students are interested in. That said, I look for connections to math standards to help the students with their learning. Goals with expressions, variables, and geometry are easy to include in programming projects. To give the students an audience, we plan mini-showcases a couple of times a semester where we invite other classes to come see our work, we give presentations about what we learned, and we have food (always an important part of real-world meetings). The students are starting to explore functions and the programming behind simulated gravity. When we have some more work to share, I will post it!

## Recent Comments