Tag Archives: hackspace

Build an arcade cabinet | Hackspace 35

via Raspberry Pi

Games consoles might be fast and have great graphics, but they’re no match for the entertainment value of a proper arcade machine. In this month’s issue of Hackspace magazine, you’re invited to relive your misspent youth with this huge build project.

There’s something special about the comforting solidity of a coin-eating video game monolith, and nothing screams retro fun like a full-sized arcade cabinet sitting in the corner of the room. Classic arcade machines can be a serious investment. Costing thousands of pounds and weighing about the same as a giant panda, they’re out of reach for all but the serious collector. Thankfully, you can recreate that retro experience using modern components for a fraction of the price and weight.

An arcade cabinet is much easier to make than you might expect. It’s essentially a fancy cupboard that holds a monitor, speakers, a computer, a keyboard, and some buttons. You can make your own cabinet using not much more than a couple of sheets of MDF, some clear plastic, and a few cans of spray paint.

If you want a really authentic-looking cabinet, you can find plenty of plans and patterns online. However, most classic cabinets are a bit bigger than you might remember, occupying almost a square metre of floor space. If you scale that down to approximately 60 cm2, you can make an authentic-looking home arcade cabinet that won’t take over the entire room, and can be cut from just two pieces of 8 × 4 (2440 mm × 1220 mm) MDF. You can download our plans, but these are rough plans designed for you to tweak into your own creation. A sheet of 18 mm MDF is ideal for making the body of the cabinet, and 12 mm MDF works well to fill in the front and back panels. You can use thinner sheets of wood to make a lighter cabinet, but you might find it less sturdy and more difficult to screw into.

The sides of the machine should be cut from 18 mm MDF, and will be 6 feet high. The sides need to be as close to identical as possible, so mark out the pattern for the side on one piece of 18 mm MDF, and screw the boards together to hold them while you cut. You can avoid marking the sides by placing the screws through the waste areas of the MDF. Keep these offcuts to make internal supports or brackets. You can cut the rest of the pieces of MDF using the project plans as a guide. 

Why not add a coin machine for extra authenticity

Attach the side pieces to the base, so that the sides hang lower than the base by an inch or two. If you’re more accomplished at woodworking and want to make the strongest cabinet possible, you can use a router to joint and glue the pieces of wood together. This will make the cabinet very slightly narrower and will affect some measurements, but if you follow the old adage to measure twice and cut once, you should be fine. If you don’t want to do this, you can use large angle brackets and screws to hold everything together. The cabinet will still be strong, and you’ll have the added advantage that you can disassemble it in the future if necessary.

Keep attaching the 18 mm MDF pieces, starting with the top piece and the rear brace. Once you have these pieces attached, the cabinet should be sturdy enough to start adding the thinner panels. Insetting the panels by about an inch gives the cabinet that retro look, and also hides any design crimes you might have committed while cutting out the side panels.

The absolute sizing of the cabinet isn’t critical unless you’re trying to make an exact copy of an old machine, so don’t feel too constrained by measuring things down to the millimetre. As long as the cabinet is wide enough to accept your monitor, everything else is moveable and can be adjusted to suit your needs.

Make it shiny

You can move onto decoration once the cabinet woodwork is fitted together. This is mostly down to personal preference, although it’s wise to think about which parts of the case will be touched more often, and whether your colour choices will cause any problems with screen reflection. Matt black is a popular choice for arcade cabinets because it’s non-reflective and any surface imperfections are less noticeable with a matt paint finish.

Aluminium checker plate is a good way of protecting your cabinet from damage, and it can be cut and shaped easily.

Wallpaper or posters make a great choice for decorating the outside of the cabinet, and they are quick to apply. Just be sure to paste all the way up to the edge, and protect any areas that will be handled regularly with aluminium checker plate or plastic sheet. The edges of MDF sheets can be finished with iron-on worktop edging, or with the chrome detailing tape used on cars. You can buy detailing tape in 12 mm and 18 mm widths, which makes it great for finishing edges. The adhesive tape provided with the chrome edging isn’t always very good, so it’s worth investing in some high-strength, double-sided clear vinyl foam tape.

You’ve made your cabinet, but it’s empty at the moment. You’re going to add a Raspberry Pi, monitor, speakers, and a panel for buttons and joysticks. To find out how, you can read the full article in HackSpace magazine 35.  

Get HackSpace magazine 35 Out Now!

Each month, HackSpace magazine brings you the best projects, tips, tricks and tutorials from the makersphere. You can get it from the Raspberry Pi Press online store, The Raspberry Pi store in Cambridge, or your local newsagents.

Each issue is free to download from the HackSpace magazine website.

If you subscribe for 12 months, you get an Adafruit Circuit Playground Express , or can choose from one of our other subscription offers, including this amazing limited-time offer of three issues and a book for only £10!

The post Build an arcade cabinet | Hackspace 35 appeared first on Raspberry Pi.

Rotary encoders: Raise a Glitch Storm | Hackspace 34

via Raspberry Pi

A Glitch Storm is an explosive torrent of musical rhythms and sound, all generated from a single line of code. In theory, you can’t do this with a Raspberry Pi running Python – in this month’s new issue, out now, the HackSpace magazine team lovingly acquired a tutorial from The Mag Pi team to throw theory out the window and show you how.

What is a Glitch Storm

A Glitch Storm is a user-influenceable version of bytebeat music. We love definitions like that here at the Bakery: something you have never heard of is simple a development of something else you have never heard of. Bytebeat music was at the heart of the old Commodore 64 demo scene, a competition to see who could produce the most impressive graphs and music in a very limited number of bytes. This was revived/rediscovered and christened by Viznut, aka Ville-Matias Heikkilä, in 2011. And then JC Ureña of the ‘spherical sound society’ converted the concept into the interactive Glitch Storm.

