Friday, May 26, 2017

Byte: Raspberry Picraft Weekend - Challenge 2



Challenge 2: Push button to work as a light switch

As impressive as our achievement in the first challenge was, you may have noticed that whenever you want to turn on a light, you don’t need to stand around holding the switch down to keep the light on. This is for two reasons: one, that would be incredibly annoying and you’d have to employ someone to hold down the button every time you wanted to turn on a light; and two, for this very reason, lights tend to be connected to circuits using switches, rather than push buttons. So how can we turn our push button into a switch, so that we don’t have to keep pressing whenever we want our LED to turn on? You use code, of course! (Well, you could use an actual switch instead of a push button, but where’s the fun in that?!?)

The obvious place to start is with the code that imports all the necessary libraries to command the buttons and the LEDs, and await further instructions. ‘Save As’ your current script and rename it appropriately to reflect the intended functionality of the new code: lightswitch.py or something similar. Then trim back the code to the following starting point:

#import necessary libraries
from gpiozero import LED, Button
from time import sleep

#define variables
red = LED(17)
amber = LED(18)
green = LED(23)
blue = LED(24)
button1 = Button(5)
button2 = Button(6)
button3 = Button(12)
button4 = Button(13)
while True:

We need the sleep library, as we’re going to have to put in small time delays so that the buttons can act as a toggle switch, rather than a push button. We will also need to use a slightly different method with the push buttons to accept inputs, as we want to leave the LEDs on or off until the script registers a user input. So rather than using the is_pressed() method, we will use the wait_for_press() method of the push button instead.

#import necessary libraries
from gpiozero import LED, Button
from time import sleep

#define variables
red = LED(17)
amber = LED(18)
green = LED(23)
blue = LED(24)
button1 = Button(5)
button2 = Button(6)
button3 = Button(12)
button4 = Button(13)
#turn off the LEDs to ensure they are all off before the main script runs
red.off()
amber.off()
 green.off()
 blue.off()
while True:
    #poll for input from the buttons
    button1.wait_for_press()
    red.toggle()
    sleep(0.2)
    button2.wait_for_press()
    amber.toggle()
    sleep(0.2)  
    button3.wait_for_press()
    green.toggle()
    sleep(0.2)
    button4.wait_for_press()
    blue.toggle()
    sleep(0.2)

Huzzah! Our script now turns the LEDs on and off at the push of a button masquerading as a switch! It’s almost like we’re masters of technology developed in the 19th century! (In case you didn’t know, the ‘quick break’ light switch, which is still used today, was invented in 1884 by John Henry Holmes, an English pioneer of electrical engineering and lighting. You can read about him on Wikipedia.)

Thursday, May 25, 2017

Bark: Climb! Climb!

Wow. I've been so out of it lately that it wasn't until after I posted my Raspberry Pi post that I noticed that I haven't blogged once for the entire year up to this point.

Suffice to say, there are REASONS, mainly due to some pretty nasty mental health issues, but the good news is that I'm starting to see some light at the top of The Pit, and while the walls might still be tall, slippery and vertiginous, at least I'm making some progress. Today was actually a great day, as work has finally come through with providing me with some (but not all - not by a long shot) of the resources I need to do my job properly and with something approaching satisfaction and reward. This is doubly good news, because it means that I've liberated four of the Raspberry Pis I had to buy for the school myself to be able to do any kind of computing programme, meaning that I can use them for my own projects, including a Google AI assistant, a wildlife camera trap and a 'hunter-killer' motion-sensing robot rover.

The Picademy I attended last year was definitely one of the few highlights of 2016 (otherwise a pretty fecking dire year), and I'm really feeling motivated to give something back to the RPi community. So it's good to have the time and the opportunity to develop and share resources for them. I'm even giving thought to trying to crowd-fund setting up an educational charity/consultancy to promote coding skills in primary and secondary schools, since I'm becoming less and less enamoured with working within the mainstream education sector, I'd quite like to strike out on my own if it ever becomes financially viable (the mortgage doesn't pay itself, unfortunately...)

But I am starting to feel a bit more like myself again, and as well as the Raspberry Pi stuff, I've got no less than two writing projects on the go (one of which should be finished and serialised here before the end of the year), and I've even had the opportunity to develop a Creative Writing curriculum for my school. Last week I was working with a student who (like me) has issues with depression, and we wrote poems on the topic.

Poetry isn't a writing form I'm very well versed in (forgive the deliberately terrible pun, please), but I was quite pleased with this, given that I wrote it in half an hour during a break for lunch. It might go some way to explaining why I haven't been posting much around here lately...

