Raspberry Pi running from Batteries

Read this first http://simon.fearby.com/blog/?p=2202

Parts:
1x Raspberry Pi Model 2B
1x MoPi: Hot-Swap Mobile Power for the Pi (Manual)
1x 12V18AH Sealed Lead Acid Battery from JayCar (Manual)

1x 2 Watt 12 Volt Solar Panels – Amorphous 2 Watt 12 Volt Solar Panels – Amorphous

Read this post to see how my pi is configured and setup.

The Pi is running a public facing website here: http://sipi02.fearby.com

Step 1: Running on battery.

This is my battery and pi on my work bench.

PiBattery01

This is a close up of my Raspberry Pi + WittyPi (RTC and auto startup/shutdown hat) + MoPi (dual power and safe shutdown on low battery hat).

PiBattery02

I am not going to detail how to setup the MoPi but here is the MoPi output from the MoPi configured to be run from Lead Acid batteries.

PiBattery03

The default 6 cell Lead Acid battery profile says there is a low power condition when the battery is at 10.42v and the minimum charge s 9.48v.

Status Screen.

PiBattery04
This is the battery reading I have from the Pi itself.

PiBattery05

After 3 days of 24/7 use (saving an image every minute) and running a web server for the camera the battery has fallen from 12.73v to 12.28v.

Cheap multimeter reading (after 2 days use).

battery_3day

Mopi Reading (after 3 days use)

mopi3day

I will ignore my multimeter and trust the Mopi to decide when to power down the Pi.

mopi3dayb

I would expect the MoPi to shut down the pi when the battery falls another 2,456mv (that may be i n 18~25 days based on current trends (pun intended)).

voltchart1

Step 2:  Have the battery in Standby and top up the battery with Solar.

I have a cheapie “2 Watt 12 Volt Solar Panels – Amorphous 2 Watt 12 Volt Solar Panels – Amorphous”.  I have no idea if this will be enough to charge up the battery during the day? I have no idea about the solar stuff.

solar

Time to ask the experts at http://www.eevblog.com/forum/beginners/raspberry-pi-running-from-batteries-and-solar/

Update 30th March 2016

Ian.M at EEV Blog informed me that the lowest the battery should be discharged to is 10.5v.  I have edited the “/etc/default/simbamond” file to now specify safer low and shutdown power levels.  The “Sinabamond” service is a battery monitoring service (read about it here)

new-limits

If you edit the “/etc/default/simbamond” you may need to run the following command before and after you edit the file

  • sudo service simbamond stop
  • sudo service simbamond restart

Now when the MoPi detects the battery is below the low level the lights flash and broadcast messages appear on the terminal.

new-limits-warning

If the battery gets below the critical it shuts down the pi (safely).

Testing it (letting the battery getting below the critical limit).

new-limits-shutdown

The good think about the MoPi it shuts down the Pi safely and turns off the power (all power).

I must be getting a few low power spikes as the spikes because the Pi seems to be shutting down early.

I adjusted my max, good, low and critical values to 1200 11500 11100 and 11000 to test the levels of where my battery was at and the MoPi flashed to say it was shutting down then decided not to.  I ran a few volt outputs and the voltage detection was dipping.

new-limits-shutdown2

You may want to space your voltages enough to prevent voltage dipping triggering an early shutdown.

Ok this is the voltages that I will set my pi to shutdown at.

new-limits-shutdown3

Recharging the battery.

Ok, time to shutdown the pi and recharge my battery.

cahrger

Building the Prototype box

Installed 12v supply, 5v backbone, master off, RTC  and Dual PSU safe shutdown reset triggers. Next analog/digital sensors (smoke/co2, light, lazers, temp, humidity, pressure, moisture, motor and proximity motion sensor and vibration sensor), speaker and 240v relay for external control. Wifi, SMS and push notification code ready.

I killed a MoPi dual power input Pi board (silly me put the wrong colour shrink wrap protective layer over the top) and when I turned on the power with reverse polarity much blue smoke was released.

