Tag Archives: HackSpace

OctoPrint: a baby monitor for your 3D printer

Post Syndicated from Andrew Gregory original https://www.raspberrypi.org/blog/octoprint-a-baby-monitor-for-your-3d-printer/

In issue 32 of HackSpace magazine, out now, we talk to Gina Häußge, creator of OctoPrint – it sits on a Raspberry pi and monitors your 3D printer.

Gina Häußge, creator and maintainer of OctoPrint

There’s something enchanting about watching a 3D printer lay down hot plastic. Seeing an object take shape before your eyes is utterly compelling, which is perhaps why we love watching 3D printing time-lapse videos so much.

Despite this, it would be impractical and inefficient to sit and watch every time you sent a print job through. That’s why we should all be grateful for OctoPrint. This free, open-source software monitors your 3D printer for you, keeping you from wasting plastic and ensuring that you can go about your business without fearing for your latest build.
OctoPrint is the creation of Gina Haüßge. We enjoyed a socially distant chat with her about the challenges of running an open-source project, making, and what it’s like to have a small project become huge.

HackSpace: Most people who have used a 3D printer will have heard of OctoPrint, but for the benefit of those who haven’t, what is it?

Gina Haüßge: Somebody once called it a baby monitor for your 3D printer. I really like this description. It’s pretty much a combination of a baby monitor and a remote control, because it allows you to go through any web browser on your network and monitor what your printer is currently up to, how much the current job has progressed. If you have a webcam set up, it can show you the print itself, so you can see that everything is working correctly, it’s still on the bed, and all that.

It also offers a plug-in interface so that it can be expanded with various features and functionality, and people have written a ton of integrations with notification systems. And all of this runs on pretty much any system that runs Python. I have to say Python, not MicroPython, the full version. Usually Linux, and the most common use case is to run it on a Raspberry Pi, and this is also how I originally set it out to work.

Most people think it only runs on a Raspberry Pi, but no. It will run on any old laptop that you still have lying around. It’s cross-platform, so you don’t need to buy a Raspberry Pi if you have another machine that will fit the bill.

OctoPrint is most commonly run on a Raspberry Pi

HS: How long have you been working on it?

GH: I originally sat down to write it over my Christmas break in 2012, because I had got my first 3D printer back then. It was sitting in my office producing fumes and noise for hours on end, which was annoying when trying to work, or game, or anything else.

I thought there must be a solution involving attaching one of these nifty new Raspberry Pis that had just come out. Someone must have written something, right? I browsed around the internet, realised that the closest thing to what I was looking for treated the printer as a black box – to fire job data at it and hope that it gets it right. That was not what I wanted; I wanted this feedback channel. I wanted to see what was happening; I wanted to monitor the temperatures; I wanted to monitor the job progress.

The very first version back then was a plug-in for Cura, before Cura even supported plug-ins. After my Christmas break, I went, OK, it’s doing everything I wanted it to do; back to work at my normal regular job. And then it exploded. I started getting emails, issue reports, and feature requests from all over the world. ‘Can you make it also do this?’ ‘Hey, I have this other printer with this slightly different firmware that behaves like this; can you adapt it so that it works with this?’. ‘Can you remove it from Cura, and have it so it works standalone?’ Suddenly I had this huge open-source project on my hands. I didn’t do any kind of promotion for it or anything like that. I just posted about it in a Google+ community, of all things, and from there it grew by word of mouth.

A year or so later, I reduced my regular job to 80%, to have one day a week for OctoPrint, but that didn’t suffice either with everything that was going on. Then I had the opportunity to go full-time, sponsored by a single company who also made 3D printers, and they ran out of money in 2016. That was when I turned to crowdfunding, which has been the mode of operation ever since. Around 95% of everything that is done on OctoPrint is run by me, and I work on it full-time now. Since 2014.

A lot of the stuff that I have been adding over the years, for instance, the plug-in system itself, would not have been possible as a pet side project, not with a day job.

HS: What are you working on at the moment?

GH: In March just gone, I released the next big version, to make OctoPrint Python 3-compatible, because at the start of the year Python was deemed end of life, so I had to do something. The problem is that there’s a flourishing plug-in ecosystem written in Python 2, so for now, I’m stuck with having to support both, and trying to motivate the plug-in maintainers to also migrate, which is a ton of fun actually. I wrote a migration guide, tracking in the plug-in repository how many plugs are compatible. Newly registered plug-ins have to be compatible too.

HS: Do you have any idea how many people use OctoPrint?

GH: Nine months, a year ago, I introduced usage tracking. It’s my own bundled plug-in that ships with OctoPrint that does anonymous user tracking through my own platform, so no GDPR issues should arise there. And what this shows me is that, over the course of the last seven days, I saw 66,000 instances, and the last 30 days, I saw 91,000 instances.

But that’s only those who have opted into the usage tracking, which obviously is only a fraction. I have no idea about the fraction – whether the real number is five times, ten times higher, I’ve no way of knowing.

When I did the most recent big update, I got some statistics back from piwheels [a Python package repository]. They saw a spike in repositories that were being pulled from their index, which corresponded to dependencies that the new version of OctoPrint depends on, and the spike that they saw corresponded with the day that I rolled out the new version. Based on that, it looks like there’s probably ten times as many instances out there. I didn’t expect that. So the total number of users could be 700,000, it could be over a million, I have no idea. But based on these piwheels stats, it’s in that ballpark.

HS: And are you seeing a growth in those figures?

GH: Yes. Especially now, with the pandemic going on. If you had asked me three or four months ago, just when the pandemic started, I would have told you more like 60,000 per 30 days. So I saw a significant increase. I also saw a significant usage increase in the last couple of weeks.

I also saw a significant increase in support overheads in the last couple of weeks, which was absolutely insane. It was like everyone and their mother wanted to know something from me, writing me emails, opening tickets and all that, and this influx of people has not stopped yet. At first I thought, well I’ll just go into crunch mode and weather this out, but that didn’t work out. I had to find new ways to cope in order to keep this sustainable.

HS: You can’t have crunch mode for three months!

GH: I mean it’s OK for four weeks or so, but then you start to notice side effects on your own well-being. It’s not a good idea. I’m in for the long haul.

HS: Wanting a feedback channel instead of just firing off commands that work silently makes a lot of sense.

GH: It’s not like a paper printer where you fire and forget, so treating it as a black box, where you don’t get anything back on status and all that, is bound to be trouble. This is a complicated machine where a lot of stuff can go wrong, so it makes sense to have a feedback channel — at least that was my intuition back then, and evidently, a lot of people thought the same.

HS: You must have saved people countless hours and hours of wasted time, filament, and energy.

GH: I’ve also heard that I’ve saved at least one marriage! Someone wrote me an email a couple of years ago thanking me because the person had a new printer in their garage and was constantly monitoring it, sitting in front of it. Apparently the wife and kids were not too thrilled by this. They installed OctoPrint, and since then they’ve been happy again.

Get HackSpace magazine issue 31 — out today

HackSpace magazine issue 32: on sale now!

You can read the rest of HackSpace magazine’s interview with Gina Häußge in issue 32, out today and available online from the Raspberry Pi Press online store. You can also download issue 32 for free.

The post OctoPrint: a baby monitor for your 3D printer appeared first on Raspberry Pi.

The Raspberry Pi Press store is looking mighty fine

Post Syndicated from Alex Bate original https://www.raspberrypi.org/blog/the-raspberry-pi-press-store-is-looking-mighty-fine/

Eagle-eyed Raspberry Pi Press fans might have noticed some changes over the past few months to the look and feel of our website. Today we’re pleased to unveil a new look for the Raspberry Pi Press website and its online store.

Did you know?

Raspberry Pi Press is the publishing imprint of Raspberry Pi (Trading) Ltd, which is part of the Raspberry Pi Foundation, a UK-based charity that does loads of cool stuff with computers and computer education.

Did you also know?

Raspberry Pi Press publishes five monthly magazines: The MagPi, HackSpace Magazine, Wireframe, Custom PC, and Digital SLR Photography. It also produces a plethora of project books and gorgeous hardback beauties, such as retro gamers’ delight Code the Classics, as well as Hello World, the computing and digital making magazine for educators! Phew!

And did you also, also know?

The Raspberry Pi Press online store ships around the globe, with copies of our publications making their way to nearly every single continent on planet earth. Antarctica, we’re looking at you, kid.

It’s upgrade time!

With all this exciting work going on, it seemed only fair that Raspberry Pi Press should get itself a brand new look. We hope you’ll enjoy skimming the sparkling shelves of our online newsagents and bookshop.

Ain’t nothin’ wrong with a little tsundoku

You can pick up all the latest issues of your favourite magazines or treat yourself to a book or three, and you can also subscribe to all our publications with ease. We’ve even added a few new payment options to boot.

New delivery options

We’ve made a few changes to our shipping options, with additional choices for some regions to make sure that you can easily track your purchases and receive timely and reliable deliveries, even if you’re a long way from the Raspberry Pi Press printshop.

Customers in the UK, the EU, North America, Australia, and New Zealand won’t see any changes to delivery options. We continue to work to make sure we’re offering the best price and service we can for everyone, no matter where you are.

Have a look and see what you think!

So hop on over to the new and improved Raspberry Pi Press website to see the changes for yourself. And if you have any feedback, feel free to drop Oli and the team an email at [email protected].

The post The Raspberry Pi Press store is looking mighty fine appeared first on Raspberry Pi.

Design your own Internet of Things with HackSpace magazine

Post Syndicated from Andrew Gregory original https://www.raspberrypi.org/blog/design-your-own-internet-of-things-with-hackspace-magazine/

In issue 31 of HackSpace magazine, out today, PJ Evans looks at DIY smart homes and homemade Internet of Things devices.

In the last decade, various companies have come up with ‘smart’ versions of almost everything. Microcontrollers have been unceremoniously crowbarred into devices that had absolutely no need for microcontrollers, and often tied to phone apps or web services that are hard to use and don’t work well with other products.

Put bluntly, the commercial world has struggled to deliver an ecosystem of useful smart products. However, the basic principle behind the connected world is good – by connecting together sensors, we can understand our local environment and control it to make our lives better. That could be as simple as making sure the plants are correctly watered, or something far more complex.

The simple fact is that we each lead different lives, and we each want different things out of our smart homes. This is why companies have struggled to create a useful smart home system, but it’s also why we, as makers, are perfectly placed to build our own. Let’s dive in and take a look at one way of doing this – using the TICK Stack – but there are many more, and we’ll explore a few alternatives later on.

Many of our projects create data, sometimes a lot of it. This could be temperature, humidity, light, position, speed, or anything else that we can measure electronically. To be useful, that data needs to be turned into information. A list of numbers doesn’t tell you a lot without careful study, but a line graph based on those numbers can show important information in an instant. Often makers will happily write scripts to produce charts and other types of infographics, but now open-source software allows anyone to log data to a database, generate dashboards of graphs, and even trigger alerts and scripts based on the incoming data. There are several solutions out there, so we’re going to focus on just one: a suite of products from InfluxData collectively known as the TICK Stack.

InfluxDB

The ‘I’ in TICK is the database that stores your precious data. InfluxDB is a time series database. It differs from regular SQL databases as it always indexes based on the time stamp of the incoming data. You can use a regular SQL database if you wish (and we’ll show you how later), but what makes InfluxDB compelling for logging data is not only its simplicity, but also its data-management features and built-in web-based API interface. Getting data into InfluxDB can be as easy as a web post, which places it within the reach of most internet-capable microcontrollers.

Kapacitor

Next up is our ‘K’. Kapacitor is a complex data processing engine that acts on data coming into your InfluxDB. It has several purposes, but the common use is to generate alerts based on data readings. Kapacitor supports a wide range of alert ‘endpoints’, from sending a simple email to alerting notification services like Pushover, or posting a message to the ubiquitous Slack. Multiple alerts to multiple destinations can be configured, and what constitutes an alert status is up to you. More advanced uses of Kapacitor include machine learning and anomaly detection.

Chronograf

The problem with Kapacitor is the configuration. It’s a lot of work with config files and the command line. Thoughtfully, InfluxData has created Chronograf, a graphical user interface to both Kapacitor and InfluxDB. If you prefer to keep away from the command line, you can query and manage your databases here as well as set up alerts, metrics that trigger an alert, and the configurations for the various handlers. This is all presented through a web app that you can access from anywhere on your network. You can also build ‘Dashboards’ – collections of charts displayed on a single page based on your InfluxDB data.

Telegraf

Finally, our ’T’ in TICK. One of the most common uses for time series databases is measuring computer performance. Telegraf provides the link between the machine it is installed on and InfluxDB. After a simple install, Telegraf will start logging all kinds of data about its host machine to your InfluxDB installation. Memory usage, CPU temperatures and load, disk space, and network performance can all be logged to your database and charted using Chronograf. This is more due to the Stack’s more common use for monitoring servers, but it’s still useful for making sure the brains of our network-of-things is working properly. If you get a problem, Kapacitor can not only trigger alerts but also user-defined scripts that may be able to remedy the situation.

