Translate

Saturday, October 25, 2014

Raspberry Pi - RPOf project


The Raspberry Pi can be used to run some kind of embedded Linux.
Like any *nix system, removing suddenly power is not a  good thing, it is very easy to corrupt  some SD card sector if the power removal happens during a writing cycle.

So, especially if the board is running some kind of "embedded" code, i.e. no keyboard/HDMI/remote connection, it is important to be able to shutdown it properly.



There are mainly two main operations to perform to correctly turn OFF a *nix system.

  • send a shutdown to the system
  • remove the power after the shutdown

It is possible to use a spare GPIO on the Raspberry Pi to allows to have a easy way to accomplish the job to shutdown the machine.
Using some external hardware is possible to remove the power supply when the shutdown sequence is completed.

The easiest way is to use a cheap microcontroller, like an AVR, PIC or MSP430 or anything programmable.

RPOf (Raspberry Pi On/off)


The RPOf is a circuit that allows to turn ON and OFF a Raspberry Pi with a single pushbutton.
Specifically the circuit allows to:
  • indicate the state of the power to the Raspberry Pi
  • give/remove main power (5V) to the Raspberry Pi
  • send to the Raspberry Pi a signal on a GPIO for the shutdown
  • monitor the status of the shutdown
  • remove the power after the shutdown is performed
Similar circuits are already on the market but it was fun to design my own.

Hardware


The circuit is based on a MSP430 family microcontroller but anything can really be used, also an Arduino or Trinket or bare AVR or any other small microcontroller.
This article describes a RPOf based on a MSP430F2012, the one that can be programmed using a TI LaunchPad (probably a smaller MSP430F2002 will be used since the code is very small and no particular peripherals are used).




The circuit has a 5V stabilized input, usually coming from an USB wall wart (at least 1A) and is connected to the Raspberry Pi on two points:
  • the power supply (+5V)
  • the shutdown input/feedback
The choice is to control the +5V and not supply the Raspberry Pi with the 3.3V for two reasons.
First the Raspberry Pi can control 5V peripherals (for example an LCD) and thus needs to have the full power, and second, in this way there is no need to modify the Raspberry Pi power supply.
A relay feeds the power to the Raspberry Pi and a single pushbutton (with LED) control all the operations.

When the power is applied to the circuit, the relay is deactivated, so NO power is provided to the Raspberry Pi.

It is important to note that the MSP430 is powered at 3.3V, so the I/O lines going to the Raspberry Pi are already set for the correct voltage level.
There is no need to interface the signals with transistors.

The first prototype was built over a Launchpad, thus some I/O were chosen to match what already existing on the Launchpad.
For example the LED output and the pushbutton input are the default ones on the Launchpad so that in the early stage of the development it was possible to use the Launchpad ones.

The circuit uses 2 LEDs.
  • One fixed red LED powered when there are the 5V input, to indicate that there is power to the RPOf.
  • The second LED is included in the On/Off pushbutton and indicates the status of the power.
    - OFF   Raspberry Pi not powered
    - ON     Raspberry Pi powered
    - FLASH  Raspberry Pi doing shutdown
  • Optional a  third LED can be is used as debug and it can be used to indicate that the Raspberry Pi is working.

Prototype


After the first tests on the Launchpad board, a  prototype was built over a perforated board.
It is round because is what I had around at the moment.






Operations


The operations are  based on a state machine with seven states :
  • IDLE
  • POWERON_START
  • POWERON_WAIT
  • POWERON
  • POWEROFF_START
  • POWEROFF_WAIT
  • POWEROFF

IDLE state

The default state is IDLE.
In this state the power to the Raspberry is OFF, the Power LED is OFF and it is constantly monitored the on/off pushbutton.
When the on/off pushbutton is pressed set the state to POWERON_START.


POWERON_START state

In the POWERON_START state :
  • The relay is turned ON
  • The Power LED is turned ON
  • Change state in POWERON when the on/off pushbutton is released.


POWERON_WAIT state

In the POWERON_WAIT state :
  • it is monitored a signal coming from the Raspberry Pi.
    This signal is set to one by the Raspberry Pi when is running and is reset after a shutdown.
    By default this signal is zero when the Raspberry Pi starts and remains to zero until a program on the Raspberry Pi starts and set it to one.
  • A safety timer of 2 minutes is set.
    If expires it means that in 2 minutes the Raspberry Pi didn't start and the power is removed from the Pi (forced PowerOff state).
  • When the signal goes ON:
      - Power LED is set to ON
      - the safety timer is removed.

POWERON state