The Pit

Churchill imagined his depression as a black dog,
But mine is more like a pit.
Dark and deep, with sides so steep, and murky like dense fog.
I think I'll stay down here for a bit.

It's safe and warm.
A place of despairing calm.
Take cover here until nicer thoughts can form.
In here, nothing can do you harm.

My motivation is low.
It's too much effort to even get out of bed.
My thoughts fly! - and then slow,
And I really should go - but The Pit still needs to be fed.

I form a shield with my duvet cover
To armour myself against the world
And the doom-laded impulses I need to smother,
But in my mind the surrender flag has unfurled.

Staying here does more harm than good.
Body and mind recede from the light
And the darkness covers me in a flood.
Drowning in self-inflicted sorrow, I won't see tomorrow, unless I rise up and fight.

Make my way back up to the top,
It's the only option I've got... Climb!
Ignore all the slips and the falls - I can't ever stop.
Climb! Climb!

Byte: Raspberry Picraft Weekend - Challenge 1



Last weekend I set myself a challenge. With one Raspberry Pi 3B, a breadboard, a GPIO breakout board, four push button switches, four LEDs, four 100 ohm resistors, a PiCamera module and a handful of jumper wires, how many different projects could I make?

The answer, as it turned out, was quite a few. The elegance of this challenge was that it would be fairly easy to evolve the code from one project to another, starting simply, and then getting increasingly more complicated and downright outlandish as the weekend wore on.  The starting place was obvious: I had four LEDs and four push button switches, after all. 

Challenge 1: Push button to light LED

Switches turn lights on. This one thing that we definitely know, as experienced users of high technology, that switches are designed to do. How hard can it be? Well, it’s all in the setup and the details. I chose to use Python to control my circuits, primarily because it would make it easier to integrate the outputs from the circuits into Minecraft later on. You could conceivably complete some of these challenges in Scratch instead, but for simplicity, I’m just going to assume you use Python scripts, using the Python 3 IDLE. 

After you’ve created a new .py script , the first thing we need to do is tell the Pi that we’re going to be using the GPIO interface, and that we’re going to need to be able to control push buttons and LEDs. We do that by importing the appropriate library and functions. Note that it’s good coding practice to give other users of your code hints to what it does (or what it ought to do!) using comments, which can be inserted by prefixing with the # symbol. They can be a great help in determining and solving problems while debugging errors. These lines of code are simply for human consumption, as they’re completely ignored by the computer. While some coders choose not to bother with comments, in my experience, the time spent illustrating the intended function of the code is more than made up for by the time saved during debugging unforeseen errors that could not have been anticipated at the design stage. 

Pro-Tip: Never, EVER forget to add detailed comments to your code. Don’t assume that you’re going to be the person fixing any bugs in it, as you might not find them! 

#import necessary libraries
from gpiozero import LED, Button 

So now that the Pi knows that it’s going to be interacting with the GPIO pins, we really ought to let it know where it should be receiving inputs and outputs...

#define variables
red = LED(17)
amber = LED(18)
green = LED(23)
blue = LED(24)
button1 = Button(5)
button2 = Button(6)
button3 = Button(12)
button4 = Button(13)

The numbers in the brackets should correspond to the GPIO pin you have used to connect to the component to the GPIO breakout board. Otherwise things won’t work, and that would be bad. We will use the same GPIO pin references for all the subsequent challenges, just to make our lives that bit easier while we evolve the code from one project to the next. 

Having set variables to recognise inputs and outputs for our push button switches and our LEDs, we can now add the code to make them interact with each other. We are going to use an infinite loop to detect inputs from the buttons and deal with them accordingly, so we need to alert the Pi to be ready to accept input signals:

while True:

All the code subsequently added to this execution block needs to be indented by one tab to ensure that it only gets called when it is needed. For clarity, I will post all the subsequent code statements from the beginning of the file so that the indent level needed to allow the code to run is obvious. Your code so far should look like this:

#import necessary libraries
from gpiozero import LED, Button
#define variables
red = LED(17)
amber = LED(18)
green = LED(23)
blue = LED(24)
button1 = Button(5)
button2 = Button(6)
button3 = Button(12)
button4 = Button(13)
while True:

Pro-Tip: It’s a good idea to save your progress after you add each line of code to your .py script. After all, you never know when you might have a power cut (or be abducted by aliens!)...

Now that our Pi knows that it is control of LEDs and buttons, now all we need to do is tell them how to interact with each other. To do this, we need to the tell the Pi what it should do while it’s waiting for input in the while True: loop. 

