micro:bit Analog Inputs

IMG_0541(1)For the last few days I have been playing with the micro:bits builtin capability to measure analog voltages on P0, P1 & P2 (you can set up some of the other IO lines as analog inputs but this is a bit of an involved process and best avoided if possible).

** WARNING **  – YOU MUST ENSURE THAT ANY VOLTAGE APPLIED TO THE MICRO:BIT DOES NOT EXCEED THE SUPPLY RAIL [TYPICALLY 3V] DOING SO WILL RESULT IN DAMAGE TO YOUR MICRO:BIT

 

 

By default the analog converter in the micro:bit is referenced to the micro:bit supply rail and is configured for 10 bit operation. Hence the following code;

from microbit import *
a = pin0.read_analog()
print(a)
display.scroll(str(a))

will return 1023 if you connect the 3V & P0 pads together, irrespective of battery condition of if you power via the micro USB connector. For many applications this is fine and using the micro:bits 3V supply as the source voltage for any analog experiments is the best way to minimize risk of damage the the micro:bit.

However if you want to measure a voltage not derived from the micro:bits supply things can become a bit more problematic. It’s fine if you can power the micro:bit from a constant source – for instance a phone mains power adapter, but not so good if you are running from a battery. This because as the ADC (analog to digit converter) reference voltage will drop as the battery discharges resulting in a change to the count value returned. For instance assuming a new set of batteries provides 3V, a 1.5V source on P0 would return 512, but if the battery voltage drops to 2.5V the reading would change to 614 counts. To get around this the ADC in the micro:bit can be configured to reference an internal fixed 1.2V voltage reference. This means the count value will not vary with a changing supply voltage.IMG_0547(1)

In it’s basic setup this would mean a voltage of 1.2V on P0 would give a result of 1023. However 0-1.2V is quite a small range so the ADC circuit includes a configurable ‘pre-scaler’ to help us. Configuring this to 3:1 we get full scale ADC range of 0-3.6V. It is important to note however that the rule of keeping the maximum voltage applied to a micor:bit input pin at or below the supply rail still applies. 

The following code will setup the ADC to use the internal reference on P0 together with a 3:1 pre-scaler.

Code to demo using the micro:bit internal ADC reference 
# based on material and help from Carlos Pereira Atencio https://gist.github.com/microbit-carlos/
# David Saul 2017. Released to the public domain.

from microbit import *

NRF_ADC_BASE = 0x40007000
NRF_ADC_CONFIG = NRF_ADC_BASE + 0x504

# functions used to modify ADC setup
@micropython.asm_thumb
def reg_read(r0):
 ldr(r0, [r0, 0])

@micropython.asm_thumb
def reg_bit_clear(r0, r1):
 ldr(r2, [r0, 0])
 bic(r2, r1)
 str(r2, [r0, 0])
 
 
# change ADC config for pin0

# mbed configured: 10bit, input 1/3, ref 1/3 vdd, enable ADC in AIN4-P0.03-pin0
pin0.read_analog() 
#Set ref voltage to internal ref 1.2V (band gap), set bits 5-6 to 0x00
reg_bit_clear(NRF_ADC_CONFIG, 0x60)
print("ADC config should be 0x100A: {:#010x}".format(reg_read(NRF_ADC_CONFIG)))

#variable definition
vt = 0 # raw / scaled analog value
vf = "0000" # measured voltage as a formatted string 
cal = 352 # calibration variable
# cal is calculated as (Vin / raw count)*10000
while True
 vt = pin0.read_analog()
 print ('raw count = ',vt)
 
 # the following lines of code scale the measured value and derive a
 # string (vf) that equates to it - there are simpler ways to do this
 # but this method avoids the use of floating variables which are very
 # inefficient on cards like the micro:bit
 
 vt = int((vt * cal)/1000) 
 vs = str(vt)
 if vt > 1000:
  vf = vs[0:2]+'.'+vs[2:3] 
 elif vt > 100 :
  vf = vs[0:1]+'.'+vs[1:3]
 elif vt > 10 :
  vf = '0.'+vs
 elif vt > 1 :
  vf = '0.0'+vs
 else :
  vf = '0.000' 
 
 vf = vf+"V"
 print ('Scaled', vf)
 display.scroll(vf)
 
 sleep(2000)

 

link to code on GitHub

The ‘keep to the rail voltage’ is a generally safe but slight simplification of the ADC operating rules. If you are looking to work with source voltages not limited to the micro:bit supply rail there are specific rules you need to be aware of to avoid damaging your micro:bit. A number of discussion threads have been written on these [ probably because it’s not very understandable in the NORDIC chip datasheet ] one example which is ‘relatively’ clear is https://devzone.nordicsemi.com/question/102/what-voltage-range-can-be-measured-with-the-adc/

 

 

 

Advertisements
Posted in Uncategorized

Meandering Pi and Friends

