Raspberry Pi Foundation Site

My blog entry was featured on the Raspberry Pi and Make sites!

Update – RaspberryPi Camera for Astrophotography

Saturn 2 June 2013

NexStar 6SE using a 6mm eyepiece

The weather finally cleared up enough to capture some video of Saturn.  I experimented with several settings on the Raspberry Pi Camera (exposure, brightness etc).  I also used a 6mm eyepiece that captured a larger image and processed it through RegiStax.  I might have overdone the sharpness, but the image does show all the detail captured.  The complete video is here.

On a separate note, I found another project for the telescope control server (by Ferran Basora Roca) based on NodeJS.  It is based on the C++ version and since I’m currently working on other projects using NodeJS on the rPI, it seemed like a good fit.   My plan is to include some additional telescope control commands via a rPI served web-page.  The current software is limited to GoTo commands via Stellarium.  I would also like to be able to update the current time and geo location via the rPI.  More to follow.

Video of Saturn

 

Telescope Remote Control via Raspberry Pi

The ingenuity of the on-line community never ceases to amaze.  A group of telescope enthusiast have already written a Telescope Control Server that I was able to compile on the rPi and remote control via Stellarium (see post below).  The set-up is straight forward…the telescope is connected to the rPi via a USB-RS232 cable.  The Telescope Server software takes two parameters (TCP IP port, serial port):

TelescopeServerNexStar 10000 /dev/ttyUSB0

On Stellarium, I configured the Telescope Control plug-in to send commands via TCP/IP to the server.  Works like a charm!  I’ll post videos of the set-up once the skies clear up for some star watching.

 

RaspberryPi Camera for Astrophotography

My rPi camera board arrived from Element14 this week.  I was anxious to get it connected to my rover, but once I saw the quality of the image it produced, I decided to use it as a wireless image/video capture for a Celestron NexStar 6″ Telescope.  After a day of learning how to stream video and crafting an attachment to an eyepiece, I spent a couple of hours waiting for the clouds to clear and was able to catch some great video of the Moon and Saturn.

Saturn

Captured using a 17mm Plossl Eyepiece; next time I’m using a 6mm for a closer look.

moon2

 

I used the following guide to get a video stream from the rPi to my laptop:  Raspberry Pi camera board – Gstreamer. Gstreamer enabled me to see a live view from my telescope and once I centered on an object, I used raspivid to capture about 20 seconds of video.  I then used ffmpeg to convert the .h264 video to an uncompressed .avi file in order to process it in a image stacking program (RegiStax 6).  The image produced by RegiStax speaks more to my inexperience with the software and in the rushed aligning of the telescope.  

The rPi camera setup has great potential for astrophotography.  One additional note…I use Stellarium (a free, open source planetarium) to control and aim the telescope via my laptop.  Once I figure out how to route the telescope control signals through the rPi, I can star gaze from the comfort of my couch :)

 The Set-up

raspiPiI used foam packing material to attach the camera to the eyepiece.  Aligning the camera to the eyepiece was a matter of trial and error; both in vertical distance and horizontal placement.   The rPi was operating from a battery back and was attached to the telescope using velcro.  The camera’s short cable drove the placement of the rPi at the edge of the telescope.

Next Steps

I would like to reduce the number of steps in the video capture workflow by using  ffmpeg to stream, capture and convert the video coming from the rPi camera.  Also, I need to learn how to adjust gain, contrast, exposure etc.  Add one more item to my ‘must research list.’

Also, the rPi is streaming the video through my router; not a good option if I’m looking at the stars away from home.  I need to do a direct connection from rPi to my laptop or better yet…add a small screen and controls for stand alone operation :)

Astrophotography is a challenging hobby for an amateur astronomer and one can quickly become overwhelmed by the jargon, equipment, software etc.   One of the ways to produce a great image of a planet is to capture several frames (or a video) and use a image stacking program (article here).  A dedicated Celestron 5M pixel  imager costs $200 and I doubt it is nearly as versatile as the rPi.  This was a fun project, but I have so much more to learn.