Get HackSpace magazine issue 31 — out today

HackSpace magazine issue 31: on sale now!

You can read the rest of HackSpace magazine’s DIY IoT feature in issue 31, out today and available online from the Raspberry Pi Press online store. You can also download issue 31 for free.

The post Design your own Internet of Things with HackSpace magazine appeared first on Raspberry Pi.

Build low-power, clock-controlled devices

Post Syndicated from Andrew Gregory original https://www.raspberrypi.org/blog/build-low-power-clock-controlled-devices/

Do you want to make a sensor with a battery life you can measure in days rather than hours? Even if it contains a (relatively!) power-hungry device like a Raspberry Pi? By cunning use of a real-time clock module, you can make something that wakes up, does its thing, and then goes back to sleep. While asleep, the sensor will sip a tiny amount of current, making it possible to remotely monitor the temperature of your prize marrow in the greenhouse for days on end from a single battery. Read on to find out how to do it.

A sleeping Raspberry Pi Zero apparently consuming no current!

You’ll need:

  • DS3231 powered real-time clock module with battery backup: make sure it has a battery holder and an INT/SQW output pin
  • P-channel MOSFET: the IRF9540N works well
  • Three resistors: 2.2 kΩ, 4.7 kΩ, and 220 Ω
  • A device you want to control: this can be a PIC, Arduino, ESP8266, ESP32, or Raspberry Pi. My software is written in Python and works in MicroPython or on Raspberry Pi, but you can find DS3231 driver software for lots of devices
  • Sensor you want to use: we’re using a BME280 to get air temperature, pressure, and humidity
  • Breadboard or prototype board to build up the circuit

We’ll be using a DS3231 real-time clock which is sold in a module, complete with a battery. The DS3231 contains two alarms and can produce a trigger signal to control a power switch. To keep our software simple, we are going to implement an interval timer, but there is nothing to stop you developing software that turns on your hardware on particular days of the week or days in the month. The DS3231 is controlled using I2C, which means it can be used with lots of devices.

You can pick up one of these modules from lots of suppliers. Make sure that you get one with the SQW connection, as that provides the alarm signal

MOSFET accompli

The power to our Raspberry Pi Zero is controlled via a P-channel MOSFET device operating as a switch. The 3.3 V output from Raspberry Pi is used to power the DS3231 and our BME280 sensor. The gate on the MOSFET is connected via a resistor network to the SQW output from the DS3231.

You can think of a MOSFET as a kind of switch. It has a source pin (where we supply power), a drain pin (which is the output the MOSFET controls), and a gate pin. If we change the voltage on the gate pin, this will control whether the MOSFET conducts or not.

We use a P-channel MOSFET to switch the power because the gate voltage must be pulled down to cause the MOSFET to conduct, and that is how P-channel devices function.

MOSFET devices are all about voltage. Specifically, when the voltage difference between the source and the gate pin reaches a particular value, called the threshold voltage, the MOSFET will turn on. The threshold voltage is expressed as a negative value because the voltage on the gate must be lower than the voltage on the source. The MOSFET that we’re using turns on at a threshold voltage of around -3.7 volts and off at a voltage of -1.75 volts.

The SQW signal from the DS3231 is controlled by a transistor which is acting as a switch connected to ground inside the DS3231. When the alarm is triggered, this transistor is turned on, connecting the SQW pin to ground. The diagram below shows how this works.

The resistors R1 and R2 are linked to the supply voltage at one end and the SQW pin and the MOSFET gate on the other. When SQW is turned off the voltage on the MOSFET gate is pulled high by the resistors, so the MOSFET turns off. When SQW is turned on, it pulls the voltage on the MOSFET gate down, turning it on.

Unfortunately, current leaking through R1 and R2 to the DN3231 means that we are not going to get zero current consumption when the MOSFET is turned off, but it is much less than 1 milliamp.

We’re using a BME280 environmental sensor on this device. It is connected via I2C to Raspberry Pi. You don’t need this sensor to implement the power saving

Power control

Now that we have our hardware built, we can get some code running to control the power. The DS3231 is connected to Raspberry Pi using I2C. Before you start, you must enable I2C on your Raspberry Pi using the raspi-config tool. Use sudo raspi-config and select Interfacing Options. Next, you need to make sure that you have all the I2C libraries installed by issuing this command at a Raspberry Pi console:

sudo apt-get install python3-smbus python3-dev i2c-tools

The sequence of operation of our sensor is as follows:

  1. The program does whatever it needs to do. This is the action that you want to perform at regular intervals. That may be to read a sensor and send the data onto the network, or write it to a local SD card or USB memory key. It could be to read something and update an e-ink display. You can use your imagination here.
  2. The program then sets an alarm in the DS3231 at a point in the future, when it wants the power to come back on.
  3. Finally, the program acknowledges the alarm in the DS3231, causing the SQW alarm output to change state and turn off the power.

Clock setting

The program below only uses a fraction of the capabilities of the DS3231 device. It creates an interval timer that can time hours, minutes, and seconds. Each time the program runs, the clock is set to zero, and the alarm is configured to trigger when the target time is reached.

Put the program into a file called SensorAction.py on your Raspberry Pi, and put the code that you want to run into the section indicated.

import smbus

bus = smbus.SMBus(1)

DS3231 = 0x68

SECONDS_REG = 0x00
ALARM1_SECONDS_REG = 0x07

CONTROL_REG = 0x0E
STATUS_REG = 0x0F

def int_to_bcd(x):
    return int(str(x)[-2:], 0x10)

def write_time_to_clock(pos, hours, minutes, seconds):
    bus.write_byte_data(DS3231, pos, int_to_bcd(seconds))
    bus.write_byte_data(DS3231, pos + 1, int_to_bcd(minutes))
    bus.write_byte_data(DS3231, pos +2, int_to_bcd(hours))

def set_alarm1_mask_bits(bits):
    pos = ALARM1_SECONDS_REG
    for bit in reversed(bits):
        reg = bus.read_byte_data(DS3231, pos)
        if bit:
            reg = reg | 0x80
        else:
            reg = reg & 0x7F
        bus.write_byte_data(DS3231, pos, reg)
        pos = pos + 1

def enable_alarm1():
    reg = bus.read_byte_data(DS3231, CONTROL_REG)
    bus.write_byte_data(DS3231, CONTROL_REG, reg | 0x05)

def clear_alarm1_flag():
    reg = bus.read_byte_data(DS3231, STATUS_REG)
    bus.write_byte_data(DS3231, STATUS_REG, reg & 0xFE)

def check_alarm1_triggered():
    return bus.read_byte_data(DS3231, STATUS_REG) & 0x01 != 0

def set_timer(hours, minutes, seconds):
    # zero the clock
    write_time_to_clock(SECONDS_REG, 0, 0, 0)
    # set the alarm
    write_time_to_clock(ALARM1_SECONDS_REG, hours, minutes, seconds)
    # set the alarm to match hours minutes and seconds
    # need to set some flags
    set_alarm1_mask_bits((True, False, False, False))
    enable_alarm1()
    clear_alarm1_flag()

#
# Your sensor behaviour goes here
#
set_timer(1,30,0)

The set_timer function is called to set the timer and clear the alarm flag. This resets the alarm signal and powers off the sensor. The example above will cause the sensor to shut down for 1 hour 30 minutes.

You can use any other microcontroller that implements I2C

Power down

The SensorAction program turns off your Raspberry Pi without shutting it down properly, which is something your mother probably told you never to do. The good news is that in extensive testing, we’ve not experienced any problems with this. However, if you want to make your Raspberry Pi totally safe in this situation, you should make its file system ‘read-only’, which means that it never changes during operation and therefore can’t be damaged by untimely power cuts. There are some good instructions from Adafruit here: hsmag.cc/UPgJSZ.

Note: making the operating system file store read-only does not prevent you creating a data logging application, but you would have to log the data to an external USB key or SD card and then dismount the storage device before killing the power.

If you are using a different device, such as an ESP8266 or an Arduino, you don’t need to worry about this as the software in them is inherently read-only.

The SQW output from the DS3231 will pull the gate of the MOSFET low to turn on the power to Raspberry Pi

Always running

To get the program to run when the Raspberry Pi boots, use the Nano editor to add a line at the end of the rc.local file that runs your program.

sudo nano /etc/rc.local

Use the line above at the command prompt to start editing the rc.local file and add the following line at the end of the file:

python3 /home/pi/SensorAction.py &

This statement runs Python 3, opens the SensorAction.py file, and runs it. Don’t forget the ampersand (&) at the end of the command: this starts your program as a separate process, allowing the boot to complete. Now, when Raspberry Pi boots up, it will run your program and then shut itself down. You can find a full sample application on the GitHub pages for this project (hsmag.cc/Yx7q6t). It logs air temperature, pressure, and humidity to an MQTT endpoint at regular intervals. Now, go and start tracking that marrow temperature!

Issue 30 of HackSpace magazine is out now

The latest issue of HackSpace magazine is on sale now, and you can get your copy from the Raspberry Pi Press online store. You can also download it for free to check it out first.

UK readers can take advantage of our special subscriptions offer at the moment.

3 issues for £10 & get a free book worth £10…

If you’re in the UK, get your first three issues of HackSpace magazine, The MagPi, Custom PC, or Digital SLR Photography delivered to your door for £10, and choose a free book (itself worth £10) on top!

The post Build low-power, clock-controlled devices appeared first on Raspberry Pi.

Special offer for magazine readers

Post Syndicated from Russell Barnes original https://www.raspberrypi.org/blog/special-offer-for-magazine-readers/

You don’t need me to tell you about the unprecedented situation that the world is facing at the moment. We’re all in the same boat, so I won’t say anything about it other than I hope you stay safe and take care of yourself and your loved ones.

The other thing I will say is that every year, Raspberry Pi Press produces thousands of pages of exciting, entertaining, and often educational content for lovers of computing, technology, games, and photography.

In times of difficulty, it’s not uncommon for people to find solace in their hobbies. The problem you’ll find yourself with is that it’s almost impossible to buy a magazine at the moment, at least in the UK: most of the shops that sell them are closed (and even most of their online stores are too).

We’re a proactive bunch, so we’ve done something about that:


From today, you can subscribe to The MagPi, HackSpace magazine, Custom PC, or Digital SLR Photography at a cost of three issues for £10 in the UK – and we’re giving you a little extra too.

We like to think we produce some of the best-quality magazines on the market today (and you only have to ask our mums if you want a second opinion). In fact, we’d go as far as to say our magazines are exactly the right mix of words and pictures for making the most of all the extra home-time you and your loved ones are having.

Take your pick for three issues at £10 and get a free book worth £10!

If you take us up on this offer, we’ll send the magazines direct to your door in the UK, with free postage. And we’re also adding a gift to thank you for signing up: on top of your magazines, you’ll get to choose a book that’s worth £10 in itself.

In taking up this offer, you’ll get some terrific reading material, and we’ll deliver it all straight to you — no waiting around. You’ll also be actively supporting our print magazines and the charitable work of the Raspberry Pi Foundation.

I hope that among our magazines, you’ll find something that’s of interest to you or, even better yet, something that sparks a new interest. Enjoy your reading!

The post Special offer for magazine readers appeared first on Raspberry Pi.

Build a physical game controller for Infinite Bunner

Post Syndicated from Andrew Gregory original https://www.raspberrypi.org/blog/build-a-physical-game-controller-for-infinite-bunner/

In HackSpace magazine issue 28 we had a look at how to create an ultrasonic controller for a version of Pong called Boing!. This month, we’re going to take a step further forward through video game history and look at the game Frogger. In this classic game, you control a frog as it makes its way across logs, roads, and train tracks, avoiding falling in the water or getting hit.

Infinite Bunner

The tribute to Frogger in the new Code the Classics Volume 1 book is called Infinite Bunner, and works in much the same way, except you control a bunny.

Jump along the logs, dodge the traffic, avoid the trains, and keep your bunny alive for as long as possible

All this hopping got us thinking about a controller. Our initial idea was that since the animals jump, so should the controller. An accelerometer can detect freefall, so it shouldn’t be too hard to convert that into button presses. However, it turns out that computer-controlled frogs and rabbits can jump much, much faster than humans can, and we really struggled to get a working game mechanic, so we compromised a little and worked with ‘flicks’.

The flick controller

The basic idea is that you tilt the controller left or right to move left or right, but you have to flick it up to register a jump (simply holding it upright won’t work).

We’ve used a Circuit Playground Bluefruit as our hardware, but it would work equally well with a Circuit Playground Express. There are two key parts to the software. The first is reading in accelerometer values and use these to know what orientation the board is in, and the second is the board mimicing a USB keyboard and sending keystrokes to any software running on it.

