Category Archives: programming

Arduino Workshop for Teachers @ EMU

Presented by SIGCS and The Department of Computer Science at Eastern Michigan University

This workshop is intended for teachers who are interested in learning to wire and program the Arduino. Arduinos will be supplied for use during the workshop. We are using kits purchased from Amazon and Parallax – Arduino robots.

Introduction:

I’ve been teaching a one semester class with Arduino for ten year. I learned how to use Arduino along with my students and my course has continuously evolved over time. My complete course is posted on this website.

From the Arduino website:

Arduino is an open-source electronics platform based on easy-to-use hardware and software. Arduino boards are able to read inputs – light on a sensor, a finger on a button, or a Twitter message – and turn it into an output – activating a motor, turning on an LED, publishing something online. You can tell your board what to do by sending a set of instructions to the microcontroller on the board. To do so you use the Arduino programming language (based on Wiring), and the Arduino Software (IDE), based on Processing.

Blink:
Lets make sure the boards will communicate and take a quick look over the Arduino IDE. We are going to cause an LED on the Arduino to flash at different rates.

Paste this Code into the Arduino IDE:
Here’s the complete code:

/*
  Blink
  Turns on an LED on for one second, then off for one second, repeatedly.
 
  This example code is in the public domain.
 */
 
// Pin 13 has an LED connected on most Arduino boards.
// give it a name:
int led = 13;

// the setup routine runs once when you press reset:
void setup() {                
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);     
}

// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);               // wait for a second
}

If you have programming experience this should look very familiar. If you are new to programming, this page will explain all the code. Play a bit, make the LED flash at different rates.

Now build the circuit shown below (need more help?). If you’ve done it correctly the LED on the Breadboard will flash along with the LED on the Arduino board.

Breadboard with Arduino and LED

Add on a couple more LEDs (don’t forget the resistors). Then make all the LEDs flash together and/or in sequence.

Digital Input:

Next we’ll add in a push button. Build this circuit:

Arduino wired to LEDs on Pins ( and 10 and a pushbutton on pin2

Try this Code. You won’t see anything unless you open the Serial Monitor:

int buttonPin = 2;
int buttonState = 0;
int led = 10;

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(led, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  delay(10);
  buttonState = digitalRead(buttonPin);
 
  if (buttonState == HIGH)
  {
    digitalWrite(led, HIGH);
    Serial.println("Button Pressed");
  }
  else
  {
    digitalWrite(led, LOW);
    Serial.println("Button Released");
  }
}

Now, do something with the second LED. Doesn’t really matter what. You should also check out the Serial Monitor. You should notice that “Button Pressed” and “Button Released” print over and over again. This code will stop that from happening:

int buttonPin = 2;
int buttonState = 0;
int buttonPressed = 0;

void setup() {
  Serial.begin(9600);
  pinMode(buttonPin, INPUT);
}

void loop() {
  delay(100);
  buttonState = digitalRead(buttonPin);
  
  if (buttonState == HIGH && buttonPressed == 0)
  {
    Serial.println("Button Pressed");
    buttonPressed = 1;
  }
  
  if (buttonState == LOW && buttonPressed == 1)
  {
    Serial.println("Button Released");
    buttonPressed = 0;
  }
}

This should print Button Pressed only one time when the button is pressed. This idea can be built upon to create a toggle. The code below will turn an LED on when the button is pressed and the LED will stay on until the button is pressed again.

HIGH, true, and 1 are Synonymous:

int buttonPin = 2;
int buttonState = 0;
int buttonPressed = 0;
int ledPin = 10;
bool ledState = false;

void setup() {
  Serial.begin(9600);
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  delay(100);
  buttonState = digitalRead(buttonPin);
  
  if (buttonState && !buttonPressed)
  {
    Serial.println("Button Pressed");
    buttonPressed = 1;
    ledState = !ledState;
  }
  
  if (!buttonState && buttonPressed)
  {
    Serial.println("Button Released");
    buttonPressed = 0;
  }

  digitalWrite(ledPin, ledState);  
}

Analog Read and Write:

Time to explore the Example Sketches. In the Arduino IDE open:

File->Examples->Analog->Fading

Wire an LED (with resistor) up to Pin 9 and upload the code. You should see your LED pulsing on and off. Can you make it faster? Slower?

Things to know:

    • analogWrite is 8 bit (0-255)
    • overflow – 256 is the same as 0
    • Only certain pins support analogWrite. Marked with either PWM or a ~

Next load up:

File->Examples->Analog->AnalogInput

Potentiometer wired to pin A0 LED wired to pin 10

Change the cod to light up the LED plugged into pin 10. The turn the knob to see the flash rate change. Then try this code:

int sensorPin = A0;    
int ledPin = 10;
int sensorValue = 0;
int val = 0;

void setup() {
  pinMode(ledPin, OUTPUT);

}

void loop() {
  sensorValue = analogRead(sensorPin);
  val = map(sensorValue, 0, 1023, 0, 255);
  analogWrite(ledPin, val);
}

analogRead returns a 10 bit number (0 – 1023), so we use the map() function to adjust it to use with analogWrite. If you are feeling ambitious you can swap your potentiometer out for a light sensitive resistor (Note: the code example on this page is incomplete. You will need to fix it).

Make things Move
Next dig out the Servo motor and wire it as shown below:

Servo wired to pin 9 and potentiometer wired to A0

Open: File->Examples->Servo->Knob

Note: Standard servo motors adjust from 0 to 180°. Here we use map() to adjust our analogRead values to this range.

Arduino Robot

We are using the NICERC Shield Bot with Arduino Kit. The kit comes with a complete guide, but I don’t know that I’d use it as more than a general reference. I should note that I am not a classically trained coder. So I might be wrong in this.

Here are a couple of my general recommendations:

  • Do not use Pins 12 and 13 for the servos as recommended. When an Arduino is powered up or reset it hits pin 13 briefly. If you use Pin 13 for one of your servos the robot will move slightly when this happens. Instead use the other set of headers, which are wired to pins 10 & 11.
  • You might want to use servo.write() instead of servo.writeMicroseconds(). Most of the example Arduino servo code you (or your students) will find on the net uses servo.write(). Additionally if you add a standard servo to the robot later you will probably use this function as well.

I will be using servo.write() in this workshop. The servo motors on our robots have been modified to be continuous rotation servos. Wire your potentiometer (from the Arduino Kit) to your robot as shown:

Use the Servo example sketch we used earlier: File->Examples->Servo->Knob

Change the servo pin to one of the pins attached to our robot’s servos. Note how the wheel responds as you adjust the servo. For continuous rotation servos, 90° should cause the servo to stop, 0° is maximum speed in one direction and 180° is max speed in the other direction.

Be sure the robot’s servo motors are attached to pins 10 & 11 (or change the code) and try this:

#include <Servo.h>

Servo left;  // Creates an instance of Servo for the left motor
Servo right; // Creates an instance of Servo for the left motor

void setup() {
  right.attach(10); // attach right servo to pin 10
  left.attach(11);  // attach left servo to pin 11

  forward(1000);
  turnRight(900);
  forward(1000);
  turnLeft(900);
  stop();
}

void loop() {

}

void stop(){
  right.write(90);  // setting servos to 90 degrees
  left.write(90);   // stops them from turning
}

void forward(int driveTime){
  // Both just as far from 90 degrees means both motors
  // should be turning the same speed. Opposite directions
  // becuase motors are oriented in different directions.
  right.write(60);
  left.write(120);
  delay(driveTime);
}

void backwards(int driveTime){
  right.write(120);
  left.write(60);
  delay(driveTime);
}

void turnRight(int turnTime){
  right.write(90);
  left.write(120);
  delay(turnTime);
}

void turnLeft(int turnTime){
  right.write(60);
  left.write(90);
  delay(turnTime);
}

void disableServos(){  
  right.detach(); // disconnect servos
  left.detach();
}

Challenge: Write code to navigate the course taped out on the floor.

Add simple sensors to your robot:
Flip to page 148 in the guide and add the Whiskers to your robot.

The Whiskers act as push buttons. In their current configuration they will read as HIGH when the whisker is not touching anything. When the whisker is pushed back into the headers, this will “close” the button and the digitalRead() will return LOW.

Here’s some quick code I put together to read the whiskers:

#include <Servo.h>

Servo left;  // Creates an instance of Servo for the left motor
Servo right; // Creates an instance of Servo for the left motor

bool rightWhisker;
bool leftWhisker;

void setup() {
  pinMode(7, INPUT);
  pinMode(5, INPUT);

  
  right.attach(10);
  left.attach(11);

}

void loop() {
  
  forward(10);
  
  rightWhisker = digitalRead(7);
  leftWhisker = digitalRead(5);
  
  if(rightWhisker == LOW){
    backwards(500);
    turnLeft(900);
  }else if(leftWhisker == LOW){
    backwards(500);
    turnRight(900);
  }
}

void halt(){
  right.write(90);  // setting servos to 90 degrees
  left.write(90);   // stops them from turning
}

void forward(int driveTime){
  right.write(60);
  left.write(120);
  delay(driveTime);
}

void backwards(int driveTime){
  right.write(120);
  left.write(60);
  delay(driveTime);
}

void turnRight(int turnTime){
  right.write(90);
  left.write(120);
  delay(turnTime);
}

void turnLeft(int turnTime){
  right.write(60);
  left.write(90);
  delay(turnTime);
}

It could probably use some additional tweaking and maybe an extra function or two to make it work better. This one will get stuck in a corner pretty easily. Can you change the code to keep that from happening?

Where Steve Buys stuff:

Playing with Programming

I’m teaching AP Computer Science Principles this year following along with the CS50 AP from Harvard. I like it, but this curriculum is way too heavy on the coding end to really match the intent of APCSP.

My plan next year is to mix and match Code.org’s material with ideas from CS50, but instead of C we’ll use JavaScript. With this in mind I’ve been playing with p5.js. I like it a lot for two very important reasons. First it gets students to graphics right away. It’s a lot easier to get student excited about code when they can create cool pictures on the screen than it is when all the do is print text.

The other thing I really like about JavaScript is students can run their code on pretty much any device with a modern web browser. As an example, check out the sketch below. I created after watching a cool video by Dan Shiffman. I made this in Openprocessing, a cloud editor for p5.js. If you’re interested, Wikipedia has a great explanation of the math involved in my program.

Learning with OpenSCAD

I’m currently teaching a class to pilot AP Computer Science Principles (will be AP for the first time in the 2016-17 school year). At the beginning of the second semester I decided to deviate from my planned curriculum and drop in a little 3D printing. I had students play with OpenSCAD. OpenSCAD is used to create 3D models with programming rather than more traditional means.
 OpenSCAD is really cool for a number of reasons. If students have any experience with writing code they can dive right in. They quickly realize there are many different ways to create the same part, just as there are always multiple ways to get any program to do what you want it to. Most of these ways will involve thinking in 3-dimensional coordinates while also thinking about positive and negative space. Depending on the chosen approach students may also need to bring in a variety of mathematical knowledge and skills they’ve developed over the years.

The task I gave my students was to develop a stand/holder for their own cell phones. It took them a bit to settle into this idea. I kept getting questions like, “Do I need to plan for a case?” To which I’d reply, “I don’t know, does you phone have a case?” I really wanted them to plan for a holder for their own phone.

In the future I’ll need to put some limits on their designs. Most designs were much bigger than they needed to be, many would easily hold an iPad. Maybe I’ll put a limit on the mass of plastic they could consume. I also need to make sure their design will fit the printer. I had one that would not.

After printing their stands they all realized there were problems with their designs, things that were not obvious before they tried using the physical objects. This was a great lesson and gave us a chance to talk about rapid prototyping and iteration. Each student shared their first designs with the class so everyone could learn from each other’s mistakes. The designs were then updated to fix the problems. In the redesign I also had students add in variables for phone size. This would then allow the program to be used to make a holder for any phone by simply changing the values of the variables for phone height, width, and thickness.

Overall I really liked this assignment. Students got to use their programming knowledge in a new way with a new language. I personally delivered no instruction in OpenSCAD. Students had to rely on the principles of computer science they’d already learned, tutorials found on the net, and each other, just as they would in the real world. The task was simple enough that I knew this would not be a problem. I will be doing this again as a planned part of the curriculum next year, but I’ll add in design constraints related to size and total cost of materials.

Arduino or PICAXE?

This is a pretty geeky post… You’ve been warned.

Among the courses I teach is electronics. It is a one semester course, where we cover basic theory in the first half of the semester and students breadboard circuits for the second half of the semester. I inherited the course and its general structure from the previous electronics teacher and it seems to work pretty well.

Anyway, I’ve been thinking about changing it. I’ve been wanting to incorporate microprocessors into the course for some time, but I’ve been daunted with either the price tag or for the cheap stuff with the technical know-how that I just don’t have. By bringing in microprocessors I can also get students doing some programming . Additionally, a lot of electronics these days includes embedded microprocessors.

Enter the PICAXE and Arduino micro-controllers. Both can be had relatively cheaply and are fairly easy to program. Unfortunately I discovered these at about the same time. If I only knew about one of them I’d have been content to buy a bunch and get to work redesigning my course. As it stands right now, I have no idea which one to choose. So I’m writing this post to get my ideas down and I’m partly hoping for some insight from potential experts.

PICAXE: The PICAXE micro-controller is a Pic based chip that has a bootloader loaded onto it allowing for a very simply programming cable to be used. It can be programmed using a form of basic or with a flow chart based interface. There are some great guides online for its use, but they’d have to be edited a bit to make them usable for my course. There are multiple versions of this chip with different numbers of inputs/outputs. The programming is slightly different from chip to chip.

Pros: Cost. The chip (8M) itself costs less than $4. Theoretically students could easily make permanent projects with this. Basic programming: I know basic and basic programming is relatively easy.

Cons: The 8M, the chip I’d focus on, is a bit limited. There are other chips we could add in, but their structure is different. Apparently limited availability. I’d really have to plan ahead to ensure I had the supplies I’d need (unless I want to order from the UK). Windows only.

Arduino: This board is really a Basic Stamp replacement. I’d thought it was going to be outside of the price range I’d set for the course, but then I found a supplier who supplies a version that I can get for $11/board in bulk. The programming for this chip is in a C++ like language. There is also a lot online support for this board and at least one project designing a course in basic electronics with the Arduino as the platform.

Pros: Expandability. This chip has some wickedly cool potential. It interfaces circuitry directly with a computer easily, making it possible to create circuits that control or respond to functions on the computer. Support for Mac, WinXP, and Linux.

Cons: I don’t know C++ or any other object oriented programming language. More expensive so it would cost more for students to make permanent projects.

I guess the bottom line is the PICAXE is probably simpler to start using but while the Arduino has a steeper learning curve at the start it allows for more advanced functions more easily. At least I think. Right now I’m leaning towards the Arduino. I’ve already got one independant student working with the PICAXE. I’ll get a couple working with the Arduino this semester as well and see what they all think.