Below are two short videos of the moon and Saturn:

Moon, Saturn.

 

NodeJS Rover

For the last several weeks I have been pursuing the knowledge needed to finish a robot project I started with my son.  I made some progress toward building a solid software framework for future expansion.

Hardware and Software: Raspberry Pi (rPi), Arduino Uno/Adafruit Motor Shield, Node.JS (Socket.IO, SerialPort, Express, Jade) and  JQuery Mobile.

Summary: Last year my son gave up his Snap Rover for some…experimentation (Snap Circuits toys are great for kids learning electronics).  The Snap Rover base is four wheel vehicle powered Snap Rober.jpgby two DC motors and 4 AA batteries.  Access to the power and DC motor leads are available in the back of the Rover…no hacking required.  Our first step was to hook up an Arduino UNO with the Adafruit Motor Shield along with a servo attached to a Parallax Ping Sensor.   When encountering an obstacle, the robot would stop, back up and seek a path by turning the ping sensor to the left and right.  Fun, but hardly a challenging project.

Enter the Raspberry Pi.   The rPi uses a Edimax Wifi USB adapter for wireless communication and runs a Node.JS server with the Socket.IO and SerialPort packages (details below).  Node.JS serves a JQuery Mobile page which allows the use of an iPad or iPhone to control the robot and receive feedback from its ‘sensors.’  Node.JS also serves as the link between the rPi and the Arduino via USB.  Two way communication via Socket.IO is surprisingly responsive even with a continuous stream of serial data traveling back and forth.

IMG_7009

The code for the rPi and the Arduino is well documented and available on GitHub.

Arduino Code:  The Rover operates in two modes: Auto (simple obstacle avoidance) or Manual (controlled from an iPhone) and  receives instructions via the Arduino Serial port.  The instruction set is rudimentary, consisting of  5-characters that determine the mode of operation, various scanning modes, and rover speed / direction.  The code also sends back a JSON encoded string of the rover’s current status, modes and sensor readings.  In searching for efficient robot code, I stumbled across Behavioral Programming for Robots.  Fortunately,  I had segmented the code to make it easy to incorporate new sensors and add additional behaviors, but the code is not (yet) aligned with the Behavioral Programming concept.

//Initial Guidance Parameters
Guidance[DRIVE_MODE] = 'm'; //Drive Mode Manual
Guidance[SCAN_MODE] = 'f'; //Scan Mode Forward
Guidance[POWER] = '0'; //Power = 0
Guidance[MOVE_GUIDANCE] ='s'; //Stopped
Guidance[INFO] = '0'; //No information feed from Arduino
//JSON Encoded Update from Arduino
String Get_Info() {
return ("{\"Status\":\"" + Status+ 
"\", \"Drive\":\"" + Guidance[DRIVE_MODE]+
"\", \"Scan\":\"" + Guidance[SCAN_MODE]+
"\", \"Power\":\"" + Guidance[POWER]+
"\", \"Guidance\":\"" + String(Guidance[MOVE_GUIDANCE])+
"\", \"Left\":\"" + String(left_distance)+
"\", \"Forward\":\"" + String(forward_distance)+
"\", \"Right\":\"" + String(right_distance)+
"\"}");
}

Raspberry Pi: Search Google for instructions on installing Node.js and npm (Node Package Modules) on the rPi–there are several sites with instructions on how to compile from source .  I used the easy method:
$ sudo apt-get install nodejs npm.

Once Node.js is installed and the NodeJS-Rover GitHub folder downloaded on your rPi, run the following command then point your browser to the Node.js server:

$ node robot_control_app.js
NOTE: Modify ‘public/js/mobile-functions.js’ with the IP address of your Node.JS server.

The Node.js packages included in this project:

  1. Express (Node.js development framework)
  2. Jade (Node.js template engine)
  3. SerialPort (for communicating with the Arduino)
  4. Socket.IO (for controlling the rover via the web).

