# Raspberry Pi

樹莓派是基於Linux的單晶片電腦，由英國樹莓派基金會開發，目的是以低價硬體及自由軟體促進學校的基本電腦科學教育。

# Learning

##### Tutorials

- [Create your own custom Raspberry Pi image](https://opensource.com/article/21/7/custom-raspberry-pi-image)
- [PiShrink – Make Raspberry Pi Images Smaller](https://ostechnix.com/pishrink-make-raspberry-pi-images-smaller/)
- [Getting Started with Raspberry Pi | Random Nerd Tutorials](https://randomnerdtutorials.com/getting-started-with-raspberry-pi/)
- [RaspberryTips – Raspberry Pi projects and tutorials](https://raspberrytips.com/)

##### Pi Kiosk

- [https://github.com/geerlingguy/pi-kiosk](https://github.com/geerlingguy/pi-kiosk)

#### Hardware

##### Raspberry Pi Laptop

- [CrowPi](https://www.crowpi.cc/) - Rasberry Pi Laptop 
    - \[Video\] [This New Raspberry Pi Laptop Is Actually Pretty Good, CrowPi L Hands On](https://www.youtube.com/watch?v=DxCawfE3eq0)
- [Argon One Up](https://argon40.com/)
    - [Argon 40 推出 One Up 具有 GPIO 端子的筆記型電腦套件，利用 Raspberry Pi CM 5 打造 14 吋筆電 | T客邦](https://www.techbang.com/posts/125245-argon-40-one-up)
    - [Argon ONE UP: An Open Source ARM Laptop for the Community by Argon Forty — Kickstarter](https://www.kickstarter.com/projects/argonforty/upton-one-the-true-raspberry-pi-compute-module-5-laptop)

##### Components

- Case 
    - [樹莓派Raspberry Pi4B鋁合金散熱外殼](https://shop.playrobot.com/products/rpi-dtr0271)
    - [樹莓派4B直條紋鋁合金機殼(內建導熱柱)](https://www.meiyagroup.com.tw/product/%E6%A8%B9%E8%8E%93%E6%B4%BE4b%E7%9B%B4%E6%A2%9D%E7%B4%8B%E9%8B%81%E5%90%88%E9%87%91%E6%A9%9F%E6%AE%BC%E5%85%A7%E5%BB%BA%E5%B0%8E%E7%86%B1%E6%9F%B1/)
    - [Is This The Best Raspberry Pi 4 Case? The New Argon One M.2 - Review](https://www.youtube.com/watch?v=LLc4pF3jZQg)
- DHT22 Sensor 
    - [Monitor temperature and humidity with Grafana and Raspberry Pi](https://grafana.com/blog/2023/10/23/monitor-temperature-and-humidity-with-grafana-and-raspberry-pi/)
- NVMe SSD 
    - \[Video\] [FINALLY! NVMe SSDs on the Raspberry Pi](https://www.youtube.com/watch?v=EXWu4SUsaY8)
- SunFounder 
    - [Raspberry Pi Store (sunfounder.com)](https://www.sunfounder.com/collections/raspberry-pi-store)

# Picroft

#### Introduction

Picroft is a ready-made way to run Mycroft on a Raspberry Pi 3, 3B+ or 4 and is provided as a disk image that you can burn to a Micro SD card.

Links

- [Official Home](https://mycroft-ai.gitbook.io/docs/using-mycroft-ai/get-mycroft/picroft)
- Youtube Tutorials 
    - [https://www.youtube.com/watch?v=M398I6YIleM](https://www.youtube.com/watch?v=M398I6YIleM)
    - [https://www.youtube.com/watch?v=4luTnRpfgbs](https://www.youtube.com/watch?v=4luTnRpfgbs)

# Raspberry Pi OS

#### Installation

- [Raspberry Pi Imager](https://www.raspberrypi.com/software/)

Ubuntu 22.04

```bash
sudo apt install rpi-imager
```

#### Create User

<p class="callout info">NOTE: 新版 Raspberry Pi OS 已經移除內建帳號 pi。使用前需要手動先建立帳號。</p>

##### Headless Setup

SD Card &gt; Boot partition &gt; File: `userconf`

userconf:

```
alang:<encrypted-password>
```

Generate encrypted password

```bash
echo 'mypassword' | openssl passwd -6 -stdin
```

##### CLI

```bash
# Add user
sudo adduser <username>
sudo usermod -a -G adm,dialout,cdrom,sudo,audio,video,plugdev,games,users,input,netdev,gpio,i2c,spi <username>

# Delete user
sudo deluser -remove-home <username>
```

#### Enable SSH

> Default credential is pi / raspberry

##### Headless setup

SD Card &gt; Boot partition &gt; File: `ssh` (an empty file)

SSH can be enabled by placing a file named `ssh`, without any extension, onto the boot partition of the SD Card.

##### Desktop

1. Launch *Raspberry Pi Configuration* from the *Preferences* menu
2. Navigate to the *Interfaces* tab
3. Select *Enabled* next to *SSH*
4. Click *OK*

Option #3: Using the `raspi-config`

1. Enter *sudo raspi-config* in a terminal window
2. Select *Interfacing Options*
3. Navigate to and select *SSH*
4. Choose *Yes*
5. Select *Ok*
6. Choose *Finish*

#### Wireless LAN

##### Headless setup

SD Card &gt; Boot partition &gt; File: `wpa_supplicant.conf`

wpa\_supplicant.conf :

```
country=TW # Your 2-digit country code
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
network={
    ssid="YOUR_NETWORK_NAME"
    psk="YOUR_PASSWORD"
    key_mgmt=WPA-PSK
}
```

##### CLI

rasp-config CLI

```bash
# Usage: sudo raspi-config nonint do_wifi_ssid_passphrase <ssid> <passphrase> [hidden] [plain]
sudo raspi-config nonint do_wifi_ssid_passphrase myssid 'mypassphrase' 0 0 # Visible SSID, passphrase quoted
```

nmcli

```bash
nmcli dev wifi list
sudo nmcli dev wifi connect <example_ssid>
sudo nmcli --ask dev wifi connect <example_ssid> hidden yes
```

#### Python

Install pip

```bash
sudo apt install python3-pip
pip --version
sudo pip install --upgrade pip
```

雖然 pip 可以成功安裝，不過要繼續安裝 3rd-party 套件時，會遇到以下錯誤。

> error: externally-managed-environment
> 
> × This environment is externally managed  
> ╰─&gt; To install Python packages system-wide, try apt install  
>  python3-xyz, where xyz is the package you are trying to  
>  install.  
>    
>  If you wish to install a non-Debian-packaged Python package,  
>  create a virtual environment using python3 -m venv path/to/venv.  
>  Then use path/to/venv/bin/python and path/to/venv/bin/pip. Make  
>  sure you have python3-full installed.  
>    
>  For more information visit http://rptl.io/venv

新版 Raspberry Pi OS 已經不允許直接安裝 3rd-party 套件；而是必須在 python 虛擬環境才能安裝套件。

建立 python 虛擬環境

```bash
# 以下指令在 user 帳號下執行，例如 pi
mkdir myproject
cd myproject
python -m venv env
source env/bin/activate
which python
# 記得先升級 pip 至最新版
pip install --upgrade pip
# 開始安裝套件
pip install paho-mqtt
# 檢視已安裝套件
pip list
```

要執行 python 程式時，開頭宣告指向虛擬環境的 python，可以避免需要手動進入 python venv。

```python
#!<path-to-venv>/bin/python
```

# PiShrink

##### Dumping existing image

Install cockit on Raspberry Pi

```shell
sudo apt install cockpit
```

Shutdown Raspberry PI, take out the SD card, and connect it to your PC.

The `boot`- and `rootfs`-partitions were automatically mounted at the mentioned mount points. Before you proceed, unmount them with :

```shell
umount /dev/mmcblk0p1
umount /dev/mmcblk0p2
```

Now we copy the contents of the SD card to our file system.

```shell
sudo dd if=/dev/mmcblk0 of=/home/alang/worktmp/PiShrink/my_rasp.v2.img bs=32M
```

Download the PiShrink

[https://github.com/Drewsif/PiShrink ](https://github.com/Drewsif/PiShrink)

Now invoke the script by typing:

```shell
sudo ./pishrink.sh my_rasp.v2.img
```

##### Flash the image to the SD card

- [BalenaEtcher](https://www.balena.io/etcher/)
- [SD Cards and Writing Images](https://learn.sparkfun.com/tutorials/sd-cards-and-writing-images/)

# Xiaomi Mijia Temperature and Humidity Sensor

#### 硬體規格

- 名稱：小米藍芽溫溼度計
- 型號：LYWSD03MMC

#### Raspberry Pi OS

##### 藍芽

> 不需要與溫濕度計做配對，就可以直接讀資料。

```
bluetoothctl
> scan on
> devices
> scan off
> exit
```

##### 安裝 Python module

> NOTE: 新版 Pi OS 只允許在 Python venv 環境下用 pip 安裝第三方套件。

```bash
# 以下指令必須用 user 帳號下執行 (non-root)
mkdir mitemp
cd mitemp
python -m venv env
source env/bin/activate
which python
# 記得先升級 pip 至最新版
pip install --upgrade pip
# 開始安裝套件
sudo apt install libglib2.0-dev
pip install bluepy
pip install lywsd03mmc
pip install paho-mqtt
```

> 錯誤：ERROR: Could not build wheels for bluepy, which is required to install pyproject.toml-based projects

解決：

```bash
sudo apt install libglib2.0-dev
```

#### Telegraf

##### Option 1: Python script

建立設定檔

```bash
mv /etc/telegraf/telegraf.conf /etc/telegraf/telegraf.conf.orig
telegraf --input-filter exec --output-filter influxdb_v2 config > /etc/telegraf/telegraf.conf
```

telegraf.conf

```
[[outputs.influxdb_v2]]
  urls = ["http://127.0.0.1:8086"]

  ## Token for authentication.
  token = "YOUR-TOKEN"
  ## Organization is the name of the organization you wish to write to.
  organization = "YOUR-ORAG"
  ## Destination bucket to write into.
  bucket = "YOUR-BUCKET"

  ## Timeout for HTTP messages.
  timeout = "5s"


[[inputs.exec]]
    interval = "180s"
    commands = ["sudo -u pi /home/pi/mitemp/env/bin/python /home/pi/mitemp/go-mitemp.py"]

    ## Timeout for each command to complete.
    timeout = "30s"

    ## Data format to consume.
    ## Each data format has its own unique set of configuration options, read
    ## more about them here:
    ## https://github.com/influxdata/telegraf/blob/master/docs/DATA_FORMATS_INPUT.md
    data_format = "influx"
```

Test the configuration

```bash
telegraf -config /etc/telegraf/telegraf -test
```

Set the sudo for telegraf

> NOTE: Pi OS 的 telegraf 服務是用 non-root 帳號啟動，如果要執行另一個帳號的 script，必須使用 sudo。

Edit: `/etc/sudoers.d/011_telegraf-nopasswd`

```
telegraf ALL=(ALL) NOPASSWD: /home/pi/mitemp/env/bin/python /home/pi/mitemp/go-mitemp.py
```

##### Option 2: MQTT Consumer

- Plugin: [telegraf/plugins/inputs/mqtt\_consumer/README.md at release-1.29 · influxdata/telegraf (github.com)](https://github.com/influxdata/telegraf/blob/release-1.29/plugins/inputs/mqtt_consumer/README.md)
- [MQTT Broker 伺服器 Mosquitto 安裝、帳號密碼、加密傳輸設定教學與範例 - Office 指南](https://officeguide.cc/mqtt-broker-server-mosquitto-installation-tutorial-examples/)

#### Tutorials

- [pip: LYWSD03MMC](https://pypi.org/project/lywsd03mmc/)
- [制霸 IoT 30Day！ Day 18 藍芽溫濕度計使用](https://blog.sd.idv.tw/posts/2019-10-03-iot30day-day18/)
- [Xiaomi Mijia Hygrothermo v2 sensor data on Raspberry Pi](https://zsitko.com/xiaomi-mijia-hygrothermo-v2-sensor-data-on-raspberry-pi/)
- [Custom firmware for the Xiaomi Thermometer LYWSD03MMC](https://github.com/atc1441/ATC_MiThermometer)
- [Home Asssistant Xiaomi Mijia LYWSD03MMC Temperature and Humidity Sensor Tutorial September 2022](https://community.home-assistant.io/t/home-asssistant-xiaomi-mijia-lywsd03mmc-temperature-and-humidity-sensor-tutorial-september-2022/456403)
- [Xiaomi Mijia Temperature, and Humidity Dashboard](https://grafana.com/grafana/dashboards/15853-xiaomi-mijia-temperature-and-humidity-dashboard/)
- [How to Use Bluetooth on Raspberry Pi: GUI &amp; Command Guide – RaspberryTips](https://raspberrytips.com/raspberry-pi-bluetooth-setup/)

# Monitoring

##### Tutorials 

Telegraf + InfluxDB + Grafana

- [TheMickeyMike/raspberrypi-temperature-telegraf: Collect RaspberryPi CPU and GPU temperature with telegraf (github.com)](https://github.com/TheMickeyMike/raspberrypi-temperature-telegraf)
- [Raspberry Pi Monitoring | Grafana Labs](https://grafana.com/grafana/dashboards/10578-raspberry-pi-monitoring/)
- [System monitoring | Nelis Oostens](http://oostens.me/projects/raspberrypiserver/system-monitoring/)
- [Simple Pi Stats | Grafana Labs](https://grafana.com/grafana/dashboards/12883-simple-pi-stats/)
- [Telegraf / Raspberry Metrics InfluxDB 2.0 (Flux) | Grafana Labs](https://grafana.com/grafana/dashboards/17191-telegraf-raspberry-metrics-influxdb-2-0-flux/)
- [Telegraf: system PI dashboard | Grafana Labs](https://grafana.com/grafana/dashboards/12032-telegraf-system-pi-dashboard/)
- [使用 vcgencmd 指令查看 Raspberry Pi 的 CPU 溫度、運行速度與電壓等資訊 - G. T. Wang](https://blog.gtwang.org/iot/raspberry-pi-vcgencmd-hardware-information/)

Telegraf + InfluxDB

- [Monitoring Your Raspberry Pi System using InfluxDB Telegraf | Random Nerd Tutorials](https://randomnerdtutorials.com/monitor-raspberry-pi-influxdb-telegraf/)

##### Dashboard ID 17191

- Link: [Telegraf / Raspberry Metrics InfluxDB 2.0 (Flux) | Grafana Labs](https://grafana.com/grafana/dashboards/17191-telegraf-raspberry-metrics-influxdb-2-0-flux/)
- Dependencies: InfluxDB v2, Flux Language, Telegraf

telegraf.conf:

```
[[outputs.influxdb_v2]]
  ## The URLs of the InfluxDB cluster nodes.
  ##
  ## Multiple URLs can be specified for a single cluster, only ONE of the
  ## urls will be written to each interval.
  ##   ex: urls = ["https://us-west-2-1.aws.cloud2.influxdata.com"]
  urls = ["http://your.influxdb.server:8086"]

  ## Token for authentication.
  token = "THIS-IS-TOKEN"

  ## Organization is the name of the organization you wish to write to.
  organization = "YOUR-ORG"

  ## Destination bucket to write into.
  bucket = "YOUR-BUCKET"
```

```
[[inputs.net]]
[[inputs.netstat]]
[[inputs.file]]
  files = ["/sys/class/thermal/thermal_zone0/temp"]
  name_override = "cpu_temperature"
  data_format = "value"
  data_type = "integer"
[[inputs.exec]]
#Für ein 32bit System (welches überwacht werden soll)
  commands = ["/usr/bin/vcgencmd measure_temp"] 
#oder für ein 64bit System (welches überwacht werden soll), dann die Raute(#) entfernen und bei 32bit die Raute hinzufügen
# commands = ["/usr/bin/vcgencmd measure_temp"]
  name_override = "gpu_temperature"
  data_format = "grok"
  grok_patterns = ["%{NUMBER:value:float}"]
# Read metrics about cpu usage
[[inputs.cpu]]
  ## Whether to report per-cpu stats or not
  percpu = true
  ## Whether to report total system cpu stats or not
  totalcpu = true
  ## If true, collect raw CPU time metrics
  collect_cpu_time = false
  ## If true, compute and report the sum of all non-idle CPU states
  report_active = false
  ## If true and the info is available then add core_id and physical_id tags
  core_tags = false
# Read metrics about disk usage by mount point
[[inputs.disk]]
  ## By default stats will be gathered for all mount points.
  ## Set mount_points will restrict the stats to only the specified mount points.
  # mount_points = ["/"]
  ## Ignore mount points by filesystem type.
  ignore_fs = ["tmpfs", "devtmpfs", "devfs", "iso9660", "overlay", "aufs", "squashfs"]
  ## Ignore mount points by mount options.
  ## The 'mount' command reports options of all mounts in parathesis.
  ## Bind mounts can be ignored with the special 'bind' option.
  # ignore_mount_opts = []
# Read metrics about disk IO by device
[[inputs.diskio]]
  ## By default, telegraf will gather stats for all devices including
  ## disk partitions.
  ## Setting devices will restrict the stats to the specified devices.
  # devices = ["sda", "sdb", "vd*"]
  ## Uncomment the following line if you need disk serial numbers.
  # skip_serial_number = false
  #
  ## On systems which support it, device metadata can be added in the form of
  ## tags.
  ## Currently only Linux is supported via udev properties. You can view
  ## available properties for a device by running:
  ## 'udevadm info -q property -n /dev/sda'
  ## Note: Most, but not all, udev properties can be accessed this way. Properties
  ## that are currently inaccessible include DEVTYPE, DEVNAME, and DEVPATH.
  # device_tags = ["ID_FS_TYPE", "ID_FS_USAGE"]
  #
  ## Using the same metadata source as device_tags, you can also customize the
  ## name of the device via templates.
  ## The 'name_templates' parameter is a list of templates to try and apply to
  ## the device. The template may contain variables in the form of '$PROPERTY' or
  ## '${PROPERTY}'. The first template which does not contain any variables not
  ## present for the device is used as the device name tag.
  ## The typical use case is for LVM volumes, to get the VG/LV name instead of
  ## the near-meaningless DM-0 name.
  # name_templates = ["$ID_FS_LABEL","$DM_VG_NAME/$DM_LV_NAME"]
# Get kernel statistics from /proc/stat
[[inputs.kernel]]
  # no configuration
# Read metrics about memory usage
[[inputs.mem]]
  # no configuration
# Get the number of processes and group them by status
[[inputs.processes]]
  # no configuration
# Read metrics about swap memory usage
[[inputs.swap]]
# Read metrics about system load & uptime
[[inputs.system]]
```

Set the sudo

```bash
sudo usermod -aG video telegraf
```

# Optimization

##### Disable Desktop Booting

`raspi-config` &gt; 1 System Options &gt; S5 Boot / Auto Login

##### Limit GPU Memeory to 16B

 `raspi-config` &gt; 4 Performance Options &gt; P2 GPU Memory

##### Disable HDMI

Edit `/etc/rc.local`

```
/usr/bin/tvservice -o
exit 0
```

##### Disable Bluetooth

```bash
sudo systemctl disable hciuart
systemctl disable bluetooth.service
```

Edit `/boot/config.txt`

```
dtoverlay=disable-bt
```

##### Disable Onboard LED

Edit `/boot/config.txt`

```
dtparam=pwr_led_trigger=none
dtparam=pwr_led_activelow=off

dtparam=act_led_trigger=none
dtparam=act_led_activelow=off
```

# USB to TTL

##### Tutorials

- [使用 PL2303 HXD USB 轉 TTL 傳輸線，從序列埠登入到 Raspberry Pi B+ - G. T. Wang (gtwang.org)](https://blog.gtwang.org/iot/pl2303-hxd-usb-ttl-raspberry-pi-b-plus/)
- [在 Raspberry Pi 4B 上設定 UART 連線 - HackMD](https://hackmd.io/@oscarshiang/rpi_uart)
- [Using a USB Serial Adapter (UART) to Help Debug Your Raspberry Pi](https://itsfoss.com/use-uart-raspberry-pi/)

##### Hardware

- [【產品/介紹】PL2303HXD USB 轉 TTL 序列埠傳輸線 - 台灣樹莓派 (piepie.com.tw)](https://piepie.com.tw/2044/pl2303hxd-usb-to-ttl-serial-cable)
- [PL2303HX USB 轉 TTL 序列傳輸線 – 台灣物聯科技 TaiwanIOT Studio](https://www.taiwaniot.com.tw/product/pl2303hx-usb-%E8%BD%89-ttl-%E5%BA%8F%E5%88%97%E5%82%B3%E8%BC%B8%E7%B7%9A/)

# DietPi

DietPi is a **highly optimised &amp; minimal Debian-based Linux distribution**. DietPi is extremely lightweight at its core, and also extremely easy to install and use.

Setting up a single board computer (SBC) or even a computer, for both regular or server use, takes time and skill. DietPi provides an **easy way to install and run favourite software you choose**.

- [https://dietpi.com/](https://dietpi.com/)
- [What Is DietPi, and Should You Install It on Your Raspberry Pi?](https://www.howtogeek.com/what-is-dietpi/)