In the POWERON state, it is monitored the pushing of the on/off pushbutton.
When the on/off pushbutton is pressed set the to  POWEROFF_START.


POWEROFF_START state

In the POWEROFF_START state :
  • Send the signal to the Raspberry Pi to execute the shutdown.
  • The Power LED is set to FLASH
  • Start 15 minutes safety timer
  • Set the state to POWEROFF.

POWEROFF_WAIT state

In the POWEROFF_WAIT state :
  • Monitor when the Raspberry Pi shutdown is completed
    - if safety timer expires:
      - relay is turned OFF
      - Power LED is turned OFF
      - Shutdown signal is turned OFF

    - if shutdown completed:
      - Start OFF TIMER


POWEROFF state

In the POWEROFF state :
  • Wait for the OFF TIMER to expire. When it expires:
      - relay is turned OFF
      - Power LED is turned OFF
      - Shutdown signal is turned OFF
      - Set the state to IDLE


Forcing and Detecting shutdown

We need two free GPIO on the Raspberry Pi to be used for the shutdown procedure.

  • Shutdown request
    Raspberry Pi side will be an input
    RPOf side will be an output
    This signal will indicate to the Raspberry Pi to start the Shutdown command (sudo shutdown -h now)
  • Shutdown feedback
    Raspberry Pi side will be an output
    RPOf side will be an input
    This signal will indicate to the RPOf that the Raspberry Pi successfully completed the shutdown procedure and thus the power can be removed.
    That GPIO is set as output and forced to high (1).
    When the shutdown is complete, all the I/Os are forced to low, thus the RPOf can monitor the GPIO we set up as output and it  can determine if the shutdown was executed and completed.

There are a couple of options to do so.

1) Raspberry Pi script


In order for the RPOf to work, a daemon need to run on the Raspberry Pi, monitoring a GPIO input connected to the RPOf circuit.
When the signal monitored goes down, the script starts the shutdown sequence.
Handling the GPIO via script uses a different GPIO listing. Read the notes.

The same script, started automatically after the Raspberry Pi boot up, set also the GPIO to allow RPOf to detect the completion of the shutdown.

2) Local program


If a program is supposed to run, it is possible to add the I/O management in the program itself.
The program will set up the Shutdown feedback signal ON (it will be set to zero when the shutdown will be completed).
On the same time, the program will include the constant monitoring of the Shutdown request signal.


RPOf Software

The software is written in C, compiled with the  mspgcc compiler and load in the chip with the mspdebug, all under Linux.
The timing for this project is not critical, so no crystal is used. Instead is used the internal oscillator set for the maximum speed, 16 Mhz

The code resides in a single file called RPOf.c and uses a very easy makefile to compile.

Makefile


CC=msp430-gcc
CFLAGS=-O0 -Wall -g -mmcu=msp430f2012

OBJS=RPOf.o


all: $(OBJS)
$(CC) $(CFLAGS) -o RPOf.elf $(OBJS)

%.o: %.c
$(CC) $(CFLAGS) -c $<

clean:
rm -fr RPOf.elf $(OBJS)

Code


The code is quite straightforward.
There are specific functions for the main basic tasks, like reading the pushbutton or reading the shutdown feedback signal or handling the pushbutton LED behavior.

Function readPushbutton()

Reads the status of the On/Off pushbutton.
It returns 1 (ON) if pressed, 0 (OFF) if not pressed.

Function readShutdownFeedback()

Reads the status of the signal to monitor the end of the shutdown sequence.
It returns 1 (ON) if shutdown ended (machine stopped), 0 (OFF) otherwise.
It can be used to determine if the Raspberry Pi is running.

Function LEDPower()

Control the Power LED of the On/Off pushbutton.
A global variable (LEDStatus) control how the LED behave:

Value   Define       Description       
 0      OFF           LED Off
 1      ON            LED On
 2      FLASH         LED Flash (.5 sec)

Function Relay()

Control the Relay.
A global variable (RelayStatus) control how the Relay behave:

Value   Define       Description       
 0      OFF           Relay Off
 1      ON            Relay On

Git

The RPOf project is on github.

Improvements


Here some possible improvements to the circuit:

  1. work to reduce the power usage.
    Reduce the frequency, have it working in low power mode when in IDLE
  2. Add a 5V battery.
    A 5V battery charged from the main supply, could allow to guarantee a correct shutdown even if the external power is suddenly removed

Resources


Here some links:

Saturday, October 11, 2014

Raspberry Pi - connecting a traditional LCD display