The GitHub repository has all the required files including JQuery Mobile.

One can use Node.js without Jade (or Express).  It took me a couple of days to work through the Jade syntax but once I was able to bend the learning curve, I appreciated the simplicity and elegance of using a solid template engine.   Initially I used straight JavaScript for the rover control web page, but it required a lot of work getting it to look right on the iPad and iPhone.  Switching to JQuery Mobile led me to yet another learning opportunity, but yielded significantly cleaner and faster code.  The web page is a simple collection of controls (buttons & switches) and clearly shows the limits of my HTML5 design prowess.

Way Ahead: More sensors–IR distance sensors (front and back), 2-axis accelerometer to help determine speed and turn rates.  Also, I would like to add a web-cam and use SimpleCV to track an object or a person.  I already have SimpleCV running on the rPi, but haven’t decide whether to do the computation for the object tracking on the rPi or send the images back to another computer for processing.

Moved

I decided to move my nascent blog from Google Blogger to (self-hosted) WordPress site.  It was a relatively easy migration and has opened up a whole new area for exploration and learning.  Who knew ssh tunneling could be so interesting!

Genetic Algorithms

I took a great Genetic Algorithm course from the University of Idaho a few years back.  My project is still listed on the U of I website:

http://people.ibest.uidaho.edu/~foster/pub/ga-course/projects.txt

I completed the program…it was an excel add-in that applied my GA to the scheduling problem.  Time to re-examine the technique for some upcoming projects.

Cristos Vasilas Scheduling Students

     I have an idea for a project that closely relates to my work. Within my
     flight I am responsible for scheduling the training of our students. The
     goal of the project would be to find the best daily schedule to optimize
     training and instructor continuity for students enrolled in Undergraduate
     Flying Training.

     Each student follows a strict syllabus which defines which events can be
     accomplished. At any one time, a student can be opted for an event in any
     one of four categories of training. This all depends on having met the
     required prerequisites.

     Each student performs an event with an instructor. Which instructor
     depends on a set of rules pertaining to instructor continuity. For
     example, a student should fly no more than 4 and no less than 2 sorties in
     a row, with the same instructor. Also he/she is limited to the maximum
     number of instructors in a phase of training.

     Each day is broken up into 2 or 3 periods in which a given number of
     events can be accomplished. Each instructor has additional duties that
     make him/her unavailable to accomplish any student events in a given
     period.

     The amount of events scheduled in a day or a period depends on the number
     of sorties available to the group of students (a flight).

     An optimum schedule would have each student accomplish a least one event a
     day with good instructor continuity, and also fill all sorties scheduled
     for the flight.

     This is a very simple representation of the problem. There are many more
     factors to take into account. For example, the weather precludes certain
     types of events. Also, a certain number of events in a particular block of
     training must be accomplished solo.

USB RGB-LCD Update

Update: I ordered a ATtiny 4313 because I ran out of flash memory on this project.   I was running the ATtiny 2313 at 3.6 volts and 16 MHz which worked despite the datasheet recommended voltage range for that frequency (0 – 20 MHz @ 4.5 – 5.5V).  After some fumbling with the -4313, I was able to get it working at 16Mhz as well.

Time to write some additional code!

Another USB based LCD Project–now in Color!

Summary:  This project uses the V-USB library from Objective Development (V-USB) to control a RGB Backlight LCD using a ATtiny 2313. The USB code is based on the outstanding tutorials found at CodeandLife. My write-up will not focus on the V-USB implementation using the ATtiny 2313, but rather on the issues I had to research and work through to implement my design. Specifically, (1) changes to the V-USB code required to use pins other than the default configuration, (2) using Pulse Width Modulation (PWM) to drive the RGB LCD, and (3) PC console code. For those experienced with AVR micro controllers, these are simple issues, but required a bit of research and ‘tinkering’ on my part and I wish to share my experience. Video below.