IMG_0406(1)Over the last couple of months I have spent quite a lot of time experimenting with the BBC micro:bit developing various things including a model train speed controller.  This uses 2 micro:bits one acting as a remote control the other providing a PWM drive to the track. They communicate using a simple 2.4Ghz radio connection builtin to the micro:bit [you sort of get it free with the Bluetooth] .

You can get more details on it’s dedicated project page .

One thing which has been great to discover is that the Raspberry Pi works really well as a desktop environment – to program the micro:bit, either using one of the online tools such as the C/C++ mbed environment or standalone with the micropython ‘mu‘ application.

If you want more information I have created page focused on using the raspberry Pi to program the micro:bit.

IMG_0396(1)

If you haven’t had a play with the micro:bit I really recommend you get one and have a go. They are not a raspberry pi and never will be, but in terms of getting the ‘barrier to programming’ as low possible it is difficult to beat – not least you can be up and doing something in seconds from unwrapping it.

In recognition that I am now talking about more than just Raspberrry Pi’s on this site I am changing the name of the blog to  Meandering Pi and Friends . Hopefully I will be posting to my blog a bit more regularly as well …..

 

Posted in Uncategorized | Tagged ,

RGBtree Working on an Ardunio – Yay

img_2610Having got the Pi variant of Andrew Gale’s RGBtree working nicely I thought I would use some spare time over the last couple of days to setup the alternative Micro:bit/codebug  version on a Arduino Uno clone, for a bit of fun. Cobbling various bits of Ardunio code together I now have an RGBtree that can will play one of  5 different Christmas songs, when the switch is activated – while running through a random series of colour changes in time with the music. Once the tune has finished playing the Neopixels will continue to change randomly. You can download the code from my Github here. I have also uploaded a quick video to YouTube if you want to see and hear it in action !   .

The music uses quite a lot of the Arduino’s ‘variable’ resources, so Iimg_2610 have kept the Neopixel effects simple here. I did not have to make any changes to the RGBtree to get it working with the Arduino, but do be careful if you change from the default brightness settings as the Neopixels can get very bright. The RGB tree is supported on two pins that I was able to position spaced correctly to pickup 5V and GND on the Arduino board. [The Neopixels seem fine working at 5V rather than the labeled 3V.]

I think it is relatively obvious from the code if you want to adapt the code to play different tunes – the size and number of tunes is limited by the ‘variable’ memory size of the Arduino. I guess you could change it to store the tune data in program memory which would greatly extend the storage as an option.

Posted in Uncategorized

An RGB Tree Happy Christmas

img_2581A big thanks to Andrew Gale for getting a missing RGB  tree to me in time for Christmas. To celebrate (and avoid the wrapping),  I’ve cobbled together a quick Python App that gently runs through the spectrum on each of the LEDs in a random order. You can down load it from my git hub here (The colours look a lot better in real life).

Now the next question do I get on with wrapping or see if I can get it working with an Arduino …..

 

Posted in Uncategorized | Tagged , ,

Mk2 Low Cost Home Automation

time2A While ago I setup a Pi to control some quite cheap 433Mhz RC mains switches I got from Maplin [ code N78KA]. The controllers were connected to Lamps to automatically light up various rooms in the house after dark.

The RC switch comes with a simple 4 way hand controller and initially I was just planning to hack this. However looking on the internet I found a few examples where people had used Arduino’s and Pi’s with cheap RC transmitters to ‘mimic’ the signals rc-switchgenerated by the hand controllers, to operate the remote units. I could not find any examples of people who had used the exact Maplin RC switches I had, but reading around it looked like the rc-txcodes were relatively common between products. After a very frustrating day of trial and error I decided to apply a bit intelligence and got the oscilloscope out and started comparing the serial data coming from the Pi and that produced by the hand controller. Quite quickly I realised that the data from the Pi was correct but back to front, having correcting this I was able to activate the remote switches at will !

From here I wrote some simple Python code to control light positioned around the house, planning to tidy it up. Well that was over a year ago ……

The main drive to produce a mk2 version was to avoid me having to manually alter the timings as the length the day changed. It had always been a plan to sort this out with a light dependent resistor (LDR) but I just never got around to it.

