Thursday, 5 December 2013

Intro to Arduino at KMS

Adafruit Trinket
controlling an
RGB LED


Update: By popular demand I will be running this workshop again on April 14, 2014.

I volunteered to facilitate a workshop at Kingston MakerSpace next week to provide a very basic introduction to Arduino micro controllers. Here's the event advertising. There are many variants and imitators of Arduino. (Here's a Make article on which board?) Don't get hung up on picking one. Anything that is supported by the Arduino environment will give you a good learning platform to find out what you can do and what you need for each project.

There's an Arduino UNO hiding under there, matched up
with a breadboard and mounting plate that makes it
way easier to keep things together
That said, I would recommend the Arduino UNO board for beginners because it sets the standard and others may deviate a little from that standard and get confusing. It also has nice readable labels beside all the pin connections.

 You'll also need some way to connect the Arduino with components like LEDs and pushbuttons, and so on. A solderless breadboard makes that easy, and a mounting plate will hold them both together and help keep the wires from pulling out. (Bad connections are a very frustrating problem to debug.) I like the version in the Experimenter's Kit.

We'll get started step by step before you move on to other learning projects you choose yourself:

Install the Arduino integrated development environment (IDE) on your laptop in advance so you can bring it to the MakerSpace, or install it once you get there. (We have wireless and the password is on the wall.) I like the Adafruit Arduino 1.05 distribution. It is the latest standard version (1.05) from Arduino with  additional support for some of the Adafruit boards like Trinket and Flora that some of you will be using. (Any version of the Arduino IDE should be fine for this workshop if you are using the UNO.) The Mac install is seamless. The Windows install says it requires some fancy footwork with device drivers as detailed on the instruction pages, but the Win 7 machine I tested on automatically loaded the drivers for the UNO and worked. Same for the Arduino Micro. For windows you will have to unzip the distribution and copy it to your program files directory, then make a shortcut to run it from your desktop.

For the Trinket I had to do the detailed device driver install explained on the Adafruit pages, then set the programmer to USBTinyISP, and hook the Trinket to the USB through a hub (I had the same problem on a Macbook Pro). For a linux install you will probably have to edit the config files and add some stuff, but linux users are used to that ;-)

Connect your Arduino to a USB port and then create a program to say "Hello World". Open the Arduino program on your laptop and use the tools menu to pick the right Board and the Serial Port it's connected to. Type (or copy and paste) this code into the sketch window (a sketch is a little program).

void setup() {                
  Serial.begin(57600);   // get the serial port ready at 57600 baud
  pinMode(13,OUTPUT);    // set pin 13 to be in output mode
}

void loop() {
  digitalWrite(13,0);              // turn the LED off
  if(millis() % 1000 == 0){        // if we're at a round second
    Serial.print("Hello World! "); //   then say hello
    Serial.print("time is now ");
    Serial.print(millis());
    Serial.print(" ms from boot.\n");
    digitalWrite(13,1);            //   then turn the LED on
    delay(500);                    //   then wait half a second   
  }
}

Hit the right arrow icon to verify your sketch and upload it to the Arduino. Once it's running the LED on the board should start blinking on and off and the magnifying glass icon will let you see the serial port output from your sketch. (You may need to open the serial window and change the port speed to 57600 baud before anything good happens.) 

If you have a Trinket the sketch below from Adafruit will just flash the built-in LED on pin 1 for the Trinket, since it doesn't support Serial. (You'll need to push the button on the Trinket just before you upload.)


int led = 1; // blink 'digital' pin 1 - AKA the built in red LED

// 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); 
    delay(1000);
    digitalWrite(led, LOW);
    delay(1000);
}
 
It will also work with the UNO and others if you switch the coded pin number to 13, where they have a built-in LED. Can you explain to your partner what each line of code does and how it works?

Try changing the code to have it say hello to you by name.

How often does the Arduino run through the loop() function? How can you find out?

Now we'll try to light up our own LED, or three. This will tell you All About LEDs, or we can cut to the chase:

