How To Guides - PC Guide https://www.pcguide.com Practical Guides to PC & Tech at Home, Work, and Play Sat, 20 Apr 2024 15:58:27 +0000 en-US https://www.pcguide.com/wp-content/uploads/2019/11/PCguide-favicon-75x75.png How To Guides - PC Guide https://www.pcguide.com 32 32 How to play retro games on Raspberry Pi with RetroPie RetroPie is effectively a complete replacement of Raspberry OS (Raspbian), which focuses resources on providing you with the best retro gaming experience on a single board computer that isn't the MiSTer. Building off the work of those behind RetroArch, RetroPie brings a wide range of emulators, but does limit some to single board computers (like the ROCK Pi) that run more traditional hardware. However, we're not locked out of a lot, so just don't expect to be running a PS2 emulator or having a good time digging for your Wii remotes.

Obviously, emulation is in a weird grey area legally, but as long as you already own the game and just want an easier way to play it, this is more than likely just preservation. Emulation is one of the only ways that preservation is actively happening in video games, as major companies have only recently begun to see it as a net positive and you can absolutely see this through the plenty of remakes and remasters that have clogged up release schedules since 2013.

Of course, this means we won't be sharing with you links to acquire games. We know and you know that's highly illegal.

A pretty famous example is Konami's complete carelessness with the Silent Hill HD ports, as the studio that got them found out into development, that they were in fact working with a pre-release build that wasn't finished. Konami had binned the original files after development is probably one of the biggest cases of short-sightedness in the industry, resulting in a Silent Hill game - known for its mysterious fog - to be completely fogless.

Flash an SD Card with RetroPie

A dead-simple step, but we'll need to use a microSD card (preferably with plenty of space to store ROMs on!) and then format it to boot into RetroPie. What we're doing is cutting the fat of the potential PC and turning this into a very small jukebox that you'll turn on to play games. Some light Raspberry Pi stuff will carry over - the way we'll be transferring games is over SSH - and the customization offered by RetroPie is pretty extensive the further you drill down into it.

So start by heading to balenaEtcher, the software needed to graft RetroPie onto the SD Card. Once you're done downloading and installing, be sure to format your SD Card to exFAT. If you want FAT32 you'll need a sub-32GB MicroSD Card, but exFAT allows you to transfer larger file sizes.

Press Flash from File, then choose your SD Card (it should choose it automatically), and then once you hit Flash, just let it do its thing!

Once it's completed, you can remove the SD card and pop it back into the Raspberry Pi.

Recommended SD Card

If you want any other recommendations, our Steam Deck SD card recommendations should line up naturally with your needs for the Raspberry Pi.

Load up RetroPie

RetroPie is very hands off with its installation process, as once you boot up the Pi with the SD card slotted in, it'll simply do the heavy lifting of configuring itself for you. This includes most, if not all, emulators you might need and more. The only things you'll have to do now is turn on SSH and get some ROMs onto the Pi itself!

When you load it up for the first time and it's finished with the initial setup, you can connect a controller to one of the USB ports (and later set up Bluetooth) to map the controller's buttons to how you see fit. This then does it across the board.

 

]]>
https://www.pcguide.com/raspberry-pi/how-to/how-to-play-retro-games-on-raspberry-pi-with-retropie/ https://www.pcguide.com/?p=37652 Thu, 24 Nov 2022 09:53:20 +0000
How to set up Raspberry Pi Compute Module 4 (CM4) The Raspberry Pi Compute Module line is not really intended to be used by the average consumer, lacking any real day-to-day use unless you have a plan for an embedded system at the end of everything. This didn't stop me from buying one back in August and only just manage to get hold of one. Pandemics, turns out they're bad for production.

The super tiny form factor of the device means that it does require a bit more of an investment, but to not be burdened by an SD card or dedicated form factor is more than enough to convince me. I could pop this in a makeshift games console or use the unique feature on the I/O board - sold separately - to start adding extra cameras, displays and use the PCIe slot included (a whole 1x PCIe 2.0!). It also has full-fat HDMI ports on it, making it super easy to take around if I happen to forget a micro HDMI cable.

You'll need an I/O board, as otherwise there's absolutely no way to use the CM4. There's nothing on it but the optional storage and wireless connectivity. Mine came with no Wi-Fi or Bluetooth (not something I need right now and easily rectified) but has 8GB of onboard storage - more than enough before I expand it with the PCIe slot with an M.2 drive.

The CM4 is an exceptional piece of kit and you can absolutely expect more projects from us to begin using it. The low profile options for different carrier boards, combined with the lessons we can learn together (like designing our own PCB!) is more than enough for me to recommend one of these. If you want an easy life, of the Pi400 or Pi4B would always be my first recommendation, but if you want to get weird and a little strange, you might want to consider the CM4...

When it comes back in stock.

So who is this guide for? Well, if you're someone who is vaguely interested in another fork in the journey of Raspberry Pi projects, the CM4 is certainly the right step. Just having hold of the brain at all times is more than enough to kickstart many projects. Get your own PCBs made and you can start to condense down the form factor on the device to something much slimmer for say, fitting behind a TV without the bulk of multiple USB ports and such interfering with the low profile.

What will you need before you start?

A Raspberry Pi CM4 (heavily, heavily out of stock)A Raspberry Pi CM4 Carrier Board (recommending the official I/O board to start)An HDMI cableA Micro USB CableAn SD Card (for those without eMMC memory)EthernetA USB Mouse or KeyboardA 12V DC plugJumper cables or jumper connector

The Micro USB Cable is only for data transfer and will not power your device. It's useless after the fact unless you need to flash the CM4 itself. So make sure the brief time we'll have with it isn't wasted, that it's rated for data transfer.

Connect your CM4 to the Board

Attach the CM4 to the board by simply aligning it with the two connectors on the IO board, then give it a good squeeze. It'll crunch into place and you should be set.

Make sure the Raspberry on the Pi is pointing towards the GPIO pins (leaves away from it) and you should be good to go!

Connect the jumper and micro USB

I'm using one of those weird little nubbins from my Bitcoin Tracker project that let the connector to the LCD actually work. If you have a PIR sensor, there's one on there too. If not, you can always just place two breadboard jumper cables on the ends. This will stop the eMMC from trying to boot and place it into a loading state, ready for us to install the operating system onto it. Plug it into your power.