Figure 1 AVR Attiny 2313/4313

Hardware: ATtiny 2313 running at 16Mhz; RGB Backlight LCD, USBTinyISP programmer, re-cycled

PD0-3 –> LCD (4-bit mode)
PA0-1 –> 16Mhz crystal
PB0 –> USB/D+
PB1 –>USB/D-
PB2-4 –> LCD RGB Backlight
PB5-7 –>LCD Control (Enable, R/W, Register Select)

Figure 2 V-USB Wiki Hardware Considerations

The entire device runs off USB power; the LCD draws directly from USB +5V and the -2313 is connected via two diodes that drop the voltage to 3.6V (see figure 2). The LCD draws ~75mA max, so the entire device is well within the 500mA USB limit.

Software: AVR Studio 5 , VC++ Express and GCC (PC console application) and lib-usb-win32 for the PC USB driver. I use a Win7/64 machine and all the development software is available for free.

Source Code:

1. Using different pins for D+ and D- in V-USB.   (Again, for an excellent tutorial series on V-USB: CodeandLife).

V-USB is configured to use PD2(INT0) for D+ and PD3(INT1) for D-. D+ must be connected to INT0 and if you want to use a different set of pins, you have to change the settings in usbconfig.h. I used PB0 (D+) and PB1 (D-) and configured the appropriate settings in the file below (I have included the original settings for comparison):

/* ----------------------- Optional MCU Description ------------------------ */
#define USB_INTR_CFG            PCMSK // Originally MCUCR
#define USB_INTR_CFG_SET        ((1 << PCINT0))//((1 << ISC00)|(1 << ISC01))
#define USB_INTR_CFG_CLR        0
#define USB_INTR_ENABLE         GIMSK
#define USB_INTR_ENABLE_BIT     PCIE  //INT0
#define USB_INTR_PENDING        EIFR  //GIFR
#define USB_INTR_PENDING_BIT    PCIF  //INTF0
#define USB_INTR_VECTOR        PCINT_vect //INT0_vect

2. Setting up Pulse Width Modulation (PWM) to drive RGB LCD:

The ATtiny 2313 microprocessor has four pins that can be setup for hardware PWM–PB2, PB3, PB4 and PD5. The datasheet lists the additional functions related functions as OC0A, OC1A, OC1B and OC0B respectively. PB2 & PD5 are controlled by 8-bit counters, PB3 & PB4 are controlled by 16-bit timers. My project uses PB2, PB3 and PB4 to drive the Red, Green and Blue back light LEDs. The PWM set up occurs within the PWM_Init() function below and prior to setting pin direction.

NOTE: There are two great tutorials on AVR Freaks that I used to understand the fundamentals of PWM: Timer Tutorial and PWM Tutorial.

Figure 3, Fast PWM Mode (datasheet Figure 32, page 68)

A couple of notes on my choice of PWM set-up.

