Sunday, April 14, 2024

 Solar Eclipse April 8th, 2024

 

I had become aware in 2017 that our place of domicile, Norfolk County, Ontario would be in the path of totality for the solar eclipse of April 8th, 2024. So I was hoping to live long enough to see that day...

 And, indeed, I did make it. My preparations for viewing the eclipse started a few weeks before the big event. Of course, clear weather is very important for a proper eclipse experience, so as soon as the first weather forecasts were available, (10 days) I started monitoring them. Sunny weather is by no means guaranteed here in early April, so I kept a close eye on various forecasts from different sources. As the day got closer, they all seemed to say something different, e.g. Niagara will be fine, but points further west might be cloudy. Others said it will just be high, whispy clouds, still other predicted sunshine. Who to believe?

Meanwhile, I did the usual YouTube search and viewing of various videos pertaining to other people's experiences during previous eclipses, with a specific interest toward the photography aspect of things. Initially, I had just thought of projecting the sun's image on a piece of white paper using binoculars, as I had done during the partial eclipses of 2012 (in California) and 2017 (here at home). I soon came to the realization, however, that during a total eclipse, that was not going to work, as the corona probably would not be strong enough to be visible using that method. So I started thinking about using my DSLR with zoom telephoto lens to directly photograph the sun's corona during the full eclipse.

 

I wasn't too interested in the partial portion of the eclipse, as I had seen this quite a few times before (snob that I am). But, in order to be ready to photograph the full eclipse, I needed to have my camera already aimed at the sun. Having the camera look directly at even a reduced portion of the sun's surface is a very bad idea (burnt out sensor could be the result), so I created a filter out of some cut up eclipse glasses and a roll of packing tape. The shape of the roll fit snugly over the telephoto lens and was easy to remove once the eclipse had started.

I had also decided to remotely control my camera from my laptop using a USB cable. For software I used the Canon EOS Utility. The user interface on the laptop is much easier to use than the controls on the camera themselves. Plus cranking your neck through a viewfinder in dark conditions does not sound like fun.  

I had looked up the exact times of when the eclipse was to occur here. It was to start at 3:16:53 and last for 2 minutes and 39.5 seconds. I wrote a small application in Visual FoxPro that announced various important times relating to the eclipse, e.g. "Full eclipse will start in 5 minutes". This application made sure that I would be well prepared for the start and end of the eclipse.

I had also decided to put my second DSLR on a tripod in the backyard to film the entire event. I synchronized the times of cameras to the current date and time.I also synchronized the time used by my laptop with that of the internet.

On the eventful day, I woke up and immediately ask Google "OK Google, what's the weather going to be like." I couldn't help but laugh when she replied "Rainy with a high of 16".  However, looking on the Environment Canada website's image of clouds over our area, I noticed, yes it was cloudy, but this band of clouds stretching from north west to south east was slowly moving northeasterly, with Windsor, Ontario already being in sunshine. So, with a bit of luck, we would be in sunshine by early afternoon...

When returning home from getting some groceries, I noticed quite a stream of cars westbound on Hwy 3, probably coming from Niagara Falls area, trying to find the sunshine. And yes, the sun came out around 1:00 and things looked perfect. Nephew Chris Peake phoned from Toronto, asking how things were here, I told him in all likelyhood we'd be fine, so he decided to come down. At about the same time, Wendy, Greg and their kids Brock, Amaryn and Marek arrived.

At 2:05 there was the first sighting of the moon encroaching on the sun's territory: the partial eclipse portion was starting. We all got out our eclipse glasses and had a look. Nephew Chris arrived at around 2:45. Next, I  set up the tripods in a good spot with full view, mounted the cameras, put a table with my laptop next to the main camera, tethered them, aimed the camera (with filter) at the sun, started the timing application. General laughter ensued when it immediately announced all important times in very quick succession. Oops, software glitch, quickly fixed. I then started the camera filming in the back yard.

As the eclipse became more prominent, it got darker and darker, with the sunlight becoming a kind of grey. However, I was unprepared for how quickly the light level dropped off from 99% eclipse to 100%. Literally within 30 seconds in became dark as night. I had to make a switch on the camera from 'Program' to 'Manual' and for a very brief moment, panic struck me, as I didn't know whether I would be able to see it in the dark. Fortunately, I was able to so, in quick succession I shot images of the corona, keeping aperture at f8 and ISO at 100, but successively stepping down the speed starting at 1/1000th, down to 1/100th.

Following that I decided just to enjoy the spectacle, as someone had advised on YouTube. And a spectacle it was. Standing in the middle of the backyard, in the middle of the day with the sky as black as ink. You could clearly see planet Jupiter to the left of the sun and Venus off to the right. I didn't notice too much about the animal life, except for the mosquitoes: they came out immediately and started to bite us!

 Soon it was over and the light coming back was equally impressive as it was fading beforehand. My granddaughter had made a little video of the fading light when the full eclipse set in, which was most illustrating.

To celebrate the event, we immediately broke out the beer and toasted one another to our good fortune of having been able to watch such a spectacular event in our lifetime. In sunshine, nonetheless. At the time of the full eclipse, Niagara Falls was still clouded over.

The backyard eclipse video was a success as well, although I did some adjustments, brightening it up and raising the sound level in Photoshop. When viewing it, I discovered the planet Venus was visible as well.

My corona effort:
 

My granddaughter Amaryn's light dropoff video:
 
 
The backyard video (available on YouTube)

 

Sunday, February 07, 2021

Coupling a home made microphone to Bluetooth

I stumbled across a tweet a few months ago from @helenleigh who was doing/had done a presentation at Hackaday's Remoticon, showing the world how to make your own microphone using mostly materials found around the home. This got me really intrigued, since I have an affinity for using articles out of the realm of their original intent.

So I watched the video on YouTube Remoticon 2020 // Finding Sound and Making Microphones Workshop and then went to work acquiring the supplies. Our local dollar store proved instrumental in supplying the quilting hoop and hair bands. I could have used ones we already had at home, but I do want to get along with the rest of the family. We did have enough binder clips, I also had a spare USB cable, as a matter of fact, I probably have a box full of them, but then again, who doesn't?

So I got to work and built the mic, using a slightly different method than Helen. Instead of rubber bands, I used hair bands, no need to tie knots. Also, rather than plastic, I used the inner circle cut out of an aluminum pie plate. Plus the aforementioned USB cable (which is shielded to prevent the leads from picking up hum.)

The only real electronic components are 2 piezo pickups, which I got from Amazon (in a pack of multiples).

I didn't have an amp of any sort to plug it into, and connecting the output from the mic straight to a set of headphones barely produced any output, so I hunted around for a preamp circuit. I found this:https://samtechpro.blogspot.com/2013/12/dynamic-mic-pre-amplifier.html

I simply doubled up on the circuit to make it stereo (ya gotta be professional about these things), prototyped it on a breadboard, it worked, so I got to transferring it to KiCad (version 5.1.8) 

Not being too familar with KiCad, it took me a lot longer than I anticipated, but here is the design seen from the bottom and then from the top: 

 

 



Next, I undertook the usual routine of creating my own PCB, always fraught we difficulties aplenty. In the end though, I ended up with a nice looking print and PCB.

I mounted the components and decided that the output would go to a 3.5mm jack. The 5V power would come to the board via a micro USB jack. Next, I installed all this in a small box. Finally, I hooked it up to a very small set of speakers and it worked.

Not being satisfied with that, I decided to try and employ a set of Bluetooth transmitters and receivers. Not having any idea if it would work, I tried to get the two to pair, and surprise, surprise, they did. The transmitter is an Aigital Bluetooth transmitter, the receiver is SZMDLX transmitter/receiver combo, the latter being used by me obviously only in receive mode.

