Category: goatee-stroking musing, or something

  • Simple ADC with the Raspberry Pi

    Raspberry Pi wearing an MCP3008

    Hey! This is a really old article. You should really be using gpiozero these days.

    I hadn’t realised it, but the The Quite Rubbish Clock did something that a lot of people seem to have trouble with on the Raspberry Pi: communicating using hardware SPI. Perhaps it’s because everything is moving so fast with Raspberry Pi development, tutorials go out of date really quickly. Thankfully, hardware SPI is much easier to understand than the older way of emulation through bit-banging.

    SPI is a synchronous serial protocol, so it needs a clock line as well as a data in and data out line. In addition, it has a Chip Enable (CE, or Chip Select, CS) line that is used to choose which SPI device to talk to. The Raspberry Pi has two CE lines (pins 24 and 26) so can talk to two SPI devices at once. It supports a maximum clock rate of 32 MHz, though in practice you’ll be limited to the rate your device supports.

    The device I’m testing here is an MCP3008 10-bit Analogue-to-Digital Converter (ADC). These are simple to use, cheap and quite fast converters with 8 input channels. If you hook them up to a 3.3 V supply they will convert a DC voltage varying from 0-3.3 V to a digital reading of 0-1023 (= 210 – 1). Not quite up there in quality for hi-fi audio or precision sensing, but good enough to read from most simple analogue sensors.

    The sensor I’m reading is the astonishingly dull LM35DZ temperature sensor. All the cool kids seem to be using TMP36s (as they can read temperatures below freezing without a negative supply voltage). One day I’ll show them all and use a LM135 direct Kelvin sensor, but not yet.

    To run this code, install the SPI libraries as before. Now wire up the MCP3008 to the Raspberry Pi like so:

     MCP 3008 Pin          Pi GPIO Pin #    Pi Pin Name
    ==============        ===============  =============
     16  VDD                 1              3.3 V
     15  VREF                1              3.3 V
     14  AGND                6              GND
     13  CLK                23              GPIO11 SPI0_SCLK
     12  DOUT               21              GPIO09 SPI0_MISO
     11  DIN                19              GPIO10 SPI0_MOSI
     10  CS                 24              GPIO08 CE0
      9  DGND                6              GND

    The wiring for the LM35 is very simple:

     LM35 Pin        MCP3008 Pin
    ==========      =============
     Vs              16 VDD
     Vout             1 CH0
     GND              9 DGND

    The code I’m using is a straight lift of Jeremy Blythe’s Raspberry Pi hardware SPI analog inputs using the MCP3008. The clever bit in Jeremy’s code is the readadc() function which reads the relevant length of bits (by writing the same number of bits; SPI’s weird that way) from the SPI bus and converting it to a single 10-bit value.

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    # mcp3008_lm35.py - read an LM35 on CH0 of an MCP3008 on a Raspberry Pi
    # mostly nicked from
    #  http://jeremyblythe.blogspot.ca/2012/09/raspberry-pi-hardware-spi-analog-inputs.html
    
    import spidev
    import time
    
    spi = spidev.SpiDev()
    spi.open(0, 0)
    
    def readadc(adcnum):
    # read SPI data from MCP3008 chip, 8 possible adc's (0 thru 7)
        if adcnum > 7 or adcnum < 0:
            return -1
        r = spi.xfer2([1, 8 + adcnum << 4, 0])
        adcout = ((r[1] & 3) << 8) + r[2]
        return adcout
    
    while True:
        value = readadc(0)
        volts = (value * 3.3) / 1024
        temperature = volts / (10.0 / 1000)
        print ("%4d/1023 => %5.3f V => %4.1f °C" % (value, volts,
                temperature))
        time.sleep(0.5)
    

    The slightly awkward code temperature = volts / (10.0 / 1000) is just a simpler way of acknowledging that the LM35DZ puts out 10 mV (= 10/1000, or 0.01) per °C. Well-behaved sensors generally have a linear relationship between what they indicate and what they measure.

    If you run the code:

    sudo ./mcp3008_lm35.py

    you should get something like:

      91/1023 => 0.293 V => 29.3 °C
      93/1023 => 0.300 V => 30.0 °C
      94/1023 => 0.303 V => 30.3 °C
      95/1023 => 0.306 V => 30.6 °C
      96/1023 => 0.309 V => 30.9 °C
      97/1023 => 0.313 V => 31.3 °C
      97/1023 => 0.313 V => 31.3 °C
      98/1023 => 0.316 V => 31.6 °C
      99/1023 => 0.319 V => 31.9 °C
      99/1023 => 0.319 V => 31.9 °C
     100/1023 => 0.322 V => 32.2 °C
     100/1023 => 0.322 V => 32.2 °C
     100/1023 => 0.322 V => 32.2 °C
     101/1023 => 0.325 V => 32.5 °C
     101/1023 => 0.325 V => 32.5 °C
     102/1023 => 0.329 V => 32.9 °C
     102/1023 => 0.329 V => 32.9 °C
     103/1023 => 0.332 V => 33.2 °C

    Note that the sensor had been sitting over the Raspberry Pi’s CPU for a while; I don’t keep my house at 29 °C. I made the temperature go up by holding the LM35.

    So, you’ve just (fairly cheaply) given your Raspberry Pi 8 analogue input channels, so it can behave much more like a real microcontroller now. I remember from my datalogging days that analogue inputs can be pretty finicky and almost always return a value even if it’s an incorrect one. Check the chip’s datasheet to see if you’re doing it right, and if in doubt, meter it!

  • stats stats lay down flat

    blog stats for yesterday: over 4000 hitsOh my. This blog is usually a quiet little backwater, ticking along on a few hundred hits a day. And I’m okay with that. But yesterday, my astonishingly impractical QR code clock hit the front page of RaspberryPi.org, and blammo! More visitors than I thought possible. Are there really over 4000 people who read that? Cor, to use a good British comic-ism.

    I’ve been blogging for nearly ten years, filed under what could only charitably be called “miscellaneous”. Yesterday, I got 2% of all the hits I’ve ever had. See the tiny little bar just to the left of the big one? Yeah, that was my previous best ever, with nearly 600 hits.

  • Like the sun shines out its ____

    Ariel_Rojo-cerdo_ahorradorI’m very taken with Ariel Rojo‘s Piggy Bank Lamp. It’s the first ornament I’ve seen that uses the form of a compact fluorescent bulb as an integral part.

    Not sure I’m quite taken enough with it to pay the $98 that the AGO store wants, though …

  • mosaics

    Random fills of Hoop Tiles, perhaps slightly influenced by 10 PRINT.

  • Bad Kids Jokes

    Lost Tractor

    what did the farmer say when he lost his tractor?

    where’s my tractor?

    Old Man

    why is it when a old man with one kid people thinks ”stranger”, but when its a old man with 20 kids people think ”school trip” . im on to you old people

    Mountain Climbing

    Q) why did’nt the man clime up the mountain

    A) because there wasn’t a mountain

    — from Bad Kids Jokes (via)

  • My American Science & Surplus haul

    american
    I went to American Science and Surplus yesterday, and picked up:

    • a pair of cross lock tweezers
    • a small 12V stepper motor
    • two P-38 can openers
    • a musical box mechanism that plays “For He’s a Jolly Good Fellow“.
  • pretty-printing Arduino sketches

    I don’t often need it, but the code printing facility in the Arduino IDE is very weak. It has some colour highlighting, but no page numbering, no line numbering, and no headers at all.

    a2ps will sort you right out here. Years back, it was a simple text to PostScript filter, but now it has many wonderful filters for pretty-printing code. The Wiring/Arduino language is basically C++, and a2ps knows how to deal with that. So, to create a PostScript file with a nice version of the the most basic Blink sketch:

    a2ps --pro=color -C -1 -M letter -g --pretty-print='c++' -o ~/Desktop/Blink.ps Blink.ino

    If you’re somewhere that uses sensible paper sizes (in other words, not North America), you probably don’t want the -M letter option. a2ps is supposed to have a PDF print option (-P pdf), but it doesn’t work on my installation, so I just splat the output through ps2pdf. You can’t use the -P «printer» option combined with the -o «file» option, but cups-pdf is your friend if you need to print to a PDF. The results are linked below:

    Not bad, eh?

    (Update: think I must have written this post on a Mac with a case-insensitive filesystem. Using the --pretty-print='C++' option I had before failed on Linux.)

  • yay tiny stepper motor!

    Active Surplus Electronics is the best. I was wanting to learn about driving stepper motors from a microcontroller, but didn’t want to spend a lot or rig up a complex power supply. Active Surplus had a bin of tiny 5V stepper motors at under $3 each. The one I bought is marked:

    50-03500-    028
    MADE IN
     MALAYSIA   7115
    SYMBOL TECHNOLOGIES, INC.

    I have no data sheet, but I’ve been able to work out that it’s a unipolar stepper motor, 20 steps/revolution (18°/step; quite coarse), wired:

    • Centre tap: Brown
    • Coil A: White, Red
    • Coil B: Orange, Blue

    It’s small enough to be driven directly by USB power through an Arduino and the Adafruit Motor Shield. No idea how much torque this thing puts out, but it can’t be much.

    (Setting up my motor shield was a pain, as I’d accidentally put non-stacking headers on it. This required an hour of swearing-filled desoldering; lead-free through-hole desoldering is just the worst*. With wick and solder pump, I finally managed to clear everything up well enough to fit the new headers.)
    (more…)

  • Chirp is a thing

    Chirp is a new annoyance, a way of sending links and stuff via audio. Sounds like it’s doing it via MFSK, and is only sending the ID of the link on Chirp’s server, as there’s not much data sent. Here’s what the spectrum plot looks like:

    This is what it sounds like: test chirp [mp3].

  • facebook paranoia

    (idea and script by Catherine Raine. animation by me.)

  • peaksaver plus, dammit

    Toronto Hydro’s just announced peaksaver PLUS, where you get a free Blueline Power Cost Monitor. Dammit! If only I hadn’t already bought one

    (and no, I haven’t yet got the Arduino wireless monitor running, which was actually the whole reason I got into ham radio.)

  • truly, the internet is made of cats

    After years of carefully crafting comments on MetaFilter for maximal content, value or lulz, my most popular comment by far is about cats and Animal Control. Two subjects that, due to allergies and the relatively docility of aquarium fish respectively, I know nothing about. There’s a moral here, and it’s sitting on your router mewing at you.

  • A not-very-good golf joke

    Mike Mike Weir Mike Weir Still
    Mike
    Mike Weir
    Mike Weir Still

    (image nicked from Canadian Family magazine)

  • What if you build it, and they leave?

    City Hall is currently tearing itself apart over transit. You’d think that in a city with a downtown that’s pretty much gridlocked for three hours of the day, the answer to the transit question would be “More please everywhere”, but in this precious city, it’s less than that.

    We have a mayor who is obsessed with subways because he thinks they’re fast and will keep the automobiles running. Unfortunately, Toronto is a big sprawly city with less than infinite cash, so we’re not going to get subways everywhere. Our last venture into subway building — the Sheppard line — has been a bit rubbish, running a stubby distance to nowhere in particular, and being quiet enough that you can always get a seat.

    Though I live in Toronto, I’m originally from Glasgow. Glasgow has a subway; in fact, it’s one of the world’s oldest. It was opened in 1896, when Glasgow was at the height of its “Second City” fame. Glasgow made the ships and trains that maintained the empire, and trained the engineers of the world. We were pretty hot shit at the time, and we had a bunch of workers we needed to get around every day from the shipyards and offices of the city. Lots of people moving in to work. Ergo, subway!

    Just one problem: cities change, subways don’t. Even though shipbuilding was never a hugely lucrative industry (according to my grandfather, who worked at John Brown’s, they never cleared more than 7% even at the best times), Glasgow and environs would probably have never thought that its industries would change and contract the way they did.

    So what’s the subway that Glasgow’s been left with?

    • The industry has gone, so has most of the ridership. There’s an awkward mix of residential stations and, well, nothing stations. I mean, West St? C’mon!
    • Both of the major rail hubs that the subway serves — Buchanan St and St Enoch — are long gone. I just remember the shell of St Enoch station used as a car park in the very early 1970s, but no trains.
    • Given that Scots were a bit squat in the 19th century, the subway’s not built for 21st century people. I could never stand up in the trains.
    • Ridership is frankly pants; indeed, even Toronto’s Sheppard line carries more people every day than the Glasgow subway. Riders are pretty much now park ‘n ride office drones, students (bored [on the way to uni], drunk [doing the subcrawl; a pint at the pub nearest ever station] or daredevil [the subway challenge]) or huns.

    Glasgow used to have quite an extensive tram network. Of course, you wouldn’t know now, ‘cos it’s all been ripped up, but you can do that with street-level transit. Subways you’re stuck with.

    Cities and cultures never know when they’re at their height. Glasgow had it going on when it built its subway, yet I’m sure the city planners never thought that the city would change the way it did. At least Glasgow made stuff that everyone needed; Toronto, what do you do that keeps you anchored here?