The main compartment will we air right with silica bags and protected from the elements with loads of styrofoam. I don’t think I need active cooling (therms electric peltier element).

proto-working

Checking (and verifying) the internet on a raspberry pi with a bash script

This is how I check the internet with a bash script on a raspberry pi. It verifies the internet by downloading a file from a webserver (e.g http://www.your-domain/pi/test/simple_text_file.txt
(change this to a file of your choice)).

Script: CheckInternet.sh

    #!/bin/bash
    printf "BASH Version: $BASH_VERSION\n"

    printf "Testing Internet Connection (http://www.your-domain.com):\n\n"
    # ping -q -t 10 -w1 -c1 www.your-domain.com
    wget -q --tries=2 --timeout=20 http://www.your-domain.com
    if [[ $? -eq 0 ]]; then
    printf "Internet appears online.\n\n"
    TMP_FILE="./simple_text_file.txt"
    if [ -f $TMP_FILE ]
    then
    echo "Deleting old temp files.."
    sudo rm ./simple_text_file.txt
    fi
    printf "Downloading file from the internet.\n"
    sudo wget http://www.your-domain/pi/test/simple_text_file.txt
    if [ -f $TMP_FILE ]
    then
    printf "File downloaded ok.\n"
    printf "File Contents:\n"
    echo "----------------------------------------------------------"
    printf "\n"
    cat $TMP_FILE
    printf "\n\n"
    echo "----------------------------------------------------------"
    else
    printf "File failed to download.\n"
    fi
    else
    printf "Internet appears offline, unable to download files."
    fi

    printf "Tiding up..\n\n"
    sudo rm ./simple_text_file.txt

    printf "Goodbye\n\n"

To call this script from the command line do this.

    sudo bash CheckInternet.sh

Alternatively you can schedule emails by adding this to your “/etc/crontab” file


    # run every 15 minutes
    */15 * * * * root bash /usr/bin/simon/CheckInternet.sh

    # run every 5 minutes
    */5 * * * * root bash /usr/bin/simon/CheckInternet.sh

Or you can run this on pi start-up by adding the python call to your “/etc/rc.local” file.

    bash /usr/bin/simon/CheckInternet.sh

Make sure you make you file executable.

Send Email from Raspberry Pi

This is how I am sending emails (boot and 15 min runtime notifications) from my Pi

Python Script: /usr/bin/simon/SendEmail.py

You will need to type in your mail server Username/Password/IP/Port to get this to work.


    #!/usr/bin/python
    import smtplib

    EMAIL_USER = 'your-email@your-domain.com'
    EMAIL_PASS = 'your_email_password_goes_here'
    SMTP_SERVER = '192.0.0.1'
    SMTP_PORT = 587

    def send_email(recipient, subject, msg):
    smtpserver = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
    smtpserver.set_debuglevel(0)
    smtpserver.ehlo()
    smtpserver.starttls()
    smtpserver.login(EMAIL_USER, EMAIL_PASS)
    header = 'To:' + recipient + '\n' + 'From:' + EMAIL_USER + '\n' + 'Subject:' + subject + '\n'
    header = header + '\n' + msg + '\n\n'
    msg = header + '\n' + msg + '\n\n'
    smtpserver.sendmail(EMAIL_USER, recipient, msg)
    smtpserver.close()

    send_email('recipient-name@gmail.com','Subject Goes Here', 'Email contents goes here.')

To call this script from the command line do this.

    sudo python SendEmail.py

Alternatively you can schedule emails by adding this to your “/etc/crontab” file


    # run every 15 minutes
    */15 * * * * root python /usr/bin/simon/SendEmail.py

    # run every 5 minutes
    */5 * * * * root python /usr/bin/simon/SendEmail.py

Or you can run this on pi start-up by adding the python call to your “/etc/rc.local” file.

    python /usr/bin/simon/SendEmail.py

Setting up eth0 and wlan0 on a Raspberry PI RevB (no drivers)

Recently I setup a raspberry pi to talk to the internet via ethernet here. I asked myself how do you configure Ethernet and wireless on the radpberry pi?