Raspberry Pi is a powerful enough platform and  it is possible to use many recent touchscreen with a nice graphic on it.
However often a traditional LCD is more useful, and surely is more cheap than a touchscreen solution.

Here one way to connect a traditional LCD and use it in projects, like the TeirmiLab one.
This article describes how to connect a traditional LCD but with RGB capabilities to the Raspberry Pi B.

We need :

It is possible to hook a display without the need of the GPIO expander, however a normal LCD uses at least 6 signals. 9 if the LCD display is an RGB one like the one used for this project.
Considering that the Raspberry Pi B doesn't have many GPIO available and that usually the speed required to handle the display is not critical, using a chip like the MCP23017 make sense.
In this way it will be enough to "hook" the  chip to the I2C bus, leaving all the Raspberry Pi GPIO free for other use.

Let see a schematic.


Software


There are many ways to control the hardware.
For now I found a ready-to-use Python library published by Adafruit that is working nicely.
Again, the important thing is that control an LCD is not a critical task, so a python script is Ok.
Maybe in future I'll explore the possibility to control it directly in C.

Python 

To use our display we need to install some code in our Raspberry.
Here a quick step-by-step guide (see Adafruit tutorials for a more detailed and easy instructions) :


  1. sudo apt-get update
  2. sudo apt-get install build-essential python-dev python-smbus python-pip
  3. sudo apt-get install i2c-tools
  4. sudo pip install RPi.GPIO
  5. cd ~
  6. git clone https://github.com/adafruit/Adafruit_Python_CharLCD.git
  7. cd Adafruit_Python_CharLCD
  8. sudo python setup.py install
Before to be able to use it, we need to be sure a configuration file is correctly set-up.

Execute : sudo nano /etc/modules

and if the file exists, add these two lines in the end.

i2c-bcm2708 
i2c-dev

Save the file then open another one in edit.
Execute : sudo nano /etc/modprobe.d/raspi-blacklist.conf

In this file comment out the two lines showed below, adding # at the beginning:

#blacklist spi-bcm2708
#blacklist i2c-bcm2708


Reboot Raspberry : sudo shutdown -r now
or : sudo reboot

At this point everything should be installed in order to use the display.
First is better to run an utility to see if the I2C GPIO expander is seen correctly.

sudo i2cdetect -y 1

The command should display a table and in the table should be present a 0x20 address.

pi@raspberrypi ~ $ sudo i2cdetect -y 1
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- -- -- -- -- -- -- -- -- 
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
20: 20 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
60: -- -- -- -- -- -- -- -- 68 -- -- -- -- -- -- -- 
70: -- -- -- -- -- -- -- --                         
pi@raspberrypi ~ $ 


If so, the chip is correctly seen by Raspberry.

To test if the display is working you can execute a test script :
  1. cd Adafruit_Python_CharLCD/examples
  2. sudo ./char_lcd_mcp.py
Some test messages should be displayed on the LCD display.


Wednesday, October 8, 2014

Airflow sensor test

I used a little board with a MSP430-2013 and a LCD display  to develop the basic code to test and read the airflow sensor.

The circuit


Here a picture of the prototype


The software

The airflow sensor reading is based on counter and a timer.
The MSP430 pin connected to the airflow sensor is set in interrupt mode (rising) and after a check on the pin state to be sure is not a spike, a counter is incremented.
Every time a related timer expire, the value of the counter is copied into another variable (to be displayed) and the counter is reset.
I use another timer to display the read value on the display, after a integer-to-ascii conversion.
The code described is not reading the DS1820, only the airflow sensor.


TeirmiLab - prepare Raspbian

For the TeirmiLab project, one of the platform I choose to prototype it, is the Raspberry Pi B (or B+).

This is a quick step-by-step reminder about how to prepare Raspbian for the Raspberry Pi B and B+ for this project.

There are on-line hundreds of places where is described how to install a Raspbian over a Raspberry Pi.


If this quick step-by-step is not enough for you, try this.
If you think that this is too technical ... are you sure you want to play with microcontrollers ? :)

Lets start.
I used a 8 Gbyte micro SD card with a low profile adapter. In this way is easy to eventually swap to the Raspeberry Pi B+.

It is necessary, at least for the installation, to have :
  • a 5 Volt 1A USB power supply
  • a USB cable (microUSB) for the power supply
  • an internet connection, better if wired
  • a computer (needed to download the image and prepare the SD card)
Optionally if you want to enable the graphic interface or plan to use Noobs, better to have also:
  • a HDMI monitor or a composite monitor (suggested an HDMI one)
  • an USB keyboard
  • an USB mouse