Playing Infinite Bunner

The first step is to get Infinite Bunner working on your machine.

Get your copy of Code the Classics today

You can download the code for all the Code the Classics Volume 1 games here. Click on Clone or Download > Download ZIP. Unzip the download somewhere.

You’ll need Python 3 with Pygame Zero installed. The process for this differs a little between different computers, but there’s a good overview of all the different options on page 186 of Code the Classics.

Subscribe to HackSpace magazine for twelve months and you get a Circuit Playground Express for free! Then you can make your very own Infinite Bunner controller

Once everything’s set up, open a terminal and navigate to the directory you unzipped the code in. Then, inside that, you should find a folder called bunner-master and move into that. You can then run:

python3 bunner.py

Have a few goes playing the game, and you’ll find that you need the left, right, and up arrow keys to play (there is also the down arrow, but we’ve ignored this since we’ve never actually used it in gameplay – if you’re a Frogger/Bunner aficionado, you may wish to implement this as well).

Reading the accelerometer is as easy as importing the appropriate module and running one line:

from adafruit_circuitplayground import cpx, y, z = cp.acceleration

Sending key presses is similarly easy. You can set up a keyboard with the following:

from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS
from adafruit_hid.keycode import Keycode

keyboard = Keyboard(usb_hid.devices)

Then send key presses with code such as this:

time.keyboard.press(Keycode.LEFT_ARROW) time.sleep(0.1)
keyboard.release_all()

The only thing left is to slot in our mechanics. The X-axis on the accelerometer can determine if the controller is tilted left or right. The output is between 10 (all the way left) and -10 (all the way right). We chose to threshold it at 7 and -7 to require the user to tilt it most of the way. There’s a little bit of fuzz in the readings, especially as the user flicks the controller up, so having a high threshold helps avoid erroneous readings.

The Y-axis is for jumping. In this case, we require a ‘flap’ where the user first lifts it up (over a threshold of 5), then back down again.

The full code for our controller is:

import time
from adafruit_circuitplayground import cp
import usb_hid
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS
from adafruit_hid.keycode import Keycode

keyboard = Keyboard(usb_hid.devices)

jumping = 0
up=False
while True:
    x, y, z = cp.acceleration
    if abs(y) > 5:
        up=True
    if y < 5 and up:
        keyboard.press(Keycode.UP_ARROW)
        time.sleep(0.3)
        keyboard.release_all()
        up=False
    if x < -7 :
        keyboard.press(Keycode.LEFT_ARROW)
        time.sleep(0.1)
        keyboard.release_all()
    if x < 7 : keyboard.press(Keycode.RIGHT_ARROW)
        time.sleep(0.1)
        keyboard.release_all()
        time.sleep(0.1)
    if jumping > 0:
        jumping=jumping-1

It doesn’t take much CircuitPython to convert a microcontroller into a games controller

The final challenge we had was that there’s a bit of wobble when moving the controller around – especially when trying to jump repeatedly and quickly. After fiddling with thresholds for a while, we found that there’s a much simpler solution: increase the weight of the controller. The easiest way to do this is to place it inside a book. If you’ve ever held a copy of Code the Classics, you’ll know that it’s a fairly weighty tome. Just place the board inside and close the book around it, and all the jitter disappears.

That’s all there is to the controller. You can use it to play the game, just as you would any joypad. Start the game as usual, then start flapping the book around to get hopping.

HackSpace magazine is out now

The latest issue of HackSpace magazine is out today and can be purchased from the Raspberry Pi Press online store. You can also download a copy if you want to see what all the fuss is about.


Code the Classics is available from Raspberry Pi Press as well, and comes with free UK shipping. And here’s a lovely video about Code the Classics artist Dan Malone and the gorgeous artwork he created for the book:

Code the Classics: Artist Dan Malone

No Description

The post Build a physical game controller for Infinite Bunner appeared first on Raspberry Pi.

Play Pong with ultrasonic sensors and a Raspberry Pi | HackSpace magazine

Post Syndicated from Andrew Gregory original https://www.raspberrypi.org/blog/play-pong-with-ultrasonic-sensors-and-a-raspberry-pi-hackspace-magazine/

Day three of our Pong celebration leads us here, to HackSpace magazine’s ultrasonic hack of Eben’s Code the Classics Pong tribute, Boing!

If you haven’t yet bought your copy of Code the Classics, you have until 11:59pm GMT tonight to get £1 off using the discount code PONG. Click here to visit the Raspberry Pi Press online store to secure your copy, and read on to see how you can use ultrasonic sensors to turn this classic game into something a lot more physical.

Over to the HackSpace magazine team…

Code the Classics is an entertaining book for a whole bunch of reasons, but one aspect of it that is particularly exciting to us makers is that it means there are some games out there that are really fun to play, but also written to be easy to understand and have high-quality game art to go along with them. Why does this excite us as makers? Because it makes them ideal candidates for testing out novel DIY games controllers!

Pong

We’re going to start right at the beginning of the book (and also at the beginning of computer game history) with the game Pong. There’s a great chapter on this seminal game in the book, but we’ll dive straight into the source code of our Boing! tribute game. This code should run on any computer with Python 3 (and a few dependencies) installed, but we’ll use a Raspberry Pi, as this has GPIO pins that we can use to add on our extra controller.

Download the code here by clicking the ‘Clone or download’ button, and then ‘Download ZIP’. Unzip the downloaded file, and you should have a directory called Code‑The‑Classics-master, and inside this, a directory called boing-master.

Open a terminal and navigate to this directory, then run:

python3 boing.py

If everything works well, you’ll get a screen asking you to select one or two players – press SPACE to confirm your selection, and have a play.

Hacking Code the Classics

So that’s how Eben Upton designed the game to be played. Let’s put our own spin on it. Games controllers are basically just sensors that take input from the real world in some way and translate that into in-game actions. Most commonly, these sensors are buttons that you press, but there’s no need for that to be the case. You can use almost any sensor you can get input from – it sounds trite, but the main limitation really is your imagination!

We were playing with ultrasonic distance sensors in the last issue of HackSpace magazine, and this sprung to mind a Pong controller. After all, distance sensors measure in one dimension and Pong bats travel in one dimension.

Last issue we learned that the main challenge when using the cheap HC-SR04 sensors with 3.3V devices is that they use 5V, so we need to reduce their output to 3.3V. A simple voltage divider does the trick, and we used three 330Ω resistors to achieve this – see Figure 1 for more details.

There’s support for these sensors in the GPIO Zero Python library. As a simple test, you can obtain the distance with the following Python code:

import gpiozero
import time
sensor = gpiozero.DistanceSensor(echo=15,trigger=14)

while True:
    print(sensor.distance)

time.sleep(0.1)

That will give you a constant read-out of the distance between the ultrasonic sensor and whatever object is in front of it. If you wave your hand around in front of the sensor, you’ll see the numbers changing from 0 to 1, which is the distance in metres.

So far, so straightforward. We only need to add a few bits to the code of our Boing! game to make it interact with the sensor. You can download an updated version of Boing! here, but the changes are as follows.

Add this line to the import statements at the top:

import gpiozero

Add this line to instantiate the distance sensor object at the end of the file (just before pgzrun.go()):

p1_distance = DistanceSensor(echo=15,trigger=14,queue_len=5)

We added the queue_len parameter to get the distances through a little quicker.

Finally, overwrite the p1_controls function with the following:

def p1_controls():
    move = 0
    distance = p1_distance.distance
    print(distance)
    if distance < 0.1:
        move = PLAYER_SPEED
    elif distance > 0.2:
        move = -PLAYER_SPEED
    return move

This uses the rather arbitrary settings of 10 cm and 20 cm to define whether the paddle moves up or down. You can adjust these as required.

That’s all there is to our ultrasonic Pong. It’s great fun to play, but there are, no doubt, loads of other versions of this classic game you can make by adding different sensors. Why not see what you can come up with?

Code the Classics

Today is the last day to get £1 off Code the Classics with the promo code PONG, so visit the Raspberry Pi Press online store to order your discounted copy before 11:59pm GMT tonight.

You can also download Code the Classics as a free PDF here, but the book, oh, the book – it’s a marvellous publication that deserves a physical presence in your home.

The post Play Pong with ultrasonic sensors and a Raspberry Pi | HackSpace magazine appeared first on Raspberry Pi.

How to play sound and make noise with your Raspberry Pi

Post Syndicated from Andrew Gregory original https://www.raspberrypi.org/blog/how-to-play-sound-and-make-noise-with-your-raspberry-pi/

If your amazing project is a little too quiet, add high-fidelity sound with Raspberry Pi and the help of this handy guide from HackSpace magazine, written by PJ Evans.

The PecanPi HAT features best-in-class components and dual DACs for superior audio reproduction

It’s no surprise that we love microcontrollers at HackSpace magazine. Their versatility and simplicity make them a must for electronics projects. Although a dab hand at reading sensors or illuminating LEDs, Arduinos and their friends do struggle when it comes to high-quality audio. If you need to add music or speech to your project, it may be worth getting a Raspberry Pi computer to do the heavy lifting. We’re going to look at the various audio output options available for our favourite small computer, from a simple buzz, through to audiophile bliss.

Get buzzing

Need to keep it simple and under a pound?
An active buzzer is what you need

The simplest place to start is with the humble buzzer. A cheap active buzzer can be quickly added to Raspberry Pi’s GPIO. It’s surprisingly easy too. Try connecting a buzzer’s red wire (positive) to GPIO pin 22 (Broadcom numbering) and the black wire (ground) to any GND pin. Now, install the GPIO Zero Python library by typing this at the command line:

sudo apt install python3-gpiozero

Create a file called buzz.py in your favourite editor and enter the following:

import time
from gpiozero import Buzzer
buzzer = Buzzer(22)
buzzer.on()
time.sleep(1)
buzzer.off()

Run it at the command line:

python3 buzz.py

You should hear a one-second buzz. See if you can make Morse code sounds by changing the duration of the sleep statement.

Passive but not aggressive

Raspberry Pi computers, with the exception of the Zero range, all have audio output on board. The original Raspberry Pi featured a stereo 3.5mm socket, and all A and B models since feature a four-pole socket that also includes composite video. This provides your cheapest route to getting audio from your Raspberry Pi computer.

A low-cost passive speaker can be directly plugged in to provide sound, albeit probably quieter than you’d like. Of course, add an amplifier or active speaker and you have sound as loud as you like. This is the most direct way of adding sound to your project, but how to get the sound out?

Need a simple solution? USB audio devices come in all shapes and sizes but are mostly plug-and-play

Normally, the Raspbian operating system will recognise that an audio device has been connected and route audio through it. Sometimes, especially if you’ve connected an HDMI monitor with sound capability (e.g. an HDMI TV), sound will not come out of the correct device.

To fix this, open up a terminal window and run sudo raspi-config. When the menu appears, go to Advanced Options and select Audio, then select the option to force the output through the audio jack. You may need to reboot Raspbian for all changes to take effect.

Plug and playback

A USB sound device is another simple choice for audio playback on Raspberry Pi. Literally hundreds are available, and a basic input/output device with better audio quality than the on-board system can be purchased for a few pounds online. Installation tends to be no more complicated than plugging the device into the USB port. You may need to select the new output, as the underlying audio system, ALSA (see the ALSA and PulseAudio section for more), may mute it by default. To fix this, run alsamixer from the command line, press F6 to select the new sound device, and if you see ‘MM’ at the bottom of the volume indicator, press M to unmute and adjust the volume with the cursor keys.

Many DACs also come with on-board amplifiers. Perfect for passive speakers

Unsurprisingly, when choosing your USB sound device, you can start at a few pounds and go right up to professional equipment costing hundreds. As they are low-power, USB devices do not tend to feature amplification, unless they have a separate power source.

Let’s play

The simplest way to play audio on Raspbian is to use OMXPlayer. This is a dedicated hardware-accelerated command-line tool that takes full advantage of Raspberry Pi’s capabilities. It sends audio to the analogue audio jack by default, so playing back an MP3 file is as simple as running:

omxplayer /path/to/audio/file.wav

There are many command-line options that allow you to control how the audio is played. Want the audio to loop forever? Just add --loop to the command. You’ll notice that when it’s running, OMXPlayer provides a user interface of sorts, allowing you to control playback from within the terminal. If you’d just like it to run in the background without user input, run the command like this:

omxplayer --no-keys example.wav &

Here, —-no-keys removes the interface, and the ampersand (&) tells the operating system to run the job ‘in the background’ so that it won’t block anything else you want to do.

OMXPlayer is a great choice for Raspbian, but other players such as mpg321 are available, so find the tool that’s best for you.

Another useful utility is speaker-test. This can produce white noise or vocal confirmation so you can check your speakers are working properly. It’s as simple as this:

speaker-test -t wav -c 2

The first parameter sets the sound to be a voice, and the -c tests stereo channels only: front left and front right.

Phat Beats

If space is an issue, a Raspberry Pi 4, amplifier, and speaker may not be what you have in mind. After all, your cool wearable project is going to be problematic if you’re trailing an amplifier on a cart with a 50-metre extension lead powering everything. Luckily, the clever people at Pimoroni have you covered. The Speaker pHAT is a Raspberry Pi Zero-sized HAT that not only adds audio capability to the smallest of the Raspberry Pi family, but also sports a 3 W speaker. Now you can play any audio with a tiny device and a USB battery pack.

Small, cheap, and fun, the Speaker pHat features a 3 W speaker and LED VU meter

The installation process is fully automated, so no messing around with drivers and config files. Once the script has completed, you can run any audio tool as before, and the sound will be routed through the speaker. No, the maximum volume won’t be troubling any heavy metal concerts, but you can’t knock the convenience and form factor.

Playing the blues

An easy way to get superior audio quality using a Raspberry Pi computer is Bluetooth. Recent models such as the 3B, 4, and even the Zero W support Bluetooth devices, and can be paired with most Bluetooth speakers, even from the command line. Once connected, you have a range of options on size and output power, plus the advantage of wireless connectivity.

Setting up a Bluetooth connection, especially if you are using the command line, can be a little challenging (see the Bluetooth cheatsheet section). There is a succinct guide here: hsmag.cc/N6p2IB. If you are using Raspbian Desktop, it’s a lot easier. Simply click on the Bluetooth logo on the top-right, and follow the instructions to pair your device.

If you find OMXPlayer isn’t outputting any audio, try installing mpg321:

sudo apt install mpg321

And try again:

mpg321 /path/to/audio/file.mp3

But seriously

If your project needs good audio, and the standard 3.5 mm output just isn’t cutting it, then it’s time to look at the wide range of DACs (digital-to-analogue converters) available in HAT format. It’s a crowded market, and the prices vary significantly depending on what you want from your device. Let’s start at the lower end, with major player HiFiBerry’s DAC+ Zero. This tiny HAT adds 192kHz/24-bit playback via two RCA phono ports for £12.50. If you’re serious about your audio, then you can consider the firm’s full HAT format high-resolution DAC+ Pro for £36, or really go for it with the DSP (digital sound processing) version for £67. All of these will require amplification, but the sound quality will rival audio components of a much higher price.

Money no object? The Allo Katana is a monster DAC, and weighs in at £240, but outperforms £1000 equivalents

If money is no object and your project requires the best possible reproduction, then you can consider going full audiophile. There are some amazing high-end HATs out there, but one of the best-performing ones we’ve seen is the PecanPi DAC. Its creator Leonid Ayzenshtat sourced each individual component carefully, always choosing the best-in-class. He even used a separate DAC for each audio channel. The resulting board may make your wallet wince at around £200 for the bare board, but the resulting audio is good enough to be used in professional recording studios. If you’ve restored a gorgeous old radio back to showroom condition, you could do a lot worse than add the board in with a great amp and speaker.

ALSA and PulseAudio

There’s often confusion between these two systems. Raspbian comes pre-installed with ALSA (Advanced Linux Sound Architecture), which is the low-level software that makes sound work. It comes with a range of utilities to control output device, volume, and more. PulseAudio is a software layer that sits on top of ALSA to provide more features, including streaming capabilities. Chances are, if you need to do something a bit more clever than just play audio, you’ll need to install a PulseAudio server.

Bluetooth cheatsheet

If you want to pair a Bluetooth audio device (A2DP) on the command line, it can be a little hairy. Here’s a quick guide:

First-time installation:

sudo apt-get install pulseaudio pulseaudio-module-bluetooth
sudo usermod -G bluetooth -a pi
sudo reboot

Start the PulseAudio server:

pulseaudio --start

Run the Bluetooth utility:

bluetoothctl

Put your speaker into pairing mode. Now, within the utility, run the following commands (pressing Enter after each one):

power on
agent on
scan on

Now wait for the list to populate. When you see your device…
pair <dev>
Where <dev> is the displayed long identifier for your device. You can just type in the first few characters and press Tab to auto-complete. Do the same for the following steps.

trust <dev>
connect <dev>

Wait for the confirmation, then enter:

quit <dev>

Now try to play some audio using aplay (for WAV files) or mpg321 (for mp3). These instructions are adapted from the guide by Actuino at hsmag.cc/N6p2IB.

File types

There are command-line players available for just about every audio format in common use. Generally, MP3 provides the best balance of quality and space, but lower bit-rates result in lower sound quality. WAV is completely uncompressed, but can eat up your SSD card. If you don’t want to compromise on audio quality, try FLAC, which is identical in quality to WAV, but much smaller. To convert between audio types, consider installing FFmpeg, a powerful audio and video processing tool.

HackSpace magazine

This article comes direct from HackSpace magazine issue 28, out now and available in print from your local newsagent, the Raspberry Pi Store in Cambridge, and online from Raspberry Pi Press.

If you love HackSpace magazine as much as we do, why not have a look at the subscription offers available, including the 12-month deal that comes with a free Adafruit Circuit Playground! Subscribers in the USA can now get a 12-month subscription for $60 when joining by the end of March!

And, as always, you can download the free PDF from the Raspberry Pi Press website.

The post How to play sound and make noise with your Raspberry Pi appeared first on Raspberry Pi.

USA magazine subscriptions offer: 48% off standard prices

Post Syndicated from Alex Bate original https://www.raspberrypi.org/blog/usa-magazine-subscriptions-offer-48-off-standard-prices/

Today we’re launching a time-limited special offer on subscriptions to HackSpace magazine and The MagPi magazine for readers in the USA, saving you a whopping 48% compared to standard overseas subscriptions. We want to help as many people as possible get their hands on our fantastic publications.

Starting today, you can subscribe to these magazines for the discounted price of $60 a year – just $5 per issue. Not only will you receive twelve issues direct to your door, but you’ll also receive a free gift and save up to 35% compared with newsstand prices!

You’ll need to be quick – this discounted offer is only running until 31 March 2020.

HackSpace magazine

HackSpace magazine is packed with projects for fixers and tinkerers of all abilities. We’ll teach you new techniques and give you refreshers on familiar ones, from 3D printing, laser cutting, and woodworking to electronics and the Internet of Things. HackSpace magazine will inspire you to dream bigger and build better.

Your $60 subscription will get you twelve issues per year and a free Adafruit Circuit Playground Express, worth $25. Click here to subscribe today!

The MagPi magazine

The MagPi is the official Raspberry Pi magazine. Written by and for the community, it’s packed with Raspberry Pi-themed projects, computing and electronics tutorials, how-to guides, and the latest news and reviews.

Your $60 subscription will get you twelve issues per year and a free Raspberry Pi Zero W with accessories. Click here to subscribe today!

The post USA magazine subscriptions offer: 48% off standard prices appeared first on Raspberry Pi.

3D printing infill patterns — what, why, and why not!

Post Syndicated from Alex Bate original https://www.raspberrypi.org/blog/3d-printing-infill-patterns-what-why-and-why-not/

How many types of infill pattern have you tried? The latest video from Raspberry Pi Press takes a closer look at 3D printing infill patterns, and why you may want to use a certain pattern over another.

3D PRINTING INFILL PATTERNS – What, why, and why not! || HackSpace magazine

There’s more than one option when it comes to selecting infill patters for your 3D prints. But what are the differences, and why should you use one over the other? #HackSpacemagazine is the monthly magazine for people who love to make things and those who want to learn.

Raspberry Pi Press publishes a variety of magazines and books, and the Raspberry Pi Press YouTube channel covers them all. Subscribe today to keep up to date with all new video releases, and let us know in the video comments what other content you’d like to see.

The post 3D printing infill patterns — what, why, and why not! appeared first on Raspberry Pi.

Our brand-new HackSpace magazine trailer

Post Syndicated from Alex Bate original https://www.raspberrypi.org/blog/our-brand-new-hacksapce-magazine-trailer/

Our brand-new trailer for HackSpace magazine is very pretty. Here, have a look for yourself.

THIS IS MAKING || Hackspace magazine

HackSpace magazine is the new monthly magazine for people who love to make things and those who want to learn. Grab some duct tape, fire up a microcontroller, ready a 3D printer and hack the world around you!

As we mentioned last week, this month’s HackSpace magazine contains a very cool Raspberry Pi special feature that we know you’ll all love.

HackSpace magazine is available at major newsagents in the UK, at the Raspberry Pi store, Cambridge, at Barnes & Noble in the US, and in our online store.

You can also download the latest issue as a free PDF, so if you’re new to HackSpace, there really is no reason not to give it a go. We know you’re going to love it.

The post Our brand-new HackSpace magazine trailer appeared first on Raspberry Pi.

HackSpace’s 25 ways to use a Raspberry Pi

Post Syndicated from Alex Bate original https://www.raspberrypi.org/blog/hackspaces-25-ways-to-use-a-raspberry-pi/

The latest issue of HackSpace magazine is out today, and it features a rather recognisable piece of tech on the front cover.

25 ways of using this tiny computer

From personal computing and electronic fashion to robotics and automatic fabrication, Raspberry Pi is a rather adaptable piece of kit. And whether you choose to use the new Raspberry Pi 4, or the smaller, $5 Raspberry Pi Zero, there are plenty of projects out there for even the most novice of hobbyists to get their teeth into.

This month’s HackSpace magazine, a product of Raspberry Pi Press, is packed full of some rather lovely Raspberry Pi projects, as well as the magazine’s usual features from across the maker community. So, instead of us sharing one of the features with you, as we usually do on release day, we wanted to share them all with you.

Free PDF download

Today’s new issue of HackSpace is available  as a free PDF download, and, since you’re reading this post, I imagine you’re already a Raspberry Pi fan, so it makes sense you’ll also like this magazine.

So download the free PDF (the download button is below the cover image) and let us know what you think of HackSpace magazine in the comments below.

More from HackSpace magazine

If you enjoy it and want to read more, you can get a HackSpace magazine subscription or purchase copies from Raspberry Pi Press online store, from the Raspberry Pi store, Cambridge, or from your local newsagent.

As with all our magazines, books, and hardware, every purchase of HackSpace magazine funds the charitable work of the Raspberry Pi Foundation. So if you enjoy this free PDF, please consider purchasing future issues. We’d really appreciate it.

The post HackSpace’s 25 ways to use a Raspberry Pi appeared first on Raspberry Pi.

How to set up OctoPrint on your Raspberry Pi

Post Syndicated from Alex Bate original https://www.raspberrypi.org/blog/how-to-set-up-octoprint-on-your-raspberry-pi/

If you own a 3D printer, you’ll likely have at least heard of OctoPrint from the ever benevolent 3D printing online community. It has the potential to transform your 3D printing workflow for the better, and it’s very easy to set up. This guide will take you through the setup process step by step, and give you some handy tips along the way.

Octoprint

Before we start finding out how to install OctoPrint, let’s look at why you might want to. OctoPrint is a piece of open-source software that allows us to add WiFi functionality to any 3D printer with a USB port (which is pretty much all of them). More specifically, you’ll be able to drop files from your computer onto your printer, start/stop prints, monitor your printer via a live video feed, control the motors, control the temperature, and more, all from your web browser. Of course, with great power comes great responsibility — 3D printers have parts that are hot enough to cause fires, so make sure you have a safe setup, which may include not letting it run unsupervised.

OctoPrint ingredients

• Raspberry Pi 3 (or newer)
MicroSD card
• Raspberry Pi power adapter
• USB cable (the connector type will depend on your printer)
• Webcam/Raspberry Pi Camera Module (optional)
• 3D-printed camera mount (optional)

Before we get started, it is not recommended that anything less than a Raspberry Pi 3 is used for this project. There have been reports of limited success using OctoPrint on a Raspberry Pi Zero W, but only if you have no intention of using a camera to monitor your prints. If you want to try this with a Pi Zero or an older Raspberry Pi, you may experience unexpected print failures.

Download OctoPi

Firstly, you will need to download the latest version of OctoPi from the OctoPrint website. OctoPi is a Raspbian distribution that comes with OctoPrint, video streaming software, and CuraEngine for slicing models on your Raspberry Pi. When this has finished downloading, unzip the file and put the resulting IMG file somewhere handy.

Next, we need to flash this image onto our microSD card. We recommend using Etcher to do this, due to its minimal UI and ease of use; plus it’s also available to use on both Windows and Mac. Get it here: balena.io/etcher. When Etcher is installed and running, you’ll see the UI displayed. Simply click the Select Image button and find the IMG file you unzipped earlier. Next, put your microSD card into your computer and select it in the middle column of the Etcher interface.