Today I added a wireless card and set it up so it can talk to the network too.

Step 1: Wireless Dongle.

I purchased 1x EDUP Model EP-N8537 Wireless LAN 150Mbps USB Adapter from eBay for $7.95 ( , item).

wlan0b

Step 2: Configuration.

I plugged my new Wireless card into Windows and ran the following command to get the MAC Address for the new card. Write the Mac Address down.

    ipconfig /all

I then connected to my ADSL router and went to the Static IP section under LAN/DHCP.

I added a static IP reservation for this mac address to my router and gave it an IP that I was happy with.

I then booted the Raspberry Pi (don’t connect the Wireless card yet). I typed the following command to open the network interfaces file.

    sudo nano /etc/network/interfaces

I deleted the contend of my interfaces file and typed this in.


    auto lo
    face io inet loopback

    iface eth0 inet static
    address 192.168.1.200
    netmask 255.255.255.0
    network 192.168.1.0
    broadcast 192.168.1.255
    gateway 192.168.1.1

    auto wlan0
    allow-hotplug wlan0
    iface wlan0 inet static
    address 192.168.1.204
    netmask 255.255.255.0
    network 192.168.1.0
    broadcast 192.168.1.255
    gateway 192.168.1.1
    wpa-ssid yourwirelessnetworknamehere
    wpa-psk yourwirelesspasswordhere

If you are unsure of what to type above go and check out the hundreds of awesome and free security/networking podcasts here https://www.grc.com/securitynow.htm.

Step 3:Reboot.

I ran a safe shutdown, inserted the WLAN adapter and rebooted.

Now I can use the ethernet or WIFI.

wlan0a

No drivers or non fee DEB packages were installed to get this NIC working.

Bonus tip: I am using a Ethernet over Power adapter connected to a wireless extender to allow my arduino/raspberry pi to connect to my router.

Arduino/Pi -> Gigabit Switch -> EoP A -> 240v (50m) -> EoP B -> 100MB Switch -> WiFi (30m) Extender A -> WiFI -> WiFi Extender B -> Router -> Internet 🙂

Raspberry Pi Setup

What is the Raspberry Pi?

The Raspberry Pi is a cheap computer designed by the Raspberry Pi Foundation (UK registered charity) to help kids build knowledge and experience in the computer Science, engineering and programming fields. Read more here: http://www.raspberrypi.org/about and here http://en.wikipedia.org/wiki/Raspberry_pi )>.

Post01b

My Raspberry Pi Setup

The Raspberry Pi is a very forgiving device to get started on, first you plug in your power (mine was a USB cable), SD card. keyboard, mouse, monitor (HDMI) and turn it on. My SD card was empty and nothing booted so i..

  • Downloaded NOOBS (Off-line Installer:) http://www.raspberrypi.org/downloads
  • Installed SD Card Formatting Tool: https://www.sdcard.org/downloads/formatter_4/eula_mac/
  • Performed an overwrite Format on my SD card.
  • Copied the contents of noobs13.zip to the Pi.
  • Booted the pi (with hdmi, kbrd and mouse plugged in).

Basic Commands

How to safely shutdown the OS.

    sudo halt

How to update all os packages

    sudo rpi-update (Sorry I had “dpi-update” before)
    sudo apt-get update && sudo apt-get upgrade

Setting up a FTP server (so you can upload files to the Pi from another PC).

    sudo apt-get install proftpd
    Restart the FTP Service:
    sudo service proftpd restart

Networking Setup