The first thing we need to do is make sure that the LEDs are turned off, so that there’s no chance of receiving false signals from previous times that the code has been run or tested (speaking of which, make sure you kill the Python shell after you’ve finished each test, otherwise your poor Pi might get confused by trying simultaneously process signals in multiple instances of running code – making it seem like your script isn’t working. When in doubt; kill everything and start from scratch... a valuable piece of philosophy in videogames as well as programming!!)

Your code at this point needs to look like this, incidentally:

#import necessary libraries
from gpiozero import LED, Button

#define variables
red = LED(17)
amber = LED(18)
green = LED(23)
blue = LED(24)
button1 = Button(5)
button2 = Button(6)
button3 = Button(12)
button4 = Button(13)
while True:
    #turn off the LEDs
    red.off()
    amber.off()
    green.off()
    blue.off()

Now that the LEDs are set to off by default when the script is run, we can use the Button API to check for any inputs. If there is a signal from one of the four buttons, we need to light the corresponding LED, but we also want to add in a short time delay, so that the script has time to register any changes in input. To do this, we need to import a new Python library, time, and use the sleep method to prevent simultaneous inputs from two or more of the push button switches. 

#import necessary libraries
from gpiozero import LED, Button
from time import sleep

#define variables
red = LED(17)
amber = LED(18)
green = LED(23)
blue = LED(24)
button1 = Button(5)
button2 = Button(6)
button3 = Button(12)
button4 = Button(13)
while True:
    #turn off the LEDs
    red.off()
    amber.off()
    green.off()
    blue.off()
    #poll for input from the buttons
    if button1.is_pressed:
        red.on()
        sleep(0.05)
    elif button2.is_pressed:
        amber.on()
        sleep(0.05)  
    elif button3.is_pressed:
        green.on()
        sleep(0.05)
    elif button4.is_pressed:
        blue.on()
        sleep(0.05)

If your code is working correctly, you should find that pressing each of the buttons makes one of the LEDs blink. You can alter the value in the sleep() lines to change the frequency of the flickering – the number in the brackets corresponds to the number of seconds the line of code executes for; the smaller the number, the faster the LED flickers.

Congratulations! You’ve just used physical interactions with push button switches to make electronic components bow to your will and control! But where will it end? <insert ominous, maniacal laughter here>

Thursday, December 01, 2016

Bark: The Rim of The Pit

Well, it's been a while since I've been here, both figuratively and literally.

It's been quiet around here lately for a few reasons. Firstly, because I ran out of short stories to post, and secondly, because like a coral sponge that's been put through a liquidiser, I've been slowing trying to self-reassemble the neural pathways in my brain to get them working in a way something approaching normal.

As I intimated in one of my last non-fiction posts, way back in April, I was quitting my job in teaching and finding a new career to help me climb out of 'The Pit'. I handed in my resignation, gave myself a short break and went jobhunting. The intention was to get the hell out of teaching and back into industry, preferably as a Business Intelligence Analyst, which might not be the most thrilling job in the world, but it does pay well. Of course, after 7 years in teaching, the only interest my CV was getting was not coming from the IT industry. I've disappointed a lot of Educational Recruitment Consultants over the last six months... (Thanks, I've got a new job now, you can stop calling and leaving me messages!)

Then something interesting dropped into my inbox: a teaching position in a psychiatric unit for adolescents. It wasn't anything like my original plan, but I thought it had possibilities. So I applied for the job, and wasn't entirely surprised to get it. (I probably didn't have much competition, to be fair - you'd have to be crazy to work with mentally ill teenagers, right?)