Having decided that I could not face another autumn with the family moaning about the house being dark I decided now was a time to get this updated. In addition to auto correcting for the daylight I also wanted to improve the status feedback. The mk1 version simply had a single LED which flashed every few seconds to show the Python code was still running.
img_2439For the display I landed on a miniature OLED display I had picked up from a JAM earlier in the year. You can see the details for this on my last blog posting. As part of the ‘upgrade’ I decided to start from a clean installation of the latest Rasbian . This necessitated trying to re-learn how to get the RC serial libraries working again as I had not written it down the first time around [there is a lesson here], somehow in this process I ended up with different library [https://github.com/lexruee/pi-switch-python] which turned out to be a whole lot easier to work with than the one I used first time around.

The next thing to sort out was adjusting for the changing daylight hours. Using an LDR to detect darkness was fine until my daughter left the light on in the room where the Pi was….. I wanted a self-contained control unit so running wires from a remotely mounted LDR attached to a window was not any option. The solution I landed was to use sun rise and set times, initially I looked at getting these from the web, but that assumes a good long terms stable wifi link, which is a little unrealistic in my experience. After a bit of searching I found an quite old [2004] bit of s/w called sunwait. I think it was originally developed to be used with cron, but can be run from the command line to give sun rise / set times for any given latitude and longitude. The the output is a fixed format so it is possible to reliably grab the target information without too much difficulty. I have written a page in the ‘random Pi notes’ section of my site which describes how to install and basic usage of sunwait.

rc-testHaving tested the individual bits of code I pulled them all together. The resulting application and a number of the test programmed I used to figure out how bits worked can be found on my git-hub. I have tried to comment the code so it is understandable – not least as I struggle to otherwise. Currently the code allows for each controller channel to define an on time relative to sun-set, an off time and a random element. The timings are adjusted daily, in-line with changes to sun rise and set times. In addition, when the code is first run it does a basic check to see if it has missed any comments so it will recover straight away from power cuts which are quite comment where we live. The code is still a little work in progress although stable it needs a tidy up and a cleaner way to setup the timings.time1

Hardware wise I have manged to get everything into an old Pimoroni Pibow case. Pi wise it
is running on an early [no mounting holes] Pi B. I find applications like this a great way to use older hardware which is bit slow to experiment with but still more than fast enough for an application like this. It also helps to keep the costs down as I had all the bits already.

Links to Instructions / help

Setting up an OLED

Install instructions for sunwait

Setting up the RC433 switch library

Link to my Git-Hub  – you can find my controller Python code here

Maplin RC controller product codes – N78KA  [ 1 off] N38HN [ 5 off]

Posted in Uncategorized | Tagged , ,

Tiny OLED displays

img_2439At the recent CAMJAM I got lots of questions about a small OLED display I was using as part of a home lighting control project.

If you are looking to include a small inexpensive status display on your next project, one of these may be just what you need. Prices range from around £16 from the UK Adafruit distributors to £6 on a UK Ebay site – if you are happy to take a bit of chance you can find them even cheaper from sites in the Far East.  img_2435

The picture to the right gives you an idea of how much you can display – this is a single colour 132 * 64 pixels module. The great thing about these displays is being OLED, they don’t have a backlight avoiding the separate drive circuit often needed for ‘traditional’ LCDs.

The modules generally seem to come  with either and I2C or SPI interface.  I have only used I2C varients but the driver software from Adafruit can be configured for either type.

It is worth highlighting that all the small displays of this type that I have seen run on 3.3V not 5V – I have not had any problems running them directly from the Pi 3.3v supply.

Configuring a Pi to drive them was quick and simple – follow this link to see some detailed instructions that work for me.

Posted in Uncategorized | Tagged , ,

Tempus Fugit WordClock Section Goes Live

IMG_2096With the first TF WordClock kits shipping yesterday the TF area on the blog is now  fully live. In addition to information about the TF there is a new instruction page where you can find links to the instruction / operation manual and github for software downloads. I am happy that the cloIMG_2102ning process for SD cards is good so will be working on these from tomorrow. Just under half the early bird kits have now been shipped covering destinations from Australia to Swindon the rest should all go out over the next few days.

Posted in Uncategorized | Tagged , ,

Happy Arduino Day 2016

ard_day2016Happy Ardunio Day 2016 from the Meandering IMG_1868Pi.
We will be at the Peterborough Raspberry Jam on the 9th of April  showing off the latest work on the Tempus Fugit WordClock in both Pi Zero and Arduino Nano Versions, together with other Pi projects old and new.

 

T5Cjj0Qd_400x400

Posted in Uncategorized | Tagged , , , ,

WordClock Prototype PCB Tested

IMG_1814The prototype Tempus Fugit PCB arrived as promised last week from Ragworm, leaving me just enough time to get it built up our Show & Tell at the Pi Party on Sunday. We had lots of positive feedback particularly with demonstrating the ability to swop from a PiZero to a Arduino Nano without having to make any changes to board. With 13 days to go on the Kickstarter we are just £250 short of the stretch target – adding automatic brightness control to the design.bigb

I really enjoyed the Pi Party meeting people new and old. A particular shout out to the Marshal who helped get omxplayer to loop for me and putting my wife in-touch with with someone to talk about Bluetooth.

Posted in Uncategorized

Tempus Fugit WordClock Kickstarter for your Pi or Arduino

IMG_1764aAs trailed in an earlier blog posting I have spent a bit of time over the last couple of weeks working up my Word Clock to run as a Kickstarter. The result is the Tempus Fugit WordClock. you can see in the picture  what the PCB will look like, I will update this with an actual photo in  a couple of weeks when I have got a prototype PCB build. pcb rev4The big development as you might have guessed from the blog title is that the Tempus Fugit will work with an Arduino Nano as an alternative to a Pi Zero so hopefully will still be attractive to people struggling to get hold of the Zero.

Check out the Kickstarter by clicking here.

 

Posted in Uncategorized | Tagged , , , , , ,