As keyboard and mouse, I used a wireless Logitech keyboard with an included touch-pad with USB dongle, in this way there is still available an USB Port.

SD card preparation  

Once all the HW components are available and connected, is possible to prepare the SD card.
Raspberry Pi does not have flash, it boots from the SD card that is used also as hard drive.
Because of that it needs to be formatted in Fat32.

Using kparted erase all the data on the SD card (new partition) and then simply format all the card in Fat32.
If you DON'T plan to use Noobs, there is no need to format the SD card.

Problems
Use a decent SD card for the job.
It should be fast and good quality/brand.
I had some SD cards not working properly because not fast enough or bad brand.
I found more reliable to use microSD cards with the adapter.

Installing distribution

There are two main choices about installing a distribution/OS on the SD card:

  • installing Noobs
  • installing a specific distribution

Noobs
If you choose to use Noobs, here some notes.
It is easier, shows you the latest available distributions and install automatically everything needed.
You must connect an HDMI monitor and a keyboard/mouse to the Raspberry Pi.

To install Noobs, simply download it and extract it on the SD card.
That's it. No strange formatting of the SD card, no partitions, secret code, ecc.
Just a plain copy.

Once copied, insert the card on the Raspberry Pi and turn it on.
After few seconds will appear on the HDMI screen the list of available OS to install.
If you have enough space on the SD card, it is possible to install more than one.

With 8Gbyte SD card, generally there is space for 1 or 2 OS.

The suggested distro to install is the Raspbian , accessible via the Noobs menu.

It is a Debian based distro and is probably the most used.
Once installed, a configuration menu' will allows to set up some parameters, like starting the distro in graphic mode rather than command line.
The default is command line ! So it is normal to boot in command line if no configuration modifications are made.

Raspbian
It is possible to install directly Raspbian. The main advantage is to have much more space on the SD card.
Here how to do it.
Go on the Raspberry Pi website download page , locate the Raspbian image and download it on your computer (look for Operating Systems Images - Raspbian).
Detailed explanations about how to do that are available on the Raspberry website, shortly here a quick reminder. I'm using Linux and I'm assuming you KNOW how to work on Linux.
  • download the image on your PC
  • extract the image from the zip file
  • open a terminal
  • df -h
    to see what memory devices are present
  • insert the new SD card
  • df -h
    identify the latest device inserted - ignore the partitions, we need to overwrite the entire card with the image
    If nothing appears, try with gparted or kparted to identify the new card
  • umount /dev/sdxx
    umount the device added if for any reason it was mounted.
    In case the card has more than one partition, umount all of them.
    Eventually better reformat the card with gparted so to have a single partition but is not necessary.
  • copy the entire image downloaded on the sd card with the command:

    dd bs=4M if=name_image_downloaded.img of=/dev/sdx

    where name_image_downloaded is the path/name of the downloaded Raspbian image and sdx is the name of the unmounted device (DEVICE !  NON PARTITION !)

    CAUTION!  Take your time and triple check ! If you use the wrong /dev you can lose your data !
At this point you have the SD card ready to be inserted in the Raspberry Pi.
Do it, be sure to have connected the board to the network, no need to have HDMI and keyboard/mouse, you can operate via ssh.

The image installed allows for the default user named 'pi' and password 'raspberry'.
Hook up  a terminal to the board, for example in ssh, is possible to login with:

- ssh pi@192.168.xxx.xxx   (address of the board - see your DHCP assignment)
- password : raspberry

Once gained access, is better to do an update with :  sudo apt-get update

After the reboot is better to configure Raspbian running the command sudo raspi-config.
At least run the option
- Expand Filesystem and the
- Advanced Options/A6 I2C in order to enable the I2C support.

No need to run other options.

The Raspberry Pi B (or B+) board is ready for the next step.

Saturday, October 4, 2014

TeirmiLab - Designing a laboratory thermometer

Sometime is necessary to "reinvent the hot water".
In a  laboratory is necessary to measure the temperature of liquids and not always are easily available the last technological gadgets or practical one.

This article describes very generally some characteristics, requirements and usage of the gadget to design, a thermometer to be used in a laboratory

Important ! This project is based on specific requirements. Is not meant to be a "universal laboratory thermometer" but rather an instrument with specific characteristics needed in a specific laboratory.
The idea is that it can become a starting base for similar lab thermometers.

So here this project trying to design and build quickly a thermometer suitable to be used in a laboratory : the TeirmiLab

Lets start with the name.
The name is invented taking the first part of the Irish translation of "thermometer" (teirmiméadar) and of course "Lab" does not need of explanation.
Why Irish ? Well, I liked the sound of the name. The beauty of globalization.