Never connect an LED to power without a resistor of more than 100 ohms in series (pick one with a third colour band that's brown). With no resistor to limit the current your LED will either get hot and wear out faster, flash brightly and never work again, or maybe go BANG! None of these are good outcomes.

Make sure the long lead (the anode) on the LED is on the positive side of the circuit. Getting it backwards will give you no light, but won't break anything.

This UNO based RFID reader opens and
locks the door at KMS
Try connecting an LED and resistor between the 5V (5 volts) and GND (ground or 0 volts) pins on your Arduino. Using some wires and a breadboard will make this easier. If the LED doesn't light up, you probably have it backwards. If it still doesn't light up, somebody probably connected it with no resistor and it needs to be thrown away.

Now connect to pin 13 (or pin 1 on the Trinket) instead of 5V and the LED should blink in time with the built-in LED.

There's tons more complicated things you can do with LEDs but start with Blink (we already did) and Pulse (below) then move on to RGB LEDs that combine three LEDs in one package and can give you any colour you want.

int led = 1; // pulse 'digital' pin 1 - AKA the built in red LED

// 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() {
  for (int i=0; i<256; i++) {
    analogWrite(led, i);  // PWM the LED from 0 to 255 (max)
    delay(5);
  }
  for (int i=255; i>=0; i--) {
    analogWrite(led, i);  // PWM the LED from 255 (max) to 0
    delay(5);
  }
}

This Pulse sketch is just a little different from the Blink sketch up above. What's the difference between digitalWrite() and analogWrite()? What does PWM stand for and does it work on all the pins?

Add a pushbutton (or two) to control what happens based on user input. Can you use a pin for input and for output at the same time? Get more detailed control with Analog Inputs and a potentiometer.

Try controlling a servo motor next for an experience that's easy to wire up and pretty gratifying (Trinket version). The door lock on the MakerSpace is mostly just a servo being controlled to open and close the deadbolt. Please don't try to reprogram the lock until you are sure you know what you're doing.

If we get anywhere near this far in a two hour workshop, then I will be impressed.

Sunday, 1 December 2013

Trinkets, Guino, and Updating the Teensy from Beta

The Adafruit trinket and flora require some special capabilities that I covered by installing the Adafruit Arduino 1.05 distribution. This is way easier than the original distribution that had to be installed manually over the stock Arduino 1.05. It also has support for all the usual Arduinos.

I installed the teensyduino 1.16 release with all libraries over the Adafruit 1.05 to support the teensy 3. Easy as pi and seems to work more smoothly than the betas, although I still have to push the button on the T3 at unpredictable times when uploading.

Guino provides a cool looking operational dashboard for the Arduino. It works with the UNO. It can't work with the Trinket because they don't do serial, and it doesn't work with the Arduino Micro or Teensy 3 because of software differences. Be sure to disconnect the GUI while reloading from Arduino or communications can get messed up.

Wednesday, 27 November 2013

RFID Servo Lock for Kingston MakerSpace



Every MakerSpace needs a hackable lock system, so that was a project that had to happen immediately after we took possession. The target was simple, fast, and with as little new hardware as possible, not to mention avoiding damage to the landlord's lovely doors in our heritage building.

The basis for the control was an Arduino Uno with an Adafruit RFID Shield. Some of the pins were pulled out to some right angled header on the end for power and control to a servo. A MOS-FET was added to switch the servo power on and off as needed under control from a digital pin.

The servo is a Tower Pro with a max rating of 6 volts. Powered at 5 volts it is working hard and drawing quite a bit of current, so the board has to be powered through the USB port. If you try an external source, the current draw overloads the regulator on the Arduino and it resets.

The frame is from a tomato can and mounts between the latch knob and the door. The knob is a spare that I drilled a couple of holes in, leaving the original safe in the closet, and the actuation is with nylon blind cord.

The code gets the servo to back off and take a run at the actuation, then slack the cord after it's done. By turning the servo power off between actuations we save electricity and make it easy to operate the lock by hand or with an old fashioned mechanical key.




Owen helped me make the video by swiping cards while I tried to hold the camera steady.

Saturday, 21 September 2013

Adafruit Trinket Trial