If you're on Windows, head to Github and download the entire ZIP folder. In it, you'll find Win32, a folder containing a setup wizard for RPIBoot, the program to kickstart the CM4 into life and open its doors for you to install Raspberry Pi OS. Once it gets going, don't close it until it is absolutely done. It's going to install a specific driver and then also install the program needed. Now plug in the Micro USB to your PC.

Your Windows PC should immediately recognize it with the regular jingle, but you won't be able to access it. If it comes up and asks you to format it, ignore it or hit cancel. This is Windows trying to get to the Linux part of the device and you really don't need it breaking.

 

RPIBoot

RPIBoot is a bit of software that allows you to flash the eMMC of the CM4 so that you can do away with the SD cards of the regular Pi 4 and cut about without one.

Obviously, this doesn't apply to those without eMMC, you will want to install Raspberry Pi OS to the SD card as usual.

This will run through a sequence and activate the bootloader onboard the CM4, which you'll then need to download Raspberry Pi Imager, which is a program that downloads, writes, and finishes up the complex task of creating a bootable drive on the CM4's eMMC.

If RPIBoot doesn't work or seems stuck in a loop, don't fret, this happened to me too. I closed the installation and driver install too soon. Just unplug and restart the process from the previous couple of steps.

Raspberry Pi Imager

The imaging software will handle downloads and writing to the eMMC for you, but if you're new to this and want to know which version you should download, just go with the one that is the official Raspberry Pi OS image.

There's also now an official version of Pop! OS from System76 and other versions of Linux or RetroPie is available within the imaging app.

 

Edit the Config File

Before we unplug, now that your CM4 is fully flashed and ready to go, you'll be surprised to learn that the USB Ports are disabled by default. Yes, really. Remember, this is a board designed to be embedded elsewhere and not for consumer-level off-the-shelf use.

In the "boot" folder, find the config.txt and add the following:

dtoverlay=dwc2,dr_mode=host

This will turn on the USB ports when you boot up, but if you accidentally keep the micro USB in, you will run into issues. Before you begin your first boot, make sure everything is unplugged. Boot and then plug in your mouse or keyboard.

If you're like me and couldn't get a wi-fi version, this is where you'll plug in your dongle or ethernet cable.

Boot up and enjoy!

You're done! Let Raspberry Pi OS set up, follow any instructions needed and if you want to SSH or VNC in, be sure to head into the configuration menu in the "start menu". This will let you also turn on I2C and other options for using the GPIO pins for various projects.

CM4, we love you

]]>
https://www.pcguide.com/raspberry-pi/how-to/set-up-compute-module-4-cm4/ https://www.pcguide.com/?p=39277 Fri, 15 Oct 2021 17:03:05 +0100
Build your own Crypto Ticker with Raspberry Pi Following on from my fight against Jeff, with a Ring Clone and building the basics of a camera with buttons, I decided the only way up was to bash my head against the wall until I made two screens work on a Raspberry Pi without any real hassle.

This was a task and a half. Screens wouldn't work together, learning the very, very basics of I2C and how to coerce it to do what I want, along with a couple of almost-fires, but the "finished" product has a face only a father/mother could love. The string of wires and two screens that sort of just hinge on a breadboard, it's been a fascinating experiment and I'm going to take you through the excursion, with the hopes you make your own!

At some point, we will begin placing these in custom cases and enclosures, but for now, just appreciate the mess.

 

Making some changes to the Pi

Install the Python Libraries

We're going to be using the Luma OLED library for this project, which you can get by the Terminal:

sudo -H pip3 install --upgrade luma.oled

Be sure to install Pip and Pip3 if you haven't yet!: sudo apt-get install python3-pip

We'll also need to install the RPI_LCD library via:

sudo pip3 install rpi_lcd

And Requests, to handle getting things from the internet for us:

sudo -H pip3 install requests

Everything else we'll be using comes installed already with Python 3. I'm using Python 3.7.

Import Python Libraries #1

Now we're getting into it. Load up Thonny (or your chosen IDE) and import the following libraries (it's a lot, but trust me):

from signal import pausefrom time import sleepfrom threading import Threadimport sysimport timefrom time import strftime

Your standard libraries for things when dealing with timings. Threading is something we'll get into later, but it's the method of getting Python to do two things at once for us.

from rpi_lcd import LCD

This is the library to use the LCD.

from luma.oled.device import ssd1306, ssd1309, ssd1325, ssd1331, sh1106, ws0010from luma.core.interface.serial import i2cfrom luma.core.render import canvas

Now this is overkill for what we're doing, but it does cover all bases depending on what OLED you happened to buy. If you wanted to simplify it down you could easily just remove the devices you won't be using. Leave the other two, as we need this to tell Luma how to draw on the screen and where the I2C is.

Define Each Screen

Now type in:

lcd = LCD()serial = i2c(port=1, address=0x3c)device = sh1106(serial, rotate=0)

This is simply naming the components we're using, as well as dictating to Python where things are on the I2C bus.

For instance, if we went into the LCD init file, which contains the instructions for the LCD screen and changed the Bus to 5, it'd look for the I2C connections on the Raspberry Pi 4 and 400 on the alternate I2C pins and bus.

Get the Crypto Prices

So this script I'm using is adapted from the Luma.OLED library, which comes with a few examples - including a Bitcoin Ticker. However, I found the code messy and decided to do my best to clean it up. I'm by no means any good at coding, I just know how to make things legible - I hope.

Here, we're going to be importing the requests library, but also using the Luma script's method of immediately killing the script if it can't find the library - in the event we move the script to another Pi or do a fresh install.

try:

import requests

except ImportError:

print("The requests library was not found. Run 'sudo -H pip3 install requests' to install it.")sys.exit

Now we have the method of grabbing data from the web, we're going to actually grab the ticker and tell Python what we want to display it as, while also giving us an error if (and probably when) Bitstamp goes down:

def fetch_price(crypto_currency, fiat_currency):

bitstamp_api = "https://www.bitstamp.net/api/v2/ticker/" + crypto_currency.lower() + fiat_currency.lower()

try:

r = requests.get(bitstamp_api)

return r.json()

except:

print("error fetching from Bitstamp API")

Now let's fetch the prices:

def price_text(crypto_currency, fiat_currency):

data = fetch_price(crypto_currency, fiat_currency)return [

'{}/{} {}'.format(crypto_currency, fiat_currency, data['last']),'24h Hi {}'.format(data['high']),'Lo {}'.format(data['low'])

]