The RGB LED back light is common-anode, that is, the LED are on when the voltage drops to ground and off when the voltage is Vcc, in this case 3.6V from the ATtiny. That influenced my choice of the Output Compare (OC) Mode. From figure 3 above, I used the (middle) Output Compare mode: set the output (OCn) on Compare Match (when the timer equals the desired duty cycle (OCRxn), and clear the output when the timer reaches TOP (0xFF or 255 for an 8-bit timer). With this configuration, I’m able to set the duty cycle of the LED from 0 (off) to 255 (on) and anywhere in between. The datasheet table below is for the 8-bit timer, the 16-bit timer related table is found on page 104 and looks similar.

Figure 4 Compare Output Mode (datasheet, Table 35 page 73)

static void PWM_Init() {
//   **** Set up PWM output on PB2, PB3 and PB4 *******
// Red - PB2/OC0A (based on 8 bit timer/counter)
// Green - PB3/OC1A (based on 16 bit timer/counter)
// Blue - PB4/OC1B (based on 16 bit timer/counter)
// see the interrupt/timer section of the datasheet
// for the various timer PWM modes

// Configuration for Red
// Waveform Generation Mode (WGM) 3, Fast PWM (additional WGM bit set in TCCR0B
// Set OC0A on Compare Match, clear OC0A at TOP
       TCCR0A = ((1 << WGM01) | (1 << WGM00) | (1 << COM0A1) | (1 << COM0A0) );
// Set timer (CS00, CS01 & CS02) pre-scaler to Fcpu/8 (timing based on experimentation)
// WGM is split across the two registers; combined with TCCR0A above, set to PWM Fast mode
       TCCR0B = (0 << CS00) | (1 << CS01)  | (0 << CS02)| (0 << WGM02);     

// set up green and blue PWM pins; controlled by 16-bit counters
// but we will operate them exactly like the Red LED 8-bit mode above
// the WGM mode are outlined in a separate table in the datasheet, but reflect
// the same set-up as the Red LED mode above.   

// WGM 5 fast PWM (16-bit) mode (same as WGM 3, 8 bit mode)
// Set OC1A on Compare Match, clear OC1A at TOP (mirrors Red LED)
// Set OC1B on compare Match, clear OC1B at TOP (mirrors Red LED)
     TCCR1A = ((0  <<  WGM11) | (1  <<  WGM10)| (1  <<  COM1A1) | (1  <<  COM1A0)
     | (1  <<  COM1B1) | (1  <<  COM1B0));    

// Set timer prescaler at Fcpu/8 (same as above)
// WGM is split across the two registers; combined with above, set to PWM mode 5
     TCCR1B = (0   <<   CS00) | (1   <<   CS01)  | (0   <<   CS02)
           | (1   <<   WGM12) | (0   <<   WGM13);
  return;
}

Setting the duty cycle for the PWM is as simple as placing a value (0-255) into the appropriate Output Compare Register (OCRnx). The RGB values are send by the PC console application which is discussed below.

void set_color(const uint8_t r, const uint8_t g, const uint8_t b) {

 // Set the PWM duty cycle by setting an 8-bit value (0-255) in the appropriate register
 // 0 - off, 255- max.  The main loop calls this function to set the values which are passed
 // via the PC command line program.
 OCR0A = r; //OCR0A is based on an 8-bit counter and controlled via this 8 bit register

 // OCR1A is based on an 16-bit counter and controlled via these 16 bit registers
 // Since we are treating this as an 8-bit fast PWM (see table 46 in the datasheet)
 // we only have to set the duty cycle value in the low portion of the 16-bit register
 // and ignore the high byte.  If we need to read or write to the entire 16 bit register,
 // we would have to follow the guidance in datasheet (page 84) on Accessing 16 bit registers
 OCR1AL = g; //low byte of 16-bit register
 OCR1BL = b; //low byte of 16-bit register
 return;
}

Results: The firmware is 10 bytes short of the ATTiny 2313 2K limit. I had to eliminate some of the features I wanted in order to make it all fit. V-USB takes a lot of space! I plan to upgrade the micro to a ATtiny 4313 which has 4K of flash and should be a drop in replacement. The next step is to implement the device as a HID in order to eliminate using lib-usb as a device driver.

Pen Light

This is my first (post-Arduino) attempt at AVR programming. I got the idea for this project from the book: Tiny AVR Projects for the Evil Genius. Some good ideas for projects, but the code style is arcane and not well documented.

Summary: My son (7 1/2) and I had a great time building and using this pen. The Light Pen has two buttons, one to cycle through the eight pre-programmed colors and an on/off switch. When the last color is selected, the pen auto-cycles through all the colors every couple of seconds. We accidentally turned on the camera flash which went off after a 10 second exposure capturing some great photos (see bottom of the post).

Hardware: This was an easy build once I found the right ‘enclosure.’ We had these big Spiderman Markers which proved perfect for the job. The electronics consist of an ATtiny85, an RGB led (common anode), a resistor, a diode and a couple of push button switches. For power I used a Enercell PX28A 6V/105mAh Alkaline Battery (Radio Shack $4.99) that was a perfect fit for the bottom cap of the marker. I used the diode to drop the battery voltage from 6V to a more ATtiny85-friendly 5.3V. I also shaped a perf board to fit into the narrow, forward part of the marker. I used a single button in my first version, but discovered that having to cycle through all the colors to turn off the LED was problematic when trying to draw.

Software: I had to re-write the code to work with an ATtiny85 versus the ATtiny13 used in the book. My code is commented through-out, mostly for my own benefit as I tried to reconcile the author’s code with the ATTiny85 data sheet. The original source code was trying to accomplish too much within the Timer Overflow Interrupt Service Routine (ISR). Code within an ISR should be very short–adjust some (volatile) variables and get out. Even I go too far by calling a function (set_led) within my ISR, but I broke the rule for the sake of code readability.

Single button version, code below is for two buttons

The main reason for the Timer Overflow ISR is to implement Pulse Width Modulation (PWM). The ATtiny85 only has two pins capable of hardware PWM. In order to drive all three colors of the RGB LED, one has to implement PWM in software. This was my first experience with software PWM, so I’ll discuss what I learned in a future post.

Programming Environment: I recently installed the ATMEL AVR Studio 5…a MS Visual Studio environment. If you are familiar with Visual Basic or Visual C++, you will feel at home in AVR Studio 5.  I purchased and built a USBTiny programmer from Adafruit, but have also used an Arduino Uno as an In-system Programmer (ISP).
Source Code:
//**************************************************************//
//  Name    : LED Pen                                
//  Author  : Cristos Vasilas 
//  Date    : 24 Sept 11    
//  Modified: 24 Sept 11                                 
//  Version : 1.5                                            
/*  Notes   : LED pen used to draw with light; Original code from Chapter 2 of the 
     TinyAVR microcontrolers Projects for the Evil Genius
     I cleaned  up the code and provided
     some much needed comments and reduced the number of colors.  Major
                          changes in the timer overflow routine.
     I have left some of the original ADC code commented out in case I want to
     use it for another project.
     The single press button cycles through the color pallet; the last color position is a special
     setting that allows the pen to auto cycle through the colors.*/
//****************************************************************
#include
#include
#define F_CPU 1200000UL
#include
#include
#include


//Prototype Functions
void set_led(unsigned char r,unsigned char g,unsigned char b,unsigned char status); //display the correct color
void power_off (void); //puts the ATtiny to sleep


#define  MAX_COLORS 7 
#define  AUTO_MODE 7


const int R_BIT = 2;  //maps to the actual pin of the ATtiny 85
const int G_BIT = 1;
const int B_BIT = 0;


const int Power_Button = 3; //momentary switch (PB3) used as an on/off button
const int Color_Button = 4; //momentary switch (PB4); cycles through colors either manually or automatically


//the following variables are declared volatile because they are changed within the interrupt routine
volatile unsigned char color_level;    //part of the software pwm routine...more on this below
volatile unsigned char pwm[3]={0,8,8};   //holds the color value; this is connected to a common anode LED, 
                                                                                       //so 0 is full on and 8 is completely off.

unsigned char val=0,color_index=0;  //working variables


//preset pallet of colors; 0 is full on, 8 is off.
//technically the last color doesn't matter since the pen will go into 'auto' mode when we advance to 'MAX_COLORS'
//red, green, blue, purple, yellow, orange, yellow, white?
const unsigned char Red[8] PROGMEM =   {0, 8, 8, 4, 5, 6, 6, 8};
const unsigned char Green[8] PROGMEM = {8, 0, 8, 8, 0, 5, 0, 5};
const unsigned char Blue[8] PROGMEM =  {8, 8, 0, 0, 2, 8, 0, 2};


int main(void) {
 
 DDRB  &= ~((1<

Results:

Pen Light Results

Results