I had issues with a raspberry Pi that was already on my network (a Pi driven 24/7 webcam that was built by the awesome Brisbane Storm Chasers, my camera uploads images to the http://webcams.bsch.au.com/index.htm weather cam network for my http://www.twitter.co/2340weather twitter feed.

How to change the Pi’s name:

    sudo hotname SiPi01

Change the Pi’s name permanently:

    sudo nano /etc/hostname
    sudo nano hosts

    tip: change 127.0.0.1 to SiPi01

Check network Interfaces:

    cat /etc/network/interfaces

How to check the network connection:

    ifconfig

Reboot:

    sudo reboot

I also wanted my ADSL router to give the SiPo01 the same IP every time. so I followed this guide to set a Static IP.

    This ended up being my config.
    ip: 192.168.1.100
    bcast: 192.168.1.255
    mask
    255.255.255.0
    gateway: 192.168.1.1
    destination: 192.168.1.0

Keyboard Setup

I noticed my keyboard setup was set to UK and # symbols were not working. This allowed me to reset the keyboard to whatever region I wanted.

sudo dpkg-reconfigure keyboard-configuration
sudo reboot
sudo raspi-config

Sound Stuff

Enabling audio on the 3.5mm audio jack (not HTML sound).

I followed this guide: http://www.raspberrypi-spy.co.uk/2013/06/raspberry-pi-command-line-audio/

    How to install an easy mp3 player called mpg321: http://www.include.gr/debian/mpg321/

      Quick Summary:
      sudo apt-get install mpg321

    How to Play a MP3 file.

      sudo mpg321 -g 50 RogerWaters-FletcherMemorialHome.mp3

    How to turn the volume up:

      alias volu='sudo amixer set PCM -- $[$[amixer get PCM|grep -o [0-9]*$|sed 's/%//')+10]%'

    How to set command line aliases to type the stuff above for your when you type “volup.”

      sudo nano ~/.bash_aliases

      Add the following lines:

      # increase volume by 5%
      alias volup='sudo amixer set PCM -- $[$(amixer get PCM|grep -o [0-9]*%|sed 's/%//')+5]%'

      # decrease volume by 5%
      alias voldown='sudo amixer set PCM -- $[$(amixer get PCM|grep -o [0-9]*%|sed 's/%//')-5]%'

      Now you can type “volup” and “voldown” to change the volume.

First BASH Script

Make a folder for scripts to live in.

    mkdir /usr/bin/simon

Change to the new scripts folder.

    cd /usr/bin/simon

Make a script file.

    sudo nano testScript001

Make the script file executable.

    bash -x testScript001
    First Script Contents

      I wont bore you with details line by line but the script outputs a few system variables, tests the internet connection, downloads a file the exits.


      #!/bin/bash

      printf "Hello, $USER\n"

      OS_TYPE=$(uname -o)
      printf "OS Type: $OS_TYPE\n"

      OS_VER=$(uname -r)
      printf "OS Version: $OS_VER\n"

      CPU_TYPE=$(uname -m)
      printf "CPU TYPE: $CPU_TYPE\n"

      _IP=$(hostname -I) || true
      if [ "$_IP" ]; then
      printf "IP: $_IP\n"
      fi

      printf "BASH Version: $BASH_VERSION\n"

      DATE=$(date)
      printf "Today's date: $DATE\n"

      echo "Pi Updtime:"
      uptime
      printf "\n"

      printf "Testing Internet Connection (https://www.websitenameremoved.com):\n\n"
      # ping -q -t 10 -w1 -c1 https://www.websitenameremoved.com
      wget -q --tries=2 --timeout=20https://www.websitenameremoved.com/
      if [[ $? -eq 0 ]]; then
      printf "Internet appears online.\n\n"

      TMP_FILE="./simple_text_file.txt"
      if [ -f $TMP_FILE ]
      then
      echo "Deleting old temp files.."
      sudo rm ./simple_text_file.txt
      fi
      printf "Downloading file from the internet.\n"
      sudo wget https://www.websitenameremoved.com/test/simple_text_file.txt
      if [ -f $TMP_FILE ]
      then
      printf "File downloaded ok.\n"
      fi

      else
      printf "Internet appears offline, unable to download files."
      fi

      printf "Goodbye\n\n"

    All you do to run the script is type the following.

    • sudo ./testScript001

Setting the script to run every 15 minutes

    sudo nano /etc/crontab

    Add the following line at the end of crontab to run the script every 15 minutes:

      # */15 * * * * root /usr/bin/simon/testScript001

Misc Commands

Viewing the startup script (that executes after each user logs in)

    sudo apt-get install mpg321

Installing a Webcam Driver

    sudo apt-get install fswebcam

      Capturing a Webcam Image:
      /usr/bin/fswebcam -r 960x720 -d /dev/video0 /home/pi/webcam.jpg

Quest to learn to build and program electronics

I have decided to create another blog category on my personal blog to throw information and progress while expanding one of my earliest childhood interests “electronics”. Like many other kids I looked at electronic XMAS toys and wondered how they really worked inside. This resulted in me grabbing the nearest screwdriver (pointy knife) and opening the toy with much vigour and excitement. Often I would break something and I would forgot what order to reassemble it in and the toys would never be the same again (remote control semitrailer and electronic battle ship game comes to mind, sorry mum). But one the toys was opened my mind went nuts, I could see batteries, motors, lights, fans, wires and funny coloured bits (resistors and capacitors) power thingies etc.

When I was a child I remember my grandads sheds (he had a few as he moved house every 6 years or so), sometimes my granddad was in his shed fixing something (mower blades or tools). He always had neatly arranged tools and boxes of stuff and jars with nuts and bolts. I had a great time playing in his sheds and searching for things to do and play with. I want to pass on my fascination of electronics and programming to my kids in a similar environment to my grandads shed and also automate my home and make some cool gadgets along the way.

Part of my quest to learn electronics (for real) was triggered by my desire to fill my 3yo son’s (and soon to be 2nd child) minds with knowledge, wonder and a more than basic knowledge in STEM (Science, Technology, Engineering and Maths), electronics can help teach a fair bit of this as well and hands on experience. Also learning electronics is a kind of stress reducer, work/home demands are always changing but electrical knowledge all but stays constant (apart from miniaturization of components).

I find it quicker to do date calculations in code in excel so I am sure I will be able to program the electronics with ease but I have no doubt it will be an uphill battle teaching this old dog all the ins and outs of electronics (the right way). I will be hitting google a fair bit when it comes to searching for information and schematics and I would lie to share that with kids and older tinkerers.

Post01a

With a second child on the way I need a non-time consuming hobby to use to distract my 3yo when bubby 2 and mummy need a rest and to read up on in the small hours when I am putting baby to sleep.

Learning Goals:

  • Learn basic Electronics (components and theory).
  • Learn to program a Raspberry Pi
  • Create and control basic electronic circuits, read sensors, move mechanical objects and talk to the internet.
  • Learn to scale down code and hardware to the Arduino‎ platform.
  • Fix household items.

Physical Goals:

  • Create a battery powered Arduino circuit to install in the greenhouse to auto mist in hot weather from tank water). Report on temperature, and humidity.
  • Create a 100% automatic weather station that uploads details about temperature, humidity, barometric pressure, wind speed, smoke detectors, wind gusts, dew point, solar exposure, cloud cover, rainfall, soil moisture etc (how: many cheap sensors and custom circuits).
  • Create a battery powered automatically arming home security system with cameras, sensors (pressure, line of sight intrusion detection, magnetic car detection in the driveway, sonic, movement, infrared etc), sms and email alerts with offsite image backup.
  • Home automation (air conditioner on/off, watering system, wild bird seed deployment, rain cover, water tank level reporting, smoke detector (inside and out) remote bushfire protection (recycling roof sprays) etc) (how: many cheap sensors and custom circuits).
  • Remote control grey-water diverted from the shower (how: waterproof remote and 80mm solenoid to divert flow).
  • Auto detect and count bird species at the bird feeder (how: webcam and image processing).

  • Automatic home brew temp system for my dad.
  • Weather cam for my mum.
  • Fun kids projects, remote control robots.

Costs:

Setting up for a Raspberry Pi and or Arduino is about $100 each, much less than gold clubs.
Raspberry Pi Board.

Post01b

Choices of Arduino boards and bits.

Post01c

Sensors are dirt cheap on ebay (about $3 each) and are often compatible with the Raspberry Pi and Arduino boards.

Post01d

I already have a Raspberry pi and Arduino and have started my quest, watch this space.