Finally, click on Flash!, and while the image is being burned onto the card, get your WiFi router details, as you’ll need them for the next step.

Now that you have your operating system, you’ll want to add your WiFi details so that the Raspberry Pi can automatically connect to your network after it’s booted. To do this, remove the microSD card from your computer (Etcher will have ‘ejected’ the card after it has finished burning the image onto it) and then plug it back in again. Navigate to the microSD card on your computer — it should now be called boot — and open the file called octopi-wpa-supplicant.txt. Editing this file using WordPad or TextEdit can cause formatting issues; we recommend using Notepad++ to update this file, but there are instructions within the file itself to mitigate formatting issues if you do choose to use another text editor. Find the section that begins ## WPA/WPA2 secured and remove the hash signs from the four lines below this one to uncomment them. Finally, replace the SSID value and the PSK value with the name and password for your WiFi network, respectively (keeping the quotation marks). See the example below for how this should look.

Further down in the file, there is a section for what country you are in. If you are using OctoPrint in the UK, leave this as is (by default, the UK is selected). However, if you wish to change this, simply comment the UK line again by adding a # before it, and uncomment whichever country you are setting up OctoPrint in. The example below shows how the file will look if you are setting this up for use in the US:

# Uncomment the country your Pi is in to activate Wifi in RaspberryPi 3 B+ and above
# For full list see: https://en.wikipedia.org/ wiki/ISO_3166-1_alpha-2
#country=GB # United Kingdom
#country=CA # Canada
#country=DE # Germany
#country=FR # France
country=US # United States

When the changes have been made, save the file and then eject/unmount and remove the microSD card from your computer and put it into your Raspberry Pi. Plug the power supply in, and go and make a cup of tea while it boots up for the first time (this may take around ten minutes). Make sure the Raspberry Pi is running as expected (i.e. check that the green status LED is flashing intermittently). If you’re using macOS, visit octopi.local in your browser of choice. If you’re using Windows, you can find OctoPrint by clicking on the Network tab in the sidebar. It should be called OctoPrint instance on octopi – double-clicking on this will open the OctoPrint dashboard in your browser.

If you see the screen shown above, then congratulations! You have set up OctoPrint.

Not seeing that OctoPrint splash screen? Fear not, you are not the first. While a full list of issues is beyond the scope of this article, common issues include: double-checking your WiFi details are entered correctly in the octopi-wpa-supplicant.txt file, ensuring your Raspberry Pi is working correctly (plug the Raspberry Pi into a monitor and watch what happens during boot), or your Raspberry Pi may be out of range of your WiFi router. There’s a detailed list of troubleshooting suggestions on the OctoPrint website.

Printing with OctoPrint

We now have the opportunity to set up OctoPrint for our printer using the handy wizard. Most of this is very straightforward — setting up a password, signing up to send anonymous usage stats, etc. — but there are a few sections which require a little more thought.

We recommend enabling the connectivity check and the plug-ins blacklist to help keep things nice and stable. If you plan on using OctoPrint as your slicer as well as a monitoring tool, then you can use this step to import a Cura profile. However, we recommend skipping this step as it’s much quicker (and you can use a slicer of your choice) to slice the model on your computer, and then send the finished G-code over.

Finally, we need to put in our printer details. Above, we’ve included some of the specs of the Creality Ender-3 as an example. If you can’t find the exact details of your printer, a quick web search should show what you need for this section.

The General tab can have anything in it, it’s just an identifier for your own use. Print bed & build volume should be easy to find out — if not, you can measure your print bed and find out the position of the origin by looking at your Cura printer profile. Leave Axes as default; for the Hotend and extruder section, defaults are almost certainly fine here (unless you’ve changed your nozzle; 0.4 is the default diameter for most consumer printers).

OctoPrint is better with a camera

Now that you’re set up with OctoPrint, you’re ready to start printing. Turn off your Raspberry Pi, then plug it into your 3D printer. After it has booted up, open OctoPrint again in your browser and take your newly WiFi-enabled printer for a spin by clicking the Connect button. After it has connected, you’ll be able to set the hot end and bed temperature, then watch as the real-time readings are updated.

In the Control tab, we can see the camera stream (if you’re using one) and the motor controls, as well as commands to home the axes. There’s a G-code file viewer to look through a cross-section of the currently loaded model, and a terminal to send custom G-code commands to your printer. The last tab is for making time-lapses; however, there is a plug-in available to help with this process.

Undoubtedly the easiest way to set up video monitoring of your prints is to use the official Raspberry Pi Camera Module. There are dozens of awesome mounts on Thingiverse for a Raspberry Pi Camera Module, to allow you to get the best angle of your models as they print. There are also some awesome OctoPrint-themed Raspberry Pi cases to house your new printer brains. While it isn’t officially supported by OctoPrint, you can use a USB webcam instead if you have one handy, or just want some very high-quality video streams. The OctoPrint wiki has a crowdsourced list of webcams known to work, as well as a link for the extra steps needed to get the webcam working correctly.

As mentioned earlier, our recommended way of printing a model using OctoPrint is to first use your slicer as you would if you were creating a file to save to a microSD card. Once you have the file, save it somewhere handy on your computer, and open the OctoPrint interface. In the bottom left of the screen, you will see the Upload File button — click this and upload the G-code you wish to print.

You’ll see the file/print details appear, including information on how long it’ll take for the object to print. Before you kick things off, check out the G-code Viewer tab on the right. You can not only scroll through the layers of the object, but, using the slider at the bottom, you can see the exact pattern the 3D printer will use to ‘draw’ each layer. Now click Print and watch your printer jump into action!

OctoPrint has scores of community-created plug-ins, but our favourite, Octolapse, makes beautiful hypnotic time-lapses. What makes them so special is that the plug-in alters the G-code of whatever object you are printing so that once each layer has finished, the extruder moves away from the print to let the camera take an unobstructed shot of the model. The result is an object that seems to grow out of the build plate as if by magic. You’ll not find a finer example of it than here.

Satisfying 3D Prints TimeLapse episode 7 (Prusa I3 Mk3 octopi)

3D Printing timelapses of models printed on the Prusa i3 MK3! Here’s another compilation of my recent timelapses. I got some shots that i think came out really great and i hope you enjoy them! as always if you want to see some of these timelapses before they come out or want to catch some behind the scenes action check out my instagram!

Thanks to Glenn and HackSpace magazine

This tutorial comes fresh from the pages of HackSpace magazine issue 26 and was written by Glenn Horan. Thanks, Glenn.

To get your copy of HackSpace magazine issue 26, visit your local newsagent, the Raspberry Pi Store, Cambridge, or the Raspberry Pi Press online store.

Fans of HackSpace magazine will also score themselves a rather delightful Adafruit Circuit Playground Express with a 12-month subscription. Sweet!

The post How to set up OctoPrint on your Raspberry Pi appeared first on Raspberry Pi.

Raspberry Pi 3 baby monitor | Hackspace magazine #26

Post Syndicated from Andrew Gregory original https://www.raspberrypi.org/blog/raspberry-pi-3-baby-monitor-hackspace-magazine-26/

You might have a baby/dog/hamster that you want to keep an eye on when you’re not there. We understand: they’re lovely, especially hamsters. Here’s how HackSpace magazine contributor Dr Andrew Lewis built a Raspberry Pi baby cam to watch over his small creatures…

When a project is going to be used in the home, it pays to take a little bit of extra time on appearance

Wireless baby monitors

You can get wireless baby monitors that have a whole range of great features for making sure your little ones are safe, sound, and sleeping happily, but they come with a hefty price tag.

In this article, you’ll find out how to make a Raspberry Pi-powered streaming camera, and combine it with a built-in I2C sensor pack that monitors temperature, pressure, and humidity. You’ll also see how you can use the GPIO pins on Raspberry Pi to turn an LED night light on and off using a web interface.

The hardware for this project is quite simple, and involves minimal soldering, but the first thing you need to do is to install Raspbian onto a microSD card for your Raspberry Pi. If you’re planning on doing a headless install, you’ll also need to enable SSH by creating an empty file called SSH on the root of the Raspbian install, and a file with your wireless LAN details called wpa_supplicant.conf.

You can download the code for this as well as the 3D-printable files from our GitHub. You’ll need to transfer the code to the Raspberry Pi. Next, connect the camera, the BME280 board, and the LEDs to the Raspberry Pi, as shown in the circuit diagram.

The BME280 module uses the I2C connection on pins 3 and 5 of the GPIO, taking power from pins 1 and 9. The LEDs connect directly to pins 19 and 20, and the camera cable fits into the camera connector.

Insert the microSD card into the Raspberry Pi and boot up. If everything is working OK, you should be able to see the IP address for your device listed on your hub or router, and you should be able to connect to it via SSH. If you don’t see the Raspberry Pi listed, check your wireless connection details and make sure your adapter is supplying enough power. It’s worth taking the time to assign your Raspberry Pi with a static IP address on your network, so it can’t change its IP address unexpectedly.

Smile for Picamera

Use the raspi-config application to enable the camera interface and the I2C interface. If you’re planning on modifying the code yourself, we recommend enabling VNC access as well, because it will make editing and debugging the code once the device is put together much easier. All that remains on the software side is to update APT, download the babycam.py script, install any dependencies with PIP, and set the script to run automatically. The main dependencies for the babycam.py script are the RPi.bme280 module, Flask, PyAudio, picamera, and NumPy. Chances are that these are already installed on your system by default, with the exception of RPi.bme280, which can be installed by typing sudo pip3 install RPi.bme280 from the terminal. Once all of the dependencies are present, load up the script and give it a test run, and point your web browser at port 8000 on the Raspberry Pi. You should see a webpage with a camera image, controls for the LED lights, and a read-out of the temperature, pressure, and humidity of the room.

Finishing a 3D print by applying a thin layer of car body filler and sanding back will give a much smoother surface. This isn’t always necessary, but if your filament is damp or your nozzle is worn, it can make a model look much better when it’s painted

The easiest way to get the babycam.py script to run on boot is to add a line to the rc.local file. Assuming that the babycam.py file is located in your home directory, you should add the line python3 /home/pi/babycam.py to the rc.local file, just before the line that reads exit 0. It’s very important that you include the ampersand at the end of the line, otherwise the Python script will not be run in a separate process, the rc.local file will never complete, and your Raspberry Pi will never boot.

Tinned Raspberry Pi

With the software and hardware working, you can start putting the case together. You might need to scale the 3D models to suit the tin can you have before you print them out, so measure your tin before you click Print. You’ll also want to remove any inner lip from the top of the can using a can opener, and make a small hole in the side of the can near the bottom for the USB power cable. Next, make a hole in the bottom of the can for the LED cables to pass through.

If you want to add more than a couple of LEDs (or want to use brighter LEDs), you should connect your LEDs to the power input, and use a transistor on the GPIO to trigger them

If you haven’t already done so, solder appropriate leads to your LEDs, and don’t forget to put a 330 Ω resistor in-line on the positive side. The neck of the camera is supported by two lengths of aluminium armature wire. Push the wire up through each of the printed neck pieces, and use a clean soldering iron to weld the pieces together in the middle. Push the neck into the printed top section, and weld into place with a soldering iron from underneath. Be careful not to block the narrow slot with plastic, as this is where the camera cable passes up through the neck and into the camera.

You need to mount the BME280 so that the sensor is exposed to the air in the room. Do this by drilling a small hole in the 3D-printed top piece and hot gluing the sensor into position. If you’re going to use the optional microphone, you can add an extra hole and glue the mic into place in the same way. A short USB port extender will give you enough cable to plug the USB microphone into the socket on your Raspberry Pi

Paint the tin can and the 3D-printed parts. We found that spray blackboard paint gives a good effect on 3D-printed parts, and PlastiKote stone effect paint made the tin can look a little more tactile than a flat colour. Once the paint is dry, pass the camera cable up through the slot in the neck, and then apply the heat-shrink tubing to cover the neck with a small gap at the top and bottom. Connect the camera to the top of the cable, and push the front piece on to hold it into place. Glue shouldn’t be necessary, but a little hot glue might help if the front parts don’t hold together well.

Push the power cable through the hole in the case, and secure it with a knot and some hot glue. Leave enough cable free to easily remove the top section from the can in future without stressing the wires.

If you’re having trouble getting the armature wire through the 3D-printed parts, try using a drill to help twist the wire through

This is getting heavy

Glue the bottom section onto the can with hot glue, and hot-glue the LEDs into place on the bottom, feeding the cable up through the hole and into the GPIO header. This is a good time to hot-glue a weight into the bottom of the can to improve its stability. I used an old weight from some kitchen scales, but any small weight should be fine. Finally, fix the Raspberry Pi into place on the top piece by either drilling or gluing, then reconnect the rest of the cables, and push the 3D-printed top section into the tin can. If the top section is too loose, you can add a little bit of hot glue to hold things together once you know everything is working.