I hooked up the mic to the input of my preamp, the output to the Bluetooth transmitter. Then the Bluetooth receiver was plugged into the 3.5mm AUX jack on my computer. Upon insertion, a MaxxAudioPro screen popped up, asking me what sort of device I was plugging in. I chose Microphone in. Then over to Control Panel, Hardware and Sound, Manage Audio Devices, Recording, Jack Mic, then choose Properties and place a tick mark in the Listen checkbox. And voila, I heard my own voice!

This way I can record as well. I must say, the sound quality is pretty decent. Here is a sample:


Additionally, some photographs of how it all looks:


Microphone front above, microphone back below.




The complete setup. For microphone stand, I used a slightly modified cell phone holder, bought at the dollar store for a couple of bucks. Plus, of course, a binder clip.


From left to right, battery pack, preamp in a case, Bluetooth transmitter, Bluetooth receiver, laptop. The circuit board on the top is a prototype of the final result.




Tuesday, May 17, 2016

Circuit Chaser: Raspberry Pi + NFC = timer for children's run thru a playground.

Circuit Chaser uses a Raspberry Pi along with an NFC reader to clock outgoing and incoming times for cards (or wristbands in this case) being placed near it.


Hardware wise, it consists of 3 major components:
Software wise, the main components are:
  • Python application using NFC.py to track card touches
  • Python application using CherryPy to supply latest info to web browser display
  • Web page running in Epiphany browser using some heavy duty JavaScripting to update screen continuously
  • Python application monitoring usage and enabling/disabling screen when required
 And then, of course, there is the case, which is actually a case within a case. But more about that later.

This project got started when my daughter bought Zoom Zoom's, an indoor children's playground. Always looking to get an edge up on the competition, we brainstormed several ideas around until the idea of Circuit Chaser came to the fore. This device lets kids clock out, run through a previously determined course in the playground and then clock back in. Runs can be done simultaneously, i.e. more than 1 kid can be out on course at the same time (up to 11).

I covered the installation of the NFC reader on the Pi here: http://khekker.blogspot.ca/2014/01/raspberry-pi-clean-install-of-nfcpy.html.

As a card is brought near the reader, it triggers the reader into action. It reports the unique id of the card, and my Python application then records this in a SQLite3 database table. If a card currently is 'out', the application records the new time as 'in' (or finish, if you like). Otherwise, it records this as 'out', along with the time of the event. The application next does a retrieval of the last 11 records and creates a text file, which will be used by the CherryPy based application described below.

The application also retrieves the pseudonym of the card, making it more palatable for human eyes.

The application based on CherryPy continuously monitors this text file for changes. If found, it will send this file to any browser currently connected to it. If none are found, it goes to sleep for .25 seconds and repeats.

Along with the file sent to the browser is a variable containing the number of seconds expired since midnight, since this is important to keep the times shown on the display accurate. Each system does not necessarily have the same time as the next.

An insight as to how the browser gets to display this information I provided here: http://khekker.blogspot.ca/2013/12/raspberry-pi-cherrypy-and-asynchronous.html

Once received by the browser, the JavaScript takes over and runs continuously, every second updating times for every card/wristband line shown on the display. It uses the variable containing seconds since midnight sent from the CherryPy application and compares it to its own, and either adds or subtracts the difference.

Lastly, the application monitoring usage runs continuously and shuts down the display if no activity has been detected in the last half hour and turns it back on when a card is entered near the reader. The shutting off and starting up is based on this hack by Alex Eames for the HDMPi.

The normal screen blanking on the Pi has been disabled, as explained here:http://khekker.blogspot.ca/2015/12/screen-blanking-raspberry-pi-b.html

I spent an inordinate amount of time on the case. I knew I wanted a transparent case. First, I found a lexan case on the web, which I spent alot of time hacking so the Pi and all its connectors would fit. It looked really good. Then I realized, hey, this has to be used with kids, they can break 'pretty near' (Canadian for 'almost') anything. So I built yet another lexan case around it. Next time, I'll simply go to the specialty place where they sell lexan sheets and for not too much money they can build me a case. A couple of aluminum strips attached to the back of the case allow for attaching to a wall.

The device has been running for over three months now, and has been received well. Better still, it hasn't been broken, hardware nor software wise. It is connected wirelessly to ZoomZooms LAN, and its output could, if port forwarding was employed, be visible on the greater Interweb.

 All files are up on Github: https://github.com/khekker/CircuitChaser, with the exception of NFC.py and CherryPy, as explained above.

The NFC wristbands I obtained from Overair.ca

Monday, May 16, 2016

Raspberry Pi Zero + HD44780 in a slim package for use as fuel computer

Back in August 2013, I blogged about the fact that I had constructed a car fuel computer. In a nutshell, this device displays instantaneous fuel consumption (last 3 seconds), as well as the trip average, using any one of 4 output formats on a dashboard mounted LCD. The device is hooked up thru a USB port to an ELM327 Car scanner, which, in turn, is plugged into the car's OBDII port.

Creation of the device was based on earlier work done by Martin O'Hanlon. It used a Nokia 5110 LCD to display the output. One might argue that it was more of a prototype than anything else, since the display was held to the dash with electrical tape and a case of any sort was absent. Proof of concept.