I couldn't resist buying a six pack of Trinkets, so now it's time to see if I can get one working. I went straight to the http://learn.adafruit.com/introducing-trinket/setting-up-with-arduino-ide page in the tutorial and followed the mac instructions. I renamed the ld file to avr-ld to match the one that was already in the package, then followed the instructions to select Trinket 8Mz as the board and USBtinyISP as the programmer. (Serial Port seems to be a non-issue...)

The blink sketch loaded and ran on a 3V Trinket with the results you would expect. Tried uploading the Button sketch from the next tutorial page and got avrdude: Error: Could not find USBtiny device (0x1781/0xc9f) repeatedly. Apparently you need to press the button on the Trinket before uploading to wake up the boot loader and the red LED will pulse for about 10 seconds, then fall back to whatever program was already loaded. Pulse also loaded and ran with the expected result. Switching to the 5V Trinket produced the same results.

Can it replace an Arduino Micro in the Hat Demo?

The brim of the ball cap has a little sign that
flips up and down on a servo
The Hat Demo is a ball cap I augmented for the Kingston Maker Space booth at this summer's Princess Street Promenade. It uses a Sharp proximity sensor to measure distance to whoever is fight in front of you, then actuates a servo to raise a little sign. Basically, the sign pops up when somebody comes close. It couldn't get much simpler. (Motors/ServoSharp has the code.)

Compiling produced errors from the servo library, which I would have expected if I had read http://learn.adafruit.com/trinket-gemma-servo-control/overview before I tried it. Switching the code over to the Adafruit_SoftServo library lets it compile.

The Arduino Micro version of the hat controller drives the servo and the Sharp sensor from the 5V regulated voltage on the Micro, which can supply an unspecified current. The trinket can provide up to 150 mA on the 5V pin. I tried a straight substitution and it didn't work for me. Back to start. Tried the TrinketKnob sketch and circuit and it provided sensible results. Turns out I needed some extra code for interrupts to keep the SoftwareServo stuff working. I also found that the servo rotated only half as far as it did with the Micro and the standard servo library.

Once I got it working I ran into some odd behaviour with the system working on USB, but behaving strangely when powered from a 9V battery. It seems to have been just loose wires, but there may have been some elements of getting slightly different voltages back from the analog sensor with the different supply. Still, with a little fiddling around I now have liberated the $30 Micro from the hat demo and replaced it with the $8 Trinket and that has the potential to bring down the cost of many small projects!

The trinket version has a controller smaller than the sensor, and cheaper too!






Thursday, 18 July 2013

Python Arduino DAQ on the Mac

Kevin Hughes created a basic DAQ system in python to read Arduino analog voltages and display them on screen. He told me it should be platform independent, so I decided to try it on my mac. Steps to getting there [including mistakes where I slipped up]:

Get the arduino sketch running. This was simple, although I dropped the serial data rate to 57600 because that works with all the other stuff in my ecosystem.

