Thursday, 12 May 2016

Line following

If you're up for a programming challenge the 3Pi robot is capable of following lines (and they can do it really fast!). Luckily Anibit includes an example you can try:


Its a lot to understand, but if you want to jump ahead a bit you can start by loading the following XML file (these bits do calibration and battery display so you don't need to worry about them too much). 



Start with an infinite repeat:

Each repeat, do the following:

Start by reading the sensor:

(display is if you want to)

Then make a decision based on the sensor
Greater than 2000 means the line is on the left, less than means the line is on the right

Here's a diagram to explain what the sensor gives you:

The simplest thing is to turn on the motors based on which side of the line you are on:



If you want to move more smoothly you can try making even more decisions:


Wednesday, 11 May 2016

Checking the 3Pi's batteries

This code can be loaded into Arduino to check the batteries on the 3Pi:

#include <Pololu3pi.h>
#include <PololuQTRSensors.h>
#include <OrangutanLCD.h>
#include <OrangutanAnalog.h>
OrangutanLCD lcd;
OrangutanAnalog analog;

void setup()
{
  Pololu3pi::init();
  analog.setMode(MODE_10_BIT);
}


void loop()
{
  lcd.clear();
  lcd.print("Battery ");
  lcd.gotoXY(0,1);
  lcd.print((long)(100.0 * (analog.readBatteryMillivolts_3pi() - 3000.0) / (4000.0)));
  lcd.print('%');
  delay(500);
}

Monday, 9 May 2016

Getting started with 3Pi


The 3Pis is a small completed robot with all the parts from previous modules



It has a buzzer, motors, line/distance sensors and LEDs.

Top view:


Bottom View:



The easiest way to program the 3Pi is using Arduino and Anibit's free graphical programming tool. To set these things up see the post about 3Pi software. The installable Anibit program might be a bit trickier to set up and only works on Windows. Another way to use it is to copy your code from The Anibit online tool.

To get started lets make the robot move forward and backward a few times, we'll also display the current battery level in millivolts (5 volts = 5000 millivolts).

Note: we need to display the battery level. 
If you program on a battery level near or below 5000mV you can destroy your robot.

Here are the blocks we will use:


  • Math is where you get number blocks to plug into other slots.
  • From Arduino the Setup block is similar to Ardublock: it runs the code inside just once
  • From Motors the Set Motors block sets the power level of the motors between 0 and 255. Faster speeds will drain your batteries. If you're moving you'll need a Delay to tell the robot how long to keep moving (in milliseconds: 1000 * second).
  • From Display you can get blocks to put words on the robot's screen. Try adding the battery level from 3Pi Analog.
  • If you turn on the motors, don't forget to turn them off by setting them back to 0!
When you have the blocks arranged correctly you must switch to the top Arduino tab and copy your code. (Shortcut: use <Ctrl>+<A> then <Ctrl>+<C> to copy it all).

Open up the regular Arduino program and paste in your code (Shortcut: use <Ctrl>+<V> to paste).


Make sure you have selected:
  • Tools > Board > Pololu ... 3Pi robot w/ ATmega328P
  • COM4 (if this doesn't work ask somebody for help- you have to check 'devmgmt.msc' to find the right one)
  • Programmer > Pololu USB  AVR Programmer
If you're all set turn on your robot and hit upload!










Sunday, 8 May 2016

Day 1

11: Making Robots Move





Wiring

How it works

HG7881 (L9110) Dual Channel Motor Driver Module Connector
PinDescription
B-IAMotor B Input A (IA)
B-IBMotor B Input B (IB)
GNDGround
VCCOperating Voltage 2.5-12V
A-IAMotor A Input A (IA)
A-IBMotor A Input B (IB)

InputOutput
IAIBOAIBDescription
LLLLOff
HLHLForward
LHLHReverse
HHHHOff
'

Code

Basic code to drive forward

Extensions

  • Can you make it go forward, then backward?
  • How about turning?
  • Can you make it drive forward if the distance sensor reads 'LOW'?
  • If you have 2 distance sensors can you make it turn left for one, then right for the other? This is how you follow a line!




10: Distance and line sensing


Using the same code which reads from the joystick we can read distance. Reflecting light, or reflecting sound can be used to measure distance:


A reflectance sensor can be connected as follows:



9: Buzzer

Background Information

By precisely modulating a pin, the Digital Sandbox can create electronic waves which, when routed through a loudspeaker, can produce a musical tone. We can program the Sandbox to control two characteristics of musical tone: pitch and duration.
A tone’s pitch is what we perceive when we think of a note as being very high (screams, forks scratching plates, etc.) versus very low (like earth-rumbling bass). The pitch of a tone is very closely related to the frequency played through a speaker. If we toggle a pin from HIGH-to-LOW then LOW-to-HIGH 440 times per second, for example, it produces a 440 Hz (hertz) frequency - a “middle A” pitch. Humans can hear frequencies ranging from 20 (low-pitch, bass) to 20,000 Hz (high-pitch, “ow, my ears”).
We can also program the duration of a tone - the length of time a pitch is played. In our program we’ll use the delay function to set the duration. Playing a tone with the Sandbox is very easy. Just give it a pitch and it’ll start toggling the output pin for you. Much like analog output, you can set it and forget it; the tone won’t stop playing until you tell it to.

Hardware

The joystick should be connected as before. The buzzer is connected as follows:


Code Components


This program introduces the Tone and No Tone block.
  • Tone: This block takes two inputs: a pin number and a frequency. The pin number can be any digital pin, but in this case we’ll use 10. Frequency can be anything from 31 Hz to the extent of your audible range.

    A tone initiated by the Tone block will go on and on until you call a No Tone block. No Tone simply halts a pin from playing a tone. Both of these blocks can be found under the Utilities bin.
  • Map: This handy function maps a value from one range to another. In the example above, we’re taking a value (the output from the joystick) between zero and 60, and mapping that to a range from 440 to 880. So an analog reading of zero becomes 440, and a reading of 60 becomes 880, anything in between is relative to those two ranges. The map function can be especially useful in mapping an analog input (0-1023) to an output (0-255).

Further Explorations

If you have some sheet music, you can convert it to individual notes, made of frequencies and durations using the following table:

8: Analog Input and Serial Communication

Digital inputs, like a button, only allow for two input values: HIGH or LOW. But what about the in-betweens? When you turn the volume up on your stereo, you’re not forced to pick between mute and “OMG MY EARS.” For volume control and other “finely-tuned” settings, we need analog inputs.

Background Information

Serial communication is a form of data transmission where we can send a string of 1’s and 0’s between two devices and actually form a set of characters. So 01101000 01100101 01101100 01101100 01101111 00101100 00100000 01110111 01101111 01110010 01101100 01100100 becomes “Hello, world.”
With serial, we can send actual text from the Arduino and display it on our computer using the Serial Monitor.
Analog inputs are components that put data into a system with a range of more than two values. On the Arduino, analog inputs can produce a value anywhere between zero and 1023 (1024 total values). The value produced by an analog input is proportional to the voltage it produces. If an analog component reads a value of zero, the voltage is 0V. If the output value is 1023, then the voltage is 5V. An analog reading of 512 is about 2.5V, and so on.
A special component inside the Arduino's microcontroller called an analog-to-digital converter (ADC) is able to convert that range of input voltages to a discrete number. This is a special circuit that most pins on the Arduino don’t have. It’s so special that the ADC pins are labeled with a preceding ‘A’. The analog sensors on the board are labeled as “A0”, “A1”, “A2” and “A3.”
Many electronic components produce analog output, the most common of which is a potentiometer. “Pots” come in a variety of shapes and sizes. Rotary pots are very commonly used to adjust the volume on a stereo. Slide potentiometers are often seen adjusting sound levels on mixing boards. Joysticks use 2 rotary pots: one for side to side (VRx), one for up/down (VRy).

A joystick can be connected as follows:

Code Components

alt text
There are three new blocks this time, both of them shaded white and located under the communication bin:
  • Serial Print: This block takes two parameters. At the top, place the message you want to print. You can put anything you want into the message block (even spaces!). If you want to add a variable or number, you’ll need to add some glue. The bottom snap of Serial Print determines if a new line is printed after the message. Usually you’ll want this to be set to true.
  • Glue: Glue blocks allow you to print values like variables or numbers - anything that isn’t a message you’ve written in. If you want to print a variable, you’ll need to add a glue block between the variable and the Serial Print block. There are three different kinds of glue blocks, each with a different snap shape on the right. This time we’ll use the block with a wedge (<) termination.
  • Analog Pin #: Like the Digital Pin block, this block reads in the value of an input. But, instead of producing either true or false (1/0, HIGH/LOW), this block produces a number between zero and 1024. The pink block snapped to the right of this one indicates which analog pin should be read.

Do This

To print a variable, we need to “glue” it to the Serial Print block with a wedge-shaped glue piece. Make your drawing match the one above.
With that, upload the sketch to your Arduino. Then, to view the serial prints, click on the Serial Monitor button up top.
alt text
You’ll see your message printed.
Every 100ms an analog input value should be printed. Move the analog slider to adjust the value. Can you make the output zero? 1023? 512? Take note of which slide pot position relates to which value.

Further Explorations

  • Can you make the slider control the LEDs? You could slide the white LEDs back and forth, or try controlling the brightness of the RGB LEDs with the slider.
  • Why are there only 1024 output values? Why not an even 1000? (Hint: 210.)

7: If This Then That

Fading from the last experiment was working just fine until we got to the maximum brightness level of 255. What happens then is a mystery known only to the compiler (and you, once you learn a little something about data types). What if we added “catch” to force that fade variable to reset when it hits a certain value?

Background Information

This experiment introduces the if statement, one of the most fundamental programming structures. Not only are ifstatements important for computers, they also rule most of the decisions we make in our lives: If it’s cloudy outside,then pack your umbrella. If you’re hungry, then make a sandwich. Like us, computers use if statements to make choices.
An if statement requires two components to be complete: a condition and a consequence. A condition is a value or mathematical operation that evaluates to either true or falseIf the condition evaluates to true, then the consequence is executed. The consequence can be a code block of any size - one block or hundreds of blocks.
If the condition in the if statement is false, then the consequence is skipped, and the program starts running the code following the if block.

Code Components

Here are the blocks required to limit the fade value of our LED.
alt text
There are two new blocks to mention here:
  • If: The star of this experiment can be found under the Control bin. The If block requires at least two blocks to be snapped into it: the conditional and the consequence. In this case, the consequence is just a single block -Set Number Variable. The conditional part of the if block is a logical operator block.
  • Logical Operator: Logical operators are symbols which operate on one or two values and evaluate to either true or false, which makes them perfectly suited for the if statement conditional! In this case we’ll be using theless than (<) operator. If the value to the left of the < symbol is less than the value on the right, then the operator is true. If the left is not less than (either greater than or equal to), then the condition will evaluate to false.

Do This

In this sketch, we want the blue LED to progressively go from super bright to off, and repeat that cycle endlessly. We’ll use a variable called fade to keep track of the analog output value. At the very beginning of each loop, we’ll subtract 1 from the fade variable.
Then, after subtracting from fade, we need to use an if statement to make sure it’s not out of bounds. The ifstatement in this sketch states that if fade is less than 0 (that would mean it’s a negative number), then set fadeto 255.
Finally, once we’ve generated our fade value, we can set pin 10 (or pick another LED if you please) to that analog output value.
Now upload and enjoy a nice, controlled fade.

Further Explorations

  • Can you make the fade work the other way? Start at 0, fade up to 255, and then go back to 0. (Hint: You’ll need to flip the logical operator around.)
  • Make it even smoother! Can you make it fade smoothly up and smoothly down in the same sketch? From 0 to 255, then 255 to 0, then 0 to 255, then back again.

6: Number Storage with Variables

The herky-jerky fading from experiment four accomplished the task, but just think of all the values we were missing! How do we make the LED fade smoothly? You can whip out 256 minutely different Set analog pin blocks, or you can reduce it to one, using variables.

Background Information

Variables are like storage containers for numbers. We can put any number in a variable, and either recall it and put it to use, or manipulate it to change the value it stores. Anywhere you stick a literal number (like “0” or “255”) you can instead use a variable.
There are a few rules when it comes to creating a variable. They can be any word, but they must begin with a letter, and they can’t have spaces (use “_” instead). They are case sensitive, so a variable named “fade” isn’t the same variable as “Fade.” Try to keep variables short, but use descriptive words to keep your code legible.

Code Components

Thanks to variables, here are all the blocks we need to create a smooth fade:
(note: change pin 5 to one connected to an LED, like 9,10,11,13)
alt text
There are a few new blocks to familiarize yourself with this time:
  • Number Variable Name: These blocks are about the same size and shape as the literal number blocks we’ve been using. But, instead of writing a number in these blocks, you type in the name for your variable (make sure it’s spelled the same in every place you want to reference it). You can find this block under the Variables/Constants bin on the left.
  • Set Number Variable: This block, also found under the Variables/Constants bin, is used to set a variable to a specific value. Two blocks snap to this one – a variable name on top, and the value you want to set that variable to on the bottom. The value can be a literal number, another variable, or the result of a mathematical operator.
  • Math operator block: If you click on the Math Operators bin, and look at the first four entries, you should see some very familiar symbols: +, −, ×, and ÷. These math operators can be used to do math on a pair of variables or numbers, or a combination of the two.

Do This

Add the first Set Variable Number block, which will include a blank variable and a value. Click into the number variable name and write “fade” into it. The “fade” variable will keep track of the the brightness of our LED. The Set Variable Number block in the setup area of the program should set the “fade” variable to zero.
You should be plenty familiar with Set Analog Pin and Delay Milliseconds; grab those blocks and stick them in the loopin either order.
We’ll need to throw away the value block that comes with Set Analog Pin (drag it over to the left side of the window) and replace it with a variable. To add a variable to your sketch, drag over the Number Variable Name block and type your variable’s name into it. Alternatively, once you’ve made one variable, you can right-click it and clone it to get more of the “fade” variables you’ll need.
Finally, add another Set Number Variable block, and replace the 0 value it includes with a + operator. Modify it so it adds a 1 to “fade,” and plug it into the value part of the Set Number Variable block. Then stick that block group at the end of the loop.
Whew! Let’s see what all that work was for by uploading the drawing. The LED on pin 5 should satisfyingly and smoothly flow from fully off to fully on.

Further Explorations

  • Does it matter what order you have the loop blocks in?
  • Can you make other LEDs fade? How about more than one fading at the same time?
  • Can you make the LED fade from HIGH to LOW? (Hint: You may need to change the setup value of “fade,” and change the + to a −.)

5: Color Mixing


By combining analog output with an RGB LED, we can mix varying levels of red, green and blue to create a rainbow of colors!

Background Information

In art class you probably learned about primary colors and how you can mix them to produce any other color. While the artsy primary colors you might be familiar with are red, yellow and blue, in electronics (and programming in general) our primary colors are red, green and blue.

Additive color mixing seen in light


Subtractive color mixing as seen in paint

By selecting different analog levels for our primary colors, we can mix them to create any other color we want. Need yellow? Mix green and red. Purple? Red and blue. In this experiment we’ll combine everything we’ve learned about analog output to create any color!

Code Components

For the most basic RGB color-mixing sketch, this is all we need:
alt text
In the example, we added comments to each of the Set Analog Pin blocks. Comments have no effect on the actual code, but they do help make the code more readable to you or others. With those blocks commented, we don’t have to look back at the board to remember which pins go to which colors.
You can add comments by right-clicking on a block, and selecting “Add Comment”. Show or hide comments by clicking the “?”.

Do This

Stack those three Set Analog Pins on top of each other, in either the setup or the loop. This will set red’s value to 16, green to 255, and blue to 128. What color do you think it’ll make? Upload to find out! (If it’s hard to tell what the color is, put a piece of paper over the RGB LED.)
Play with the analog values to make your own colors. How about purple, or orange, or salmon? You can take it even further by adding delays, and blinking different colors to make animations.

Further Explorations

  • Mix the colors to make your favorite color. Or, if your favorite color is red, green or blue, try making your least favorite color.
  • Make a stop light blink from green, to yellow, to red and repeat.

4: Dimming (the Easy Way)

Manual PWM is hard, and it doesn’t leave room for anything else in the program. Why can’t we offload that chore to the microcontroller? It’s smart enough for that…right?

Background Information

PWM is such a popular tool many microcontrollers implement special hardware so they can mindlessly toggle the pin while doing something else. We call this PWM-based output analog output.
Unlike digital outputs, which only have two possible values, analog outputs have a huge range of possible values. On the Arduino we can analog-ly output 256 different values. If we set an analog output to zero, that’s like setting a pin LOW, and 255 is like setting a pin HIGH, but all of the values in between produce an output that’s neither HIGH or LOW – it’s somewhere in between.
Analog output seems great – why wouldn’t you use it all the time? Unfortunately, not all pins have special PWM powers. Only pins 3, 5, 6, 9, 10, 11 and 13 are able to produce analog outputs.

Code Components

New block alert! While it may look similar, we’ll be using Set Analog Pin this time instead of its digital counterpart:

  • Set Analog Pin: This block looks a lot like the Set Digital Pin block. We still tell it which pin to control, but instead of a restrictive, digital output option, we get to choose any number between zero and 255 for the output. Find this block under the Pins bin.

Do This

Stack the blocks in the loop section. Order them so the analog values go from zero at the top to 255 at the bottom. Then upload away!
The LED on pin 5 should cycle through five different levels of brightness (including fully on and fully off). Remember that setting the analog output to zero turns the LED off, and 255 is like setting it to HIGH.
Try adding analog control of the pin 6 LED to the drawing. You can create the same effect from the last experiment, with just two lines of code (and you can execute other code while the LEDs remain in their dimmed state!).

Further Explorations

  • What’s the dimmest value you can set the LED and still see it on?
  • Why do you think there are 256 possible analog output values? That doesn’t seem like a very round number (hint: 28).

3: Dimming (the Hard Way)

Yikes! Some of those LEDs are blindingly bright! Is there any way to dim them? (Unless one of your hobbies is staring into the sun, we recommend putting a piece of paper over the LEDs in this experiment…or wear sunglasses.)

Background Information

Remember that the Arduino is fast. It can flick an LED on and off millions of times per second. What if we blinked the LED super fast, but also make it so the length of time the LED is off is more than the length of time it’s on? This is called pulse-width modulation (PWM), a tool with a variety of applications, including dimming the LEDs.
In this experiment we’ll explore PWM the hard way, by coding it in manually.

Code Components

We’ll use a similar set of blocks:

Take note of how long each delay is, and which pins are on/off in each group.

Do This

Stack the two group of threes on top of each other, in the loop section, and Upload.
After uploading, take a close look at the LEDs connected to pins 9 and 10. Can you spot a difference between the two? One LED should look dimmer in comparison to the other. That’s because one is set to be low 90% of the time, and on only 10%. It’s blinking on and off so fast that you can’t notice. But what the blinking is creating is a dimming effect.
What happens if you swap the two Delay Millisecond blocks? What if you change the values in each of the delay blocks (try to keep the sum of the delay times to around 10ms)?

Further Explorations

  • How long can you make the delays before you start noticing a blink?
  • What happens if you add something else to the loop section, like your animation from experiment two?