In doing further testing with the Nokia display, my findings were that it was somewhat unreliable in the harsh environment that a car interior can present. For 'no good reason', the display at times would blank. Reboot the Pi, and everything would be fine again. Not good when you are travelling down the freeway at 100 km/h. (I'll never admit to speeding).

So in early 2014, I adapted the fuel computer application to use the very standard HD44780 LCD (16 characters by 2 lines) display. This time, I used a display case, but it only contained the LCD, since the Raspberry Pi 2 was too big to fit inside.

Enter the Raspberry Pi Zero and its small form factor. Just as soon as it was released November 2015, I knew that I would like to take a crack at incorporating this little miracle along with the LCD in the display box. So, early February, I started on this quest. Of course, what seemed simple from the outset, turned out to be quite the opposite: never have I stared so hard for so long at so few square inches, trying to fit it all in and still have it work reliably as well as allowing for maintenance and accessibility. Here is the result, with the device showing data for the last 3 seconds and the trip average in litres per 100 km (Canadian standard):





This is what you see when you take the 4 screws out of the back and open up the case. Note that the SD card can still be removed without taking anything else out.



For reasons explained below, I had to create an intermediate board between the Zero and the LCD. Here, the HD44780 is on its back here ready for mating with my sandwich board:


And here is the Raspberry Pi Zero and the sandwich board. Notice that only 1 row of GPIO pins from the Raspi Zero are being used.


This is a side view, the HD44780 LCD display on top and the Raspberry Pi Zero on the bottom:


The three buttons perform the following actions: pressing the top one steps thru the brightness level from 1 to 10. Pressing the middle one steps thru the contrast level from 1 to 10. Pressing the bottom one changes the readout mode from litres per 100km to miles per gallon US, then to miles per gallon Imperial, and lastly to km per litre. In addition, if the device detects the car is idling and you press this button, it will change the display to "Press shutdown again within 3 sec". If you do, the Raspberry Pi will shutdown, which is far better than simply turning the ignition key off right away.

So, to construct this, at first I thought I'll just connect individual wires from the Pi to the HD44780, plus a few more to the buttons for contrast, backlighting and display mode and then simply (and cleverly I thought) use short right OTG cables for power and data. Wrong, wrong and wrong. Loose wires tend to break if wiggled once too often or pushed into too tight a corner too vigorously. Too many wires, and you don't know what is what anymore. Besides, what length should they be? And 2 right angle OTG cables won't fit, because one overlaps the other, which makes it physically impossible for it to fit in the intended USB port.

Plan B: use male and female headers soldered directly onto an intermediate PCB (a 'sandwich' board) from both the Pi and the HD44780, then have the PCB traces hook up to the correct pins. In theory, this should work. The total depth of the case is 25 mm, a male and female combination makes up 10 mm, you have 2 of those, what could possibly go wrong? A whole lot, that is.

First off, my soldering skills are level amateur. This means heaps of solder at the base of a pin amounting to probably a few mm. Then you have the thickness of an extra PCB. There are also a few capacitors sticking out of the sandwich board.

Plan C: use right angles male and female headers. After an overnight deliver from buyapi.ca (thanks guys!), I was able to start development of a PCB in Fritzing. I had to get out my micrometer for super accurate measurements. After 12 iterations, (each time I would print a version on paper and fit the connectors on there, trying desperately not to prick my fingers too often) I decided to make a PCB. I will spare you the details, suffice to say, it took a lot of time and it wasn't half bad. Physically fitting it all together seemed to work so...

With loads of confidence, I fired it up in the car and, of course, it didn't work. It turned out, I had soldered and desoldered the HD44780 so often, I had fried it. Fortunately, I had another one at hand.
After soldering on the right angled header, another trial run. More problems. At that point, I realized I still had a database in my possession from the Raspberry Pi 2 prototype. (The Fuel Miser generates a new SQLite database every time it is run.) Since in-car testing is very time consuming and difficult, I decided to create an emulation mode where the Python 2.7 script steps through entries in the database and presents them on the LCD display as though we are driving in a car. Not perfect, but a lot quicker. This weeded out yet another pile of bugs. Next, I also incorporated in the application for info that is normally written to the console to be redirected to a text file. Very handy. This allowed me to, upon return from a trip, to review debug data I had 'print'ed. Finally, success.

But: the case wasn't put together yet and this proved impossible to do without screws through the three boards keeping it altogether. Since I had made no provision in my sandwich board for mounting screws (duh!), it was back to PCB design. A few more hours (or was it days?) in Fritzing, moving components around, making room for the screw heads, and, more importantly, the nuts. I was ready. But, by that time, I just wasn't up to making yet another PCB board myself. Instead, I sent it off to a fab house.

Waiting, waiting, waiting was the name of the game for the next 28 days. That's how long it took to get the board back. Then, soldering it all together and fitting it into the box. Time to test: it works!

I just had to do some software fine tuning. I may still have to do some more.

I used GPIO Zero to use PWM for both the brightness and the contrast levels. You can actually use RPi.GPIO in the same script as GPIO Zero. Who knew! In testing, I found that GPIO Zero was not as fast as RPi.GPIO when displaying text, so I decided to use RPi.GPIO for that.

I also incorporated the writing of text and that of the PWM for the contrast and brightness buttons into a separate class called HD44780.py. Even though I am using the whole unit for fuel economy purposes, as such it could easily be employed for some other use. Another right angle header could be mounted on the Pi, giving access to 20 more GPIO pins.

I kept the readout mode button out of this class, since it is not necessarily related to the functions of the LCD panel.

All the files are on github here: https://github.com/khekker/Raspi-Fuel-Miser. There you will also find a not-so-neat hand drawn wiring diagram. Sorry 'bout that, my Fritzing skills are limited. Check out the readme.md file for further information.

The PCB's from the fab house turned out really nice. I have some spares, in case anyone is at all interested. I'll sell them for $3.00 Canadian plus postage. Let me know in the comments.

Since the following parts are hard to get, I could supply them as well:

7 pieces 2.6 mm screws 10 mm long with nuts $1.00
7 standoffs (3 short and 4 long pieces) $0.50
3 pairs of right angle headers (male and female) (2x6 and 1x20) $1.50
1 project case $5.00

That's $11.00 Canadian, approximately $8.75 US or €7.30 plus postage.

If you want me to 'hack' the appropriate holes in this case, then there is a $5.00 charge for that. Canadian of course, $3.90 US, or  €3.30.

Just 2 observations I made using the device in-car, both of which would likely make safety experts cringe. The first is that driving behind a large truck makes a difference in fuel consumption (around 10%), the second is that on a car with standard transmission ('stick shift'), putting your foot on the clutch while coasting down the hill cuts (the already greatly reduced) fuel consumption in half. But it is not safe to do, so I strongly advise against it.

Note that the device stores a whole range of parameters generated by the engine's computer in a database, which could be reviewed or otherwise analyzed afterwards. For every trip, a new database table is created in SQLite3.

Now if only the Raspberry Pi was more readily available!  Oh, wait a minute...hot off the press...a new Raspberry Pi Zero released today...it adds a camera function. The camera connector sticks out a few mm from the Pi, but that should not present any problems fitting it into this particular case.

Saturday, March 26, 2016

How to configure ITEAD PN532 NFC Module on Raspberry Pi

The other day I received the Itead PN532 NFC module in the mail. Time to install it on Raspberry Pi.

The PN532 allows for Near Field Communications, e,g, for using an access card to enter a building or transferring info from a smart phone to a computer.

The installation instructions that came with the device were rather vague or shall I say non existent. And so was any other information about it on the Interweb. Piecing together various snippets allowed me to install it and actually have it work. That is why I am documenting it here just in case someone else comes across the same problem.

In am installing it on Raspberry Pi 2, with Raspbian Jessie as the OS. Furthermore, I will be using it with NFC.py, a Python library I am quite familiar with. It uses the UART set up (serial).

First off, we will not use the double row of pins (26 pins) on the PN532. We will use the single row of 8 pins, of which only 4 will actually be connected to the Pi. Note that you will have to flip the device over to read the markings for each pin on the back of the PN532.

The connection from the Pi to the PN532 is as follows:

Connect Pin 2 (5V) on the Pi to the Pin marked 5V on the PN532
Connect Pin 6 (Ground) on the Pi to the Pin marked GND on the PN532
Connect Pin 8 (GPIO14) (UART TX) on the Pi to the Pin marked NSS/RCL/RX on the PN532
Connect Pin 10 (GPIO15) (UART RX) on the Pi to the Pin marked MO/SDA/TX on the PN532

So much for the hardware side. Now we go on to the software side. Of course, we bring the entire system up to the latest value by issuing:

sudo apt-get update
sudo apt-get upgrade


Then, we need to modify the file /boot/cmdline.txt. Do that by issuing the following command:

sudo nano /boot/cmdline.txt
 
Within this file, change the line


dwc_otg.lpm_enable=0 console=tty1 console=serial0,115200
 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline fsck.repair=yes rootwait
 
to this:
 
dwc_otg.lpm_enable=0 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 
elevator=deadline fsck.repair=yes rootwait
 
Next, if you are running Raspbian Jessie on a Pi 3, add this to the bottom of /boot/config.txt file:
 
dtoverlay=pi3-miniuart-bt
 
This will disable Bluetooth, but allow the PN532 to work.
 
Reboot the Pi, and install NFC.py by  issuing the following commands:

sudo apt-get install python-dev 
curl -O http://python-distribute.org/distribute_setup.py 
sudo python distribute_setup.py 
curl -O https://raw.githubusercontent.com/pypa/pip/master/contrib/get-pip.py 
sudo python get-pip.py 
sudo pip install virtualenv

The above 6 commands install (fairly) standard Python utilities. They may be present on your machine already.

sudo pip install pyserial

This line will install serial library for Python used by NFC.py.

sudo apt-get install bzr

This command will install Launchpad bazaar, a VCS (Version Control System), which allows you to download NFC.py.

mkdir pythonprogs 
cd pythonprogs

Above 2 commands create and then switch to the directory where my Python programs will be stored on this machine. You may already have a favourite directory on your machine.

bzr branch lp:nfcpy

This line downloads the latest version of NFC.py.

cd /pythonprogs/nfcpy/examples

Now you've changed to the examples directory of NFC.py.
 
python tagtool.py --device tty:AMA0:pn53x show
 
Run the Python program tagtool. The ‘device’ switch following tagtool.py specifies that we want to use the serial device. If there is no error message, things should be working!

Touch a card on the reader. You should get a response on your screen. Notice that you cannot use a Mifare Classic 1K card, they are incompatible with NFC.py. However, I've had good luck with NTAG203 cards, which are readily available.

Thursday, February 04, 2016

Raspberry Pi Zero: How to first access it headlessly

I obtained a Raspberry Pi Zero a few weeks ago, but hadn't really done anything with it. I was puzzled as to how to access it initially, since it only has one USB port and no RJ45 connector built in for accessing a network.

The easiest thing would be to get a USB hub, but I wanted a minimalist approach. No screen, keyboard, mouse. This method only requires a wireless dongle. So I did some sleuthing on the old Interweb and stumbled and David Maitland's blog.

My approach varies slightly from his, that is why I describe it here:

get access to Raspberry Pi Zero on the network by:
  - downloading Raspbian Jessie and dump the image on a microSD card using your PC
  - taking another Raspberry Pi, a B+, inserting the 'Zero' microSD card in it
  - hooking this up to the network (or screen, keyboard and mouse)
  - booting the Pi B+
  - modifying the file /etc/network/interfaces file
       specifically: add 'auto wlan0' as a separate line above 'allow-hotplug wlan0'
  - modifying the file /etc/wpa_supplicant/wpa_supplicant.conf
       specifically: add to the end of this file
     network={
     ssid="MYNETWORKNAME"
     psk="MYNETWORKPASSWORD"
     proto=RSN
     key_mgmt=WPA-PSK
     pairwise=CCMP
     auth_alg=OPEN
     }
      
         Obviously you will replace MYNETWORKNAME and MYNETWORKPASSWORD with your specific values.

  - gracefully shut down the B+
  - take the microSD card from the B+ and insert it into the Zero
  - attach a wireless dongle to the Zero's USB port
  - boot the Zero, it should work. If not, check the entries you made for the network values.

Monday, December 21, 2015

Raspberry Pi how to show less info at bootup

You can substantially decrease the amount of info scrolling by on the screen at bootup time by adding the word 'quiet' (without quotes) to the end of the first line of the file /boot/cmdline.txt

Raspberry Pi Custom Splash Screen (blank screen problem)

I followed the instructions found at http://www.edv-huber.com/index.php/problemloesungen/15-custom-splash-screen-for-raspberry-pi-raspbian for a customized splash screen on the Pi. Everything went well, except….at the end of the boot sequence, the splash screen disappeared and all I was left with was a blank screen. I found out (by trying) that I could type the userid and password blindly, followed by startx (also blindly) and then LXDE would appear as normal.

Hunting around on the forums, I found a post that stated that if you were presented with a blank screen after booting, you should try pressing Ctrl+Alt+F2 to get back to a regular console screen. It worked. I hunted around some more for a better solution, but to no avail.

By the way, this problem does not occur if you have it setup so that you automatically startup startx after booting.

Saturday, December 19, 2015

Screen blanking Raspberry Pi B+

I have a Raspberry Pi running headlessly as a display. Therefore, the screen should never blank.

Here's the link where I got the solution to my problem:

https://www.raspberrypi.org/forums/viewtopic.php?f=91&t=57552

User jwzumwalt came up with the post, I'm just repeating it here for my own reference.

The long and the short of it: there are 2 files to be modified

#1

change two settings in /etc/kbd/config
BLANK_TIME=0
POWERDOWN_TIME=0

#2

Add these lines to /etc/xdg/lxsession/LXDE/autostart
@xset s noblank
@xset s off
@xset -dpms

Then reboot and test.

Thursday, December 17, 2015

Error 98 Address already in use in Python

Sometimes bottlewebserver in Python on my Raspberry Pi hangs 'for no good reason'. Upon restarting from the LX Terminal window, the above error appears and Bottle Web Server will not start.

I've read Stack Overflow postings where, if you wait for one and a half minutes the port will free up and the server can then be started. This does not seem to happen in my case.

The only way to restart the server, other than a reboot, is to do the following:

$ ps -fA | grep python

The result will then give a line something like this:

root 2130 1 0 11:08 ? 00:00:00 sudo python bottlewebserver4.py

Then simply issue:

$ sudo kill 2130
After this the bottlewebserver will start.

Monday, December 14, 2015

Putty network error connection refused

One of my Raspberry Pi’s that performs sump pump depth measurements every 5 minutes works headlessly. Last week it stopped supplying values via the network to my other Pi, which does the reporting via a web page.

So I tried to reach the Pi via putty. Putty responded with “network error connection refused”. This led me to checking cables, and I found that everything was fine. To make a long story short, it turned out that a recent power loss must have caused a corruption within the networking setup of the Pi.

I hooked up a monitor, keyboard and mouse and did a “sudo apt-get update” followed by “sudo apt-get upgrade”, followed by “sudo apt-get upgrade --fix-missing”. Lastly, I reset the SSH keys by issuing “sudo rm /etc/ssh/ssh_host_*” followed by “sudo dpkg-reconfigure openssh-server”.

After this, things were back to normal.

Wednesday, April 01, 2015

PrintIsolationProxy.dll corrupted

 

 

I have a notebook computer, ASUS VivoBook S400CA, Intel i5 processor, running Windows 8.1, around 18 months old now.

The computer had been running fine for all this time, of course it is never as fast as you would like it to be, but still…

The other day I wanted to print something (I only use the printer on average about twice a month), and Windows told me I had to install a printer? What??? I clicked on Find Printer in the Printer Settings Box and up pops dialog box telling me the local print spooler service is not running and to turn it on. What??? So I went to services (Click Start and types ‘services.msc’) and sure enough Print Spooler had stopped. I started it, it seemed to run, but after 5 seconds or so, it stopped. What???

To make an extreme long story short, what fixed it is that I ran the sfc utility from within an Administrator’s command window (type ‘command’ from Start and then right click on Command Prompt, then select Run as Administrator). To run sfc, I typed ‘sfc /scannow’. After this command completed (it takes a while), I went to Notepad (any text editor will do) and looked at the log file that sfc created. This files was stored in c:\windows\system32\logs\cbs\cbs.log. Using the Find command, I looked for occurrences of ‘Cannot’, I found 2 (well actually more than 2, but they always pointed to the same 2 files), amstream.dll and PrintIsolationProxy.dll. The ‘cannot’ refers to the fact that sfc found these files to be corrupted, but it couldn’t repair them.

Next, I took a guess and decided to try and replace PrintIsolationProxy.dll with another copy from somewhere else. I downloaded this copy from www.dllme.com, ran it through a couple of virus checkers and malware detectors, then renamed the existing version to PrintIsolationProxyOld.dll and popped the new one in its place. Even that is fairly complicated as in order to be able to rename a file, you need to be the owner of it so in the Properties box of this file I had to change that from ‘TrustedInstaller’.

Once the new file was copied to c:\windows\system32, I opened up services again, started the Print Spooler, and voila: it didn’t die after the mandatory 5 seconds went by. Next I tried to print and the printer works again!

I ran virus checkers and malware detectors over the old version, and none of them detected anything untoward. So I can only surmise that Windows Update did something.

I have no idea what amstream.dll does or which process uses it, that is a problem still remaining to be solved.

Ironically, PrintIsolationProxy.dll was added to Windows around 2009 (Vista?), to prevent wayward printer drivers from crashing the print subsystem…..

Tuesday, July 08, 2014

Using an Adafruit PowerBoost 500 charger as UPS for a Raspberry Pi

 

One of the main tasks of a Raspberry Pi I have is monitoring my automatic backup generator and sending out alerts via SMS and email when the generator kicks in. This works fine, with up to now 1 glitch: when the outside power to the house is cut off, it takes at least a minute for the generator to kick in and start providing electricity to the house. So, under that scenario, the Raspberry Pi reboots and although the monitoring applications start up again, it just didn't seem to me as though it was foolproof.

So, I had been searching for a long time for a reliable, affordable Uninterruptable Power Supply (UPS) for this Raspberry Pi. I could probably have used one for a PC, but that was just too bulky and expensive. I even went so far as to try and design e backup power circuit using supercapacitors (after all, I don't need backup power for more than a minute), however, 'miserable fail' is the only term I can accurately and honestly use to describe that effort. Theoretically, it should have worked, in practice my circuit couldn't supply power for more than about 15 seconds, before the voltage dropped below acceptable levels and the Pi conked out.

Enough about that. By having Adafruit on my Twitter feed, I became aware of their PowerBoost 500C charger. Digging a little deeper, I found that this could also act as a UPS for Raspberry Pi, Arduino, etc. So, I decided to purchase one.

It arrived in mere days, which is pretty much a miracle when you realize it had to cross the US-Canada border. I soldered the USB connector in place (this is the output side from where the power is fed to the micro USB connector on the Pi), plugged in the Lithium Ion Polymer Battery I purchased at the same time and plugged the whole ensemble into the wall outlet via a standard USB wallmount charger. No smoke! On the contrary, the on-board LEDs lit up (and bright they are). I had to wait a little while until the yellow LED (indicating battery is charging) was replaced by the green LED (indicating battery charged).

Following that, a made a little YouTube video illustrating what happens when you plug a Pi into the output side, and then unplug the wall power etc.

In the video, I only have the Pi running off the battery for a short while (approximately 30 seconds), which should be sufficient for my purposes. However, in a subsequent test, I had the wall plug removed for more than 3.5 hours and the battery (2500 mAh) was still going strong.

So I think I finally have a reliable solution for my UPS problems.

Sunday, February 02, 2014

Raspberry Pi and peer to peer networking

 

Normally, when using the Pi and doing development work, I use it headlessly. It sits somewhere in the basement and I communicate with it using Remote Desktop. However, since I am testing NFC (Near Field Communications), I had a need to be close to the Pi when doing development work.

So I installed peer-to-peer networking. After the usual Google searches, I was able to piece together how to do it. This write up really is for my own reference so I will know how to do it at some future point in time. Note that I am doing this using a cable, not a wireless dongle. Apparently using a wireless dongle is possible as well, I just haven’t tried it.

First my setup: I work from a Windows 8.1 lap top and and when the Pi is setup in the basement, I wirelessly connect to it, via my router of course.

Be forwarned, unfortunately, there is no way to make the necessary changes on the Pi without hooking it up to a monitor of sorts, be it through HDMI, VGA.

So, to install peer-to-peer networking: Take an Ethernet cable of any length, I used a short six feet (2m) cable, and plug the ends into the PC and the Pi. Restart the PI. Don’t worry about this cable needing to be a cross over type: the Pi is auto sensing.

Next, in Windows, go to Start, run and type in ‘cmd’ (no quotes). In the command window that appears type ‘ipconfig’ (no quotes). In the listing that follows, look for a heading that says ‘Ethernet adapter Ethernet’. Within that section, look for Autoconfiguration IPv4 address and write down the address that follows this. Mine was 169.254.212.0. On the next line, you should see Subnet Mask, write this down well, mine was 255.255.0.0

On the Pi, type ‘sudo nano /etc/network/interfaces’ (no quotes) In the file that opens make sure that the following lines appear:

auto lo

iface lo inet loopback

auto eth0

iface eth0 inet static

address 169.254.212.1

netmask 255.255.0.0

Modify the address line with your own IP address that you found on your PC, but add 1 to the last number (look at my example). Furthermore, use exactly the same subnet mask on the Pi as on the PC. You can comment out any other lines that appear by putting a # hastag in front of it.

Save (Control-x, then press Y). Reboot the Pi and test.

I found Remote Desktop as well as my wireless to the router and Internet to be working as usual.

Sunday, January 19, 2014

Raspberry Pi: clean install of NFCPY

NFCPY is a Python library allowing for Near Field Communications readers to be accessed directly from Raspberry Pi. As part of a project I am working on, I needed to install this library on a clean Raspbian install of a Raspberry Pi.

Once the installation was completed I used the base ‘history’ command to retrieve all the commands that I typed in the terminal to accomplish this task. I removed all the commands that were wrong or superfluous.

Please note that this was a brand new install: I used a NOOBs SD card and chose Raspbian. Once the operating system was installed, the following commands were typed in:

$  sudo nano /boot/cmdline.txt
$  sudo nano /etc/inittab

The above two commands need to be modified in order to free up the UART on the Pi (to be totally honest, I’m not sure if this needs to be done for nfcpy.) Follow these directions from Clayton Smith’s website. Initially, I used Adafruit’s website for these instructions, but they were not totally clear.

$  sudo raspi-config

This allows you to personalize your Pi through the Raspbian Configuration utility.


$  sudo reboot –n

A reboot to ensure it all still works.


$  sudo rpi-update

Update the firmware on the Pi

$  sudo apt-get update
$  sudo apt-get upgrade

Install the latest Raspbian operating system updates and upgrades


$  sudo apt-get install xrdp

Install Remote Desktop


$  sudo apt-get install python-dev
$  curl -O http://python-distribute.org/distribute_setup.py
$  sudo python distribute_setup.py
$  curl -O https://raw.githubusercontent.com/pypa/pip/master/contrib/get-pip.py

$  sudo python get-pip.py
$  sudo pip install virtualenv

Install (fairly) standard Python utilities


$  sudo pip install pyserial

Install serial library for Python used by NFCPY.



$  sudo apt-get install bzr

Install Launchpad bazaar, a VCS (Version Control System), which allows you to download NFCPY.


$  mkdir pythonprogs
$  cd pythonprogs

Above 2 commands create and then switch to the directory where my Python programs will be stored on this machine.


$  bzr branch lp:nfcpy

Download the latest version of NFCPY.


$  cd /pythonprogs/nfcpy/examples

Switch to the examples directory of NFCPY.


$  python tagtool.py --device tty:AMA0:pn53x show

Run the Python program tagtool. The ‘device’ switch following tagtool.py specifies that we want to use the serial device.

Then put a card near the reader: partial success. There is output on the screen, but the reader cannot read the card, apparently NFCPY cannot handle MIFARE Classic 1K cards. So I ordered some other ones, hopefully they will work!

UPDATE 2014/01/29 The cards I ordered from OverAir Proximity Technologies do work! They are

NFC Card - White - NTAG203 PAC-N3Card

UPDATE 2014/08/02 I purchased a Raspberry Pi B+ (mainly for the form factor) and found I needed to modify to contents of some of the links above in order to successfully install nfcpy.

Monday, December 16, 2013

Raspberry Pi, CherryPy and asynchronous communication

I have a project I am working on where graphical output is required to be sent to the screen. Using Python, where by default the output only goes to the console, one then immediately thinks of Tkinter, which is a Python module that provides a graphical interface to Python.

However, that would mean learning yet another ‘language’ as such. So I decided to pursue a different avenue. I am fairly familiar with HTML and JavaScript, even though the latter is extremely quirky and non-intuitive. Therefore, I let my gaze wander to a browser based solution.

Now what I am looking for goes beyond the request-response model usually found in browser based interfaces: the user clicks on a button (or link), the browser sends the information to the server, the server responds by sending the requested information and the connection closes. A classic case of synchronous communication.

What I am looking for is a scenario where the browser’s window is automatically updated with new information as it becomes available and no if any user action is required. Asynchronous communication.

So I started researching. What I really wanted was a short, sweet, concise code example of how to do asynchronous communication with Python. There were lots of examples, code pieces, snippets for Bottle, Flask, Tornado (all Python based webservers), but nothing that was simple enough to just run.

I even spent some time installing node.js, which is supposed to be the next best thing since HTML. Once installed though, I couldn’t find any examples that were straight forward enough or worked ‘out-of-the-box’.

Finally, I hit on CherryPy, yet another Python based web server module, specifically this page in their wiki:http://tools.cherrypy.org/wiki/Comet. On this page, author Dan McDougall discusses CherryPy approach to ‘Comet’. Comet (a cleanser). Ajax (a cleanser), however in IT lingo, Ajax can provide feedback to a browser without the entire browser window having to be refreshed. I decided to download CherryPy, run the application in Python, open a browser and voila: it worked. Success, end of a long searching marathon.

CherryPy does multithreading on its own. At its peak I had three web browsers open on various machines and the CPU Usage meter barely moved. Another neat feature that I discovered is that when I saved a new version of the application in Geany, with the old application still running, it will shut the old application down and start the new one all on its own.

The output of the application I downloaded spits out the results of pings to an ip address or web site you provide. The results just keep on streaming by on the screen. Great example, but not what I needed: what I wanted was a number of string that simply replaced the previous string, i.e. automatic updating of a value. More searching. This time I stumbled on a neat solution provided by Encosia (Dave Ward), which I adapted to work with my application.

The original CherryPy application created an iframe at the bottom of the HTML (just before the </body> tag). The asynchronous info being sent from the server gets displayed there. An iframe is really a webpage within your web page, usually used for ads.

Dave Ward’s solution is to hide the iframe (style=”display:none”), then have the web server send a function call embedded in the asynchronous communication along with the latest value of whatever we are trying to display. The function called is on our main web page (‘the parent’) and so can update anything on that page. The iframe is still there and working, but invisible to us.

In my case, I have a table and the content of the function simply reads:

document.getElementById(‘11’).innerHTML = cTimeReceived

where ‘11’ is the id of the first table data cell and cTimeReceived the new value received from the server.

I tested this on the Raspberry Pi’s various assortment of web browsers. It worked properly on Midori, Chromium, Luakit, Iceweasel but not on Dillo or Netsurfer. I let it run for hours without a problem. I ran it from a laptop elsewhere and  intentionally interrupted the network connection, and, once the connection was re-established, the page kept right on going.

On the Pi, Luakit by far required the least amount of resources (around 30% in CPU Usage Monitor), while Chromium maxed out at 100%, the others somewhere in between.

Obligatory screen shot:

cherrypyscreenshot

Below the application. I ran this on the Raspberry Pi Model B, 512 Mb, with Raspbian updated to 2013-12-15. For it to run, you need to have Python (my version 2.7). To install CherryPy:

pip install cherrypy

Then copy the application below, change my IP address (towards the bottom) to your own, change my ‘pythonprogs’ directory name to you directory name and run. Open up a browser, point to your IP address, followed by :8080 and press enter. Once the page appears click’ Start’. That’s it!

Note that the HTML for the starting page is embedded in the application, hence 1 file is all you need to run this example.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# string.Template requires Python 2.4+
from string import Template
import cherrypy
import time,datetime

__author__ = 'Dan McDougall <YouKnowWho@YouKnowWhat.com>'

# Trying to cut down on long lines...
jquery_url = 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js'
jquery_ui_url = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js'
jquery_ui_css_url = \
'http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/black-tie/jquery-ui.css'

class Comet(object):
"""An example of using CherryPy for Comet-style asynchronous communication"""
@cherrypy.expose
def index(self):
"""Return a basic HTML page with a ping form, a kill form, and an iframe"""
# Note: Dollar signs in string.Template are escaped by using two ($$)
html = """\
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<link rel="stylesheet" type="text/css" href="${jquery_ui_css_url}" media="screen" />
<script type="text/javascript" src="${jquery_url}"></script>
<script type="text/javascript" src="${jquery_ui_url}"></script>

<style>
input[type=button], input[type=submit], input[type=reset] {
background: #eee;
color: #222;
border: 1px outset #ccc;
padding: .1em .5em;
}
</style>
<script type="text/javascript">
function UpdateProgress(cTimeReceived)
{
document.getElementById('score').innerHTML = cTimeReceived
}
</script>

</head>
<body>
<script type="text/javascript">
$$(function(){
$$('#result').hide();
$$('#kill_ping').click(function() {
$$.ajax({
url: "/kill_proc",
cache: false,
success: function(html){
window.frames[0].stop();
$$("#result").html(html);
$$("#result").show('slow');
}
});
return false;
});
});
</script>
<script type="text/javascript">
$$(function(){
$$('#ping').click(function() {
$$('#result').hide();
});
});
</script>
<h3>CherryPy Comet Example</h3>
<form id="ping_form" target="console_iframe" method="post" action="/ping">
<input id="ping" type="submit" value="Start"></input>
</form>
<BR>
<form id="kill_form" method="post" action="/kill_proc">
<input id="kill_ping" type="submit" value="Stop"></input>
</form>
<div id="result" class="ui-state-highlight">
<span class="ui-icon ui-icon-check ui-icon-left" style="margin-right: .3em;">
</span>
</div>
<div><table><tr><td id="score" style="font-size:96px"></td><td></td></tr></table></div>
<iframe name="console_iframe" style="display:none"/>
</body>
</html>
"""
t = Template(html)
page = t.substitute(
jquery_ui_css_url=jquery_ui_css_url,
jquery_url=jquery_url,
jquery_ui_url=jquery_ui_url)
return page

@cherrypy.expose
def ping(self, **kw):
"
""Start a time loop (reporting time and stream the output"""
def run_command():
while True:
now = datetime.datetime.now()
cTime = str(now)[:22]
yield '<script>parent.UpdateProgress("
'+ cTime + '")</script>'
time.sleep(2)

return run_command()

# Enable streaming for the ping method. Without this it won't work.
ping._cp_config = {'response.stream': True}

@cherrypy.expose
def kill_proc(self, **kw):
"""Kill the process """
return "<strong>Success:</strong> The process was stopped successfully."

cherrypy.config.update({
'log.screen':True,
'tools.sessions.on': True,
'checker.on':False,
'server.socket_host':'192.168.0.135',
'tools.staticdir.root': '/home/pi/pythonprogs',
'tools.staticdir.on': True,
'tools.staticdir.dir':'static'})
cherrypy.tree.mount(Comet(), config=None)
cherrypy.engine.start()
cherrypy.engine.block()

Raspberry Pi: 1.6 million records in SQLite database.

Yesterday was a bit of a milestone for me in that my generator monitoring application had been in production for one year exactly.

During this time, the SQLite database logged 1,630,000+ temperature records, (3 records every minute). There have been a few minor hiccups, programming bugs, which I corrected, but other than that, the Raspberry Pi and Python have acted flawlessly. No mysterious hang ups, no unresponsiveness, it just plain old works.

It faithfully still sends out SMS messages and emails when needed. The webserver also works flawlessly all of the time.

I’m especially impressed with the gnuplot utility. Quirky to set up, yes, but very solid and quick to generate complex graphs.

The graph below (from today), as an example, shows high and low temperatures, by the hour, over the last year at our house. The SQLite database selected 8,750 records out of the 1.6 million, handing them over to Gnuplot which plotted this dataset, in about 3 seconds. Not bad at all.

Interesting things about the graph:

- spread between daytime highs and nighttime lows in a lot larger in summer than in winter.

- frost free period was from end of April till end of October, not bad considering the cold spring we had here in southern Ontario.

- so far December this year is shaping up to be a heck of a lot colder than last year.

tempsextended

Monday, September 30, 2013

Raspberry Pi and a solution waiting for a problem…

Well, not quite, maybe. Let me explain. In previous posts, I played around getting the Nokia 5110 LCD to properly work with the Raspberry Pi. After the usual set of problems, it fully cooperated and I incorporated it as my display in my carputer.

Now, I would like to mount the display on the dash of my car somewhere, but, although the Pi is small, it is still too big to fit in properly.

So I got to thinking, what if I place the display at some distance from the Pi? But how? I decided to go out on a limb and use RJ45 connectors and jacks.

I bought some RJ45 jacks via Ebay and some RJ45 breakout boards from Cooking Hacks. These breakout boards, at a whopping $0.50 a board, allow for easy hookups of the RJ 45 jack to the wires that lead either from the Pi’s GPIO pins or go to the input pins on the Nokia LCD.

After soldering the jacks and the wires to the breakout boards, it was time to grab an Ethernet cable (6 feet in this case), slip the ends into the jacks and turn on the Pi. At first, the results were ambiguous. Sometimes, the display showed correct results, sometimes there were errors in the text, sometimes nothing. So I decided to do some experimenting.

I noticed that the speed at which the Nokia LCD was processing data was set at 5Mhz. I reduced this to .5 Mhz. Voila, it worked.

Next, I tried a longer cable, 24 feet. No problem! I don’t have a longer cable, it would be interesting to see what would happen.

Here’s the 24 foot cable in action (the error message on the display has nothing to do with this project).

 IMG_9673

So, if you need a display a long way away from the Pi itself, may be this is the way to go…

Tuesday, September 03, 2013

Raspberry Pi and “sudo poweroff”

A few weeks ago I ordered a power switch for the Raspberry Pi from www.mausberrycircuits.com with the aim of using this on my Raspi Fuel Miser setup. (see previous post).

Illuminated LED shutdown switch

When this switch is situated between your Raspberry Pi’s power jack and your phone charger and you plug in the phone charger, nothing happens. You first need to press the button before the Pi lights up. Then, once you are through using it, you keep the button pressed for 2 seconds and the Pi powers off.

You need to hook up 2 wires from the switch to the GPIO pins, suggested are 23 and 24. If you do use other ones, then you need to modify /etc/switch.sh after you run setup .sh.

I first ran it using the switch.sh configuration, but then I got to thinking, why run it separately when it can be included in my Python script, which is running continuously anyway, dutifully computing gas mileage.

So I amended my script, created a new function has_ShutdownButtonBeenPressed and inserted a call to it at the start of the main loop in the obd_capture.py program. This way, it will check for a pressed key once every 3/4 second or so, the time it takes to complete a cycle of OBDII readings. I disabled the switch.sh and remove the entry in /etc/rc.local which started up switch.sh upon start up.

The ‘sudo poweroff’ command, by the way, cuts all power to the board, so it is completely disabled, unlike the ‘shutdown’ command, which still leaves the main red LED lit.

Now, at the end of my trip, if I have used the fuel miser, all I need to do is press the power button for 2 seconds, and the Python script will close the SQlite database gracefully before issuing the os.system(“sudo poweroff”) command.

Tuesday, August 27, 2013

Raspberry Pi MPG Fuel Economy Carputer

I’ve always had an interest in getting the best fuel economy out of cars that I drove. On June 14, 2006, I blogged about my Toyota Echo and its gas mileage. I’ve often wanted to buy a device like ScanGauge so I could see the instantaneous fuel economy I was getting.

A few weeks ago, the Raspberry.org site’s main item had to do with carputers. That, along with an article about the Quite Rubbish clock got me to thinking, how about a Raspberry Pi MPG reader?

Here’s the final result, well final, there is no case and I’m also thinking of adding various buttons to vary the output of the display. But for the moment…

The MPG computer in action

The top line lists the average of the last 3 seconds. The bottom line the average for the entire trip, followed by the duration of the trip in minutes. Since I’m in Canada, where fuel economy is expressed in litres consumed per 100 km driven, that’s what it is set up for. However, it would be fairly trivial to change the formula and output based on the user’s preference.

The code is based on Martin O’Hanlon’s obd_capture.py. However, I made significant changes in that the data is being captured into a SQLite3 database (which is actually used to compute the 3 second average). Furthermore, I included the output to the LCD in this class as well. (Yeah, I know, you shouldn’t be mixing data with user interface, but hey, I’m not getting paid for this, so I can do whatever I want.)

Every time the car starts, a new database with a unique name is created. It takes about 15 seconds for the Pi to boot and another 5 seconds for the Python script to start running. This database can be retrieved later for further analysis of the car’s performance.

The fuel economy is derived from the values given by the ELM327 (about $12 from China) OBDII reader for MAF (Mass Airflow meter) and VSS (vehicle speed). The formula for litres per 100 km is:

(3600 * MAF)/(9069.90 * VSS)

Credit for this formula should go to Bruce Lightner, who is probably one of the most knowledgeable people on this planet when it comes to OBDII (and moon rocks and more stuff)

The output goes to a Nokia 5110 LCD (Deal Extreme $5.60). In order to get a fairly large readout for driver visibility, I actually created an image in Python and then place that image on the LCD as a whole.

The OBDII connector in my car points downwards, and that might interfere with the driver feet, so I’ve ordered an extension cable from China for a few dollars which will alleviate this problem. This cable exits at right angles from the connector.

If you intend to build this device using the Nokia 5110 LCD, you’ll need to read my previous post regarding this device.

For Martin O’Hanlon excellent code, and related libraries type this at the command prompt:

sudo apt-get install python-serial
sudo apt-get install git-core
cd ~
git clone https://github.com/martinohanlon/pyobd
cd pyobd
python obd_capture.py

Here is my version of obd_capture.py:

   1: #!/usr/bin/env python
   2:  
   3: import obd_io
   4: import serial
   5: import platform
   6: import obd_sensors
   7: from datetime import datetime
   8: from PIL import Image,ImageDraw,ImageFont
   9: import ImageOps
  10: import nokiaSPI
  11: import time
  12: import os
  13: import sqlite3
  14: #from datetime import timedelta
  15:  
  16: from obd_utils import scanSerial
  17:  
  18: class OBD_Capture():
  19:     def __init__(self):
  20:         self.port = None
  21:         localtime = time.localtime(time.time())
  22:  
  23:     def connect(self):
  24:         portnames = scanSerial()
  25:         print portnames
  26:         for port in portnames:
  27:             self.port = obd_io.OBDPort(port, None, 2, 2)
  28:             if(self.port.State == 0):
  29:                 self.port.close()
  30:                 self.port = None
  31:             else:
  32:                 break
  33:  
  34:         if(self.port):
  35:             print "Connected to "+self.port.port.name
  36:  
  37:     def is_connected(self):
  38:         return self.port
  39:  
  40:     def nokiprint(self,cShortTerm,cLongTerm,cLongTermMinutes):
  41:         cShortTerm = cShortTerm[:4]
  42:         cLongTerm = cLongTerm[:4]
  43:         noki.cls()
  44:         im = Image.new('1', (84,48))
  45:         draw = ImageDraw.Draw(im)
  46:         print cShortTerm
  47:         draw.text((0,0),cShortTerm, font=font, fill=1)
  48:         draw.text((0,24),cLongTerm, font=font, fill=1)
  49:         draw.text((54,7),"3 s", font=fontsmall, fill=1)
  50:         draw.text((54,31),cLongTermMinutes + " m", font=fontsmall, fill=1)
  51:         # Copy it to the display
  52:         noki.show_image(im)
  53:         #noki.next_row()
  54:         
  55:     def ComputeFuelConsumption(self):
  56:         nCurrentTime = time.time()
  57:         
  58:         try:
  59:             nStart = nCurrentTime - 20
  60:             cLimit = " and time_read > " + str(nStart) + " order by time_read desc limit 6"
  61:             cursor.execute('''SELECT maf,speed from SensorReadings where speed > "0" and maf > "0" and rpm != "NODATA" ''' + cLimit)
  62:             data = cursor.fetchall()
  63:         except sqlite3.OperationalError,msg:
  64:             return msg
  65:         #print len(data)
  66:         if (len(data) > 0):
  67:             nFuelConsumption = 0
  68:             for x in range(0,len(data)):
  69:                 nFuelConsumption += (3600 * float(data[x][0]))/(9069.90 * float(data[x][1]))
  70:                 
  71:             nAvgFuelConsumption = nFuelConsumption/len(data)
  72:             print nAvgFuelConsumption
  73:             print type(nAvgFuelConsumption)
  74:             #print data[x][0],data[x][1],data[x][2]
  75:             return "{:5.2f}".format(nAvgFuelConsumption).lstrip()
  76:         else:
  77:             return "No data"
  78:  
  79:         #print nAvgFuelConsum
  80:         
  81:     def is_number(self,DataToTest):
  82:         try:
  83:             float(DataToTest)
  84:             return True
  85:         except ValueError:
  86:             return False    
  87:                 
  88:                 
  89:  
  90:                 
  91:     def capture_data(self):
  92:         #Creating new database
  93:         for kounter in range(10000):
  94:             cKounter = "{0:05d}".format(kounter)
  95:             cNewDatabase = "obdii" + cKounter + ".db"
  96:             #print cNewDatabase
  97:             if not (os.path.exists(cNewDatabase)):
  98:                 #print "New database name: " + cNewDatabase
  99:                 break
 100:  
 101:         global conn
 102:         global cursor
 103:         conn = sqlite3.connect(cNewDatabase)
 104:         cursor = conn.cursor()
 105:             
 106:         #Find supported sensors - by getting PIDs from OBD
 107:         # its a string of binary 01010101010101 
 108:         # 1 means the sensor is supported
 109:         self.supp = self.port.sensor(0)[1]
 110:         self.supportedSensorList = []
 111:         self.unsupportedSensorList = []
 112:         
 113:         
 114:         # loop through PIDs binary
 115:         for i in range(0, len(self.supp)):
 116:             if self.supp[i] == "1":
 117:                 # store index of sensor and sensor object
 118:                 self.supportedSensorList.append([i+1, obd_sensors.SENSORS[i+1]])
 119:             else:
 120:                 self.unsupportedSensorList.append([i+1, obd_sensors.SENSORS[i+1]])
 121:         
 122:         sqlCreateTable = "CREATE TABLE SensorReadings (time_read real, "
 123:         sqlInsertTemplate = "INSERT INTO SensorReadings(time_read, "
 124:         
 125:         for supportedSensor in self.supportedSensorList:
 126:             #print "supported sensor index = " + str(supportedSensor[0]) + " " + str(supportedSensor[1].shortname)
 127:             sqlCreateTable += str(supportedSensor[1].shortname)  + " text,"    
 128:             sqlInsertTemplate += str(supportedSensor[1].shortname)  + ","
 129:             
 130:         sqlCreateTable = sqlCreateTable[:sqlCreateTable.rfind(",")] + ")"
 131:         #print sqlCreateTable
 132:         try:
 133:             cursor.execute(sqlCreateTable)
 134:             conn.commit()
 135:             cursor.execute('''CREATE INDEX time_read_index on SensorReadings(time_read)''')
 136:             cMessage = "Database " + cNewDatabase + " created..."
 137:         except sqlite3.OperationalError,msg:
 138:             cMessage = msg
 139:         noki.cls()
 140:         noki.text(cMessage,wrap=True)
 141:         
 142:         sqlInsertTemplate = sqlInsertTemplate[:sqlInsertTemplate.rfind(",")] + ") VALUES ("
 143:         #print sqlInsertTemplate
 144:         
 145:         time.sleep(3)
 146:  
 147:         if(self.port is None):
 148:             return None
 149:         
 150:         #Loop until Ctrl C is pressed        
 151:         try:
 152:             nRunningTotalFuelConsumption = 0
 153:             nStartTime = time.time()
 154:             x = 0
 155:             while True:
 156:                 current_time = time.time()
 157:                 #current_time = str(localtime.hour)+":"+str(localtime.minute)+":"+str(localtime.second)+"."+str(localtime.microsecond)
 158:                 #log_string = current_time + "\n"
 159:                 sqlInsert = sqlInsertTemplate + '"' + str(current_time) + '",'
 160:                 results = {}
 161:                 for supportedSensor in self.supportedSensorList:
 162:                     sensorIndex = supportedSensor[0]
 163:                     #print sensorIndex
 164:                     (name, value, unit) = self.port.sensor(sensorIndex)
 165:                     #log_string += name + " = " + str(value) + " " + str(unit) + "\n"
 166:                     #print value,type(value)
 167:                     sqlInsert += '"' + str(value) + '",'    
 168:                 
 169:                 
 170:                 sqlInsert = sqlInsert[:sqlInsert.rfind(",")] + ")"
 171:                 #print sqlInsert
 172:  
 173:                 try:
 174:                     cursor.execute(sqlInsert)
 175:                     conn.commit()
 176:                 except sqlite3.OperationalError,msg:
 177:                     noki.cls()
 178:                     noki.text(msg,wrap=True)    
 179:                     continue
 180:                     
 181:                 cFuelConsumption = self.ComputeFuelConsumption()
 182:                 if (cFuelConsumption != "No data"):
 183:                     x += 1
 184:                 if (x > 0):
 185:                     if (self.is_number):
 186:                         nRunningTotalFuelConsumption += float(cFuelConsumption)
 187:                     nTripAverage = nRunningTotalFuelConsumption/x
 188:                     cTripAverage = "{:5.2f}".format(nTripAverage).lstrip()
 189:                 else:
 190:                     cTripAverage = "Nodata"
 191:                 
 192:                 cDurationInMinutes = "{:3.0f}".format((current_time - nStartTime)/60).lstrip()
 193:                 self.nokiprint(cFuelConsumption,cTripAverage,cDurationInMinutes)
 194:                     
 195:                 #print log_string,
 196:                 #time.sleep(0.5)
 197:                 
 198:  
 199:         except KeyboardInterrupt:
 200:             self.port.close()
 201:             print("stopped")
 202:             
 203: if __name__ == "__main__":
 204:     font = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeSansBold.ttf",26)
 205:     fontsmall = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeSansBold.ttf", 16)
 206:     # New b-w image
 207:     im = Image.new('1', (84,48))
 208:     noki = nokiaSPI.NokiaSPI(brightness=268)              # create display device
 209:     noki.cls()
 210:     noki.text("Initializing..",wrap=True)
 211:  
 212:  
 213:     o = OBD_Capture()
 214:     o.connect()
 215:     time.sleep(3)
 216:     if not o.is_connected():
 217:         print "Not connected"
 218:         noki.cls()
 219:         noki.text("Error: Not connected to OBDII...",wrap=True)
 220:         time.sleep(10)
 221:         noki.set_brightness(0)
 222:         noki.cls()
 223:         exit()
 224:     else:
 225:         o.capture_data()

In order for the Python script to automatically start when the Pi boots up, I added this line to /etc/rc.local :


(cd /home/pi/pythonprogs;python obd_capture.py)&


That line should only be added when you are relatively confident it will all work. First, for testing, you will need to run a network cable to your car (or tap in wirelessly, if you are within range). This is what my setup looked like, during early testing:


IMG_1136


The blue cable was networking, the yellow powered the Pi. Later on, I removed the power cable and ran off the car’s battery. It is quite tricky to have to program for something that has to run headless and detached from everything. So when making changes to your code, check, check and double check again.


I’ve also ordered from MausBerryCircuits.com an illuminated LED shutdown switch, which will gracefully shut down the Pi before power is removed, reducing the chance of corrupting the SD card.


That’s it!


Update 2013-08-31:


I’ve optimized the fuel consumption function and made SQLite do the average calculation, alleviating the need do to the calculation in a Python ‘for’ loop. Also, made the SQLite connection and cursor class attributes rather than global variables, which are generally considered undesirable.