Here, we're not only fetching the currency, but we're also slotting it into three rows, with a 24 hour high, lowest and at the top, its current value.

Push data to the OLED

Now we're actually going to code the OLED to take the data and present it on screen. We do that by treating it as a 'canvas' and we're going to 'draw' on it, while also putting it into the right places on the screen.

We'll start with Bitcoin:

def btc(device):

with canvas(device) as draw:

rows = price_text("BTC", "GBP")draw.text((0, 10), "PCG Ticker", fill="white")draw.text((0, 20), "Bitcoin", fill="white")draw.text((0, 30), rows[0], fill="white")draw.text((0, 40), rows[1], fill="white")draw.text((0, 50), rows[2], fill="white")

As the screen is only five rows tall, we're going to fill it up with information and leave the top blank. But if you change the ((0,10)) or any of the numbers, you can move it up and down the screen as you see fit.

To center it, just take five from each of the designated numbers.

Now this line of code is actually integrated with the fetching loop above, so we can simply just change the definition name to what we want and the chosen cryptocurrency.

So you'd want to change the following:

def btc to def eth or def ltc to tell Python it's a different definition and loop. You can name these whatever you like, but the rest of my code relies on these names so be sure to change things below if you're deciding to rename the definitions.

Then in the canvas, you're going to want to change the BTC to ETH or LTC (or whatever else is available on Bitstamp) and also the indicated name on the third row.

fill="white" is simply to tell the OLED that the screen needs to make the font white, or it'll come out the default on a black background.

If you want your currency, change GBP to USD or other currency, but check what Bitstamp calls it before doing so or the script won't recognise it.

Also be sure to keep the (device), as this tells Python which screen to send the information to.

Write to the LCD 1602

We haven't forgotten about the LCD! Don't fret! Here's how to get it running:

def lcd_time():

while True:

lcd.text(strftime("%H:%M:%S"),1)lcd.text("Time, UK",2)time.sleep(.01)

I'm using it as a clock face, saving room on the OLED - as well as just not being able to figure it out in time - but I think having a dedicated large clock is a better fit, though you're more than welcome to use it for anything else.

We're doing this the lazy way, instead of hardware, we're just using strftime and forcing the LCD to refresh every second to give the illusion of a running clock. The second row then displays the local time zone. Each row is indicated by the 1 and 2, if you have a larger LCD, you'll be able to fit more information on it.

Get the OLED screen to swap between data sets

So we've got three (or however many you have) cryptocurrencies to track and can't just rely on a tiny screen to display everything all at once. Instead we'll swap between each data set through the time.sleep(10) command. We're also going to tell Python to swamp between each screen on a ten second interval. If this is too short, just increase it.

def oled_crypto():

while True:

btc(device)time.sleep(10)ltc(device)time.sleep(10)eth(device)time.sleep(10)

Additional Things

Very quickly, we're going to add a timestamp and message to those using this through the terminal, just to keep you informed of the loop still running. All it does, is after every loop of 30 seconds, it pushes a message to the terminal, letting you know that it's working.

def tickerunning():

while True:

print("Running Ticker!" + strftime(" %H:%M:%S"))time.sleep(30)

Python Threading

So when I was looking up tutorials for my own benefit for Threading, the main one I came across was so impossibly dense, that I was taken aback. How could I make this simple thing work, if I had to know all these things? Well, it turns out, it was just made far more difficult than it needed to be.

Using another YouTube video, I found that all I needed to get things going was to use the following lines of code:

try:

oled_display = Thread(target=oled_crypto, daemon=True)lcd_display = Thread(target=lcd_time, daemon=True)ticker = Thread(target=tickerunning, daemon=True)

lcd_display.start()oled_display.start()ticker.start()

pause()

All we're doing here is telling Python that we need to run these three scripts at the same time, by point it to the def of each one, then telling it to be True, to just keep running.