Now, for obvious reasons that are obvious, I'm not going to talk much about the job itself, other than it's actually been a bit better than my preconceptions about working in a unit like this, except in one respect, which is logistical, and is being sorted, so I won't address it here. Any gripes I do have should be kept in house and go up the chain of command, rather than get bandied about in public - that's just how it should be, for the best interests of everyone involved. (That's my way of saying "don't ask"...) And anyway, they're only one small part of the biggest picture of why I'm feeling the need to write this now.

It's not been a great week. One of the issues surrounding my job is that I have very little opportunity to get things done in a reasonable time. For example, arranging a repeat prescription takes a lot longer than the two or three days it normally would, because I can't drop off the repeat instruction and pick up my meds within office hours. So at the end of every month, I always seem to be eking out my citalopram supply for an extra few days until I can get to the chemist, which isn't ideal. So I was already feeling a bit on edge when Tuesday happened. The commute to my new job is much better than my old one. On a good morning, it takes 15-20 minutes, less than half my old commute to work. Unless, of course, the police close the road because of a hit-and-run. So instead of having a straight run to work, I have to go the scenic route, via roads that are already clogged up because of the road closure on my usual route, plus all the traffic detouring around an accident on the M3. So all the time I'd hoped to spend preparing resources for my lessons that day immediately evaporated in a 90 minute hell-drive to work, precipitating a bit of a meltdown, as it happen almost a year to the day after I had a similar nightmare commute that resulted in my Head of Faculty sending me home to make an emergency appointment with my GP.

So after a year's steady progress hauling myself up an out of The Pit, all it took was a coincidence of bad timing, an unpleasant anniversary and running low on medication to have the black tendrils reach back up and try and drag me back down towards the bottom, to the ravenous insanity beast waiting for me there, kind of like this:
Or possibly like this:
(Yes, that is a cake - had I ever gone onto The Great British Bake Off, something like this would have been my cake week showstopper - possibly including Jabba's Sail Barge as well... but I digress)

As has been noted before, the brain is a fragile and complicated thing - it appears that I've still got some way to go before I've built back the levels of mental resilience that I used to have. It was quite a shock, because over the last few months, I'd been feeling good - happy in my new job, relishing the challenge of helping set up an independent school entirely from scratch, and being my own boss taking responsibility for how the Science and Computing departments should be set up and run, and not least working with the kids themselves - some of whom are great fun and amazing characters in their own right. I've even been able to do stuff and get training in things that I'd never be able to make time for in a mainstream secondary school, like attending a Raspberry Picademy, which was definitely my highlight for the entire year. (Buy a Raspberry Pi! And a PiTop!)

I've even made good steps with my insomnia, cut down my alcohol intake massively, and started getting a bit more exercise (not that my mobile phone thinks so - it spends its days sealed away safely in a locker, since smartphones are contraband items on the wards at my new workplace; I don't even look at it anymore during the week) - and even after the collapse of Western Democracy following Brexit and The Orange Terror, I'm remaining amazingly sanguine, if not exactly thrilled about it - the Generalised Anxiety Disorder is definitely under control. So the lapse this week came as a nasty surprise. Still more work, self-therapy and catharis to be done.

There's only one thing for it. I'm going to have to write another novel...

Sunday, June 26, 2016

Bark: Elite: Dangerous - The Loneliness of the Long Distance Explorer - Epilogue


LTT 4961: 291 days since departure from Conway City

With Andromeda's hull having both the durability and appearance of a scorched patchwork quilt, Mya had taken an executive decision and decreed that we should bypass all but the most profitable first discoveries and make our way back to Alliance space as quickly as possible. It took us a little over a month to reach the fringes of the Local Bubble and we timed our final run into LTT 4961 to coincide with the early hours of the morning, Galactic Standard Time, when any self-respecting privateer or pirate surely would have drunk themselves into a catatonic, alcohol-induced stupor. The Coriolis starport of Conway City was a welcome sight, its cyan blue lights burning brightly in the umbra cast over the station by the nearby volcanic planet it orbited. The short supercruise jaunt from the nav beacon had passed without incident, and the traffic controller welcomed us back politely when we signalled for permission to dock on pad 28, the very same pad we had left from.

Mya landed the Asp Explorer with just a barely perceptible jolt on the docking pad. I ascended the ladder from my station as Mya had Andromeda withdraw into the hangar bay, where the ship could be repaired and refurbished by the station's expert technicians. I stood behind Mya's right shoulder, holding onto her acceleration chair for support as she ran up the Universal Cartographics interface on the HUD.

"So, how much did we make?" I asked, resisting the temptation to take a seat on the armrest of Mya's chair.
"It'll take a good while yet for UC to download all the data from the discovery scanner." Mya said, resigned to a long wait. "You might as well get changed into something more comfortable. When I've finished the upload I'll take you out and buy you breakfast."

It was almost lunchtime before I heard Mya whoop with joy, her voice echoing all the way from the flight deck into the engineering bay, where I was switching the FSD and power plant into maintenance mode, so that they could be repaired by the station's service crews later that afternoon. I limped back to the bridge as fast as my weakened right leg would allow, to see Mya dancing enthusiastically around her acceleration chair.

"Well?" I raised an eyebrow at her expectantly.
"33.7 million." Mya leapt into my arms, practically knocking me to the deck. "But that's not the best part. I've been promoted to Explorer Elite!"
"Congratulations!" I kissed Mya and let her lead me on a waltz around the ship that ended in her stateroom.
"Screw breakfast. We're going out to celebrate properly." Mya declared, stripping off her flight suit and digging through her wardrobe for something appropriate to wear. "Give me a few minutes to get dressed."

Half an hour later, we were back in Perla's Palazzo, our expedition ending where it had began, nearly ten months ago. To complete the sense of symmetry, both Mya and I were wearing the same clothes, eating the same food and drinking the same wine as we had during that first meeting, though the nature of the conversation was very different. Instead of planning an expedition, we were planning a wedding. Before embarking on our Grand Tour, Mya and I agreed to meet each other's families and hold the ceremony on Mya's home planet, Wicca's World in the Alioth system. I dreaded what kind of reception my parents - both staunch supporters of the Federation - would get at the very heart of the Alliance, but they would have to restrain their political vociferousness if they wanted to attend the wedding. The second reason why the symmetry of the occasion wasn't quite perfect was that by the end of the meal we had drunk five bottles of wine, rather than three, somewhat compromising the possibility that we might be able to do something useful with the rest of the day. Mya paid the bill and we made our way slowly, but unsteadily back to the docking bay. When we got out of the lift from the station's commercial concourse, Mya turned left instead of right.
"Mya? Just how drunk are you?" I asked, tugging her gently to a halt with my arm looped through hers. "Bay 28 isn't that way."
"We're not going to Docking Bay 28." Mya turned her head to fix me with a mischievous gaze, her voice mildly slurred. My internal danger sense immediately started sending out urgent distress calls.
"We're not?" I asked doubtfully, unnerved by Mya's tipsy smile.
"No. We're going to Docking Bay 19." Mya said, taking both my hands in hers and walking backwards to tug me along with her.
"Why? What's in Docking Bay 19?"
"Our ship."
"You had Andromeda moved?"
"Nope!"
"I don't understand."
"You will in a minute." Mya told me enigmatically, her smile getting wider and wider across her pretty face. It was the most terrifying thing I'd seen since facing down Zhukov's Fer-de-Lance from point-blank range at Sagittarius A*. "Remember when I told you that grandfather gave me an endowment on my 18th birthday?"
"From his memorial trust fund, yes." I nodded. "To help you kickstart your career. You used it to buy your first ship. An Adder, I believe."
"Well remembered." Mya stopped to give me a quick peck on the cheek in congratulation, before continuing to tug me along the access corridor. "I didn't quite tell you everything, though. That's not the only thing I used the money for."
"This doesn't sound ominous at all."
"I also bought a share in a mining co-op franchise. These things go in and out of business all the time, so a 50% share was quite cheap, but high risk, because it's difficult to tell how profitable a particular ring system is going to be."
"Where was the franchise based?"
"Delkar 7." Mya said, her brown eyes sparkling.
"That's..."
"The biggest source of platinum, palladium and painite in the Alliance." Mya nodded as we came to a stop outside the access hatch to the hangar for Docking Bay 19. "The franchise was... quite profitable."
"How profitable?" I asked dryly.
"See for yourself." Mya stepped back to the bulkhead and opened the airlock to the hangar with a retina and fingerprint scan. I couldn't believe my eyes when the hatch rolled open. I tottered uncertainly into the hangar, dwarfed by the ship inside.
"Oh my god. Mya, this is yours?" I turned back to look at her, my mouth agape. I looked back at the ship and blinked. At over 150 metres long, 62 metres wide and standing 32 metres tall, this immense spearhead of a vessel oozed power, status and solidity. "Mya... just how much are you worth?"
"A tad over 840 million." Mya said casually as she stood at my side and wrapped an arm around my waist. "Just over a quarter of that is tied up in this beauty. She's brand new. Straight out of the Faulcon DeLacy shipyards."
"It was my dream to fly an Anaconda." I smiled, before turning to look at Mya. "There's just one problem... It's pink."
"Desert Sand." Mya corrected.
"Pink." I repeated, adamant.
"When you can afford your own Anaconda, you can pick the damn colour." Mya said warningly. "My ship, my choice of paint job."
"Seriously, though? Pink?" I asked, getting a playful smack across the back of the legs for my trouble.
"I'm not changing it." Mya giggled, kissing my cheek. "How do you fancy the Grand Tour now, Petr?"
"In that? When do we start?" Elated, I kissed Mya back, hugging her tightly in both arms. "Though, umm, doesn't the Anaconda fly best with three?"
"We'll just have to work on a third crew member." Mya replied suggestively, before kissing my lips so passionately that I never wanted it to end.