With the right type of paint, even old tin cans make a good-looking enclosure
for a project

That should be all of the steps complete. Plug in the USB and check the camera from a web browser. The babycam.py script includes video, sensors, and light control. If you are using the optional USB microphone, you can expand the functionality of the app to include audio streaming, use cry detection to activate the LEDs (don’t make the LEDs too stimulating or you’ll never get a night’s sleep again), or maybe even add a Bluetooth speaker and integrate a home assistant.

HackSpace magazine issue 26

HackSpace magazine is out now, available in print from your local newsagent, the Raspberry Pi Store in Cambridge, and online from Raspberry Pi Press.

If you love HackSpace magazine as much as we do, why not have a look at the subscription offers available, including the 12-month deal that comes with a free Adafruit Circuit Playground!

And, as always, you can download the free PDF here.

The post Raspberry Pi 3 baby monitor | Hackspace magazine #26 appeared first on Raspberry Pi.

Make your own NFC data cufflinks

Post Syndicated from Alex Bate original https://www.raspberrypi.org/blog/make-your-own-nfc-data-cufflinks/

In this project, we’ll make a pair of NFC data cufflinks, ideal for storing a website URL, a password, or a secret message. This project is perfect for a sartorial spy who loves dry Martinis, and anyone who can’t remember their WiFi password.

NFC technology

NFC stands for near-field communication, and is a protocol that allows two devices to communicate wirelessly when they are physically near each other. An evolution of RFID, NFC is becoming increasingly popular in consumer technology, and is already commonly used in contactless payment systems and identification badges. NFC wristbands are also being used to create enhanced experiences for visitors at theme parks and other venues.

The rise of NFC hasn’t bypassed hobbyists and tinkerers, and companies like Pimoroni and Adafruit sell components that make it relatively easy to add NFC functionality to your projects. Here, we’ll make use of tiny NFC tags that can be read and written to by a smartphone or external NFC reader. The tags can be read through a non-metal barrier, like plastic, so we’ll embed the tag in resin to make an elegant cabochon for our cufflink. When complete, holding the cufflink to your smartphone or NFC reader will let you read or write data to the chip inside.

Micro NFC/RFID transponders

For this project we used the smallest NFC tags we could find, micro NFC/RFID transponders from Adafruit (product number 2800). These 15.6mm x 6mm flexible tags are formatted with the now standard NDEF format, and will work as-is with newer phones and most NFC readers. If you happen to pick up older Mifare Classic formatted tags, they may need to be reformatted as NDEF to work with your reader/writer. Reformatting isn’t a function of most NFC read/write apps, but it can be done with Adafruit’s PN532 NFC/RFID controller breakout board or shield.

If this is your first time working with resin epoxy, get ready for a new, fun kind of mess! Resin epoxy comes in two parts that must be mixed together in equal proportions before use. Once mixed, the resin will be workable for a short period of time before entering the curing phase and hardening completely. Figuring out exactly how much resin to mix up is definitely an art. There are even some online tools available to help calculate this. For a small project like this, just make sure you mix up a bit more than you think you’ll need.

You don’t want to run out during the pour and have to quickly mix up more at the last minute. If you’re tinting your resin, you definitely want to pour all of your pieces from the same mix, as it’s almost impossible to match the colour of one batch of resin to another.

All of this means you’ll undoubtedly end up with more than just two cabochons for one pair of cufflinks, and if you’re going to make a mess anyway, why not go big? Pick up a few extra NFC tags and plan to pour some other pieces, like pendants or key chain fobs. These make great holiday or birthday gifts that are both technologically advanced and crafty at the same time!

Resin-cast jewellery has been made for decades and there are loads of options for resin moulds available at craft stores and online. The best moulds for resin are made of silicone. Flexible silicone moulds make it easy to remove the hardened pieces, and produce ultra-shiny surfaces. Cufflink blanks, ring blanks, and pendant bails can also be purchased at jewellery supply stores. Refer to your moulds when choosing cufflink and ring blanks, to make sure that the blanks will work with the size of cabochon you’ve chosen to cast, and vice versa.

Licence to spill

Start by gathering your materials and setting up your workspace for working with resin. There will be a lot of stirring, pouring, and drips, and things are likely to get messy! Cover your work surface with paper and keep some paper towels nearby. Read and heed the safety warnings on your resin and hardener. Although some resins are considered non-toxic when used as directed, it’s always a good idea to work in a well-ventilated area and wear nitrile gloves to keep the resin off of your skin while working.

Once the two-part resin is mixed together, you will have a limited amount of time to pour the resin before it hardens, so planning and timing is key. Check the ‘pot life’ indicated on your resin; this is the amount of working time you’ll have after mixing before the resin begins to harden. Our resin had a pot life of 30 minutes. It can be helpful to set up a timer so you can keep track of time while you work.

If you have multiple moulds, decide which ones you will use before mixing, and make sure your NFC tags will fit into the shapes you plan to use. If you are making matching cufflinks, remember that you’ll need two identical shapes. Our tiny 15.6mm tags fit perfectly into 16mm cabochons. Remember that you will mix more resin than you need for just two cufflink cabochons, so it’s good to have extra moulds in front of you to pour into.

Prepare the NFC tags

Unwrap the NFC tags and make sure they are clean and ready to be embedded in the resin. For a light-up effect, you may want to combine a data tag with an LED tag, like we did in one of our extra pieces. The back of the NFC LED nail sticker is adhesive, so it was easy to stick it directly to the larger data tag.

Measure, mix, and pour

We mixed up about 6oz (170g) of resin, then tinted it green for a tech-emerald look. This was plenty for two cabochons and three to four extra shapes. Follow the manufacturer’s instructions to mix up your resin. Generally, it’s a 1:1 ratio by volume. A good method for this is to pour each part into matching containers, up to the same measuring mark. Then, pour both into a third cup and stir. Stir slowly, but thoroughly, for at least two or three minutes, making sure to scrape the sides of your mixing cup often. If the resin is not completely and evenly mixed, it will not cure properly. If tinting your resin, add the tint to your mixed resin one drop at a time, slowly deepening the colour to your preference.

Once your resin is mixed and tinted, you’ll notice lots of tiny bubbles that have been incorporated while you were stirring. Let the mixture rest for a few minutes so the bubbles can float to the top, then use a stick to move the bubbles to the side of your container and pop them.

When you’ve removed as many bubbles as possible, it’s time to pour! Place your moulds on a level surface where they’ll be able to sit undisturbed for the amount of time required to cure (check the manufacturer’s instructions; ours specified 24 hours curing time). Pour the resin in a thin stream into the deepest point of your mould, and let it slowly rise to just below the top lip of your mould. Don’t overfill the mould, or the resin will bow and have a convex bottom when you remove it from the mould. Pouring the resin in a thin stream can help pop larger bubbles that are still in the mix.

Embed the NFC tag

With the resin in your mould, you can slide the NFC tag into place. Using tweezers, dip the tag into your unpoured resin to coat it first – this will help the resin in your mould accept the tag without adding too many bubbles. Then, gently slide the tag into the mould and centre it in the resin. It will want to slowly sink to the bottom of the mould, and ideally it stays centred on the way down. You may need to wiggle it back into place with your tweezers or a thin stick, but try not to introduce any new bubbles.

After your resin is poured and the NFC tags are in place, let the resin sit in the moulds for about ten minutes. This is enough time for most of the bubbles to rise to the top surface. Then, spray a fine mist of isopropyl alcohol over the resin to pop the bubbles. This step is optional, but we noticed that it really helped achieve clearer results.

Repeat this process for all the moulds you want to pour and add NFC tags to. Check them after a few minutes to make sure your tag hasn’t slid out of place, and remember to keep an eye on your pot life timer. Finish all your fiddling and bubble popping before the resin starts to harden. Then, leave your resin to cure for the amount of time specified in your resin’s instructions.

Demould your resin pieces

When the resin has completely hardened, it’s time for the exciting part: removing the cured resin from the moulds. If using silicone moulds, your piece should release from the mould without much fuss. Gently flex the silicone to let air seep between the hardened resin and the wall of the mould. Then you should be able to carefully pull the resin piece out of the mould.

Take a moment to admire your shiny cabochons! If you discover that you’ve over-poured your moulds, or the resin has crept up the sides of the mould, making a curved back, don’t worry. Resin can be wet-sanded; just be sure to keep both the sandpaper and the piece underwater while sanding, and wear a mask to keep from inhaling resin particles.

Make the cufflinks

Use glue to affix the flat-backed cabochons to the cufflink blanks. We used E6000, which is an industrial-strength adhesive that works great on plastics. Again, be sure to work in a well-ventilated area, and wear a respirator while working with E6000.

Apply the glue to the cufflink blank and hold the cabochon in place while the glue sets. Make two, and you’re done! You could also glue the cabochons to ring blanks to make NFC data rings. For pendants, you can use jewellery findings like bails and jump rings to make necklaces or key-chain fobs.

Program the NFC tag

Now that you’ve made your NFC cufflinks, you can load them with data like a website, a password, or a secret message. There are a few methods for doing this. If you have an NFC-capable smartphone, such as an Android phone, you won’t need any additional hardware. You can download a free app like NFC Tools to write and read data on your cufflink. NFC Tasks, another free app, lets you create automatic actions for your phone to perform when the NFC tag is read.

If you have an iPhone, (at the time of publishing of this article) you cannot write directly to NFC tags from your phone. But don’t worry! You can still join the NFC fun by purchasing a USB NFC reader/writer. You’ll be able to read and write to NFC tags with your computer using the NFC Tools desktop app. Your author purchased the NFC reader/writer shown here for about $35 on Amazon.com. You can still use NFC Tools on your iPhone to read tags, and the latest version of iOS, 12.1, supports background NFC tag reading. Some basic actions, like opening a URL in a browser, can now be performed right from the home screen or lock screen – pretty cool!

For a more custom hardware/software approach, try Adafruit’s PN532 NFC/RFID controller breakout board, which lets you add NFC functionality to Raspberry Pi or Arduino projects. It takes some soldering and programming to set up, but this breakout gives you lower-level control of the NFC tag, and is supported by an Adafruit NFC Arduino library. The library includes handy example code for reading and writing to tags, and reformatting Mifare Classic tags with the NDEF format.

Sport your new cufflinks at your next dressy event, and you’ll be both covert and classy! Or, gift these to your favourite snappy dresser, loaded with a secret message for their eyes only. Heading to a conference? Instead of handing out a business card to connect with someone, hold your wrist over their smartphone to bring up your webpage. It’s not magic, it’s technology!

More wearable tech projects

You can find more tutorials like this in Wearable Tech Projects by Sophy Wong, a HackSpace magazine publication. Wearable Tech Projects is on sale now from the Raspberry Pi Press online store, and it’s available as part of the Raspberry Pi Store Black Friday sale this weekend.

The post Make your own NFC data cufflinks appeared first on Raspberry Pi.

Get started with… Arduino?

Post Syndicated from Alex Bate original https://www.raspberrypi.org/blog/get-started-ardunio/

Yes, you read that title right, and no, you haven’t accidentally stumbled upon the Arduino Foundation’s website. Today, we’re pleased to announce a new addition to the Raspberry Pi Press family: Get Started with Arduino, a complete how-to guide to help you get hands on with the other pocket-sized board.

But why?

Why not? Our mission is to put the power of computing and digital making into the hands of people all over the world. Whether you’re using a Raspberry Pi, an Arduino, or any other piece of digital making kit, if you’re creating with tech, we’re happy. And Raspberry Pi and Arduino make wonderful project partners for all kinds of build.

What’s in the book?

Get Started with Arduino is packed full of how-tos and project tutorials to help you get better acquainted with the little blue microcontroller. Whether you’re brand new to digital making, a die-hard Raspberry Pi fan looking to expand your maker skillset, or simply a bit of a bookworm, Get Started with Arduino is a super addition to your bookshelves.


Aren’t Raspberry Pi and Arduino the same kind of thing?

Arduino is a microcontroller, while Raspberry Pi is a full computer. Microcontrollers don’t usually run a mainstream operating system, but they’re extremely power-efficient, so they can be great for projects that can’t stay plugged into the mains. You need to use a separate computer to set up your Arduino, but you can do everything on a Raspberry Pi itself… including setting up an Arduino. As we said, the two work really well together in some projects: for example, you might build a robot where the Raspberry Pi handles intensive processing tasks and provides you with a friendly environment for developing your code, while the Arduino handles precise real-time control of the motors.

Buy Get Started with Arduino today

Get Started with Arduino is out now! It’s available from the Raspberry Pi Press website with free international shipping, from the Raspberry Pi Store in Cambridge, and from WHSmith in the UK; it’ll reach Barnes & Noble stores in the US in a week or so.

Also out today…