Underneath (don't forget this step, it caught me out multiple times), we'll also tell it to start by using the names we've given each thread.

Finally, we need to have a way to kill the program if we wanted:

except KeyboardInterrupt:

pass

And also close down after a half second, as well as attempt to clear the LCD (your mileage my vary):

finally:

sleep(0.5)

lcd.clear

We're going to need to begin altering the Pi's config file, so be sure to add these correctly - it's not hard to do - and if you run into any issues of booting after the many reboots following on from this, mount the SD card into another PC and make any alterations you need to revert the Pi back to its default state.

When you hit run, it should then immediately light up both screens and display the data! Wonderful! Admire your work and feel accomplished as you watch the crypto prices potentially fluctuate.

If you wanted to only focus on your investments, say with Bitcoin, you'd simply just remove any mention of the other two currencies, and then in the loop where we're flicking between each data set, change the time.sleep(10) to time.sleep(.01) to have a true live update.

If you don't want the clock, then get rid of it too! Just erase any mention of the LCD screen and Bob's your uncle!

I'm currently working on getting this into an enclosure, including soldering it to an Adafruit 4x6 PCB.

Download the code!

How to change config.txt on Raspberry Pi

We need to go through the terminal to edit this, as accessing it via the user interface will just prevent us from doing anything. Using this command, we can jump straight into it without the hassle of a text editor.

sudo nano /boot/config.txt

We need to scroll down (with the arrow keys) to 'uncomment' and activate a few features to ensure the Pi is properly ready.

Somewhere down the page is 'Uncomment some or all of these to enable the optional hardware interfaces'. We need to delete the # from before the following:

dtparam=i2c_arm=on

dtparam=i2s=on

dtparam=spi=on

While the other two are needed for this project, we're best uncommenting them for future purposes.

Turn on I2C

We'll need to turn on I2C, which we can either do via the Pi's GUI, by hitting the raspberry and going into preferences and choosing Configuration and then in Interfaces turning on I2C. If you're running headerless or want to feel like a hacker, we can go through the terminal.

Type: sudo raspi-config and then in the configuration tool, choose section 3 and then P5 to turn on I2C.

Reboot.

How to Wire a 1602 LCD

Incredibly common around maker spaces, the 1602 LCD can display two lines of sixteen characters, it looks a little intimidating when you have to wire one up for the first time, but we're going to ignore 4 of the 16 pins for this project and actually take a small shortcut to make things easier.

The 1602 LCD can come in three varieties, one without a header pin, with headers already soldered on, and a version with the controller soldered on, which also includes a contrast toggle.

I'd highly recommend the last one, it makes life so much easier and means you won't have to buy multiple pieces or spend time soldering the screen together with the screen. However, if you wanted to, it's quite easy to fit it together.

I made my life a million times more difficult and bought one without the controller, so had to attach one separately onto the back via jumper wires which in the long run made things a lot easier on us wiring this thing up to the Raspberry Pi. Converting the 12 wires to 4 and then into the Pi just gives us a lot more flexibility - figuratively and literally.

If you're having to connect the controller, plug it into a breadboard and connect each pin via a jumper wire to each matching pin on the LCD. The ones I have actually indicate where the LED backlight is supposed to be plugged into, so work backward from there. Just skip over D0, D1, D2, and D3.

If you're still unsure, here's what each pin on your LCD actually means:

VSS - GroundVDD - +5V Power SupplyVO - ContrastRS - Controls the LCD's memoryR/W - Switches between Read and WriteE - Enable PinD0-D7 - Data reading and writing pinsA - 3.3V backlightK - Backlight ground

We're going to come back to the LCD later on when we start working on the Raspberry Pi, so don't worry about connecting it up just yet.

Get the SDA and SCL pins ready

Take two Female to Male jumper cables and place them on Pins 2 and 3, noting which are SDA (Pin 2) and SCL (Pin 3).

Plug the two jumper wires from Pins 2 and 3, noting where SDA and SCL are when you do, and place them into the breadboard with at least two pins free on above and below.

Wire up your OLED

I'm using an SH1106 OLED from AliExpress, but I'd recommend buying from a more reputable seller like Adafruit. We'll get the drivers for this and the LCD later on. First, let's wire up the OLED on our breadboard and to the Pi.

Taking jumper wires (Male to Female), VCC (or on mine, VDD) goes to the 3.3V pin and ground to any ground. With the OLED in the breadboard, plug in your SDA and SCL pins to two of the pins on the board above or below your two SDA/SCL wires.

The OLED runs on I2C, a protocol for connecting devices developed by Phillips Semiconductors (now NXP) nearly 40 years ago. I2C has set addresses - this is going to come up later - which the Pi and Python in turn use as a way to send the data to the right places.

Once you've connected it, open the Terminal.

 

Install and Use I2C Tools

Back in the terminal, use the two following commands:

sudo apt-get install -y python-smbus

sudo apt-get install -y i2c-tools

The -y skips the yes prompts that will appear during installation, letting you just get to the meat and potatoes.

Now we can use the tools to detect our OLED screen, which should be assigned address 3c, by using the following command:

sudo i2cdetect -y 1

This will go through all the I2C addresses and should hopefully bring up your OLED screen. If it appears, you're in business. If not, try rewiring.

Wire Up and Set Up the LCD 1602

The LCD works off of I2C as well, so we'll need to connect it to the same pins on our breadboard (which if we move it to a more permanent board afterward, we can solder them all together).

Once you've done that, take wires from the four-pin connector for your LCD and take the SDA and SCL pins to two of the pins matching with the wires from the Pi in the Breadboard, while you take the two power wires to the 5V pin and ground.

If you now check with i2cdetect -y 1, you should see the LCD pop up under 27.

]]>
https://www.pcguide.com/raspberry-pi/how-to/build-your-own-crypto-ticker/ https://www.pcguide.com/?p=36761 Wed, 29 Sep 2021 17:27:36 +0100
How to Setup and Solder a Raspberry Pi Pico I guess for those uninitiated, the Raspberry Pi Pico is the Pi Foundations' own microcontroller. It's not a fully-fledged PC in a little stick like the Pi Zero, but a way to do little things (motors, lights, etc.) via a specialized version of Python.

Two versions exist, CircuitPython and MicroPython, with each able to do similar tasks, but often have different intentions. It's not a brand-new product, but it is still relatively fresh in the lineup of Pi hardware. The obvious comparison would be an Arduino, which the Pico clearly trying to eat some – ahem – pie from Arduino's plate.

We'll have more tutorials based around it in the future, but for now, let's get it set up and running MicroPython. It's relatively simple, but a Pico can come nude.

At a whole four quid (seriously), you're sort of expected to provide your pins for creating headers, but some sellers will provide you with an already soldered version for a more expensive price. Think of it as the product and labour.

If you're worried about soldering, don't be! I'm 27, never soldered in my life, and I didn't set the house on fire. You'll be fine.

What you'll need

A Raspberry Pi PicoHeader Pins (20 pins each)A soldering ironSolderA breadboard

We'll need the breadboard for future projects anyway, but for now, it's the perfect little holder for us to solder on these pins!

While I can't recommend you buy a Pico from Amazon directly, the Pico kits are more in line with the cost from regular resellers:

Raspberry Pi Pico Kit: UK/USUSB Cable: UK/USBreadboards: UK/USSoldering Iron: UK/USPins: UK/US]]>
https://www.pcguide.com/raspberry-pi/how-to/setup-and-solder-a-raspberry-pi-pico/ https://www.pcguide.com/?p=35427 Wed, 22 Sep 2021 11:31:57 +0100
How to Make Private Ring Doorbell With Raspberry Pi Ring doorbells aren’t exactly the most secure things in the world and having to maintain a complete connection with Amazon’s servers to maintain footage or photos of those who come up to your door is going to be a bit of a hassle if Amazon ever pull the plug on the brand.

There’s also the fact that they seem to have a habit of sharing footage with law enforcement and potentially using the footage for their own means (we can’t all read every line of the extravaganza that is their privacy policy). So let’s build our own doorbell that can store photos, video and alert us in two different ways via IFTTT, Python and a doorbell sound.

What is IFTTT?

Setting up the Doorbell Sound #2

You’ll need to provide your own sound and place it in the same file as your Python code for it to find it. You can use whatever you want.

Next we’re going to need to define the bell actually being rung when the button is hit, so we’ll go:

def ring():r = requests.post('maker.ifttt.com/trigger/YOUR_THING_HERE/with/key/YOUR_KEY_HERE sound.play()print("Ding dong!")

In IFTTT’s WebHook documentation page it’ll give you options for JSON, but we don’t need it so only include them if you think you’ll scale up to JSON in the future.

But here, all we’re doing is telling Python that whenever our own piece of code is activated by the button we’re going to install later, to hit the WebHook and bring down a notification.

This is ideal if you don’t have a PIR sensor and still want to be included!

If you don’t have a PIR sensor and want to complete the doorbell as is, skip ahead to when we install the button further down the page.

Now let’s get the sensor up and running before we move back to the doorbell itself.

PIR Sensor Python Code

while True:filename = strftime("/home/pi/Desktop/image-%d-%m %H:%M-%S.jpg", gmtime())vid_filename = strftime("/home/pi/Desktop/image-%d-%m %H:%M-%S.h264", gmtime())doorbell.when_pressed = ring print("Waiting for Motion")sen.wait_for_motion()print("Detected Motion")r = http://requests.post('https://maker.ifttt.com/trigger/YOUR_TRIGGER/with/key/YOUR_KEY_HERE')cam.annotate_text = strftime("%Y-%d-%m-%H:%M:%S")cam.capture(filename)print("Photo Saved")cam.start_recording(vid_filename)print("Recording...")cam.wait_recording(10)cam.stop_recording()print("Recording saved")time.sleep(5)

Code Explainer: PIR Sensor

The ‘while True:’ statement triggers the rest of the script, but leaves it running on a loop. This was the one of thing that stopped me from working with PIR sensors at first, as I thought all the ones I had ordered had broken upon wrong wiring. Turns out, the script just needs to know to reset the sensor at the end.

This is why sandwiched right at the bottom is a ‘time.sleep(5)’ function, as we really don’t want every little motion to trigger this thing off and take six thousand photos because of a leaf. This will force the Pi to take a break, reset the loop in five seconds. You can set this to whatever you want, but I found five to be enough for a security camera.

You’ll notice that I’m still saving everything to the Desktop, which is wrong. You should save these to an external SSD for best performance as saving directly to the SD card will result in your entire system slowing down when you’ve finished taking photos.

Just take note of your directory you want to save to and point the code there.

The time format is dictated by the strftime and gmtime, but also allows the program to save individual images and videos instead of just overwriting everything.

While it’s not wired up, we might as well still put in the doorbell code, which we’re going to indicate with doorbell.when_pressed = ring and let our user know if they can see the shell terminal that it is currently waiting for motion with a print command.

Then, have it wait with the sen.wait_for_motion() and tell the user that motion has been detected with another print command.

Keeping up? Because this is where you can deviate if you wish.

In IFTTT, if you decided to go with two different action sets, you should take note of the other command to tell the sensor to ping WebHook with the information to send you another notification set instead of just the bog-standard one from the well-written notification.

Before we trigger the camera on, we need to tell it to write some text over the top. The font is weird and to be honest, it’s clear enough to read for any valuable use, so let’s roll with it.

Then we activate the camera! The camera code included is mostly focused on taking a photo on motion and then recording the ten seconds after for any further evidence needed. Then it tells us if it’s finished the job.

Once this is done, we loop back through with the ‘while True’.

 

Wiring up a ‘doorbell’ to the Pi

Lastly, we need to wire up our doorbell. Take a button, I have some from the Elegoo set and connect one leg to a ground and one to PIN 17.

After this, the last bit of code for our friends who aren’t with a PIR sensor goes like this:

doorbell.when_pressed = ring

So skip the previous steps and just run this bit.

Tidying it up and putting it all into a case is going to come soon, but for the time being, get some ideas of where to print cases with our articles on 3D Printers, as well as the plentiful resources online.

Right now though? We’ve got a working prototype of our very own Ring camera that doesn’t distribute files online for the police to take and misconstrue! The only thing you’ll need to add extra outside of any tidying is a simple 3.5mm speaker or connect the Pi to a Bluetooth speaker to hear your doorbell sound!

IFTTT stands for If This Then That, a freemium service that connects different services together and then when one is triggered, it sets off another. The free version allows us to work with three different actions and each action can do two things. If you wanted to spend some money on the Pro version you’re more than welcome, but we’ll be working on the free version for this project.

What do we need?

I’m using a Raspberry Pi 4 for this project, but a Raspberry Pi Zero W (the one with internet connectivity) will also do a great job.

Because we’re just prototyping for now, a breadboard, wires (female to male and male to male), a button and a PIR sensor. The Elegoo Ultimate Pack comes with everything, but the one thing I’m using different is something from another brand. It works in a similar way, just without the sensitivity knobs on the side.

A PIR sensor uses infrared to detect motion, it can be quite sensitive so don’t move the plastic top or it’ll go haywire.

A small speaker or Bluetooth speaker to hear the ring.

Let’s also make sure our Raspberry Pi is ready and updated by doing:

sudo apt-get update sudo apt-get upgrade

Powering the PIR Sensor via GPIO

Let’s begin by turning off the Pi if it’s still on and connect the wires up. On the breadboard, plug in your PIR sensor and make not of which sides are positive and negative, the middle should usually be your activity pin.

With it plugged in, plug in two easily identifiable FEMALE TO MALE wires into the positive and negative rails on the very end of your breadboard, ensuring they’re in the same line. Then, take two similar male-to-male wires, plugging those from the positive and negative rails into the PIR sensor’s own positive and negative.

This doesn’t need to be directly behind the pins, just the same row/column behind it. I have them situated just one space behind it.

Now we have power set up, let’s give it some juice. Take the positive to a FIVE VOLT PIN (top two on the left next to the yellow hole at the very top) and then your negative to a ground pin.

Choose an activity wire and plug it into the third pin on your PIR sensor and plug it into PIN 26 (you might want to choose the ground next to it) and we can begin coding.

Setting up IFTTT for Raspberry Pi

We need IFTTT to alert our phone that someone has either been detected or someone has rung the bell. We can use either clever wording in the notification or use two of the three free actions we can create to do what we need to do. Take your pick, I’ll still guide you through both.

In IFTTT, begin by creating your first action choosing WebHooks and Notifications. WebHooks is a service that receives information or sends it over the web for an end result, the notifications will allow the IFTTT app on your phone or tablet to send push notifications without having to use PushBullet.

For WebHooks, we want to just receive a web request. This will push you to the next page to name the event. Name it what you want, but make sure you change the code that we have featured here to match that if you do deviate.

We went with door_seen for the web request and then the notification we just chose a simple IFTTT push notification.

Once this is done, we need to grab the WebHook Key from the app which we can do by clicking the WebHook logo in the completed applet and then Documentation. Make note of this as it’s vitally important for the Pi to talk to IFTTT.

In the same Documentation page you’ll find the string of code needed to bring everything together later on, where you’ll also put in your event name.

That’s it for IFTTT right now, head into Thonny or your favourite Pi IDE and we’ll begin the actual scripting process.

Python to IFTTT via the Raspberry Pi

For our little doorbell and sensor, we’re going to be using Python 3 and going to need to bring in some libraries along with it.

If you followed our instructions for the Pi Camera, you’ll recognise some of these and if you’re brand new, we’ll be taking you through them anyway.

from gpiozero import Button, MotionSensor import requests import time from time import gmtime, strftime from pygame import mixer from picamera import PiCamera

Code Explainer: Libraries for Sensor

Here, we’ve told Python to bring in the GPIO Pins, but to only bring in the Button and Motion Sensor information.

To get Requests, you’ll need to head into your terminal and use:

pip install requests

If you haven’t got pip installed, you can do so by using the terminal and typing:

sudo apt-get install python3-pip

Pip is a simple way to pull down needed files and libraries from resources that support it.

Requests is described as being built for humans and is a fairly simple way to interact with the web.

Of course, we’ll need time and two alternatives for file names and annotations on the images being captured.

pygame is a resource that features a lot of different tools for Python to take advantage of, but we only need the sound-producing module for it here, so that’s why we’re only importing mixer.

If it’s not already installed do so by:

pip install pygame

And of course, the camera module, bringing in the hardware via PiCamera.

Setting up the Doorbell Sound #1

Next we need to define the hardware to the pins it is using and to tell Python what we intend to call them:

doorbell = Button(17)cam = PiCamera()sen = MotionSensor(26)

Next, define some file names. I’m not a master of python, but when cobbling this code together in an attempt to stop images overwriting one another, this worked for me.

filename = ""vid_filename = ""

And to initialise the Mixer, as well as bring in a chosen sound:

mixer.init()sound = mixer.Sound('doorbell-1.wav')]]>
https://www.pcguide.com/raspberry-pi/how-to/make-private-ring-doorbell/ https://www.pcguide.com/?p=34729 Thu, 16 Sep 2021 15:10:41 +0100
How to Install and Use Raspberry Pi Camera The Raspberry Pi's camera module is great. It really is!  While the quality isn't going to blow anyone away, nor are the alternatives, it's a really cool way to experiment or create your own security camera or even, just a fun toy to tinker with.