The idea is to have a versatile and flexible instrument, capable to collect temperatures with probes attached to the display unit, measuring the current temperature, the minimum one, the maximum and work optionally as data logger.

The TeirmiLab can be also connected to a network (enhanced version), adding the possibility to see the current measurement in real time over a browser and adding graphic capabilities, remote setting of the unit and so on.

On the market do exists a lot of thermometers for laboratory use, but one of the goal of the project is to create an open platform and a thus customizable one, without spending up to thousand dollars.

The precision of the TeirmiLab initially is set as the sensor used, the DS1820. 

Requirements


The TeirmiLab should be able to performs these functions (the list has no particular priority)

Basic

  • minimal and intuitive user interface
  • read one sensor. The sensor should be detachable to be able to change it or clean it
  • display the temperature away from the sensor
  • display the temperature in Celsius or Farheneit or Kelvin
  • Alarm
  • Capability to offset the reading locally (setup)
  • Capability to set the alarm locally

Enhanced

  • read more than one sensor
  • display locally the min and max temperature
  • data logger capability
  • capability to store locally temperatures for an amount of time
    • setting for the measurement interval
    • setting for start and stop
    • capability to transfer the log to a remote computer
  • remote connection capability
    • setting alarms
    • offsetting a probe
    • download log
    • reset log
  • remote display capability
  • (optional) print results locally
  • (optional) RFID reader for identification 
Let see more in details some requirements for the basic version/

Minimal and intuitive user interface

In a world of "apps" it is easy to forget that sometime is more important a practical approach rather than a fancy one.
The user interface of the instrument is based on a "traditional" LCD display and few push-buttons.
No fancy touch screen with nice graphics.
A lab instrument needs to be first of all simple and immediate to use and sturdy, ANYBODY should be able to use it after 5 minutes and the tools itself must be capable to work in an hostile environments (spills, dirt, etc.)

Alarm

The TeirmiLab should have the capability to generate an alarm if a specific temperature is reached.
The alarm can be visual (change color of the display for example), audio (buzzer) or web based (browser pop up).

Remote display from the sensor

The sensor should be detached from the main unit, i.e. connected via cable.
The thermometer should be placed away (inches) from the source to measure so to easily locally display the temperature on a local display

Local settings

It must be possible to set locally some functionality, like setting an alarm or setting up an offset.
So a mini keyboard with at least three pushbutton is necessary.
Alternatively is possible to use a rotary digital  encoder with a pushbutton.

Keyboard/Keypad


Here a button requirements:
  • Mode
    The Mode button allows to change the state of the instrument.
    There are 4 modes :
    • Run  (default mode)
      In this mode the temperature read from the sensor is displayed in real time (every second).
      If the alarm is set, the display will show the normal temperature in Green and will switch in Red when the alarm is reached.
    • Measurement unit
      By default the measurement unit is in Celsius.
      Alternatively is possible to select Fahrenheit or Kelvin
      The selection of the measurement unit automatically update the current values (alarm/offset)
    • Alarm Set
      In this mode is possible to enter the alarm temperature, using other two pushbutton to increment or decrement such value
    • Offset Set
      Some sensors can have an offset. This mode allows to add a value to the reading to offset the sensor.
  • Increment
    The Increment button (+) allows to increment a value
  • Decrement
    The Decrement button (-) allows to decrement a value

Digital Rotary Encoder


The pushbutton on the encode select the mode, then rotating the encoder clockwise will increase a value. Rotating the encoder counterclockwise will decrease a value.
  • Mode
    The push button  allows to change the state of the instrument.
    There are 4 modes :
    • Run  (default mode)
      In this mode the temperature read from the sensor is displayed in real time (every second).
      If the alarm is set, the display will show the normal temperature in Green and will switch in Red when the alarm is reached.
    • Measurement unit
      By default the measurement unit is in Celsius.
      Alternatively is possible to select Fahrenheit or Kelvin
      The selection of the measurement unit automatically update the current values (alarm/offset).
      Rotating the encoder will change the selection
    • Alarm Set
      In this mode is possible to enter the alarm temperature, rotate the encoder clockwise or counterclockwise to increase and decrease the alarm temperature
    • Offset Set
      Some sensors can have an offset. This mode allows to add a value to the reading to offset the sensor.
    • Reset
      This option reset the TeirmiLab in a known configuration
      • Unit used : Celsius
      • Alarm disabled
      • Alarm value = 0
      • Offset = 0
  • Setting
    When in a specific mode, rotating the encoder clockwise or counterclockwise will change the selection.