HackSpace magazine issue #25 is also out today, available from the Raspberry Pi Press website, the Raspberry Pi Store in Cambridge, and every newsagent that’s worth its salt.

And, if that’s not enough, Wireframe magazine issue 27 is also out today, and it too is available from Raspberry Pi Press, the Raspberry Pi Store, and newsagents across the UK.

But wait, there’s more!

In case you missed it, on Monday we released Retro Gaming with Raspberry Pi, your one-stop guide to creating and playing classic retro games on your Raspberry Pi.

Did someone say free?

For getting this far in today’s blog, here’s your reward: Get Started with Arduino, HackSpace magazine, Wireframe magazine and Retro Gaming with Raspberry Pi are all available as free PDF downloads. However, when you buy our publications, you’re supporting the work of the Raspberry Pi Foundation to bring computing to everyone, as well as the continued production of even more great magazines and special edition books. So, you know what to do.

The post Get started with… Arduino? appeared first on Raspberry Pi.

Listen to World War II radio recordings with a Raspberry Pi Zero

Post Syndicated from Alex Bate original https://www.raspberrypi.org/blog/listen-to-world-war-ii-radio-recordings-with-a-raspberry-pi-zero/

With the 50th anniversary of the D-Day landings very much in the news this year, Adam Clark found himself interested in all things relating to that era. So it wasn’t long before he found himself on the Internet Archive listening to some of the amazing recordings of radio broadcasts from that time. In this month’s HackSpace magazine, Adam details how he built his WW2 radio-broadcast time machine using a Raspberry Pi Zero W, and provides you with the code to build your own.

As good as the recordings on the Internet Archive were, it felt as if something was missing by listening to them on a modern laptop, so I wanted something to play them back on that was more evocative of that time, and would perhaps capture the feeling of listening to them on a radio set.

I also wanted to make the collection portable and to make the interface for selecting and playing the tracks as easy as possible – this wasn’t going to be screen-based!

Another important consideration was to house the project in something that would not look out of place in the living room, and not to give away the fact that it was being powered by modern tech.

So I came up with the idea of using an original radio as the project case, and to use as many of the original knobs and dials as possible. I also had the idea to repurpose the frequency dial to select individual years of the war and to play broadcasts from whichever year was selected.

Of course, the Raspberry Pi was immediately the first option to run all this, and ideally, I wanted to use a Raspberry Pi Zero to keep the costs down and perhaps to allow expansion in the future outside of being a standalone playback device.

Right off the bat, I knew that I would have a couple of obstacles to overcome as the Raspberry Pi Zero doesn’t have an easy way to play audio out, and I also wanted to have analogue inputs for the controls. So the first thing was to get some audio playing to see if this was possible.

Audio playback

The first obstacle was to find a satisfactory way to playback audio. In the past, I have had some success using PWM pins, but this needs a low-pass filter as well as an amplifier, and the quality of audio was never as good as I’d hoped for.

The other alternative is to use one of the many HATs available, but these come at a price as they are normally aimed at more serious quality of audio. I wanted to keep the cost down, so these were excluded as an option. The other option was to use a mono I2S 3W amplifier breakout board – MAX98357A from Adafruit – which is extremely simple to use.

As the BBC didn’t start broadcasting stereo commercially until the late 1950s, this was also very apt for the radio (which only has one speaker).
Connecting up this board is very easy – it just requires three GPIO pins, power, and the speaker. For this, I just soldered some female jumper leads to the breakout board and connected them to the header pins of the Raspberry Pi Zero. There are detailed instructions on the Adafruit website for this which basically entails running their install script.

I’d now got a nice playback device that would easily play the MP3 files downloaded from archive.org and so the next task was to find a suitable second-hand radio set.

Preparing the case

After a lot of searching on auction sites, I eventually found a radio that was going to be suitable: wasn’t too large, was constructed from wood, and looked old enough to convince the casual observer. I had to settle for something that actually came from the early 1950s, but it drew on design influences from earlier years and wasn’t too large as a lot of the real period ones tended to be (and it was only £15). This is a fun project, so a bit of leeway was fine by me in this respect.

When the radio arrived, my first thought as a tinkerer was perhaps I should get the valves running, but a quick piece of research turned up that I’d probably have to replace all the resistors and capacitors and all the old wiring and then hope that the valves still worked. Then discovering that the design used a live chassis running at 240 V soon convinced me that I should get back on track and replace everything.

With a few bolts and screws removed, I soon had an empty case.

I then stripped out all the interior components and set about restoring the case and dial glass, seeing what I could use by way of the volume and power controls. Sadly, there didn’t seem to be any way to hook into the old controls, so I needed to design a new chassis to mount all the components, which I did in Tinkercad, an online 3D CAD package. The design was then downloaded and printed on my 3D printer.

It took a couple of iterations, and during this phase, I wondered if I could use the original speaker. It turned out to be absolutely great, and the audio took on a new quality and brought even more authenticity to the project.

The case itself was pretty worn and faded, and the varnish had cracked, so I decided to strip it back. The surface was actually veneer, but you can still sand this. After a few applications of Nitromors to remove the varnish, it was sanded to remove the scratches and finished off with fine sanding.

The wood around the speaker grille was pretty cracked and had started to delaminate. I carefully removed the speaker grille cloth, and fixed these with a few dabs of wood glue, then used some Tamiya brown paint to colour the edges of the wood to blend it back in with the rest of the case. I was going to buy replacement cloth, but it’s fairly pricey – I had discovered a trick of soaking the cloth overnight in neat washing-up liquid and cold water, and it managed to lift the years of grime out and give it a new lease of life.

At this point, I should have just varnished or used Danish oil on the case, but bitten by the restoration bug I thought I would have a go at French polishing. This gave me a huge amount of respect for anyone that can do this properly. It’s messy, time-consuming, and a lot of work. I ended up having to do several coats, and with all the polishing involved, this was probably one of the most time-consuming tasks, plus I ended up with some pretty stained fingers as a result.

The rest of the case was pretty easy to clean, and the brass dial pointer polished up nice and shiny with some Silvo polish. The cloth was glued back in place, and the next step was to sort out the dial and glass.

Frequency, volume, glass, and knobs

Unfortunately, the original glass was cracked, so a replacement part was cut from some Makrolon sheet, also known as Lexan. I prefer this to acrylic as it’s much easier to cut and far less likely to crack when drilling it. It’s used as machine guards as well and can even be bent if necessary.

With the dial, I scanned it into the PC and then in PaintShop I replaced the existing frequency scale with a range of years running from 1939 to 1945, as the aim was for anyone using the radio to just dial the year they wanted to listen to. The program will then read the value of the potentiometer, and randomly select a file to play from that year.

It was also around about now that I had to come up with some means of having the volume control the sound and an interface for the frequency dial. Again there are always several options to consider, and I originally toyed with using a couple of rotary encoders and using one of these with the built-in push button as the power switch, but eventually decided to just use some potentiometers. Now I just had to come up with an easy way to read the analogue value of the pots and get that into the program.

There are quite a few good analogue-to-digital boards and HATs available, but with simplicity in mind, I chose to use an MCP3002 chip as it was only about £2. This is a two-channel analogue-to-digital converter (ADC) and outputs the data as a 10-bit value onto the SPI bus. This sounds easy when you say it, but it proved to be one of the trickier technical tasks as none of the code around for the four-channel MCP3008 seemed to work for the MCP3002, nor did many of the examples that were around for the MCP3002 – I think I went through about a dozen examples. At long last, I did find some code examples that worked, and with a bit of modification, I had a simple way of reading the values from the two potentiometers. You can download the original code by Stéphane Guerreau from GitHub. To use this on your Raspberry Pi, you’ll also need to run up raspi-config and switch on the SPI interface. Then it is simply a case of hooking up the MCP3002 and connecting the pots between the 3v3 line and ground and reading the voltage level from the wiper of the pots. When coding this, I just opted for some simple if-then statements in cap-Python to determine where the dial was pointing, and just tweaked the values in the code until I got each year to be picked out.

Power supply and control

One of the challenges when using a Raspberry Pi in headless mode is that it likes to be shut down in an orderly fashion rather than just having the power cut. There are lots of examples that show how you can hook up a push button to a GPIO pin and initiate a shutdown script, but to get the Raspberry Pi to power back up you need to physically reset the power. To overcome this piece of the puzzle, I use a Pimoroni OnOff SHIM which cleverly lets you press a button to start up, and then press and hold it for a second to start a shutdown. It’s costly in comparison to the price of a Raspberry Pi Zero, but I’ve not found a more convenient option. The power itself is supplied by using an old power bank that I had which is ample enough to power the radio long enough to be shown off, and can be powered by USB connector if longer-term use is required.

To illuminate the dial, I connected a small LED in series with a 270R resistor to the 3v3 rail so that it would come on as soon as the Raspberry Pi received power, and this lets you easily see when it’s on without waiting for the Raspberry Pi to start up.

The code






If you’re interested in the code Adam used to build his time machine, especially if you’re considering making your own, you’ll find it all in this month’s HackSpace magazine. Download the latest issue for free here, subscribe for more issues here, or visit your local newsagent or the Raspberry Pi Store, Cambridge to pick up the magazine in physical, real-life, in-your-hands print.

The post Listen to World War II radio recordings with a Raspberry Pi Zero appeared first on Raspberry Pi.

Portable Raspberry Pi 4 computer | Hackspace magazine #24

Post Syndicated from Ben Everard original https://www.raspberrypi.org/blog/portable-raspberry-pi-4-computer-hackspace-magazine-24/

Why hunch over a laptop when you can use Raspberry Pi 4 to build a portable computer just for you? Here’s how HackSpace magazine editor Ben Everard did just that…

Yes, I have mislaid the CAPS LOCK and function keys from the keyboard. If you come across them in the Bristol area, please let me know.

Raspberry Pi 4

When Raspberry Pi 4 came out, I was pleasantly surprised by how the more powerful processor and enhanced memory allowed it to be a serious contender for a desktop computer. However, what if you don’t have a permanent desk? What if you want a more portable option? There are plenty of designs around for laptops built using Raspberry Pi computers, but I’ve never been that keen on the laptop form factor. Joining the screen and keyboard together always makes me feel like I’m either slumped over the screen or the keyboard is too high. I set out to build a portable computer that fitted my way of working rather than simply copying the laptop design that’s been making our backs and fingers hurt for the past decade.

Deciding where to put the parts on the plywood backing

Portable Raspberry Pi 4 computer

I headed into the HackSpace magazine workshop to see what I could come up with.

A few things I wanted to consider from a design point of view:

Material. Computer designers have decided that either brushed aluminium or black plastic are the options for computers, but ever since I saw the Novena Heirloom laptop, I’ve wanted one made in wood. This natural material isn’t necessarily perfectly suited to computer construction, but it’s aesthetically pleasing and in occasionally stressful work environments, wood is a calming material. What’s more, it’s easy to work with common tools.

Screen setup. Unsurprisingly, I spend a lot of my time reading or writing. Landscape screens aren’t brilliant choices for this, so I wanted a portrait screen. Since Raspberry Pi 4 has two HDMI ports, I decided to have two portrait HDMI screens. This lets me have one to display the thing we’re doing, and one to have the document to write about the thing we’re doing.

No in-built keyboard or mouse. Unlike a laptop, I decided I wanted to work with external input devices to create a more comfortable working setup.

Exposed wiring. There’s not a good reason for this — we just like the aesthetic (but it does make it easier to hack an upgrade in the future).

A few things I wanted to consider from a technical point of view:

Cooling. Raspberry Pi can run a little hot, so I wanted a way of keeping it cool while still enabling the complete board to be accessible for working with the GPIO.

Power. Raspberry Pi needs 5 V, but most screens need 12 V. I wanted my computer to have just a single power in. Having this on a 12 V DC means I can use an external battery pack in the future.

There’s no great secret to this build. I used two different HDMI screens (one 12 inches and one 7 inches) and mounted them on 3 mm plywood. This gives enough space to mount my Raspberry Pi below the 7-inch screen. This plywood backing is surrounded by a 2×1 inch pine wall that’s just high enough to expand beyond the screens. There’s a slight recess in this pine surround that a plywood front cover slots into to protect the screens during transport. The joints on the wood are particularly unimpressive being butt joints with gaps in. The corners are secured by protectors which I fabricated from 3 mm aluminium sheet (OK, fabricated is a bit of a grand word — we cut, bent, and drilled them from 3 mm aluminium sheet).

You can get smaller voltage converters than this, but we like the look of the large coil and seven-segment display

I made this machine quickly as we intended it to be a prototype. I fully expected that the setup would prove too unusual to be useful and planned to disassemble it and make a different form factor after I’d learned what worked and what didn’t. However, so far, I’m happy with this setup and don’t have any plans to redesign it soon.