Installing it is relatively simple, but this won't work on the Pi 400, as there's no camera module slot and the Pi Zero requires its own special ribbon cable to connect. The Pi 400 can use USB Cameras in place, but they do require their own commands.

Before we start, shut down your Pi completely, as connecting the ribbon cable while it's on will cause it to short and shut down.

Camera Set Up

Go into Preferences from the Pi's 'start menu', then Configuration. Toggle the Camera option to Enabled and then press OK.

Reboot your Pi.

Doing it this way will prevent us from having to reboot the Pi a second time after installing the cable.

Python Script: Making Definitions

'def' in Python allows us to define what we want a specific piece of code to do by condensing it into a word, string, or letter. This way we can do a bunch of messy code things at the top of the page and then simplify it as we go down.

First, let's define the photo capturing of our code:

def capture():global outputoutput = strftime("/home/pi/Desktop/image-%d-%m %H:%M-%S.jpg", gmtime())cam.capture(output)print("saved")

Here, we're telling Python that Capture is going to look at the global output that we set to blank, then replace that blank with the time and date.

cam.capture(output) tells it to then name the file that we set as output.

Finally, print is Python's own version of repeating back what you put in, so we'll tell it to say saved to tell the user that things are a-okay.

Next, let's make one for capturing video:

def cap_vid():global outputoutput = strftime("/home/pi/Desktop/image-%d-%m %H:%M-%S.h264", gmtime())cam.start_preview()cam.start_recording(output)print("recording...")cam.wait_recording(10)cam.stop_recording()cam.stop_previewprint("saved")

Same as before for global output, except now we need to call in the recording functions, so cam.start_recording will bring in that and the brackets with output tells it to use the file name we've set.

Obviously, we need to indicate that we're recording, so print("recording...") handles this for us and the two bits sandwiching it, cam.start_preview and cam.stop_preview allow us to see what we're capturing.

Once done, the print("saved") tells users that it's done.

We now need a dedicated preview button:

def preview_cam():cam.start_preview()time.sleep(10)cam.stop_preview()

This starts a preview and then time.sleep(10) only has it last for ten seconds.

Telling the buttons what to do

Now we need to tell the buttons what they're supposed to do when we actually press them. We already indicated what each pin means to Python, so now let's tell it what happens when we make the physical connection.

preview.when_pressed = cam.start_previewpreview.when_released = cam.stop_previewphoto.when_pressed = capturevideo.when_pressed = cap_vid

This links these commands with our definitions and the Pi Camera's own library of code that we imported.

If you press Run, you should now see the results of the code so far for the physical buttons!

Building the User Interface

TKinter is a bit weird, it's why I asked you to import both the whole thing and a specific section, as when I was building this script, this was what got it working.

root = tkinter.Tk()root.title('Camera!')root.geometry("300x300")

This creates the box and labels it on the top bar. It'll create it at 300x300 pixels wide.

A = tkinter.Button(text = "preview", command = preview_cam)B = tkinter.Button(text = "video", command = cap_vid)C = tkinter.Button(text = "photo", command = capture)

This creates three individual buttons and then gives them text inside, as well as indicating what def they need to pull in.

A.pack(fill="both", expand=True, padx=20, pady=20)B.pack(fill="both", expand=True, padx=20, pady=20)C.pack(fill="both", expand=True, padx=20, pady=20)

Then we'll expand the buttons out and make it look a little nicer.

root.mainloop()

Now we need to loop it around, so this just tells Python to reset it.

When you press Run now, you'll find it'll load up a window that we created! From here, it acts exactly the same as the physical buttons.

If you want to run this without loading Thonny (maybe between different Pi devices), you can go into Terminal and load it up from there.

For instance, I have it saved in Documents on the Pi, so I will type:

cd Documentspython3 cam3.py

Everything you have said to print will now appear there too.

Python Raspiberry Pi Camera Script

Download the File! (.zip)

Copy Paste (remember to keep the indents!)

#Import librariesfrom gpiozero import Buttonfrom picamera import PiCamerafrom time import gmtime, strftimeimport timeimport tkinterfrom tkinter import messagebox