[This was probably a huge mistake, as it looks like many libraries only work with python 2.7. Restored machine state and started again. Install python 3.3.2 for the mac, because that's the latest. After the install I still got python 2.7.2 from a terminal command line, even after a restart, but 'python3' gets 3.3.2.]

Serial Communications

Rely on the installed python 2.7.2 on the mac and install pySerial using Adafruit tutorial.

tar -xzf pyserial-2.6.tar.gz
cd pyserial-2.6
sudo python setup.py install

I confirmed pyserial was functioning by creating serialTst.py

import time
import serial

ser = serial.Serial('/dev/tty.usbmodemfa13131', 57600)

while True:
    message = ser.readline()
    print(message)
    time.sleep(0.5)

and it echoed output being written by the Arduino with Serial.println.

matplotlib

[The packaged matplotlib doesn't seem to work with the Apple release of Python. (matplotlib-1.2.1-py2.7-python.org-macosx10.6.dmg) from http://matplotlib.org/downloads.html gives an error saying "matplotlib 1.2.1 can't be installed on this disk. matplotlib requires System Python 2.7 to install.]

Following http://penandpants.com/2012/02/24/install-python/ (or maybe better http://penandpants.com/install-python/ and some of http://www.tapir.caltech.edu/~dtsang/python.html) provided alternatives after installing the xcode command line tools:

ruby -e "$(curl -fsSkL raw.github.com/mxcl/homebrew/go)"
brew doctor

brew install pkg-config
brew install freetype
brew install libpng

sudo easy_install pip
sudo pip install matplotlib

The matplotlib install produced a huge number of warnings, but reported successful installation at the end.

wxPython

Install wxPython (wxPython2.8-osx-unicode-py2.7) from http://wxpython.org/download.php. To get the install to work you need to allow installs from anywhere in system settings. see http://trac.wxwidgets.org/ticket/14523 and http://www.toolfarm.com/blog/entry/installing_osx_10.8_mountain_lion_please_read

Continuing

After all that installing, serialTst.py still works. Got the Arduino running Kevin's ArduinoDAQ on a fresh port tty.usbmodemfa13141. Changed the port in daq.py  and ran, but it fails on loading wxPython 2.8 with no 64 bit environment. wxPython 2.9 claims to be OK with both 32 and 64 bit, so I installed it and then python daq.py runs!

It generates repeating warnings if the Arduino environment is still running, but quitting it and rerunning python daq.py works great.


Tuesday, 4 June 2013

Things I wish I knew about python and the WebIDE right away...

Python is interpreted, so you need to feed your source code to the interpreter program, typically with a command like python MyProgram.py. or you can just run python then start typing in commands the same as they would appear in your code. It takes me back to the bad old days of MS/BASIC. Alternately, if the first line in the .py file is #!/usr/bin/env python and you have changed the mode of the .py file to allow execution (chmod +x MyProgram.py) then you can run the file directly by name.

Indentation defines extent the way {} do in C, so whitespace matters.

The first thing you need to do is import the libraries you want to use in your code:

import sys
import RPi.GPIO as GPIO

imports the whole sys library, imports the RPi.GPIO library but lets you refer to it as GPIO for function calls like GPIO.setup(RST, GPIO.OUT)

from time import sleep

just imports the sleep function from the time library. Python finds all of these somewhere in the system libraries by following the path. You can add to the path like this:

sys.path.append("/home/pi/Examples")

so that

import Nokia.RWSpypcd8544 as nokia

will find the code in /home/pi/Examples/Nokia/RWSpypcd8544.py as long as /home/pi/Examples/Nokia/__init__.py also exists, even if it is empty. The code in the init file will run before importing the code from the named file. Note the use of a period rather than a slash. Now you can call things from RWSpypcd8544 with function calls like nokia.showFlower().

Running a WebIDE python program on system boot


It's pretty straightforward to use the WebIDE to write and run python programs from a web connection. Once those programs are working, you might want to run one of them automatically when the Pi starts up. /etc/rc.local is a script that will run as the final part of the boot sequence, so you can add a command to this script. The command I added was

sudo /usr/share/adafruit/webide/repositories/my-pi-projects/BlinkButtons/flashyNokia.py &

to run the program in background. Running it with sudo is required to give full access to the hardware features. To make the script run you will need to

sudo chmod +x /etc/rc.local

in order to make rc.local executable. You'll also have to run chmod +x against the .py file created by the IDE. You only need to do all of this once, even when you modify the program in the IDE.

Tuesday, 16 April 2013

Same Desktop on HDMI and VNC

I wanted to have my Pi connected to a big HDMI TV on the other side of the room and control the desktop from a VNC window on another computer. It took me quite a while to find out how to do this, so I'm repeating it here. The secret was to use x11vnc instead of the tightvncserver I started off with. Install it, then store a password as the user you want to have access and it will be in ~/.vnc/passwd

sudo apt-get install x11vnc

x11vnc -storepasswd

Start the GUI on the HDMI first then run the x11vnc from the command line as the same user (either on the main desktop or remotely via ssh).


x11vnc -rfbauth ~/.vnc/passwd -display :0

Then run a VNC client like Real VNC and log in remotely on port :0.

Interestingly enough, it looks like x11vnc runs right alongside tightvncserver, allowing me to have one VNC window on port :0 (x11vnc) going to the HDMI desktop and another on port :1 (tightvncserver) with a new, independent desktop.