# Raspberry Pi Pedal for Youtube

## Overview

![](https://cdn-learn.adafruit.com/assets/assets/000/097/306/medium800thumb/sensors_ezgif.com-optimize%283%29.jpg?1606754672)

Need a little more incentive to meet your exercise goals on a stationary bike?&nbsp; With Adafruit Blinka and a Raspberry Pi 4, you can use a Bluetooth BLE cadence sensor to play YouTube videos only when you are pedaling above a target RPM value.

**This project does not require any soldering or wiring or even modification to your stationary bike - the sensor can be taped onto the bottom of the pedal, and the Raspberry Pi reads the cadence data over wireless Bluetooth!**

The code is easily adjustable, you can add goals, HIIT pacing, even turn it around so you have to pedal harder to _stop_ yourself from watching disgusting videos!

![](https://cdn-learn.adafruit.com/assets/assets/000/097/358/medium800/sensors_PXL_20201201_224939879.NIGHT.jpg?1606868814)

Just hook your Pi to a TV with a Micro HDM to HDMI cable and get pedaling!

## Parts
### Raspberry Pi 4 Model B - 4 GB RAM

[Raspberry Pi 4 Model B - 4 GB RAM](https://www.adafruit.com/product/4296)
The Raspberry Pi 4 Model B is the newest Raspberry Pi computer made, and the Pi Foundation knows you can always make a good thing _better_! And what could make the Pi 4 better than the 3? How about a&nbsp;_faster_ processor, USB 3.0 ports, and updated Gigabit Ethernet chip with...

Out of Stock
[Buy Now](https://www.adafruit.com/product/4296)
[Related Guides to the Product](https://learn.adafruit.com/products/4296/guides)
![Angled shot of Raspberry Pi 4](https://cdn-shop.adafruit.com/640x480/4296-11.jpg)

Info: 

### Micro HDMI to HDMI Cable - 2 meter

[Micro HDMI to HDMI Cable - 2 meter](https://www.adafruit.com/product/1322)
Connect an HDMI device with a micro HDMI port to one with a regular size HDMI port together with this basic HDMI cable. It has nice molded grips for easy installation, and is 2 meter long (about 6 feet). This is a HDMI 1.3 cable. Works great with a BeagleBone or Raspberry Pi 4  
  
<img...></img...>

In Stock
[Buy Now](https://www.adafruit.com/product/1322)
[Related Guides to the Product](https://learn.adafruit.com/products/1322/guides)
![Coiled, 2 meter long, black, micro HDMI to HDMI cable.](https://cdn-shop.adafruit.com/640x480/1322-05.jpg)

### Official Raspberry Pi Foundation Raspberry Pi 4 Case - Red White

[Official Raspberry Pi Foundation Raspberry Pi 4 Case - Red White](https://www.adafruit.com/product/4301)
Keep your Raspberry Pi® 4 Model B&nbsp;computer safe and snug in this solid ABS acrylic enclosure. Y[ou can even pick up an official case fan + heatsink kit](https://www.adafruit.com/product/4794) to super-charge your Pi 4 projects and keep them cool even under computational...

In Stock
[Buy Now](https://www.adafruit.com/product/4301)
[Related Guides to the Product](https://learn.adafruit.com/products/4301/guides)
![Partially assembled Red and whit Raspberry Pi Foundation Raspberry Pi 4 Case. ](https://cdn-shop.adafruit.com/640x480/4301-03.jpg)

### Official Raspberry Pi Power Supply 5.1V 3A with USB C

[Official Raspberry Pi Power Supply 5.1V 3A with USB C](https://www.adafruit.com/product/4298)
The official Raspberry Pi USB-C power supply is here! And of course, we have 'em in classic Adafruit black! Superfast with just the right amount of cable length to get your Pi 4 projects up and running!

Best for use with Pi 4 series, [Pi...](https://www.adafruit.com/product/5814)

In Stock
[Buy Now](https://www.adafruit.com/product/4298)
[Related Guides to the Product](https://learn.adafruit.com/products/4298/guides)
![Angled shot of Official Raspberry Pi Power Supply 5.1V 3A with USB C with Power plug facing down. ](https://cdn-shop.adafruit.com/640x480/4298-04.jpg)

### Part: Wahoo RPM Cycling Cadence Sensor, Bluetooth/ANT+ 
quantity: 1
Other Bluetooth Low Energy Cadence Sensors may also work
[Wahoo RPM Cycling Cadence Sensor, Bluetooth/ANT+ ](https://www.amazon.com/Wahoo-Cycling-Cadence-Sensor-Bluetooth/dp/B00L9XNFPY/)

# Raspberry Pi Pedal for Youtube

## Install the cadence sensor

There are multiple ways to install a cadence sensor, but the key is to make sure it is going around in a big circle while you're pedaling. The manufacturer may include a variety of options.

This sensor uses an accelerometer so you don't need a magnet or other external sensor, its a self-contained blob!

I used the included double side adhesive to install it under one of my bike's foot pedals. It took just a minute and works great!

![](https://cdn-learn.adafruit.com/assets/assets/000/097/339/medium800/sensors_PXL_20201127_181956980.jpg?1606859680)

# Raspberry Pi Pedal for Youtube

## Set up Raspberry Pi OS

Raspberry Pi OS (the new name for Raspian), which is based on Debian Linux, also comes with Python. The latest version as of this writing, buster, comes with Python 3.7, invoked with the `python3` command. It also comes with Python 2.7, invoked as `python`. Do not use Python 2 for this guide.  
  
**This guide assumes that you are using the "full" version of Raspberry Pi OS that boots to a desktop operating system, that way you can play YouTube videos in the browser.**

We assume that you've already got your Pi set up, Pi OS (Raspbian) Full installed, keyboard and monitor attached, and you're logged in with WiFi/Ethernet networking set up you know your way around a Terminal command line

Warning: 

## Do Not Use `sudo` When Running `pip3`

You may see Internet advice to install libraries using `sudo pip3` on Linux or MacOS. This is in general a bad idea, because you can damage the libraries that the underlying system depends on, and in general end up trashing your system in mysterious ways. Always install using `pip3` without `sudo`. If your `pip3` is old, you may need to specify `pip3 --user`, but these days `--user` is often the default.

[Here's a detailed discussion](https://stackoverflow.com/questions/29310688/sudo-pip-install-vs-pip-install-user) of why `sudo pip3` is a bad idea.

Run the following command to install the required Python packages for the project:

```python
pip3 install --upgrade adafruit-blinka-bleio adafruit-circuitpython-ble adafruit-circuitpython-ble-cycling-speed-and-cadence python-xlib
```

## Add User to `bluetooth` Group

On Linux, including on Raspberry Pi, you must also add your user to the `bluetooth` group. Reboot after doing this to ensure your user is added to the group and also to ensure that `~/.local/bin` is added to your path (after doing `pip3` above). To add yourself to the group, do this (the second command will restart your computer, so save any documents or files first!):

```none
sudo usermod -a -G bluetooth $USER
sudo reboot
```

## Raspberry Pi 4B Firmware Fix

Raspberry Pi **4B** boards use different hardware for BLE and WiFi than Raspberry Pi **3B** and Pi **Zero W** boards. There is currently (as of October 2020) a bug in the firmware for the 4B boards, in package `bluez-firmware_1.2-4+rpt5_all.deb`. You must roll back the firmware package to an earlier version (`rpt2`) to get one that works. Do this **only for 3B+ and 4B boards**.

This bug is being tracked here: [https://github.com/RPi-Distro/bluez-firmware/issues/6](https://github.com/RPi-Distro/bluez-firmware/issues/6).

The third command will restart your computer, so save any documents or files first!

Danger: 

```python
wget http://archive.raspberrypi.org/debian/pool/main/b/bluez-firmware/bluez-firmware_1.2-4+rpt2_all.deb
sudo dpkg --install bluez-firmware_1.2-4+rpt2_all.deb
sudo reboot
```

# Raspberry Pi Pedal for Youtube

## Set up Chrome Browser Extension

A common but frustrating user-interface thing that we see in video or audio playing devices is they use one key for both play and pause. That's easy for humans, but annoying for us because we want to know that when we sent a certain keypress the video stops, and a _different_ key will start it, so we don't end up 'de synchronized' if the keypress is missed or double-counted somehow.

This script alters behavior on youtube.com so that pressing "p" will pause the video if it was playing. Youtube has a keypress "k" which will pause a playing video or restart a paused video, but for our program we need a way to get the video into a known state. Otherwise, the program could work backwards--pausing when you pedal, playing when you stop.

A simple extension solves this problem and gives us different keys for playing and pausing videos.

Open the Chromium browser on your Pi, go to the Chrome Web Store, and install the "tampermonkey" extension. This extension allows the installation of "user scripts", which can modify the behavior of websites.

![sensors_ksnip_20201127-120830.png](https://cdn-learn.adafruit.com/assets/assets/000/097/268/medium640/sensors_ksnip_20201127-120830.png?1606500526)

Once tampermonkey is installed, [click here to download and install the script shown below.](https://github.com/adafruit/Adafruit_Learning_System_Guides/raw/master/Pedal_For_Youtube/youtube_stop_key.user.js) Tampermonkey will pop up a screen with an "install" button. Click it.

![sensors_ksnip_20201130-093839.png](https://cdn-learn.adafruit.com/assets/assets/000/097/304/medium640/sensors_ksnip_20201130-093839.png?1606750937)

[Head over to YouTube](https://www.youtube.com/watch?v=aqz-KE-bpKQ) and check that you can pause the playing video by typing "p" and continue playback by pressing "k". If so, you're good to go. Otherwise, you will need to double check the above steps to make sure that the Tampermonkey extension and the Youtube Pause Key userscript are correctly installed.

(There are other extensions that add capabilities like this to YouTube, but they are very complex. We wrote our own so that you can see exactly what it does, and be confident it isn't doing anything you don't want.)

[Click here to download and install the script shown below.](https://github.com/adafruit/Adafruit_Learning_System_Guides/raw/master/Pedal_For_Youtube/youtube_stop_key.user.js)

```javascript
// ==UserScript==
// @name          Youtube Pause Key
// @version       1
// @namespace     http://unpythonic.net.com/youtube-pause-key
// @include       http://youtube.com/*
// @include       https://youtube.com/*
// @include       http://www.youtube.com/*
// @include       https://www.youtube.com/*
// @grant none
// ==/UserScript==

(function () {
    var inject = function() {
        var is_press_key = function (e, key) {
            document.last_target = e.target;
            document.last_event = e;
            var keyCode = e.keyCode ? e.keyCode : e.which;
            return (! (e.altKey || e.ctrlKey || e.metaKey)
                    &amp;&amp; keyCode == key);
        }

        var gr_in_bg_event = function(e) {
            var pause_key = 112; // 'p' key
            var videos = e.target.getElementsByTagName('video');
            if(videos.length == 0) { return true; }
            if (is_press_key(e, pause_key)) {
                videos[0].pause();
                e.stopPropagation();
                e.preventDefault();
                return;
            }
            return true;
        }

        document.addEventListener("keypress", gr_in_bg_event, true);
    }

    var newel = document.createElement("script");
    var newcontent = document.createTextNode("(" + inject + ")()")
    newel.appendChild(newcontent);
    document.body.appendChild(newel);
})()
```

# Raspberry Pi Pedal for Youtube

## Using and Customizing the script

Download [the main script from github](https://github.com/adafruit/Adafruit_Learning_System_Guides/blob/master/Pedal_For_Youtube/code.py) and save it as **code.py**.

![sensors_ksnip_20201201-161824.png](https://cdn-learn.adafruit.com/assets/assets/000/097/345/medium640/sensors_ksnip_20201201-161824.png?1606861131)

Double-click it and choose "Execute in terminal".

![sensors_ksnip_20201201-161923.png](https://cdn-learn.adafruit.com/assets/assets/000/097/346/medium640/sensors_ksnip_20201201-161923.png?1606861183)

The terminal will show a scary (but unimportant) message. More importantly, the OSD will appear and show "Scanning".

![sensors_ksnip_20201201-162130.png](https://cdn-learn.adafruit.com/assets/assets/000/097/347/medium640/sensors_ksnip_20201201-162130.png?1606861326)

Start the Chrome browser, navigate to youtube.com, and pick whatever kind of video is your catnip.

![sensors_ksnip_20201201-162239.png](https://cdn-learn.adafruit.com/assets/assets/000/097/348/medium640/sensors_ksnip_20201201-162239.png?1606861408)

![sensors_ksnip_20201201-162544.png](https://cdn-learn.adafruit.com/assets/assets/000/097/349/medium640/sensors_ksnip_20201201-162544.png?1606861562)

Start pedaling after a few seconds (give it a good 15 seconds), the sensor will be detected and your cadence in RPMs will be displayed.

![](https://cdn-learn.adafruit.com/assets/assets/000/097/361/medium800/sensors_image.png?1606886053)

In the default script, if you are in the red zone (below 60RPM), the video will pause after 2 seconds. If you're in the yellow zone (60 to 72RPM) or green zone (above 72RPM), the video will continue playing. You can customize these values by editing the script and restarting it.

The script is able to detect when the active window is a Chromium browser window but not whether you're on a YouTube video. If your computer is randomly typing "p" and "k" into websites, make sure you've stopped the script! Just return to the terminal window where you started the script and use the close button in the corner ( **×** ) or press **Ctrl-C** to interrupt it.

## Customization

The script is set up so that you can easily customize the following values:

`MINIMUM_RPM = 60TARGET_RPM = 72GRACE_TIME = 2`

Ready to do something more in depth? Here are just a few of the other ideas the author and his friends had while writing this guide:

- The On Screen Display of cadence is fairly crude. How would you improve it?
- Can the program manage a whole workout, with changing target cadences and timed breaks (where the video doesn't stop?)
- Make it to work with additional video services or local video players such as **vlc**
- Interface with other BLE sensors or devices—Adafruit Blinka BLE can work with a whole range of Bluetooth Low Energy modules and sensors such as heart rate monitors, temperature sensors, BLE light bulbs, or developer boards like the CircuitPlayground Bluefruit or CLUE


## Featured Products

### Raspberry Pi 4 Model B - 4 GB RAM

[Raspberry Pi 4 Model B - 4 GB RAM](https://www.adafruit.com/product/4296)
The Raspberry Pi 4 Model B is the newest Raspberry Pi computer made, and the Pi Foundation knows you can always make a good thing _better_! And what could make the Pi 4 better than the 3? How about a&nbsp;_faster_ processor, USB 3.0 ports, and updated Gigabit Ethernet chip with...

Out of Stock
[Buy Now](https://www.adafruit.com/product/4296)
[Related Guides to the Product](https://learn.adafruit.com/products/4296/guides)
### Micro HDMI to HDMI Cable - 2 meter

[Micro HDMI to HDMI Cable - 2 meter](https://www.adafruit.com/product/1322)
Connect an HDMI device with a micro HDMI port to one with a regular size HDMI port together with this basic HDMI cable. It has nice molded grips for easy installation, and is 2 meter long (about 6 feet). This is a HDMI 1.3 cable. Works great with a BeagleBone or Raspberry Pi 4  
  
<img...></img...>

In Stock
[Buy Now](https://www.adafruit.com/product/1322)
[Related Guides to the Product](https://learn.adafruit.com/products/1322/guides)
### Official Raspberry Pi Foundation Raspberry Pi 4 Case - Red White

[Official Raspberry Pi Foundation Raspberry Pi 4 Case - Red White](https://www.adafruit.com/product/4301)
Keep your Raspberry Pi® 4 Model B&nbsp;computer safe and snug in this solid ABS acrylic enclosure. Y[ou can even pick up an official case fan + heatsink kit](https://www.adafruit.com/product/4794) to super-charge your Pi 4 projects and keep them cool even under computational...

In Stock
[Buy Now](https://www.adafruit.com/product/4301)
[Related Guides to the Product](https://learn.adafruit.com/products/4301/guides)
### Official Raspberry Pi Power Supply 5.1V 3A with USB C

[Official Raspberry Pi Power Supply 5.1V 3A with USB C](https://www.adafruit.com/product/4298)
The official Raspberry Pi USB-C power supply is here! And of course, we have 'em in classic Adafruit black! Superfast with just the right amount of cable length to get your Pi 4 projects up and running!

Best for use with Pi 4 series, [Pi...](https://www.adafruit.com/product/5814)

In Stock
[Buy Now](https://www.adafruit.com/product/4298)
[Related Guides to the Product](https://learn.adafruit.com/products/4298/guides)
### 16GB Card with NOOBS 3.1 for Raspberry Pi Computers including 4

[16GB Card with NOOBS 3.1 for Raspberry Pi Computers including 4](https://www.adafruit.com/product/4266)
NOOBS 3.1&nbsp;is the fastest way to have a variety of operating systems on your Pi. Available on a 16G card, you can now boot multiple OS's such as Raspbian, Pidora, RaspBMC, Snappy Ubuntu, etc. There's a boot up menu for selecting which one you like.&nbsp; **This card has NooBs...**

No Longer Stocked
[Buy Now](https://www.adafruit.com/product/4266)
[Related Guides to the Product](https://learn.adafruit.com/products/4266/guides)
### Raspberry Pi 4 Model B - 2 GB RAM

[Raspberry Pi 4 Model B - 2 GB RAM](https://www.adafruit.com/product/4292)
The Raspberry Pi 4 Model B is the newest Raspberry Pi computer made, and the Pi Foundation knows you can always make a good thing _better_! And what could make the Pi 4...

Out of Stock
[Buy Now](https://www.adafruit.com/product/4292)
[Related Guides to the Product](https://learn.adafruit.com/products/4292/guides)

## Related Guides

- [Raspberry Pi Care and Troubleshooting](https://learn.adafruit.com/raspberry-pi-care-and-troubleshooting.md)
- [CLUE Metal Detector in CircuitPython](https://learn.adafruit.com/clue-metal-detector-circuitpython.md)
- [Feather-based Hue lighting controller](https://learn.adafruit.com/feather-hue-lighting-controller.md)
- [Raspberry Pi E-Ink Weather Station using Python](https://learn.adafruit.com/raspberry-pi-e-ink-weather-station-using-python.md)
- [Alohamora Bottle](https://learn.adafruit.com/alohamora-bottle.md)
- [DIY Pi 400 Keyboard Case](https://learn.adafruit.com/pc-keyboard-case.md)
- [Single Channel LoRaWAN Gateway for Raspberry Pi](https://learn.adafruit.com/raspberry-pi-single-channel-lorawan-gateway.md)
- [Using IFTTT with Adafruit IO to Make an IoT Door Detector](https://learn.adafruit.com/using-ifttt-with-adafruit-io.md)
- [Using an IR Remote with a Raspberry Pi Media Center](https://learn.adafruit.com/using-an-ir-remote-with-a-raspberry-pi-media-center.md)
- [Local LLMs on Raspberry Pi](https://learn.adafruit.com/local-llms-on-raspberry-pi.md)
- [Bluetooth Cycling Speed & Cadence Sensor Display with Clue](https://learn.adafruit.com/bluetooth-bicycle-speed-cadence-sensor-display-with-clue.md)
- [CircuitPython Libraries on Linux and Google Coral](https://learn.adafruit.com/circuitpython-on-google-coral-linux-blinka.md)
- [Jack-o-Theremin](https://learn.adafruit.com/jack-o-theremin.md)
- [Multi-Sensor IoT Environmental Sensor Box With CircuitPython](https://learn.adafruit.com/remote-iot-environmental-sensor.md)
- [Motion-Activated Solder Fume Extractor With Lamp](https://learn.adafruit.com/motion-activated-solder-fume-extractor-with-lamp.md)
- [Adafruit RP2350 22-pin FPC HSTX to DVI Adapter](https://learn.adafruit.com/adafruit-rp2350-22-pin-fpc-hstx-to-dvi-adapter.md)