#GPIOcam = PiCamera()preview = Button(17)photo = Button(27)video = Button(14)

#File outputoutput = ""

#capture photosdef capture():

global outputoutput = strftime("/home/pi/Desktop/image-%d-%m %H:%M-%S.jpg", gmtime())cam.capture(output)print("saved")

#capture videodef cap_vid():

global outputoutput = strftime("/home/pi/Desktop/image-%d-%m %H:%M-%S.h264", gmtime())cam.start_preview()cam.start_recording(output)print("recording...")cam.wait_recording(10)cam.stop_recording()cam.stop_preview()print("saved")

#preview the cameradef preview_cam():

cam.start_preview()time.sleep(10)cam.stop_preview()

#Camera Button Controlspreview.when_pressed = cam.start_previewpreview.when_released = cam.stop_previewphoto.when_pressed = capturevideo.when_pressed = cap_vid

#TKinter GUI

root = tkinter.Tk()root.title('Camera!')root.geometry("300x300")

#TKinter Buttons

A = tkinter.Button(text = "preview", command = preview_cam)B = tkinter.Button(text = "video", command = cap_vid)C = tkinter.Button(text = "photo", command = capture)

#TKinter Niceness

A.pack(fill="both", expand=True, padx=20, pady=20)B.pack(fill="both", expand=True, padx=20, pady=20)C.pack(fill="both", expand=True, padx=20, pady=20)root.mainloop()

Connect the cable

Do not remove the plastic covering entirely.

I learnt this the hard way, it just makes it more difficult to pop the cable in afterwards. Gently lift up the plastic cover indicated on the Pi's board with 'camera'. Then, gently slot in the camera's cable with the blue piece of plastic on the end of the cable facing towards the USB ports on the Pi's board.

If you're using another camera like I am, connect the ribbon cable to the back of the camera, with the blue tape facing away from the lens.

Take a Photo

Open a Terminal window and we can now take a photo via the Command Line! Don't worry, we'll be making it a bit easier for you to take photos with the camera in a bit, so you won't have to type this in entirely every time.

In the Terminal type:

raspistill -o /Desktop/photo.jpg

This will take a photo at the full resolution of your installed camera, but if you don't want it to, you can set the height and width.

raspistill -o /Desktop/photo.jpg -w 1920 -h 1080 (you can set it to whatever you want!)

If your camera is upside down and you don't want to edit it in post, be sure to add -vf and -hf for Vertical and Horizontal flips.

Remember that you can set the destination to anywhere, just know the path you want it to go to!

Take a Video

Taking a video works the same way as the photos, it just requires a few changes to the line in the terminal.

In the Terminal type:

raspivid -o /Desktop/vid.h264

Video by default on Raspberry Pi usually will record five seconds, we can change this by adding:

-t [time in milliseconds]

(No brackets needed on your end, just the milliseconds!)

You can also add the same resolution requirements as needed.

Now, just telling you how to build some Python code that you can find anywhere might be an easy way through, but we're about making your life easy, not providing you with the same information.

So let's build a physical and software-based camera that you can load up and use!

For the hardware, I'm using the Elegoo Ultimate Pack, which comes with a breadboard, wires, and a host of other stuff. It's a bargain and even comes with some Arduino boards if you want to taste those waters as well.

The things we'd need out of it are:

The breadboardJumper cables (Male to Female)Buttons

Obviously, if you have your own kit, this will still work!

Python Pi Camera Script - Import

Python is a complex beast, but it's pretty easy to see what it's trying to do when you breathe and look closer.

Open Thonny (Raspberry > Programming > Thonny) and then start a new file by saving it (CTRL+S) and name it whatever you want. I named mine cam3.py.

We need to tell Python what we want to pull in to work with, otherwise, it'll not understand what we need to do.

from gpiozero import Buttonfrom picamera import PiCamerafrom time import gmtime, strftimeimport timeimport tkinterfrom tkinter import messagebox

What we're asking Python to bring in is to look at the GPIO pins via gpiozero and then asking it to only really focus on Button functions. Of course, we need to work with the Pi Camera itself, but we need the commands.

While we're importing time, we need to also ask it to import from time to focus on gmtime and strftime.

Then the last one is Tkinter, which we'll have to install separately in some cases. If you're getting errors when working on things and it revolves around no module for Tkinter, open a terminal and type in:

% sudo apt-get install python3-tk

Tkinter is the part of Python that generates a user interface for those of us without hardware.

Import Tkinter with both import tkinter and from tkinter import messagebox. This will allow us to work with pop-up boxes.

Python Camera Script - Assigning Buttons and Files

If you've followed Raspberry Pi's own stop motion tutorial, this will look very familiar, but what we're about to do is tell Python where we've plugged the pins into buttons and what button is what. We'll also be naming the camera in the script.

I've written it out like so:

cam = PiCamera()preview = Button(17)photo = Button(27)video = Button(14)

They might look random, but when you begin to piece it together, the wires will be very easy to match up along the pins.

Then we need to tell Python not to assign any name to our Photo or Video output, as we'll be indicating this later down the line.

output = ""

Wire Up the Raspberry Pi

For this we'll need some jumper cables that are male to female (you'll get why they're called that) and plug in the female ends to the pins directly on the Pi. The other side will go to the buttons on the breadboard.

Make sure your buttons are facing with their legs in a vertical way if you were looking straight down at them.

Make sure you match the wires so that Ground is mostly blacks or greys and the wires going out to each button is a different colour so you can remember what is what.

With the line of holes left in a vertical line on the breadboard, plug in a ground wire to each of the lower legs and then your action wires to the one above it.

The pins that we want to use on the Pi are as follows:

17, 27, 14 - Activity Wires

You can connect the Ground wires wherever there's a spare ground pin, but try to aim to keep them clumped together. (It looks neater!)

 

]]>
https://www.pcguide.com/raspberry-pi/how-to/install-and-use-raspberry-pi-camera/ https://www.pcguide.com/?p=33432 Tue, 07 Sep 2021 09:44:16 +0100
How To SSH Into Raspberry Pi Raspberry Pi has made coding, development and programming accessible to everyone due to its low price-point and versatility of the open-source operating system. From programming robots to creating retro games consoles, most people would benefit from having a Raspberry Pi in their lives.

Go Back To Your Windows PC