Figure 1: Schematic for the sound-generating circuit

So what is it?

Most random music generators work on the level of notes; that is, notes are chosen one at a time and then played, like our Fractal Music project in The MagPi #66. However, with bytebeat music, an algorithm generates the actual samples levels that make up the sound. This algorithm performs bitwise operations on a tick variable that increments with each sample. Depending on the algorithm used, this may or may not produce something musically interesting. Often, the samples produced exhibit a fractal structure, which is itself similar on many levels, thus providing both the notes and structure.

Enter the ‘Glitch Storm’

With a Glitch Storm, three user-controlled variables – a, b, and c – can be added to this algorithm, allowing the results to be fine-tuned. In the ‘Algorithms’ box, you can see that the bytebeat algorithms simply run; they all repeat after a certain time, but this time can be long, in the order of hours for some. A Glitch Storm algorithm, on the other hand, contains variables that a user can change in real-time while the sample is playing. This exactly what we can do with rotary encoders, without having the algorithm interrupted by checking the state of them all the time.

Figure 2: Schematic for the control box

What hardware?

In order to produce music like this on the Raspberry Pi, we need some extra hardware to generate the sound samples, and also a bunch of rotary encoders to control things. The samples are produced by using a 12-bit A/D converter connected to one of the SPI ports. The schematic of this is shown in Figure 1. The clock rate for the transfer of data to this can be controlled and provides a simple way of controlling, to some extent, the sample rate of the sound. Figure 2 shows the wiring diagram of the five rotary encoders we used.

Making the hardware

The hardware comes as two parts: the D/A converter and associated audio components. These are built on a board that hangs off Raspberry Pi’s GPIO pins. Also on this board is a socket that carries the wires to the control box. We used an IDC (insulation displacement connector) to connect between the board and the box, as we wanted the D/A connection wires to be as short as possible because they carry a high frequency signal. We used a pentagonal box just for fun, with a control in each corner, but the box shape is not important here.

Figure 3: Front physical layout of the interface board

Construction

The board is built on a 20-row by 24-hole piece of stripboard. Figure 3 and Figure 4 show the physical layout for the front and back of the board. The hole number 5 on row 4 is enlarged to 2.5mm and a new hole is drilled between rows 1 and 2 to accommodate the audio jack socket. A 40-way surface-mount socket connector is soldered to the back of the board, and a 20-way socket is soldered to the front. You could miss this out and wire the 20-way ribbon cable direct to the holes in these positions if you want to economise.

Figure 4: Rear physical layout of the interface board

Further construction notes

Note: as always, the physical layout diagram shows where the wires go, not necessarily the route they will take. Here, we don’t want wires crossing the 20-way connector, so the upper four wires use 30AWG Kynar wire to pop under the connector and out through a track hole, without soldering, on the other side. When putting the 20-way IDC pin connector on the ribbon cable, make sure the red end connector wire is connected to the pin next to the downward-pointing triangle on the pin connector. Figure 5 shows a photograph of the control box wiring

Figure 5: Wiring of the control board

Testing the D/A

The live_byte_beat.py listing on GitHub is a minimal program for trying out a bytebeat algorithm. It will play until stopped by pressing CTRL+C. The variable v holds the value of the sample, which is then transferred to the D/A over SPI in two bytes. The format of these two bytes is shown in Figure 6, along with how we have to manipulate v to achieve an 8-bit or 12-bit sample output. Note that all algorithms were designed for an 8-bit sample size, and using 12 bits is a free bonus here: it does sound radically different, and not always in a good way.

The main software

The main software for this project is on our GitHub page, and contains 24 Pythonised algorithms. The knobs control the user variables as well as the sample rate and what algorithm to use. You can add extra algorithms, but if you are searching online for them, you will find they are written in C. There are two major differences you need to note when converting from C to Python. The first is the ternary operation which in C is a question mark, and the second is the modulus operator with a percent sign. See the notes that accompany the main code about these.

Figure 6: How to program the registers in the D/A converter

Why does this work?

There are a few reasons why you would not expect this to work on a Raspberry Pi in Python. The most obvious being that of the interruptions made by the operating system, regularly interrupting the flow of output samples. Well, it turns out that this is not as bad as you might fear, and the extra ‘noise’ this causes is at a low level and is masked by the glitchy nature of the sound. As Python is an interpreted language, it is just about fast enough to give an adequate sample rate on a Raspberry Pi 4.

Make some noise

You can now explore the wide range of algorithms for generating a Glitch Storm and interact with the sound. On our GitHub page there’s a list of useful links allowing you to explore what others have done so far. For a sneak preview of the bytebeat type of sound, visit magpi.cc/bytebeatdemo; you can even add your own algorithms here. For interaction, however, there’s no substitute for having your own hardware. The best settings are often found by making small adjustments and listening to the long-term effects – some algorithms surprise you about a minute or two into a sequence by changing dramatically.

Get HackSpace magazine issue 34 — out today

HackSpace magazine issue 34: on sale now!

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

You can also download the directly from PDF from the HackSpace magazine website.

Subscribers to HackSpace for 12 months to get a free Adafruit Circuit Playground, or choose from one of our other subscription offers, including this amazing limited-time offer of three issues and a book for only £10!

If you liked this project, it was first featured in The MagPi Magazine. Download the latest issue for free or subscribe here.

The post Rotary encoders: Raise a Glitch Storm | Hackspace 34 appeared first on Raspberry Pi.

OctoPrint: a baby monitor for your 3D printer

via Raspberry Pi

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.

Design your own Internet of Things with HackSpace magazine

via Raspberry Pi

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

via Raspberry Pi

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

via Raspberry Pi

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.