Power comes in via a 5.1 mm jack. This goes to both the monitors and a buck converter which steps it down to 5 V for Raspberry Pi and fan (the converter has a display showing the current voltage because I like the look of seven-segment displays). Power is controlled by three rocker switches (because I like rocker switches rather than soft switches), allowing you to turn Raspberry Pi, fan, and screens on and off separately.

We used a spade drill bit and a Dremel with a sanding attachment to carve out the space for our Raspberry Pi

We’ve had to cut USB and power cables and shorten them to make them fit nicely in the case.

We had to cut quite a lot of cables up to make them fit. Fortunately, most have sensibly coloured inners to help you understand what does what

The only unusual part of the build was the cooling for Raspberry Pi. Since I wanted to leave the body of my Raspberry Pi free, that meant that I had to have a fan directing air over the CPU from the side. After jiggling the fan into various positions, I decided to mount it at 45 degrees just to the side of the board. I needed a mount for this — 3D printing would have worked well, but I’d been working through the Power Carving Manual reviewed in issue 23, so put these skills to the test and whittled a bit of wood to the right shape. Although power carving is usually used to produce artistic objects, it’s also a good choice for fabrication when you need a bit of 
a ‘try-and-see’ approach, as it lets you make very quick adjustments.

Overall, my only disappointment with the making of this computer is the HDMI cables. I decided not to cut and splice them to the correct length as the high-speed nature of the HDMI signal makes this unreliable. Instead, I got the shortest cables I could and jammed them in.

We control the fan via a switch rather than automatically for two reasons: so we can run silently when we want, and so all the GPIO pins are available for HATs and other expansions

In use, I’m really happy with my new computer. So far, it has proved sturdy and reliable, and our design decisions have been vindicated by the way it works for me. Having two portrait screens may seem odd, but at least for technology journalists it’s a great option. The 7-inch screen may seem little, but these days most websites have a mobile-friendly version that renders well in this size, and it’s also big enough for a terminal window or Arduino IDE. A few programs struggle to work in this form factor (we’re looking at you, Mu).

Our corners are not the best joints, but the metal surrounds ensure they are strong and protected from bumps (oh, and we like the look of them)

We live in a world where — for many of us — computers are an indispensable tool that we spend most of our working lives using, yet the options for creating ones that are personal and genuinely fit our way of working are slim. We don’t have to accept that. We can build the machines that we want to use: build our own tools. This is a machine designed for my needs — yours may be different, but you understand them better than anyone. If you find off-the-shelf machines don’t work well for you, head to the workshop and make something that does.

Hackspace magazine

HackSpace magazine is out now, available in print from your local newsagent or from the Raspberry Pi Store in Cambridge, online from Raspberry Pi Press, or as a free PDF download. Click here to find out more and, while you’re at it, why not have a look at the subscription offers available, including the 12-month deal that comes with a free Adafruit Circuit Playground!

The post Portable Raspberry Pi 4 computer | Hackspace magazine #24 appeared first on Raspberry Pi.

Build a xylophone-playing robot | HackSpace magazine #22

Post Syndicated from Alex Bate original https://www.raspberrypi.org/blog/build-a-xylophone-playing-robot-hackspace-magazine-22/

HackSpace magazine issue 22 is out now, and our favourite tutorial this month will show you how to make this, a xylophone-playing robot!

Build a glockenspiel-playing robot with HackSpace magazine

Why spend years learning to play a musical instrument when you could program a robot to do it for you? This month HackSpace magazine, we show you how to build a glockenspiel-playing robot. Download the latest issue of HackSpace for free: http://rpf.io/hs22yt Follow HackSpace on Instagram: http://rpf.io/hsinstayt

If programming your own instrument-playing robot isn’t for you, never fear, for HackSpace magazine is packed full of other wonderful makes and ideas, such as:

  • A speaker built into an old wine barrel
  • Free-form LEDs
  • Binary knitwear
  • A Raspberry Pi–powered time machine
  • Mushroom lights
  • A…wait, hold on, did I just say a Raspberry Pi–powered time machine? Hold on…let me just download the FREE PDF and have a closer look. Page 14, a WW2 radio broadcast time machine built by Adam Clark. “I bought a very old, non-working valve radio, and replaced the internals with a Raspberry Pi Zero on a custom 3D-printed chassis.” NICE!


Honestly, this month’s HackSpace is so full of content that it would take me all day to go through everything. But, don’t take my word for it — try it yourself.

HackSpace magazine is out now, available in print from your local newsagent or from the Raspberry Pi Store in Cambridge, online from Raspberry Pi Press, or as a free PDF download. Click here to find out more and, while you’re at it, why not have a look at the subscription offers available, including the 12-month deal that comes with a free Adafruit Circuit Playground!

Author’s note

Yes, I know it’s a glockenspiel in the video.

The post Build a xylophone-playing robot | HackSpace magazine #22 appeared first on Raspberry Pi.

Monitor air quality with a Raspberry Pi

Post Syndicated from Andrew Gregory original https://www.raspberrypi.org/blog/monitor-air-quality-with-a-raspberry-pi/

Add a sensor and some Python 3 to your Raspberry Pi to keep tabs on your local air pollution, in the project taken from Hackspace magazine issue 21.

Air is the very stuff we breathe. It’s about 78% nitrogen, 21% oxygen, and 1% argon, and then there’s the assorted ‘other’ bits and pieces – many of which have been spewed out by humans and our related machinery. Carbon dioxide is obviously an important polluter for climate change, but there are other bits we should be concerned about for our health, including particulate matter. This is just really small bits of stuff, like soot and smog. They’re grouped together based on their size – the most important, from a health perspective, are those that are smaller than 2.5 microns in width (known as PM2.5), and PM10, which are between 10 and 2.5 microns in width. This pollution is linked with respiratory illness, heart disease, and lung cancer.

Obviously, this is something that’s important to know about, but it’s something that – here in the UK – we have relatively little data on. While there are official sensors in most major towns and cities, the effects can be very localised around busy roads and trapped in valleys. How does the particular make-up of your area affect your air quality? We set out to monitor our environment to see how concerned we should be about our local air.

Getting started

We picked the SDS011 sensor for our project (see ‘Picking a sensor’ below for details on why). This sends output via a binary data format on a serial port. You can read this serial connection directly if you’re using a controller with a UART, but the sensors also usually come with a USB-to-serial connector, allowing you to plug it into any modern computer and read the data.

The USB-to-serial connector makes it easy to connect the sensor to a computer

The very simplest way of using this is to connect it to a computer. You can read the sensor values with software such as DustViewerSharp. If you’re just interested in reading data occasionally, this is a perfectly fine way of using the sensor, but we want a continuous monitoring station – and we didn’t want to leave our laptop in one place, running all the time. When it comes to small, low-power boards with USB ports, there’s one that always springs to mind – the Raspberry Pi.

First, you’ll need a Raspberry Pi (any version) that’s set up with the latest version of Raspbian, connected to your local network, and ideally with SSH enabled. If you’re unsure how to do this, there’s guidance on the Raspberry Pi website.

The wiring for this project is just about the simplest we’ll ever do: connect the SDS011 to the Raspberry Pi with the serial adapter, then plug the Raspberry Pi into a power source.

Before getting started on the code, we also need to set up a data repository. You can store your data wherever you like – on the SD card, or upload it to some cloud service. We’ve opted to upload it to Adafruit IO, an online service for storing data and making dashboards. You’ll need a free account, which you can sign up for on the Adafruit IO website – you’ll need to know your Adafruit username and Adafruit IO key in order to run the code below. If you’d rather use a different service, you’ll need to adjust the code to push your data there.

We’ll use Python 3 for our code, and we need two modules – one to read the data from the SDS011 and one to push it to Adafruit IO. You can install this by entering the following commands in a terminal:

pip3 install pyserial adafruit-io

You’ll now need to open a text editor and enter the following code:

This does a few things. First, it reads ten bytes of data over the serial port – exactly ten because that’s the format that the SDS011 sends data in – and sticks these data points together to form a list of bytes that we call data.

We’re interested in bytes 2 and 3 for PM2.5 and 4 and 5 for PM10. We convert these from bytes to integer numbers with the slightly confusing line:

pmtwofive = int.from_bytes(b’’.join(data[2:4]), byteorder=’little’) / 10

from_byte command takes a string of bytes and converts them into an integer. However, we don’t have a string of bytes, we have a list of two bytes, so we first need to convert this into a string. The b’’ creates an empty string of bytes. We then use the join method of this which takes a list and joins it together using this empty string as a separator. As the empty string contains nothing, this returns a byte string that just contains our two numbers. The byte_order flag is used to denote which way around the command should read the string. We divide the result by ten, because the SDS011 returns data in units of tens of grams per metre cubed and we want the result in that format aio.send is used to push data to Adafruit IO. The first command is the feed value you want the data to go to. We used kingswoodtwofive and kingswoodten, as the sensor is based in Kingswood. You might want to choose a more geographically relevant name. You can now run your sensor with:

python3 airquality.py

…assuming you called the Python file airquality.py
and it’s saved in the same directory the terminal’s in.

At this point, everything should work and you can set about running your sensor, but as one final point, let’s set it up to start automatically when you turn the Raspberry Pi on. Enter the command:

crontab -e

…and add this line to the file:

@reboot python3 /home/pi/airquality.py

With the code and electronic setup working, your sensor will need somewhere to live. If you want it outside, it’ll need a waterproof case (but include some way for air to get in). We used a Tupperware box with a hole cut in the bottom mounted on the wall, with a USB cable carrying power out via a window. How you do it, though, is up to you.

Now let’s democratise air quality data so we can make better decisions about the places we live.

Picking a sensor

There are a variety of particulate sensors on the market. We picked the SDS011 for a couple of reasons. Firstly, it’s cheap enough for many makers to be able to buy and build with. Secondly, it’s been reasonably well studied for accuracy. Both the hackAIR and InfluencAir projects have compared the readings from these sensors with more expensive, better-tested sensors, and the results have come back favourably. You can see more details at hsmag.cc/DiYPfg and hsmag.cc/Luhisr.

The one caveat is that the results are unreliable when the humidity is at the extremes (either very high or very low). The SDS011 is only rated to work up to 70% humidity. If you’re collecting data for a study, then you should discard any readings when the humidity is above this. HackAIR has a formula for attempting to correct for this, but it’s not reliable enough to neutralise the effect completely. See their website for more details: hsmag.cc/DhKaWZ.

Safe levels

Once you’re monitoring your PM2.5 data, what should you look out for? The World Health Organisation air quality guideline stipulates that PM2.5 not exceed 10 µg/m3 annual mean, or 25 µg/m3 24-hour mean; and that PM10 not exceed 20 µg/m3 annual mean, or 50 µg/m3 24-hour mean. However, even these might not be safe. In 2013, a large survey published in The Lancet “found a 7% increase in mortality with each 5 micrograms per cubic metre increase in particulate matter with a diameter of 2.5 micrometres (PM2.5).”

Where to locate your sensor

Standard advice for locating your sensor is that it should be outside and four metres above ground level. That’s good advice for general environmental monitoring; however, we’re not necessarily interested in general environmental monitoring – we’re interested in knowing what we’re breathing in.

Locating your monitor near your workbench will give you an idea of what you’re actually inhaling – useless for any environmental study, but useful if you spend a lot of time in there. We found, for example, that the glue gun produced huge amounts of PM2.5, and we’ll be far more careful with ventilation when using this tool in the future.

Adafruit IO

You can use any data platform you like. We chose Adafruit IO because it’s easy to use, lets you share visualisations (in the form of dashboards) with others, and connects with IFTTT to perform actions based on values (ours tweets when the air pollution is above legal limits).

One thing to be aware of is that Adafruit IO only holds data for 30 days (on the free tier at least). If you want historical data, you’ll need to sign up for the Plus option (which stores data for 60 days), or use an alternative storage method. You can use multiple data stores if you like.

Checking accuracy

Now you’ve got your monitoring station up and running, how do you know that it’s running properly? Perhaps there’s an issue with the sensor, or perhaps there’s a problem with the code. The easiest method of calibration is to test it against an accurate sensor, and most cities here in the UK have monitoring stations as part of Defra’s Automatic Urban and Rural Monitoring Network. You can find your local station here. Many other countries have equivalent public networks. Unless there is no other option, we would caution against using crowdsourced data for calibration, as these sensors aren’t themselves calibrated.

With a USB battery pack, you can head to your local monitoring point and see if your monitor is getting similar results to the monitoring network.

HackSpace magazine #21 is out now

You can read the rest of this feature in HackSpace magazine issue 21, out today in Tesco, WHSmith, and all good independent UK newsagents.

Or you can buy HackSpace mag directly from us — worldwide delivery is available. And if you’d like to own a handy digital version of the magazine, you can also download a free PDF.

The post Monitor air quality with a Raspberry Pi appeared first on Raspberry Pi.