Open up Putty and type the Raspberry pi IP Address into the 'Host Name (or IP address)' field. Name the session whatever you'd like and click Open.

Enter Raspberry Pi Credentials into the Putty Command Line

Providing you haven't changed the default SSH login details, type 'pi' next to the 'Login As:' command line. Next, type 'raspberry' on the next command line. Hit enter and you are free to use SSH on your Raspberry Pi 4.

Bonus Hint

Right-click the Putty icon and go to properties. In The 'Target:' field, there is a handy line of text that can be put in that will boot Putty to a logged in SSH command console, no logging in. Just replace the IP address, login name and password with your own:

D:putty.exe -ssh 192.168.178.95 -1 pi -pw 1234

Going back to robot programming, most judgement day machines don’t have a screen or viewable interface as standard, making installing new software or updating code a bit of a pain. Fear not coding friends, there’s an encrypted networking technology called ‘Secure Shell’ (SSH) which is made to enable users to remotely use their Raspberry Pi creations from another machine.

Why/When Should You Use SSH?

SSH comes in super handy when running multiple Pi’s and controlling them via one monitor without ‘shelling’ out for the necessary networking kit. A good rule of thumb is to use SSH when trying to command or run something on a Raspberry PI remotely. This could be from the robotics project you’ve been running or updating a Pi that doubles as a set-top box. Other examples, executing Order 66 or initiating Judgement Day on Skynet compatible devices.

SSH Into Raspberry Pi

Download Putty

Before messing around with your Raspberry Pi, a SSH manager is needed for external connectivity. Putty is a highly recommended program and will be the foundation of this how-to. Download Putty here.

Start up Raspberry Pi

Click the Raspberry Pi Logo >  Preferences > Raspberry Pi Configuration

Enable SSH

SSH is disabled by fault, this used to be enabled in all builds before 2016 but was changed for user security. Go to Interfaces and click Enable next to SSH

Find Raspberry Pi IP Address

Simply hold the cursor over the Wi-Fi/Local connection icon on the top right of the screen to Display the Raspberry Pi IP Address. Alternatively, you can type 'hostname -I' into the command line inside the Raspberry Pi terminal.

]]>
https://www.pcguide.com/raspberry-pi/how-to/ssh/ https://www.pcguide.com/?p=30528 Fri, 20 Aug 2021 14:46:38 +0100
How to install & set up Windows 11 on Raspberry Pi 4 While there has been plenty of chatter around TPM 2.0 and CPU requirements for Windows 11, leaving owners of older generation PCs worried if they’ll ever get their hands on those rounded corners, in a huge turn of events, you can, in fact, install Windows 11 on a tiny, low powered machine - the Raspberry Pi 4.

Why this is such a big deal is because Raspberry Pis in general are known for tinkering and those wanting to maybe emulate some old school games due to their inexpensive nature and time form factor. But now, with the ability to install and run the exciting new Windows update, it opens up an array of possibilities for Pi owners or for those who want a pocket-sized PC capable of an OS of this caliber.

With this guide, we’ll be taking you through all the necessary steps for how to install Windows 11 on Raspberry Pi 4 as well as how to get it set up too so you can experience the fancy new features Microsoft has in store.

How to install Windows 11 on Raspberry Pi 4

Now, let’s not beat around the bush, there are a bunch of steps that you’re going to need to follow to get Windows 11 up and running on your Raspberry Pi 4 but don’t be overwhelmed. If you closely follow the instructions below, you should be able to get Windows 11 up and running no problem and even if you make mistakes, you can revert them and start over.

One caveat we do have to state is that the Windows 11 build used for the Pi install is not an official product from Microsoft due to the image creation process to get it working on the system. This means that installing the OS is at your own risk so proceed with caution.

Allow the process to complete and press 0 to exit.

Insert your storage device into the PC.

Download the Windows on Raspberry Imager tool to create a compatible image.

Extract the downloaded ZIP folder to the “win11” folder you created earlier.

Open the Windows on Raspberry tool.

Choose your preferred language. Click “Next”.

Choose your storage device and set the Pi device to Raspberry Pi 4.

Browse for your created Windows 11 Pi image. Hit “Next”.

Select the “Use the latest driver package on the server” option. Click “Next”.

Choose the “Use the latest UEFI firmware available on the server” option. Press “Next”.

Search for “Windows 11 Arm” on the site UUDump.

A configuration screen will appear. You don’t need to change anything here, just hit “Next”.

You should now see an installation overview. Check everything is correct and click “Install”.

The installation process will now take place. Once completed, eject your storage choice, connect it to your Pi 4 and boot up.

Windows 11 should be installed on your Raspberry Pi 4. Now, let’s get to setting that new OS up.

How to set up Windows 11 on Raspberry Pi 4

Now that you’ve got Windows 11 installed on your Raspberry Pi, you’re also going to have to do a few more tweaks to get the OS set up on your mini PC. Let’s get into how to set up Windows 11 on Raspberry Pi 4.

When booting your Raspberry Pi 4 up, press “ESC” to enter setup.

Select the “Device Manager” option and press “Enter”.

Choose the “Raspberry Pi Configuration” selection.

Within “Raspberry Pi Configuration”, select “Advanced Configuration”.

Remove the RAM limit by changing the “Limit RAM to 3 GB” to “Disabled”. Save this option by pressing “F10” then exit.

Choose the latest Windows 11 build for “arm64”.

Next, enter “Display Configuration” by selecting that option.

Set your desired resolution. Save by pressing “F10” and exit.

Exit to the initial setup menu and hit “Continue”.

And there we have it, you should have not only installed Windows 11 on your Raspberry Pi 4, you should also have it all set up correctly. You can now take advantage of the new features in the new Windows OS in all that Pi compact form factor we all know and love.

Choose the language you’d like the Windows 11 installation to be assigned to.

Opt for your preferred Windows 11 version. In our case, we chose both the Home and Pro versions. Hit ‘Next’.

Select the “Download and convert to ISO” download method and press “Create download package”.

Once the file is downloaded, extract it to your desktop, naming it “win11”.

Open your “win11” folder and double click on uup_download_windows.cmd.

When the security prompt is triggered click “More info”, “Run anyway” and then allow the app to make changes to your PC.

]]>
https://www.pcguide.com/windows-11/how-to/install-on-raspberry-pi-4/ https://www.pcguide.com/?p=27956 Fri, 02 Jul 2021 23:42:55 +0100