Raspberry Pi Documentation

From Waveshare Wiki
Jump to: navigation, search

Overview

Introduction

  • Raspberry Pi, abbreviated as RPi, is a computer only the size of a credit card.
  • Developed by the Raspberry Pi Foundation in the United Kingdom, it was originally intended to promote computer programming education for young students.
  • Since its release in 2012, it has been sought after by many students, amateur intelligent hardware enthusiasts, computer enthusiasts, and other groups.
  • The official recommended system for Raspberry Pi is Raspberry Pi OS, which is a free operating system based on Debian GNU/Linux.
  • In addition to this, the Raspberry Pi supports many operating systems: Ubuntu, RetroPie, LibreELEC, and Manjaro, among others.

Preparation

  1. TF card reader
  2. 5V 3A power adapter
  3. At least 8GB TF card
  4. micro HDMI to HDMI cable
  5. Computer monitor or TV with HDMI interface (other interface monitors can use interface converter.)

Install Operating System

Install the system using official tools

  • Raspberry Pi has officially developed Pi Raspberry Pi Imager for writing graphics TF card, which is suitable for Windows, Mac OS, Ubuntu, and other operating systems;
  • It will automatically download the image and install it to the SD card, download the latest version of Raspberry Pi Imager, and install it.

How to use:

  1. Connect the TF card to the computer.
  2. Open Raspberry Pi Imager and select the desired operating system.
  3. Select the TF card to write the image to (Note: it is better to remove other U flash drives to prevent them from being erased).
  4. To configure the system in advance, press and hold CTRL+SHIFT+X (or click the small gear in the lower right corner), and click Save after setting.
  5. Click the burn button to write the data to the TF card.

Raspberry Pi Documentation01.gif

6. At this point, the image is successfully burned, unplug the card reader, and insert the TF card into the Raspberry Pi.

Raspberry Pi Documentation02.png

7.Load the TF card, connect the peripherals, turn on the power, and the Raspberry Pi can be turned on.

Raspberry Pi Documentation03.gif

Install the system with other tools

  • You can use other methods to burn the image, use the image writing tool to write the downloaded image to the Raspberry Pi, for example, balenaEtcher or Win32DiskImager.
  • First, go to the official website of Raspberry Pi to download the image, it is recommended to use Raspberry Pi OS with a desktop.
    • The Raspberry Pi OS with desktop version features a computer desktop, which is enough for ordinary users.
    • The Raspberry Pi OS Lite version is characterized by no computer desktop, and all operations to enter the system must use the command line. Since there is no UI interface, it is suitable for the small capacity of the TF card and the mastery of Linux operations. If you do not have a Linux foundation, it will be very difficult to use. For getting started, it is recommended to choose an image with a desktop.
  • After the image is downloaded, it needs to be decompressed into ".img" file format before it can be recognized by the programming software.
  • Before programming, you need to format the TF card by Panasonic SDFormatter.zip .

Win32DiskImager

  1. Open the corresponding programming tool: Win32DiskImager-burning software.
  2. Insert the TF card into the card reader and insert the card reader into the computer.
  3. Select the downloaded Raspberry Pi image file.
  4. Click Write and wait for it to complete.

Raspberry Pi Documentation05.gif

balena

  1. Download and install balenaEtcher.
  2. Run balenaEtcher and select the unzipped Raspberry Pi OS image file.
  3. Select the TF card drive.
  4. Finally, click Burn to write the Raspberry Pi OS image to the TF card.

Raspberry Pi Documentation06.gif

  • After the programming is successful, unplug the TF card and insert it into the Raspberry Pi to run.

Raspberry Pi Operating System

Introduction

  • Raspberry Pi OS is a free operating system based on Debian, optimized for Raspberry Pi hardware, and is the recommended operating system for normal use on Raspberry Pi. The operating system comes with over 35,000 software packages: precompiled software bundled together in a nice format for easy installation on your Raspberry Pi.

Refresh and Upgrade RPi Operating System

  • It is important to keep your Raspberry Pi up to date.
    • The first and most important reason is security. Since the source code of the Raspberry Pi system will be open-sourced on Github, the source code loopholes will be exposed. The Raspberry Pi official will also update the source code in time to fix the vulnerability. As a Raspberry Pi user, you must keep your software up-to-date so as to avoid the harm caused by the bugs.
    • The second reason, related to the first, is that the software you're running on your device must contain bugs. Some bugs are CVEs, but bugs can also affect desired functionality, regardless of security. By keeping your software up to date, you can reduce the chance of encountering these bugs.

APT Usage

  • The easiest way to manage to install, upgrade, and remove software is to use Debian's APT to keep your operating system up to date.
sudo apt update
  • Upgrade all installed packages to the latest version with the following command:
 sudo apt upgrade

User Guides for Linux

Linux

  • Linux is a general-purpose operating system with a powerful network function. As its hardware consumption such as memory is also less, it is mostly used in network servers.
  • Extremely stable, safe, portable, and expandable.
  • Linux features advantages such as open source, and no copyright as many users in the technical community. Open source allows users to tailor freely, which help Linux system with high flexibility, powerful functions, and low cost.
  • Disadvantages: It is more difficult to get started than Windows. Due to the lack of a desktop Linux ecosystem, there are very few users who use it.

Why Learn Linux

  • Linux systems are widely used in people's daily life, such as mobile phones, smart homes, automotive electronics, wearable devices, etc., but many people do not know that these electronic products are running Linux systems, for example, the Android system we use is developed based on the Linux kernel.
    • More than 90% of the world's 1 million top fields use Linux systems; most of the world's stock exchanges are deployed based on Linux systems, including the New York Stock Exchange, Nasdaq, etc.
    • World-renowned e-commerce platforms such as Taobao, Amazon, eBay, and Walmart are all using Linux systems.
    • The developers and companies involved in the development of the Linux kernel are also the largest and most active. So understanding and learning Linux is very important.

Terminal

  • The terminal on the computer allows users to control their system. Windows users may already be exposed to Command Promptor Powershell, and mac OS users may already be familiar with Terminal. All these tools allow users to directly operate their systems by using commands.
  • Since there was no mouse in the early days, the Linux terminal is completely done by the keyboard and monitor, and this practice has been used to this day. The Raspberry Pi terminal can be opened using Ctrl+Alt+t on the keyboard.

RPiTerm.png

    • "pi" is the current username/login name
    • "raspberrypi" is the hostname.
    • "~" is the directory where the current user is located in /home/pi.
    • "$" character indicates that the currently logged-in user is an ordinary user.
    • "#" character indicates that the root user is logged in.
  • Type the command in a terminal window and press Enter on your keyboard to run the command.

Linux system directory

  • In Windows, each partition is a tree structure, and there are as many partitions as there are tree structures. However, in Linux, there is only one tree structure, and all files and partitions exist in a tree structure. In this structure, the top layer is the root directory, and all other directories, files, and partitions are established under the root directory. Readers can view the documents of the entire root directory through the ls/command, as shown in the figure.

Rpi linuxtree02.png
Here is an explanation of these directories:

Common directory

  • /home: User directory.
    • Except for the root user, all other user data are stored in this directory. In the Tinker Board 2 system, there is a linaro subdirectory in the /home directory, which is the default directory of the linaro user.
  • /bin: Mainly place the necessary executable file directory of the system.
    • Place binary executables related to the Linux system (including those required to run the graphical interface), such as ls, mkdir, rm, etc.
  • /boot: Boot directory.
    • It is used to store the system boot program, such as the Linux kernel and the startup configuration file. The config.txt in it is also the most frequently used file for user configuration.
  • /etc: directory for storing system configuration files
    • In this directory, almost all configuration files required by Linux system software are stored. If you need to modify the text in this directory, it is best to back up the files that need to be modified to ensure that you can return to the file after modification. to the original state.

Other directories

  • /dev : Device directory. In a Linux system, all devices are regarded as files, and all devices are stored in this directory. For example, the first SATA hard disk or U disk will be recognized as sda file, and the first partition of SATA hard disk or U disk will be recognized as sda file. Recognized as sda1 file.
  • /lib: The dynamic link library storage location of the basic system. In this directory, the library files required to maintain a basic system startup are stored. Without this directory, system programs simply cannot work.
  • /lost + found/: the directory of the partition system. The files generated by the abnormal shutdown of the system are usually stored here, and the files generated after the hard disk is repaired by programs such as fsck are also stored here.
  • /media: The linux system will automatically identify some devices, such as U disk, CD-ROM, etc. After identification, Linux will mount the identified device to this directory.
  • /mnt: Traditional external device mount point. In the early days, other partitions except the system partition, such as U disk and other devices, would be mounted to this directory for users to read and write. However, it has now been replaced by /media/.
  • /proc: proc is a virtual filesystem. This directory is stored in memory, so it does not take up hard disk space, and the system or the user learns about them by reading these devices. For example, you can use the cat /proc/cpuinfo command to view CPU information.
  • /root: This directory is the home directory of the system administrator, also known as the super-authorized user.
  • /srv: This directory stores data that needs to be extracted after some services are started.
  • /sys: Like the /proc directory, it is also a virtual directory, which is implemented by the sysfs system in the kernel. Its function is somewhat similar to that of proc, but in addition to the same function of viewing and setting kernel parameters as proc, it also has the same function as proc. There is a unified device model for Linux for management purposes.
  • /tmp: Temporary directory. Temporary files generated by the program will be stored in this directory. Don't worry about this directory taking up too much space, because the contents of this directory will be cleared every time the system is started; at the same time, this is one of the few systems that has all user-readable files. Directory to write properties to.
  • /usr: The programs installed in the Linux system are stored in this directory, similar to the program files directory under Windows.
  • /run: The file used to store the system information when the system is started. This directory was originally under the /var/ directory, but is now elevated to the root directory

Important directory

  • In the Linux system, there are several directories that are more important. Usually, you need to be careful not to delete or arbitrarily change the internal files.
  • /etc: This is the configuration file in the system. If you change a file in this directory, the system may not start.
  • /bin, /sbin, /usr/bin, /usr/sbin: This is the default directory where the executable files are placed by the system. For example, ls is in the /bin/ls directory.
  • /bin, /usr/bin are instructions for system users (normal users except root), and /sbin, /usr/sbin are instructions for root.
  • /var: This is a very important directory. There are many programs running on the system, so each program will generate corresponding logs, and these logs will be recorded in this directory, specifically in the /var/log directory.

Introduction to common commands

Document system

sudo

  • Execute sudo commands as a system administrator.
  • When using the Raspberry Pi system for the first time, the default user is pi and the password is raspberry.
  • If you want to use the root account or enable the root user, you can use the pi user to log in and execute the following command (this command sets a password for the root account, and this command is invalid after switching to the root administrator).
sudo su   #Switch to superuser
su pi     #Switch common users

RPI Sudo.png

ls

  • The ls command is used to display the contents of the specified working directory (list the files and subdirectories contained in the current working directory).
  • Common commands
ls
ls -a   #Show all files and directories (starting with . hidden files are also listed)
ls -l   #In addition to the file name, it also lists the file type, permissions, owner, file size and other information in detail
ls -lh  #File sizes are listed in an easy-to-understand format, such as 4K

RPI is.png

  • To learn about more parameters of the command, we can use the help command to view
ls --help

chmod

  • The chmod command is a command that controls users' permissions on files.
  • The file calling permissions of Linux/Unix is divided into three levels: Owner, Group, and Other Users.
  • In the figure below, the detailed file information under the Linux root directory is displayed. Among these file information, the most important is the first column, which describes the permissions of files and directories in detail, while the third and fourth columns show which user or group the file and directory belong to.

Rpi chomd2.png

  • There are three file attributes in Linux: read-only (r), write (w), and executable (x). However, the above file attributes are divided into 10 small cells, because in addition to the first cell displaying the directory, the other three groups of three cells respectively represent the file owner permissions, permissions within the same group, and other user permissions.
    • If d is displayed in the first column, it means that this is a directory; if it is a link file, l is displayed here; if it is a device file, c is displayed.
    • The first rwx field: -rwx------ indicates the permissions owned by the file owner.
    • The second rwx field: ---rwx--- indicates user rights within the same workgroup.
    • The third rwx field: ------rwx indicates other user rights.
    • E.g:
    • -rwx rwx rwx means that no matter which user can read, write and execute this file.
    • -rw- --- --- Indicates that only the file owner has read and write permissions, but no execute permissions.
    • -rw -rw -rw means that all users have read and write rights.
  • Symbolic Pattern
    • who(user type)
who user type description
u user file owner
group file owner group
o others all other users
a all All users, equivalent to ugo
    • operator(Symbolic pattern)
Operator description
+ Add permissions for the specified user type
- Remove permissions for a specified user type
= Set the specified permissions for users, that is, reset all permissions for the user
    • symbol pattern table for permission
Mode Name Description
r read set to read
w write set to write
x execute set to executable
X special execution permission Only when the file is a directory file or other types of users have executable permissions, set the file permissions to executable
s setuid/gid When the file is executed, set the file's setuid or setgid permissions according to the user type specified by the who parameter
t paste bit set paste bit, only superuser can set this bit, only file owner u can use this bit
    • Symbolic Pattern Examples

1. Add read permissions to all users of the file

chmod a+r file

2. Remove execute permission for all users of file

chmod a-x file

3. Add read and write permissions to all users of file

chmod a+rw file

4. Add read, write and execute permissions to all users of file

chmod +rwx file 

5. Set read and write permissions to the owner of the file, clear all permissions of the user group and other users to the file (space means no permission)

chmod u=rw,go= file

6. Add read permission to the user for all files in the directory Waveshare and its subdirectory hierarchy, and remove read permission for the user group and other users

chmod -R u+r,go-r waveshare
  • Octal syntax
    • The chmod command can use octal numbers to specify permissions. The permission bits of a file or directory is controlled by 9 permission bits, each of which is a group of three, which are read, write, and execute for the file owner (User), read, write, and execute for the user group (Group). Other users (Other) read, write, and execute.
# Permission rwx binary system
7 read+write+excute rwx 111
6 read+write rwx- 110
5 read+execute rwx 101
4 read r-- 100
3 read+execute -wx 011
2 write -w- 010
1 execute --x 001
0 none --- 000
  • 765 is explained as follows:
    • The owner's permission is expressed in numbers: the sum of the numbers of the owner's three permission bits. For example, rwx, which is 4+2+1, should be 7.
    • The permissions of a user group are expressed in numbers: the sum of the numbers of the permission bits that belong to the group. For example, rw-, which is 4+2+0, should be 6.
    • Permission digital expression of other users: the sum of the numbers of other users' permission bits. For example, r-x, which is 4+0+1, should be 5.
  • Common digital rights
    • 400 -r------- The owner can read, no one else can do anything;
    • 644 -rw-r–r-- all owners can read, but only the owner can edit;
    • 660 -rw-rw---- Both owner and group users can read and write, others cannot perform any operations;
    • 664 -rw-rw-r-- readable by everyone, but editable only by owner and group users;
    • 700 -rwx------ The owner can read, write and execute, other users cannot do anything;
    • 744 -rwxr–r-- everyone can read, but only the owner can edit and execute;
    • 755 -rwxr-xr-x everyone can read and execute, but only the owner can edit;
    • 777 -rwxrwxrwx everyone can read, write and execute (this setting is not recommended)
  • Example
    • Add permissions for reading to all users of the file, and the owner and group users can edit
sudo chmod 664 file

mkdir

  • The command of mkdir is used to create directories.
  • Grammar
mkdir [-p] dirName
    • -p ensures that the directory name exists, and creates one if it does not exist.
  • Create a directory named Waveshare in the working directory.
sudo mkdir waveshare

Raspberry-pi-Linux07.png

  • In the Waveshare directory under the working directory, create a subdirectory named test.
sudo mkdir -p waveshare/test

Raspberry-pi-Linux08.png

  • If the Waveshare directory does not already exist, create one. (Note: If the -p parameter is not added in this example, and the original Waveshare directory does not exist, an error will occur.)

cd

  • Switch the current working directory. The cd command is one of the most commonly used Linux commands to switch the user's current working directory. If you need to quickly return to the home directory of the logged-in user, you can directly use the cd command without parameters to return.
  • Grammar:
cd [dirName]
dirName: The target directory to switch to.
cd..         go back to the previous directory
cd /home     enter the /home directory
cd           returns to the user directory

touch

  • The touch command is used to modify the time attributes of a file or directory, including access time and change time. If the file does not exist, the system will create a new file.
    • When using the command "touch", if the specified file does not exist, a new blank file will be created. For example, using this command to create a blank file "file" in the current directory, enter the following command:
sudo touch file

Raspberry-pi-Linux09.png

cp

  • The cp command is mainly used to copy files or directories.

Grammer:

cp [options] source dest
or
cp [options] source... directory
  • parameter:
    • -a: This option is usually used when copying directories, it preserves links and files attributes and copies everything under the directory. Its effect is equal to the combination of dpR parameters.
    • -d: keep links when copying. The links mentioned here are equivalent to shortcuts in Windows systems.
    • -f: Overwrite existing object files without prompting.
    • -i: Contrary to -f, give a prompt before overwriting the target file, asking the user to confirm whether to overwrite and answer y the target file will be overwritten.
    • -p: In addition to copying the contents of the file, also copy the modification time and access rights to the new file.
    • -r: If the given source file is a directory file, all subdirectories and files in the directory will be copied.
    • -l: Do not copy files, just generate link files.
  • Use the cp command to copy all the files in the current directory test/ to the new directory newtest, and enter the following command
sudo cp –r test/ newtest

Raspberry-pi-Linux10.png

mv

  • The mv command is used to rename a file or directory, or move a file or directory to another location.
  • Grammar:
mv [options] source dest
mv [options] source... directory
  • parameter:
    • -b: When the target file or directory exists, create a backup of it before performing the overwrite.
    • -i: If the specified source directory or file to be moved has the same name as the target directory or file, it will first ask whether to overwrite the old file. Enter y to directly overwrite, and n to cancel the operation.
    • -f: If the source directory or file specified to be moved has the same name as the target directory or file, it will not be asked, and the old file will be overwritten directly.
    • -n: Do not overwrite any existing files or directories.
    • -u: The move operation is performed only when the source file is newer than the target file or the target file does not exist.
  • Use the mv command to copy the file1 file in the current directory test/ to the new directory /home/linaro, and enter the following command:
sudo mv file1 /home/pi

Raspberry-pi-Linux11.png

rm

  • The rm command is used to delete a file or directory.
  • Grammar:
rm [options] name...
  • Parameter:
    • -i: Ask for the confirmation one by one before deleting.
    • -f: Even if the original file is set to read-only, it will be deleted directly without confirming one by one.
    • -r: Delete the files in the directory and below one by one.
  • To delete a file, you can use the rm command directly. If you delete a directory, you must choose the option "-r", for example:
sudo rm  test.txt 
    • rm: delete the general file "test.txt"? y
sudo rm homework
    • rm: cannot delete directory "homework": is a directory
sudo rm -r homework
    • rm: delete the directory "homework"? y

reboot

  • The reboot command is used to restart the computer. Changing the configuration of Tinker Board 2 often requires restarting.
  • Grammar:
reboot [-n] [-w] [-d] [-f] [-i]
  • Parameter:
    • -n : do not write the memory data back to the hard disk before rebooting
    • -w : will not actually reboot, just write the log to the /var/log/wtmp file
    • -d : do not write logs to the /var/log/wtmp file (-d is included with the -n parameter)
    • -f : force reboot, do not call shutdown command
    • -i : stop all network related devices before rebooting
  • Restart
sudo reboot

shutdown

  • We cannot power off the Tinker Board 2 directly for its memory as a temporary storage area, which would cause the data loss or damage to the data on the SD card and the system would fail to boot.
  • Grammar
shutdown [-t seconds] [-rkhncfF] time [message]
  • Parameter
    • -t seconds: Set the shutdown procedure after a few seconds.
    • -k: don't actually shut down, just send a warning message to all users.
    • -r: reboot.
    • -h: power off and halt
    • -n: Do not use the normal program to power off, please use the forced method to close all the programs in execution and then power off by itself.
    • -c: Cancel the shutdown action that is currently in progress.
    • -f: Do not do fsck when power off (check Linux file system).
    • -F: Force fsck action on shutdown.
    • time: Set the shutdown time.
    • message: The warning message is sent to all users.
  • example
    • Shut down now
sudo shutdown -h now
    • Shutdown after specified 10 minutes
sudo shutdown -h 10
    • restart the computer
sudo shutdown -r now
    • No matter which command is used to close the system, root user permission is required. If the user uses a common user such as linaro, the sudo command can be used to temporarily obtain root permission.

pwd

The pwd command displays the name of the current working directory: on a Raspberry Pi, typing pwd will output something like /home/pi.

scp

  • scp is a command used to send files over SSH, which can be used to transfer files between a Raspberry Pi and a Windows computer.
  • Copy the files from your Raspberry Pi to your Windows computer:

1. Press and hold Win+R on the keyboard, enter cmd, and press enter to confirm:
Raspberry-pi-Linux13.png
2. Copy the file waveshare.py from the Raspberry Pi to the current directory of the Windows computer, enter the command on the terminal should be:

scp [email protected]:waveshare.py .

3. Enter and input "yes":

  • PS: It is normal that there is no change on the screen when entering the password. After inputting yes, press the Enter key to display the Raspberry Pi password input interface.

Raspberry-pi-Linux14.png
4. Enter and enter the default password of Raspberry Pi, raspberry:

  • PS: It is normal that there is no change on the screen when entering the password. After entering the password, press the Enter key to access the Raspberry Pi.

Raspberry-pi-Linux15.png
5. Now, the copy is done.
Raspberry-pi-Linux16.png
Raspberry-pi-Linux17.png

  • Copy the files from your computer to your Raspberry Pi user:

1. First enter the storage location of the test.py file, hold down the keyboard Shift, and right-click the blank space to open Windows PowerShell:
Raspberry-pi-Linux18.png
PS: Right-clicking directly on the blank space will not appear in the Open PowerShell window here.
2. Copy the file test.py from your computer to the Raspberry Pi user's /home/pi using the following command:

scp test.py [email protected]:

Raspberry-pi-Linux19.png
3. Enter and input the default password: raspberry
Raspberry-pi-Linux20.png
At this point, we have successfully copied:
Raspberry-pi-Linux21.png

head

  • The command displays the beginning of the file and it can be used with -n to specify the number of lines to display (default is 10), or with -c to specify the number of bytes.
head test.py -n 5

Raspberry-pi-Linux12.png

tail

  • The tail shows the end of the file. -c bytes or -n lines specify the starting point in the file

df

  • Used for df to show disk space available and used on mounted filesystems. Use df -h to see the output in a readable format, use M for MB instead of bytes.
df -h

Raspberry-pi-Linux 20.png

zip

  • The zip command is used to compress files, zip is a widely used compression program, and the suffix of compressed files is .zip.
  • If we are in the /home/pi/waveshare directory and package all the files and folders in this directory as waveshare.zip in the current directory, you can execute the following command:
zip -q -r waveshare.zip *

Raspberry-pi-Linux 21.png

uzip

  • The unzip command is used to decompress zip files, and unzip is a decompression program for .zip compressed files.
unzip waveshare.zip -d user/

Raspberry-pi-Linux23.png

    • -d is the directory where the specified file should be stored after decompression.

tar

  • The tar command is a tool program used to create and restore backup files. It can add and unpack files in backup files.
  • Compressed file:
tar -cvzf waveshare.tar.gz *

Raspberry-pi-Linux24.png

  • unzip files:
tar -xvzf waveshare.tar.gz

Raspberry-pi-Linux25.png

tree

  • Use the tree command to indent a directory and all subdirectories and files into a tree structure.

wget

  • Download the Raspberry Pi 4 datasheet and save it as raspberry-pi-4-datasheet.pdf using:
wget https://datasheets.raspberrypi.com/rpi4/raspberry-pi-4-datasheet.pdf 

Raspberry-pi-Linux26.png

curl

  • The Linux curl command is a file transfer tool that works from the command line using URL rules. It supports file uploading and downloading, so it is a comprehensive transfer tool, but according to tradition, curl is used to be called a download tool. As a powerful tool, curl supports many protocols including HTTP, HTTPS, ftp, etc. It also supports POST, cookies, authentication, downloading partial files from a specified offset, user agent string, speed limit, file size, progress bar, and other features. Automate web page processing and data retrieval, curl can help.
  • Grammar:
curl  (option)(parameter)
  • Parameter:
    • -A/--user-agent <string> Set user agent to send to server
    • -b/--cookie <name=string/file> cookie string or file read location
    • -c/--cookie-jar <file> Write cookies to this file after operation
    • -C/--continue-at <offset> breakpoint continue
    • -D/--dump-header <file> write header information to this file
    • -e/--referer source URL
    • -f/--fail do not show http errors when connection fails
    • -o/--output write output to this file
    • -O/--remote-name write output to this file, keeping the filename of the remote file
    • -r/--range <range> Retrieve byte range from HTTP/1.1 or FTP server
    • -s/--silent silent mode. don't output anything
    • -T/--upload-file <file> upload file
    • -u/--user <user[:password]> set server user and password
    • -w/--write-out [format] what to output after completion
    • -x/--proxy <host[:port]> use HTTP proxy on given port
    • -#/--progress-bar progress bar showing current delivery status

1. Basic usage: Execute the following command, the HTML of www.waveshare.net will be displayed on the screen:

curl http://www.waveshare.net

Raspberry-pi-Linux28.png
2. Save the visited webpage: Use curl's built-in option:-o (lowercase) to save the webpage, if 100% is displayed, it means the save is successful:

curl -o waveshare.html http://www.waveshare.com

Raspberry-pi-Linux29.png
3. Use curl's built-in option: -O (uppercase) to save the files on the web page. It should be noted that the URL behind here should be specific to a certain file, otherwise, it will not be caught.

curl -O http://www.waveshare.com/hello.sh

4. Test page return value

curl -o /dev/null -s -w %{http_code} www.waveshare.com

5. Download the file using curl:
Use built-in option: -o (lowercase) and builtin option: -O (uppercase)

curl -o 1.png https://www.waveshare.com/wiki/File:Test-111.png
curl -O https://www.waveshare.com/wiki/File:Test-111.png

apt

  • apt (Advanced Packaging Tool) is a shell front-end package manager in Debian and Ubuntu.
  • The apt command provides commands for finding, installing, upgrading, and removing a package, a group of packages, or even all packages, and the commands are concise and easy to remember.
  • apt command execution requires super administrator privileges (root).
  • apt common commands
    • List all updatable software inventory command: sudo apt update
    • Upgrade packages: sudo apt upgrade
    • List updatable packages and version information: apt list --upgradeable
    • Upgrade packages, delete the packages that need to be updated before upgrading: sudo apt full-upgrade
    • Install the specified software command: sudo apt install <package_name>
    • Install multiple packages: sudo apt install <package_1> <package_2> <package_3>
    • Update the specified software command: sudo apt update <package_name>
    • Display package specific information, such as: version number, installation size, dependencies, etc.: sudo apt show <package_name>
    • Remove package command: sudo apt remove <package_name>
    • Clean up unused dependencies and libraries: sudo apt autoremove
    • Remove packages and configuration files: sudo apt purge <package_name>
    • Find packages command: sudo apt search <keyword>
    • List all installed packages: apt list --installed
    • List version information of all installed packages: apt list --all-versions

Search

find

  • Linux find command is used to find files in the specified directory. Any string preceding the parameter will be treated as the directory name to look for. If you use this command without setting any parameters, the find command will search for subdirectories and files in the current directory. And all the found subdirectories and files will be displayed.

1. Find by filename, for example, we find the waveshare.py file:

find -name waveshare.py 

2. Search by file nesting level.

  • The maximum level of file search is 1, and all the files found are in the /etc directory. For example, we search for the .conf file in the /etc directory:
    find /etc/ -maxdepth 1 -name *.conf
  • The minimum level of file search is 2. The files found will not include files in the /etc directory, but will be searched in the /etc subdirectory.
    find /etc/ -mindepth 2 -name *.conf
3. List all files in the current directory and its subdirectories that have been updated in the last 20 days:
find . -ctime -20

4. Find common files in the /var/log directory with changes older than 7 days and ask for them before deleting:

find /var/log -type f -mtime +7 -ok rm {} \;

5. Find files in the current directory whose owner has read and write permissions, and users of the group to which the file belongs and other users have read permissions:

find . -type f -perm 644 -exec ls -l {} \;

6. Find all normal files with file length 0 in the system and list their full paths:

find / -type f -size 0 -exec ls -l {} \;

grep

  • Used to grep to search for certain search patterns inside files, can list all combinations that contain special letters.
ls | grep sys

Linux-grepwatermarknew.png

cat

  • You can use cat to list the contents of a file, for example, cat thisFile will display thisFile. Can be used to list the contents of multiple files, i.e. cat *.txt will list the contents of all files in the current directory of .txt.
cat test.txt

Linux-catwatermarknew.png

awk

  • AWK is a language for processing text files. It is a powerful text analysis tool. Compared with grep search and sed editing, awk is particularly powerful when it analyzes data and generates reports. Simply put, awk reads the file line by line, slices each line with a space as the default delimiter, and performs various analysis and processing on the cut part.

1. Split each line by space or TAB, output 1, 4 items in the text:

awk '{print $1,$4}' waveshare.txt

Linux-awk1watermarknew.png
2. Output rows where the first column is greater than 2:

awk '$1>2' waveshare.txt

Linux-awk2watermarknew.png
3. Output the row with the first column equal to 2:

awk '$1==2' waveshare.txt

Linux-awk3watermarknew.png
4. Output rows where the first column is greater than 2 and the third column is equal to 'SQL'

awk '$1>2 && $3=="SQL"' waveshare.txt

Linux-awk4watermarknew.png
5. Output lines containing "Python":

awk '/Python/ ' waveshare.txt

Linux-awk5watermarknew.png
6. awk -v # set variables

awk -va=1 '{print $1,$1+a}' waveshare.txt

Linux-awk6watermarknew.png

awk -va=1 -vb=nice '{print $1,$1+a,$1b}' waveshare.txt

Linux-awk7watermarknew.png

whereis

  • The location used for whereis lookup commands. It looks at standard program locations until it finds the requested command.
whereis sudo

Linux-whereiswatermarknew.png


Network

ifconfig

  • Used to display the network configuration details of an interface on the current system when run with no arguments (ie) ifconfig.
  • When connecting with SSH, you can find the IP address through ifconfig. For example, the IP address of this device is 192.168.10.51.

RPI ifconfig.png

hostname

  • The hostname command displays the current hostname of the system. When we use Tinker Board 2, we often need to use remote tools, and the default network configuration IP address adopts dynamic allocation, which will cause the problem of IP address uncertainty. When our Tinker Board 2 IP address changes, we can use the hostname to log in.

1.Log into Raspberry Pi and modify the hosts file with the following command:

sudo nano /etc/hosts

Raspberry-pi-Linux030.png
Raspberry-pi-Linux30.png

    • Replace raspberrypi with the name to be modified, such as waveshare, press Ctrl+x on the keyboard, press y on the keyboard, and press Enter to confirm:

Rpi hostname2.png

  • Modify the hostname file, and replace linaro with the name to be modified, such as waveshare, press Ctrl+x on the keyboard, press y on the keyboard, and press Enter to confirm:
sudo nano /etc/hostname

Rpi hostname3.png

  • After the modification is completed, restart Raspberry Pi:
sudo reboot

4. Modifying the hostname can also be done with System Options in sudo raspi-config.

Ping

  • This ping utility is usually used to check if it is possible to communicate with another host. It works with the default settings, just specify the hostname or IP address (eg ping 192.168.1.1). -c It can use flags to specify the number of packets to send.
ping 192.168.1.1

Raspberry-pi-Linux31.png

nmap

  • nmap is a network exploration and scanning tool. It can return port and operating system information about a host or a range of hosts. Running nmap will show the available options along with example usage.
  • First let's ping a range of addresses to find an online host:
 nmap -sP 192.168.10.1-255

Raspberry-pi-Linux32.png

Configuration

raspi-config Tool

  • raspi-config is a system configuration tool that comes with the official Raspberry Pi image.
  • If you are using the Raspberry Pi desktop, you can configure the Raspberry Pi using the graphical Raspberry Pi Configuration application in the Preferences menu.
  • To open the configuration tool, type the following at the command line:
sudo raspi-config
  • Basic operation: Up and down keys on the keyboard to select menu items, Enter key to enter, left and right keys to select buttons such as OK and cancel, Esc key to cancel and return, and space bar to select options. After the final change, select *Finish to exit, and it may restart.
  • Any changes will take effect after a reboot, which you can set by editing config.txt.

Option List

System Options

  • Configuration changes are made to various parts of the Raspberry Pi's boot, login, and networking process.
    • Wireless LAN: Raspberry Pi wireless Internet settings, select the network to be connected.
    • Audio: Audio output.
    • Password: The default user of Raspberry Pi is pi password raspberry. If you don't want others to access your Pi, you can click change to change the password.
    • Hostname: The default hostname of the Raspberry Pi system is raspberrypi. You can modify your own hostname.

Raspberry-pi-Configuration.gif

    • Boot / Auto Login: From this submenu, you can choose whether to boot to the console or the desktop, and whether to require a login. If you choose to log in automatically, you will be logged in as the pi user.
    • Network at Boot: Use this option to wait for a network connection before continuing to boot.
    • Splash Screen: Enable or disable the splash screen displayed at startup.

Dosplay Options

  • D2 Underscan removes black borders around the screen and disables overscan to allow the system to take full advantage of the entire screen.
  • D4 Screen Blanking Enable/disable screen blanking.
  • D5 VNC Resolution: Set the resolution of the remote desktop VNC.
  • D6 Composite: Combine output options.

Interface Options

  • In this submenu, there are options to enable/disable: Camera, SSH, VNC, SPI, I2C, Serial, 1-wire and Remote GPIO.
    • For example we enable ssh:

Raspberry-pi-Configuration02.gif

Performance Options

  • P1 Overclock: Properly overclocking the CPU of the Raspberry Pi can achieve some performance improvements. Note that overclocking may reduce the lifespan of the Raspberry Pi, and overclocking will also cause system instability to a certain extent. It is recommended not to change it. Changes will void the warranty.
  • P2 GPU Memory: Allocate memory to the GPU. Central Processing Unit (CPU) and Graphics Processing Unit (GPU). The memory on the Raspberry Pi is divided into some for the CPU and some for the GPU. The default occupied by the GPU is 128M.
    • If you're using your Raspberry Pi as a file server or web server and don't need to use the video output, you can reduce the amount of memory allocated to the GPU (minimum 16MB).
    • If you use it to browse the web, watch videos or even run 3D games, then you should allocate a larger amount of memory to the GPU, thereby increasing the GPU performance and making it better at rendering 3D games.
    • If you need to connect a camera, you must allocate at least 128MB of video memory to the GPU.

Raspberry-pi-Configuration03.gif

  • P3 Overlay File System: Enable/disable the read-only file system.

Localisation Options Configure language and regional settings

  • The Localization submenu can set the keyboard layout, time zone, locale, and wireless LAN country code.
    • Change Locale: Language and locale settings.
    • Change Timezone: Set the time zone.
    • WLAN Country: Set the country code. For example, we configure the country code:

Raspberry-pi-Configuration04.gif

Advanced Options

  • A1 Expand Filesystem: Allows you to expand the filesystem. Extending the filesystem will maximize the size of the partition to match the size available on the physical TF card.
  • A3 Compositor: Enable/disable xcompmgr composition manager
  • A4 Network Interface Names: Switch the network card naming rules.
  • A5 Network Proxy Settings: Configure network proxy settings.
  • A6 Boot Order: Select network or USB device to boot.
  • A7 Bootloader Version: Select the latest or default boot ROM software.

Update

  • Update the raspi-config tool to the latest version.

About raspi-config

  • Display raspi-config version information.

config.txt File

  • Since the Raspberry Pi does not have a BIOS in the traditional sense, in order to replace the function of the BIOS, the Raspberry Pi uses the "config.txt" file on the first "boot" partition of the SD card to store configuration items. The config.txt file of the Raspberry Pi is read by the GPU before the ARM core is initialized. It is located on the /boot (boot) partition of the SD card and must be edited as root.
  • Changes in the parameters will take effect only after restarting the Raspberry Pi. After Linux starts, you can view the currently active settings with the following command:
  • vcgencmd get_config <config>: This will display a specific configuration value, for example, to see the default CPU frequency of the Raspberry Pi 4B:
vcgencmd get_config arm_freq

Raspberry-pi-Configuration40.png
Where 1800 refers to 1.8GHz.

  • For some of the earliest Raspberry Pi 4, the PCB of the old version of the power supply module is still used. The official said that it can also be overclocked by manually modifying the config.txt file, and just adding the command arm_freq=1800. If the operation is unstable, It's fine to step down by 50MHz or add a little voltage.
  • The config.txt file is read by early boot firmware, so the file format is very simple. The format is a single property=value statement on each line, where the value is an integer or a string. # With a line starting with the character, comments can be added, or existing configuration values can be commented out and disabled.

AP

  • Local access is recommended, connect the screen, mouse, network cable, and keyboard to your Raspberry Pi, start the Raspberry Pi, and make sure the Raspberry Pi software source is up to date, you can update it with the command:
sudo apt update
  • Make a note of the IP configuration of the Ethernet the Raspberry Pi is connected to:
    • Set 192.168.4.0/24 as the Raspberry Pi wireless client management IP network. If the 192.168.4.0/24 segment IP network is already used by your Ethernet LAN, please select another segment IP network for wireless, such as 192.168.10.0/24,
  • Have a wireless client (laptop, smartphone...) ready to test your new wireless network.

Install AP and Management Software

1. In order for the Raspberry Pi to create a wireless hotspot, the Raspberry Pi needs to have hostapd installed:

sudo apt install hostapd

2. Enable the wireless hotspot service and set it to start automatically when the Raspberry Pi is turned on:

sudo systemctl unmask hostapd 
sudo systemctl enable hostapd

3. In order to provide network management services (DNS, DHCP) to wireless clients, the Raspberry Pi requires dnsmasq to install the following packages:

sudo apt install dnsmasq

4. Under normal circumstances, the iptables rules we write will disappear when the system restarts so that the firewall rules will still be valid after restarting, and install netfilter-persistent and its plugin iptables-persistent.

sudo DEBIAN_FRONTEND=noninteractive apt install -y netfilter-persistent iptables-persistent

Set Up A Network Router

1. Define the wireless interface IP configuration. The Raspberry Pi runs a DHCP server for the wireless network; this requires static IP configuration of the wireless interface (wlan0) in the Raspberry Pi. When the Raspberry Pi is also acting as a router on a wireless network, we generally give it the first IP address on the network: 192.168.4.1. To configure a static IP address, edit the configuration file dhcpcd, go to the end of the file and add the following content:

sudo nano /etc/dhcpcd.conf
interface wlan0
    static ip_address=192.168.4.1/24
    nohook wpa_supplicant

2. To enable the Raspberry Pi to have the routing and forwarding function, you need to configure a Raspberry Pi kernel parameter net.ipv4.ip_forward. This parameter specifies the current support for the routing and forwarding function of the Raspberry Pi; when the value is 0, it means that IP forwarding is prohibited; when the value is 1, it means that IP forwarding is allowed. Please use the following command to create a file with the following content:

sudo nano /etc/sysctl.d/routed-ap.conf
# Enable IPv4 routing
net.ipv4.ip_forward=1

3. Firewall masquerading is a simple mechanism called "masquerading" built into the Raspberry Pi itself. When "IP masquerading" is set to be used, it will bridge the internal and external networks, and automatically interpret from the inside to the outside. Or from outside to inside IP addresses, usually, this action is called network address translation. Raspberry Pi's "IP masquerading" method is to hide your IP from others on the network. Then we use the Raspberry Pi's own firewall to disguise "IP" to configure the router:

sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

4. Now save the current firewall rules for IPv4 (including the rules above) and IPv6. Since iptables-persistent has been set up as a service to start on boot during installation, it will automatically load the saved rules after booting:

sudo netfilter-persistent save

5. Configure DHCP and DNS services for the wireless network. DHCP and DNS services are used as templates by the dnsmasq default configuration file, rename the default configuration file and edit a new one:

sudo mv /etc/dnsmasq.conf /etc/dnsmasq.conf.orig 
sudo nano /etc/dnsmasq.conf

Add the following content to the file and save:

interface=wlan0 # Listening interface
dhcp-range=192.168.4.2,192.168.4.20,255.255.255.0,24h
                # Pool of IP addresses served via DHCP
domain=wlan     # Local wireless DNS domain
address=/gw.wlan/192.168.4.1
                # Alias for this router

6. Ensuring wireless operation: countries around the world regulate the use of telecommunications radio frequency bands, and 5 GHz wireless networks are disabled until the Raspberry Pi is configured with a WiFi country code. Let's disable wifi before setting the country code, and execute the following command:

sudo rfkill unblock wlan

This setting will be recovered automatically when booting. Next, we need to define the suitable national code for the access point software.
7. Configure AP software: Create the cogig file of hostapd, /etc/hostapd/hostapd.conf will add various parameters for your wireless network.

sudo nano /etc/hostapd/hostapd.conf

Add the following information to the configuration file. This configuration assumes we are using channel 7, the network name is waveshareRaspberry, and the password is waveshare12345. Note that names and passwords should not have quotation marks. The length of the passphrase should be between 8 and 64 characters.

country_code=CN
interface=wlan0
ssid=waveshareRaspberry
hw_mode=g
channel=7
macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
wpa=2
wpa_passphrase=waveshare12345
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP
rsn_pairwise=CCMP

Note the line country_code=CN: it configures the computer to use the correct wireless frequency in China. Now we are in China, so we fill in our country code CN, if you don't know your country code, you can go to wikipedia to find it.

To use the 5 GHz band, you can change the operating mode from hw_mode=g to hw_mode=a. Possible values for hw_mode are:

a = IEEE 802.11a (5 GHz) (Raspberry Pi 3B+ and above)

b = IEEE 802.11b (2.4 GHz)

g = IEEE 802.11g (2.4 GHz)

Running the new wireless AP Now reboot your Raspberry Pi and verify that the wireless access point is automatically available.

sudo systemctl reboot

After restarting the Raspberry Pi, you can search for wireless networks using your phone or computer.

HDMI configuration

  • On the Raspberry Pi 4B, there are two micro HDMI ports. It can drive up to two monitors with resolutions up to 1080p and a refresh rate of 60Hz. At 4K resolution, if two monitors are connected, the refresh rate is limited to 30Hz. You can also drive a single monitor at 4K with a 60Hz refresh rate: this requires the monitor to be connected to the HDMI port (labeled HDMI0) adjacent to the USB-C power input. hdmi_enable_4kp60=1 You must also enable 4Kp60 output by setting a flag in config.txt.

HDMI Group and Mode

  • HDMI has two common groups: CEA (Consumer Electronics Association, the standard commonly used by TVs) and DMT (Display Monitor Timing, the standard commonly used by monitors). Each group advertises a specific set of modes, one of which describes the resolution, frame rate, clock rate, and aspect ratio of the output.

Mode Support

  • Before using tvservice commands, you need to modify the default KMS driver to FKMS driver. The modified method: open the config.txt file below the boot directory:
sudo nano /boot/config.txt

In config.text:

dtoverlay=vc4-kms-v3d

Change to

dtoverlay=vc4-fkms-v3d
  • Also, you can check the modes supported in your devices by the command lines in tvservice and find other useful data:
    • tvservice -s: display the current HDMI state including mode and resolution
    • tvservice -m CEA: lists all supported CEA modes.
    • tvservice -m DMT: lists all supported DMT modes.

Set the Specified HDMI Mode

  • Modify the two lines of hdmi_group and hdmi_mode in the config.txt file to set the HDMI output format CEA or DMT. Mode selects the resolution and frame rate. Combine the modes table and use the above tvservice commands to know exactly which modes are supported by your device.
hdmi_group=1 CEA mode
hdmi_mode resolution frequency screen size remarks
1 VGA(640×480) 60Hz 4:3
2 480p 60Hz 4:3
3 480p 60Hz 16:9
4 720p 60Hz 16:9
5 1080i 60Hz 16:9
6 480i 60Hz 4:3
7 480i 60Hz 16:9
8 240p 60Hz 4:3
9 240p 60Hz 16:9
10 480i 60Hz 4:3 Quad pixels
11 480i 60Hz 16:9 Quad Pixel
12 240p 60Hz 4:3 Quad pixels
13 240p 60Hz 16:9 Quad Pixel
14 480p 60Hz 4:3 Quad Pixel
15 480p 60Hz 16:9 Quad Pixel
16 1080p 60Hz 16:9
17 576p 50Hz 4:3
18 576p 50Hz 16:9
19 720p 50Hz 16:9
20 1080i 50Hz 16:9
21 576i 50Hz 4:3
22 576i 50Hz 16:9
23 288p 50Hz 4:3
24 288p 50Hz 16:9
25 576i 50Hz 4:3 Quad pixels
26 576i 50Hz 16:9 Quad Pixel
27 288p 50Hz 4:3 Quad pixels
28 288p 50Hz 16:9 Quad Pixel
29 576p 50Hz 4:3 Quad Pixel
30 576p 50Hz 16:9 Quad pixels
31 1080p 50Hz 16:9
32 1080p 24Hz 16:9
33 1080p 25Hz 16:9
34 1080p 30Hz 16:9
35 480p 60Hz 4:3 Quad Pixel
36 480p 60Hz 16:9 Quad Pixel
37 576p 50Hz 4:3 Quad pixels
38 576p 50Hz 16:9 Quad Pixel
39 1080i 50Hz 16:9 Reduced blanking
40 1080i 100Hz 16:9
41 720p 100Hz 16:9
42 576p 100Hz 4:3
43 576p 100Hz 16:9
44 576i 100Hz 4:3
45 576i 100Hz 16:9
46 1080i 120Hz 16:9
47 720p 120Hz 16:9
48 480p 120Hz 4:3
49 480p 120Hz 16:9
50 480i 120Hz 4:3
51 480i 120Hz 16:9
52 576p 200Hz 4:3
53 576p 200Hz 16:9
54 576i 200Hz 4:3
55 576i 200Hz 16:9
56 480p 240Hz 4:3
57 480p 240Hz 16:9
58 480i 240Hz 4:3
59 480i 240Hz 16:9
60 720p 24Hz 16:9
61 720p 25Hz 16:9
62 720p 30Hz 16:9
63 1080p 120Hz 16:9
64 1080p 100Hz 16:9
65 null
66 720p 25Hz 64:27 for pi4
67 720p 30Hz 64:27 for pi4
68 720p 50Hz 64:27 for pi4
69 720p 60Hz 64:27 for pi4
70 720p 100Hz 64:27 for pi4
71 720p 120Hz 64:27 for pi4
72 1080p 24Hz 64:27 for pi4
73 1080p 25Hz 64:27 for pi4
74 1080p 30Hz 64:27 for pi4
75 1080p 50Hz 64:27 for pi4
76 1080p 60Hz 64:27 for pi4
77 1080p 100Hz 64:27 for pi4
78 1080p 120Hz 64:27 for pi4
79 1680×720 24Hz 64:27 for pi4
80 1680×720 25Hz 64:27 for pi4
81 1680×720 30Hz 64:27 for pi4
82 1680×720 50Hz 64:27 for pi4
83 1680×720 60Hz 64:27 for pi4
84 1680×720 100Hz 64:27 for pi4
85 1680×720 120Hz 64:27 for pi4
86 2560×720 24Hz 64:27 for pi4
87 2560×720 25Hz 64:27 for pi4
88 2560×720 30Hz 64:27 for pi4
89 2560×720 50Hz 64:27 for pi4
90 2560×720 60Hz 64:27 for pi4
91 2560×720 100Hz 64:27 for pi4
92 2560×720 120Hz 64:27 for pi4
93 2160p 24Hz 16:9 for pi4
94 2160p 25Hz 16:9 for pi4
95 2160p 30Hz 16:9 for pi4
96 2160p 50Hz 16:9 for pi4
97 2160p 60Hz 16:9 for pi4
98 4096×2160 24Hz 256:135 for pi4
99 4096×2160 25Hz 256:135 for pi4
100 4096×2160 30Hz 256:135 for pi4
101 4096×2160 50Hz 256:135 for pi4
102 4096×2160 60Hz 256:135 for pi4
103 2160p 24Hz 64:27 for pi4
104 2160p 25Hz 64:27 for pi4
105 2160p 30Hz 64:27 for pi4
106 2160p 50Hz 64:27 for pi4
107 2160p 60Hz 64:27 for pi4
 hdmi_group=2   DMT mode
hdmi_mode Resolution Frequency Screen Size Note
1 640×350 85Hz
2 640×400 85Hz 16:10
3 720×400 85Hz
4 640×480 60Hz 4:3
5 640×480 72Hz 4:3
6 640×480 75Hz 4:3
7 640×480 85Hz 4:3
8 800×600 56Hz 4:3
9 800×600 60Hz 4:3
10 800×600 72Hz 4:3
11 800×600 75Hz 4:3
12 800×600 85Hz 4:3
13 800×600 120Hz 4:3
14 848×480 60Hz 16:9
15 1024×768 43Hz 4:3 Not for Raspberry Pi
16 1024×768 60Hz 4:3
17 1024×768 70Hz 4:3
18 1024×768 75Hz 4:3
19 1024×768 85Hz 4:3
20 1024×768 120Hz 4:3
21 1152×864 75Hz 4:3
22 1280×768 60Hz 15:9 reduce blanking
23 1280×768 60Hz 15:9
24 1280×768 75Hz 15:9
25 1280×768 85Hz 15:9
26 1280×768 120Hz 15:9 reduce blanking
27 1280×800 60Hz 16:10 reduce blanking
28 1280×800 60Hz 16:10
29 1280×800 75Hz 16:10
30 1280×800 85Hz 16:10
31 1280×800 120Hz 16:10 reduce blanking
32 1280×960 60Hz 4:3
33 1280×960 85Hz 4:3
34 1280×960 120Hz 4:3 reduce blanking
35 1280×1024 60Hz 5:4
36 1280×1024 75Hz 5:4
37 1280×1024 85Hz 5:4
38 1280×1024 120Hz 5:4 reduce blanking
39 1360×768 60Hz 16:9
40 1360×768 120Hz 16:9 reduce blanking
41 1400×1050 60Hz 4:3 reduce blanking
42 1400×1050 60Hz 4:3
43 1400×1050 75Hz 4:3
44 1400×1050 85Hz 4:3
45 1400×1050 120Hz 4:3 reduce blanking
46 1440×900 60Hz 16:10 reduce blanking
47 1440×900 60Hz 16:10
48 1440×900 75Hz 16:10
49 1440×900 85Hz 16:10
50 1440×900 120Hz 16:10 reduce blanking
51 1600×1200 60Hz 4:3
52 1600×1200 65Hz 4:3
53 1600×1200 70Hz 4:3
54 1600×1200 75Hz 4:3
55 1600×1200 85Hz 4:3
56 1600×1200 120Hz 4:3 reduce blanking
57 1600×1200 60Hz 16:10 reduce blanking
58 1600×1200 60Hz 16:10
59 1600×1200 75Hz 16:10
60 1600×1200 85Hz 16:10
61 1600×1200 120Hz 16:10 reduce blanking
62 1792×1344 60Hz 4:3
63 1792×1344 75Hz 4:3
64 1792×1344 120Hz 4:3 reduce blanking
65 1856×1392 60Hz 4:3
66 1856×1392 75Hz 4:3
67 1856×1392 120Hz 4:3 reduce blanking
68 1920×1200 60Hz 16:10 reduce blanking
69 1920×1200 60Hz 16:10
70 1920×1200 75Hz 16:10
71 1920×1200 85Hz 16:10
72 1920×1200 120Hz 16:10 reduce blanking
73 1920×1440 60Hz 4:3
74 1920×1440 75Hz 4:3
75 1920×1440 120Hz 4:3 reduce blanking
76 2560×1600 60Hz 16:10 reduce blanking
77 2560×1600 60Hz 16:10
78 2560×1600 75Hz 16:10
79 2560×1600 85Hz 16:10
80 2560×1600 120Hz 16:10 reduce blanking
81 1366×768 60Hz 16:9 not for Raspberry Pi 4
82 1920×1080 60Hz 16:9 1080p
83 1600×900 60Hz 16:9 reduce blanking
84 2048×1152 60Hz 16:9 reduce blanking
85 1280×720 60Hz 16:9 720p
86 2366×768 60Hz 16:9 reduce blanking

Set Up Self-define HDMI Mode

  • Define the CVT mode according to the monitor parameters by yourself.
hdmi_cvt=<width> <height> <frame> <dimensions> <margin> <alternative> <rb>
  • For example, 7-inch display, the resolution is 1024×600 with 60HZ and the aspect ratio is 15:9. We can add the following codes at the end of /boot/config.txt
hdmi_cvt=1024 600 60 6 0 0 0
hdmi_group=2
hdmi_mode=87
hdmi_drive=1
    • CVT parameters:
    • The resolution is 1024×600.
    • The frame is 60Hz.
    • 1=4:3, 2=14:9, 3=16:9, 4=5:4, 5=16:10, 6=15:9
    • 0=disable margins, 1=enable margins
    • 0=progressive, 1=interlaced
    • 0=normal, 1=reduce blanking
  • hdmi_group=2 defines the HDMI output group as DMT, but we look at the last value of the DMT table is hdmi_mode=86, where hdmi_mode=87 is the custom mode.
  • hdmi_drive 1 means normal DVI mode (no sound); 2 means normal HDMI mode (sound will be sent if supported and enabled).

Display Rotation

  • Enter xrandr in the Raspberry Pi terminal to check the HDMI-ID where the main screen is located (mostly HDMI-1):
  • Enter the following command to rotate the display:
xrandr --output HDMI-1 --rotate normal rotate 0 degrees
xrandr --output HDMI-1 --rotate left rotate -90 degrees
xrandr --output HDMI-1 --rotate right rotate +90 degrees
xrandr --output HDMI-1 --rotate inverted rotate 180 degrees

Onboard analog audio (3.5mm jack)

  • Modify the config.txt file to change how analog audio is driven, and enable or disable some firmware features.

1. audio_pwm_mode

    • audio_pwm_mode=1 Select traditional low-quality analog audio from a 3.5mm AV jack.
    • audio_pwm_mode=2 (default) selects high-quality analog audio using an advanced modulation scheme.

2.disable_audio_dither

    • Set to 1 to disable the default 1LSB dithered audio output. Resolves slight background noise in some cases (eg: turning down the OS volume).

3. enable_audio_dither

    • Set to 1 to force audio dithering for all depths of audio.

4.pwm_sample_bits

    • The pwm_sample_bits is used to adjust the bit depth of the analog audio output. The default bit depth is 11.

USB Driver

  • Since the TF card reading and writing speed is relatively slow, it will affect the performance. We can connect the high-speed solid-state drive to the Raspberry Pi through the USB interface, and use the USB to boot, which will greatly improve the performance of the Raspberry Pi.

Preparation

  • Raspberry Pi 4B board
  • TF card reader
  • 5V 3A power adapter
  • At least 8GB TF card
  • Micro HDMI to HDMI cable
  • Computer monitor or TV with HDMI port
  • Solid-state hard drives with USB transfer interface, U disk, and mechanical hard disk are not recommended, and the read and write speed is not much improved

Setup USB Boot with Raspberry Pi Imager

Raspberry Pi Programming Blootloader

  • Insert the TF card into the card reader, connect to the computer, and open Raspberry Pi Imager.
  • Choose Misc utility images—>Bootloader—>USB Boot.
  • After waiting for the bootloader to be programmed, we insert the TF card into the Raspberry Pi to boot.
  • The first time you turn it on, you need to wait patiently. When the green LED will flash in steady mode, the 7inch display will turn green (or the screen will flash green). At this time, turn off the Raspberry Pi and take out the TF card.

Install Raspberry Pi System on Solid State Drive

  • Open Win32DiskImager or Raspberry Pi Imager to program the image.
  • After installing the system, insert the solid state drive into the USB3.0 port of the Raspberry Pi, wait for the boot to succeed, and then start the Raspberry Pi system from the hard disk.

Set USB Booting by raspi-config

  • Program the official system of the Raspberry Pi to the TF card and insert it into the Raspberry Pi. After the boot is completed, open the Raspberry Pi terminal and enter raspi-config.
  • Select Advanced Options—>Bootloader Order—>Select USB to boot, and restart the Raspberry Pi.

For Ubuntu18.04 and Ubuntu20.04

  • The above tutorial only supports Raspberry Pi official system and the Ubuntu22.04 system. For students who want to use the Ubuntu18.04 system and Ubuntu20.04 system, the following configuration needs to be done:

Update EEPROM

  • Flashing the bootloader with the Raspberry Pi Imager eliminates the need to upgrade the EEPROM.
  • To use the raspi-config method of the official system of the Raspberry Pi, you need to upgrade the EEPROM, and enter the following command:
sudo apt update
sudo apt full-upgrade

Update Firmware

  • Download the updated Boot.zip, copy and overwrite all .dat and .elf in the boot subdirectory to system-boot.
  • Download the complete firmware address on GitHub

Update config.txt File

  • Ubuntu18.04
  • Open config.txt file and replace the [pi4] with the following content:
[pi4]
max_framebuffers=2
dtoverlay=vc4-fkms-v3d
boot_delay
kernel=vmlinuz
initramfs initrd.img followkernel
  • For Ubuntu18.04, complete the above steps, directly connect the SSD to the USB3.0 port and start it. No subsequent operations are required.
  • Ubuntu20.04
  • Open the config.txt file with Notepad and replace the [pi4] section with the following:
[pi4]
max_framebuffers=2
dtoverlay=vc4-fkms-v3d
boot_delay
kernel=vmlinux
initramfs initrd.img followkernel

Decompress the kernel (versions after Ubuntu 20.04 need to decompress the kernel)

  • After finding vmlinuz and decompressing it using the 7-zip tool, rename the decompressed vmlinuz~ to vmlinux.

Create An Automatic Decompression Script

  • During an update of Ubuntu or one of its many packages, apt will create a new kernel image. This image will be compressed and will cause the Raspberry Pi to fail to boot after the update. To fix this, a script needs to be created to unpack the new kernel image after the update.
  • Use the SSH remote software to connect to the Raspberry Pi. To find the IP address of the Raspberry Pi, refer to the IP address query section.
  • Both login name and login password are ubuntu.
  • The first time you log in, a password change will be performed.
  • First enter the current default password: ubuntu, the system will prompt you to enter a new password, and after entering the new password, the system will ask you to confirm the new password.
  • If the modification is successful, SSH will be automatically disconnected, and you can log in again with the modified password.
  • Create decompression script
sudo nano /boot/firmware/auto_decompress_kernel

The content of the script is as follows:

#!/bin/bash -e
# auto_decompress_kernel script
#Set Variables
BTPATH=/boot/firmware
CKPATH=$BTPATH/vmlinuz
DKPATH=$BTPATH/vmlinux
#Check if compression needs to be done.
if [ -e $BTPATH/check.md5 ]; then
   if md5sum --status --ignore-missing -c $BTPATH/check.md5; then
      echo -e "\e[32mFiles have not changed, Decompression not needed\e[0m"
      exit 0
   else
      echo -e "\e[31mHash failed, kernel will be compressed\e[0m"
   fi
fi
#Backup the old decompressed kernel
mv $DKPATH $DKPATH.bak
if [ ! $? == 0 ]; then
   echo -e "\e[31mDECOMPRESSED KERNEL BACKUP FAILED!\e[0m"
   exit 1
else
   echo -e "\e[32mDecompressed kernel backup was successful\e[0m"
fi
#Decompress the new kernel
echo "Decompressing kernel: "$CKPATH".............."
zcat $CKPATH > $DKPATH
if [ ! $? == 0 ]; then
   echo -e "\e[31mKERNEL FAILED TO DECOMPRESS!\e[0m"
   exit 1
else
   echo -e "\e[32mKernel Decompressed Succesfully\e[0m"
fi
#Hash the new kernel for checking
md5sum $CKPATH $DKPATH > $BTPATH/check.md5
if [ ! $? == 0 ]; then
   echo -e "\e[31mMD5 GENERATION FAILED!\e[0m"
else
   echo -e "\e[32mMD5 generated Succesfully\e[0m"
fi
#Exit
exit 0

Set Up Autorun

  • In order for the script we just created to be called every time, the package is installed:
sudo nano /etc/apt/apt.conf.d/999_decompress_rpi_kernel
#Write the following
DPkg::Post-Invoke {"/bin/bash /boot/firmware/auto_decompress_kernel"; };
#Set to runnable permissions
cd /etc/apt/apt.conf.d/
sudo chmod +x 999_decompress_rpi_kernel
  • Once set up, we can install the package test using apt.

Login

Configure SSH

Configure SSH (with monitor)

  • Take out the SD card from the computer, install the SD card on the Raspberry Pi, connect the mouse, keyboard, and monitor to the Raspberry Pi, and turn it on.
  • Open the Raspberry Pi terminal and enter raspi-config to enter the setting interface and select Interface Options.
  • Go to the Interfaces tab.
  • Select Enable next to SSH.
  • Click OK.
  • Restart the Raspberry Pi.

Raspberry-pi-Configuration02.gif

Configure SSH (without monitor)

  • Users who use the official bullseye image need to enable SSH by themselves.
  • The opening method is as follows:
    • Create a new file named ssh under the boot drive letter, without any extension, you can create a new ssh.txt, make sure the setting in the folder options is to display the extension, and then delete .txt, so you get a file named ssh without any extension.

Raspberry-pi-Login01.png
Raspberry-pi-Login02.png

  • Do not remove the TF card before configuring WiFi.

Configure WLAN

  • On Raspberry Pi devices that support the 5GHz band (Pi3B+, Pi4, CM4, Pi400), for regulatory reasons, disable the wireless network before setting the country code. To set the country code.

Configure WLAN (With Monitor)

  • Open the terminal and type sudo raspi-config, select Localisation Options Configure language and regional settings.
  • Select L4: WLAN Country Set legal wireless channels for your country, and press enter.
  • Find the country code of your country. Now we are in China, so our country code is CN. If you don't know your country code, you can go to Wikipedia to find it. Select CN China, press Enter, and OK to confirm.
  • Press OK to confirm and it will return to the initial setting interface, press Finish, and the system will prompt you to restart the Raspberry Pi, select Yes, wait for the Raspberry Pi to restart, and then you can search for your wireless network, enter the wireless network password to Connection succeeded.

Raspberry-pi-Configuration04.gif

Configure WLAN (Without Monitor)

  • Considering that not every user has a display and keyboard for the Raspberry Pi.
  • Here we provide a method to configure the WLAN wireless network through the card reader
    • Once the image is created on the SD card, insert it into a card reader to access the boot folder.
    • Adding certain files to this folder will activate certain setup functions the first time the Raspberry Pi boots up.

1. Create a new notepad file:
Raspberry-pi-Login07.png
2. Open and enter the corresponding content ('Assume I am in China, the wireless name is test, and the wireless password is 12345678):

country=CN
update_config=1
ctrl_interface=/var/run/wpa_supplicant

network={
ssid="test"
psk="12345678"
key_mgmt=WPA-PSK
}

3. Close Notepad and save:
4. Notepad renamed to wpa_supplicant.conf:
Raspberry-pi-Login08.png
Raspberry-pi-Login09.png
5. Safely eject the SD card and plug in the Raspberry Pi.
6. Once the Raspberry Pi is connected to a power source, make sure to wait a few minutes (up to 5 minutes) for it to boot up and register on the network.

Get the IP Address of the Raspberry Pi

Get From Router

  • Login the router to view the Raspberry Pi IP address.

Raspberry-pi-Login010.png

Get From Mobile Phone (Only for Apple)

  • Use your smartphone to get your Pi's IP address, search the app store for the Fing app, it's a free network scanner for smartphones.
  • Note: Your phone and Raspberry Pi must be on the same network, so connect your phone to the correct wireless network.
  • When the Fing app is open, touch Device Scan in the upper left corner of the screen.

Raspberry-pi-Login011.png

  • After a few seconds, you can get a list of devices connected, including all devices connected to the network.

Raspberry-pi-Login012.png

  • At this point, we have successfully obtained the IP address of the Raspberry Pi: 192.168.0.105.

Use Advanced IP Scanner

1. Run Advanced IP Scanner.
2. Click the Scan button to scan the IP address in the current LAN.
BuildMecar Kit Setup01.jpg
3. Find and record "All" IP addresses with Raspberry Pi in the Manufacturer.
BuildMecar Kit Setup02.jpg
4. Power on the device and make sure the device connecting to the network.
5. Click the Scan button again and scan all the IP addresses in the current LAN.
6. You can find the Raspberry Pi IP address after filtering all the IP addresses with Raspberry Pi in the Manufacturer that are recorded before.

Get From nmap Command

  • Download and install Nmap-7.92-setup.zip, otherwise, the computer will not recognize the command.
  • Press WIN + R, enter cmd, and open the terminal.
  • We need to know the IP address of our computers before using nmap commands. Only through the IP address of the computer can we know the IP network segment, and then use nmap to scan the devices under this network segment.
 ipconfig  

Raspberry-pi-Login 7.png

  • If your IP address is 192.168.1.5, the addresses of other devices will be in this 192.168.1.0/24 subnet range (this covers 192.168.1.0 to 192.168.1.255).
  • My computer is 192.168.0.104. Now use the nmap command with flags (ping scan) on the entire subnet range. -sn This may take a few seconds:
nmap -sn 192.168.0.0/24

Raspberry-pi-Login 8.png

  • At this point, we have successfully obtained the IP address of the Raspberry Pi: 192.168.0.105.

Remote Login

Sometimes you need to access the Raspberry Pi without connecting it to a display, any device connected to the LAN is assigned an IP address. In the previous chapter, we learned how to get Pi's IP address. Let me learn how to remotely access the Pi.

  1. Make sure the Raspberry Pi is connected to the network, either via WLAN or a network cable.
  2. Make sure the Raspberry Pi and your computer are under the same router or on the same network segment.
  3. Make sure that the corresponding remote login function is enabled on the Raspberry Pi.

On April 4, the Raspberry Pi official made an update to the Raspberry Pi OS Bullseye, which deleted the default account pi of the Raspberry Pi.
The first time you log in to the Raspberry Pi, you need to create your own account. Before you create a user account, you cannot log in to the Raspberry Pi. We can create a userconf.txt file on the desktop and add it as shown below:

pi: $6$c70VpvPsVNCG0YR5$l5vWWLsLko9Kj65gcQ8qvMkuOoRkEagI90qi3F/Y7rm8eNYZHW8CY6BOIKwMH7a3YYzZYL90zf304cAHLFaZE0

After saving successfully, copy userconf.txt to the uboot directory of the Raspberry Pi. The default account is "pi" and the password is raspberry.
If you want to customize your username and login password, the easiest way to do this is to use the Raspberry Pi Imager or monitor settings.

If you want to generate your own userconf.txt content, you can use the following command to set.

echo 'your password' | openssl passwd -6 -stdin

For example, the set password is: 12345678, then the content of userconf.txt is:

cm4:$6$E9yEBJOesm27lrGZ$PCtGBDX7GMqUHHkO4QTcMQd7UnED5tc0tvOKwd7QIiMxVlq9UYebsqvGe4X9celqUVbLYdAvwuTowiYwvpWwG1

Raspberry-pi-Login 10.png

SSH Login

Make sure the SSH function is enabled, here use the SSH login command that comes with Windows.
1. Press the win key and the R key at the same time, enter cmd, press Enter, and open the command line.
2. Assuming that the address you obtained is 192.168.10.36, the command should be:

ssh [email protected]

Raspberry-pi-Login12.png
3. Enter yes to log in.
Raspberry-pi-Login13.png
4. Enter the default password raspberry:
Raspberry-pi-Login14.png
Note: It is normal that there is no change on the screen when entering the password. After entering the password, press the Enter key to access the Raspberry Pi:
5. Here the SSH login is successful:
Raspberry-pi-Login15.png

PUTTY Login

1. Open the corresponding Putty.zip, click session, and enter the IP address of the Raspberry Pi in the IP address:
Raspberry-pi-Login16.png
2. Choose Accept:
Raspberry-pi-Login17.png
3. The login is pi and the password is raspberry:
Raspberry-pi-Login18.png
4. The login is successful here:
Raspberry-pi-Login19.png

VNC Login

1. Open VNC and enter the IP address of the Raspberry Pi.
Raspberry-pi-Login20.png
2. Choose Continue:
Raspberry-pi-Login21.png
3. Username: pi Password:raspberry:
Raspberry-pi-Login22.png
4. The login is successful here:
Raspberry-pi-Login23.png

MobaXterm Login

1. Open the remote login software MobaXterm:
Raspberry-pi-Login24.png
2. Click session, ssh, and enter the IP address of the Raspberry Pi in the Remote host:
Raspberry-pi-Login25.png
3. The login is pi and the password is raspberry:
Raspberry-pi-Login26.png
4. The login is successful here:
Raspberry-pi-Login27.png

Hostname Login

  • The method of modifying the hostname has been introduced before, you can refer to the hostname and System Options sections.
  • To log in with the hostname, just replace the part of the IP address entered earlier with the hostname, take putty as an example:

Raspberry-pi-Login28.png

Configure Static IP Address

  • When the IP address of our Raspberry Pi changes, in addition to using the hostname to log in as we learned earlier, we can also configure a static IP address for the Raspberry Pi.
  • Notes on configuring IP address:
    • The static IP address is the same as the router network segment.
    • It cannot conflict with the IP address assigned by the router, otherwise the Raspberry Pi may not be able to connect to the Internet normally.
    • You can use the IP address assigned by the current router to the Raspberry Pi.

1. The first step is to find the default gateway, press and hold Win+R on the keyboard, enter cmd, and open the terminal of the computer.

 ipconfig 

2. The second step is to modify the Raspberry Pi DHCP configuration file and enter the command:

sudo nano /etc/dhcpcd.conf 

Add at the end of the file:

interface eth0
static ip_address=IP address of Raspberry Pi/24
static routers=Default gateways
static domain_name_servers=Default Gateway 8.8.8.8

For example, our Raspberry Pi address is 192.168.10.40 and the default gateway is 192.168.10.1.

interface eth0
static ip_address=192.168.10.40/24
static routers=192.168.10.1
static domain_name_servers=192.168.10.1 8.8.8.8

Ctrl+s to save, Ctrl+x to exit.

3. The last step to reboot the Raspberry Pi:
sudo reboot

NFS (Simple)

  • Sometimes when we need to transfer files between our computer and Raspberry Pi or between Raspberry Pi and Raspberry Pi, our traditional way is to use U disk, but if we configure NFS file storage on Raspberry Pi For the server, we can easily complete our complicated steps through the network, and the construction process is also very simple.

Set NFS Server

1. Install the NFS server in the Raspberry Pi.

  • First, download the basic service in the NFC:
sudo apt install portmap
  • Install the NFC core server:
sudo apt install nfs-kernel-server

2. Modify the configuration of the NFS file service.

  • Create a file folder in /mnt:
sudo mkdir -p /mnt/nfs
  • Add the following config information in sudo nano /etc/exports
/mnt/nfs *(rw,sync,no_root_squash)

Raspberry-pi-Login020.png
Raspberry-pi-Login021.png
3. Start nfs service:

  • Reboot nfs service:
sudo /etc/init.d/nfs-kernel-server restart

Set NFS Client

1. We are using another Raspberry Pi or other Linux computer to mount through the mount command. The specific mount example is as follows:

 sudo mount -t nfs -o nolock 192.168.10.46:/mnt/nfs /tmp

Raspberry-pi-Login022.jpg

  • Among them, 192.168.10.46 is the IP address of the server, which is filled in according to your actual IP.

2. We can verify whether the configuration is successful through the df command:
Raspberry-pi-Login024.png
3. Create a test file on the server side, which can be viewed and used in the client directory:
Raspberry-pi-Login023.png

NFS (Complicated)

Network File System (NFS) allows you to share directories located on a networked computer with other computers or devices on the same network. The computer on which the directory resides is called the server, and the computer or device that connects to the server is called the client. Clients typically mount the shared directory as part of their own directory structure. A shared directory is an example of a shared resource or network share.
Note: This example is built with two Raspberry Pi 4Bs, serving as the server and the client respectively. The IP address of the server is: 192.168.10.36

Set up NFS server

1. Install the required packages using the following commands:

sudo apt install nfs-kernel-server

2. We want to create the home directory for the user NFS export:

sudo mkdir -p /export/users

3. Give us 777 permissions to export the user's home directory:

sudo chmod 777 /export/users

Raspberry-pi-Login30.png
4. Mount the export home directory under /export/users.

sudo mount --bind /home/users /export/users

Raspberry-pi-Login31.png
5. To avoid us having to re-enter after every reboot, add to the last line of /etc/fstab:

sudo nano /etc/fstab

After the modification is completed, press Ctrl+X and press y to confirm:

/home/users /export/users none bind 0 0

Raspberry-pi-Login32.png
6. Set NEED_SVCGSSD to "no"

 sudo nano /etc/default/nfs-kernel-server

Raspberry-pi-Login032.png
7. To set the directory for the shared server, we add the following two lines to the end of /etc/exports:

sudo nano /etc/exports
/export 192.168.10.0/24(rw,fsid=0,insecure,no_subtree_check,async)
/export/users 192.168.10.0/24(rw,nohide,insecure,no_subtree_check,async)

Raspberry-pi-Login33.png
8. To set access to the specified client, first block all clients, modify the configuration file, and add in the last line of /etc/hosts.deny:

sudo nano /etc/hosts.deny
 
rpcbind mountd nfsd statd lockd rquotad : ALL

Raspberry-pi-Login35.png
9. To allow access to the server client, modify the configuration file, add the IP address list of the server and all clients to the end of /etc/hosts.allow:

sudo nano /etc/hosts.allow
rpcbind mountd nfsd statd lockd rquotad : 192.168.10.0/24

Raspberry-pi-Login34.png
10. Finally need to restart the service to take effect:

sudo systemctl restart nfs-kernel-server

Configure NFS Client

1. Authentication, add at the end of /etc/idmapd.conf:
sudo nano /etc/idmapd.conf
[Translation]

Method = nsswitch

Raspberry-pi-Login 41.png

2. Download the installation package required by the client:
sudo apt install nfs-common

3. Mount the complete export tree to mnt:

sudo mount -t nfs -o proto=tcp,port=2049 192.168.10.36:/ /mnt

4. Create a new directory under /home to mount the server:

sudo mkdir -p /home/users

5. Mount the server /users to the client's /home/users:

sudo mount -t nfs -o proto=tcp,port=2049 192.168.10.36:/users /home/users

6. To avoid us having to re-enter after every reboot, add to the last line of /etc/fstab:

192.168.10.36:/ /mnt nfs auto 0 0

Raspberry-pi-Login 42.png
7. We can verify whether the configuration is successful, and create a test file on the server side, which can be viewed and used in the client directory:

sudo nano test.py

Raspberry-pi-Login 43.png
Or use commands:

df -hT

Raspberry-pi-Login 45.png

Share Files (Samba)

  • When we use the Raspberry Pi, we often need to transfer files between Windows and the Raspberry Pi, and use the samba service to achieve file sharing. It is very convenient to access the Raspberry Pi file system in the Windows Network Neighborhood.

1. First, update the source, the command is as follows:

sudo apt update

2. Run the following command to install samba:

sudo apt install samba samba-common-bin

3. After the installation is complete, modify the configuration file /etc/samba/smb.conf:

sudo nano /etc/samba/smb.conf
 Change read only = yes under homes to read only = no

Raspberry-pi-Login50.png
4. Restart samba service:

sudo /etc/init.d/samba-ad-dc restart

Raspberry-pi-Login51.jpg
5. Add the default user pi to samba, set the password and confirm the password:

sudo smbpasswd -a pi

Raspberry-pi-Login52.jpg
Raspberry-pi-Login53.png
Raspberry-pi-Login54.png
6. To access the Raspberry Pi, enter the Windows address bar:

\\192.168.10.30\pi

Raspberry-pi-Login55.png
7. Enter the name pi and the password set earlier:
Raspberry-pi-Login56.png
8. At this point, you can see the directory of the Raspberry Pi:
Raspberry-pi-Login57.png

GPIO

Introduction

  • GPIO: General-purpose input/output
  • Raspberry Pi pin classification
    • Power pins: 5v, 3.3v, GND (Ground).
    • Regular GPIO control pins: The high and low levels of these pins can be controlled by programming.
    • Special GPIO communication pins: SPI communication, 12C communication, TxD/RxD serial communication.
  • Raspberry Pi Pin Coding
    • Functional physical pins: This coding method is based on the pin numbering on the Raspberry Pi motherboard. Corresponding to pin headers 1 to 40 respectively. Left to right, top to bottom: cardinal on the left, even on the right.
    • BCM: This method refers to the channel number of the Broadcom SOC and focuses on the CPU registers. When using Python to control the Raspberry Pi pins, the WiringPi coding is used.
    • WiringPi coding: WiringPi coding, code the extended GPIO port from 0. When using the C language to control the Raspberry Pi pins, the WiringPi code is used.

Raspberry Pi Documentation-GPIO01.png

  • Terminal window to view pin numbers

1. Enter the command in the terminal:

pinout

Raspberry Pi Documentation-GPIO02.png
2. Use the Raspberry Pi to enter the gpio readall command to view the pin status.

  • Enter the following command to install Git:
sudo apt install git-core
  • Enter the following command to download the WiringPi file to the current directory of the Raspberry Pi system.
sudo git clone https://github.com/WiringPi/WiringPi
  • Wait patiently for its installation to complete. After the download is complete, we can see a WiringPi folder in the current directory. As shown below:

Raspberry Pi Documentation-GPIO03.png

  • Enter the following command to enter the WiringPi folder directory.
cd WiringPi/
  • Enter the following command to install WiringPi.
sudo ./build

Raspberry Pi Documentation-GPIO04.png
Raspberry Pi Documentation-GPIO05.png

  • Wait patiently for its installation to complete. When we see the interface below without any errors, it means the installation is complete.
  • Enter the following command to check the gpio version.
gpio -v

Raspberry Pi Documentation-GPIO06.png

  • Finally, we can view the status of each pin of the Raspberry Pi and enter the command:
gpio readall

Raspberry Pi Documentation-GPIO07.png

Light Up LED

  • This tutorial is an example of the Pioneer600 designed by WaveShare.
  • The Pioneer600 expansion board includes GPIO, I2C, SPI, Serial, and other interface devices. It is a good expansion board for learning Raspberry Pi programming.
  • We are using LED1 on the Pioneer600 expansion board. According to the schematic diagram, LED1 is connected to pin 25 of the Raspberry Pi (BCM code is 26).

Raspberry Pi Documentation-GPIO 10.png
Raspberry Pi Documentation-GPIO 11.png

shell Control

  • Set up the BCM26 output
   cd /sys/class/gpio 
   echo 26 > export 
   cd gpio26 
   echo out > direction 
   echo 1 > value # high output
   echo 0 > value # low output

Standard I/O

Demo Download

  • Run in the Raspberry Pi terminal:
sudo apt-get install p7zip
wget https://files.waveshare.com/upload/3/3a/Pioneer600_code.zip
unzip Pioneer600_code.zip 
sudo chmod 777 -R Pioneer600_code
cd Pioneer600_code/LED/
  • bcm2835 program

Enter the Linux terminal and execute the following command in the terminal:

cd bcm2835
make
sudo ./led

Expected result: LED1 can be seen blinking. Press Ctrl+C to end the program.

  • wiringPi program

Enter the Linux terminal and execute the following command in the terminal:

cd wiringPi
make
sudo ./led

Expected result: LED1 can be seen blinking. Press Ctrl+C to end the program.
Breathing light:

sudo ./pwm

Expected result: You can see a gradual change in the brightness of LED1.
Press Ctrl+C to end the program.

  • python program

Enter the following command in the terminal to execute the program:

cd python
sudo python led.py

Expected result: LED1 can be seen blinking. Press Ctrl+C to end the program.
Breathing light:

sudo python pwm.py

Expected result: You can see a gradual change in the brightness of LED1. Press Ctrl+C to end the program.

  • shell program

Enter the following command in the terminal to execute the program:

cd shell
sudo sh LED.sh 26 1
sudo sh LED.sh 26 0

Expected result: LED1 state changes according to 0/1 of the input.

I/O File

  • Through the above operations, we can find that in the Linux system, the corresponding device can be operated by reading and writing device files.
  • In the world of Linux, everything is a file. Below we can operate GPIO by reading and writing files in C language.
  • sysfs program

Enter the Linux terminal and execute the following command in the terminal:

cd fs
make
sudo ./led

Expected result: The program exits automatically after 10 flashes of LED1. Press Ctrl+C to end the program.

Serial Port

Introduction

  • Serial port, also known as serial communication interface or COM interface.
  • Serial communication refers to a communication mode in which data is transmitted bit by bit on a signal line using a serial communication protocol (serial communication).
  • Raspberry Pi 3/4B has two serial ports, one is called hardware serial port (/dev/ttyAMA0) and the other is mini serial port (/dev/ttyS0).
    • The hardware serial port is realized by hardware, has a separate baud rate clock source, and has high performance and reliability.
    • The "mini serial port" has low performance and simple functions, and there is no dedicated clock source for the baud rate but is provided by the CPU core clock. Therefore, the "mini serial port" has a fatal weakness: the baud rate is affected by the kernel clock, and the kernel If the power consumption is intelligently adjusted to reduce the main frequency, the corresponding baud rate of the mini serial port will be affected.
  • Raspberry Pi serial port classification:
    • Main serial port: Communication can be achieved through pins.
    • Auxiliary serial port: cannot use GPIO pin communication is assigned to the Bluetooth side by default.
    • On the Raspberry Pi, pin 8 (transmit) and pin 10 (receive) are used as the transceiver of the main serial port. Pin 8 is called TXD (Transmit Data) and pin 10 is called RXD (Receive Data).
  • In the Raspberry Pi 3/4B, the "hardware serial port" is assigned to the auxiliary serial port by default (communication with Bluetooth), while the "mini serial port" is assigned to the main serial port (communication with pins GPIO Tx Rx), and the "mini serial port" is assigned by default. "It is disabled by default and needs to be manually enabled by raspi-config.
Linux Device Description
/dev/ttyS0 mini UART
/dev/ttyAMA0 hardware serial port
/dev/serial0 Main serial port
/dev/serial1 Auxiliary Serial Port

Setting Steps

  • For stable communication, it is necessary to exchange the default mapping between the "hardware serial port" and "mini serial port", and assign the "hardware serial port" /dev/ttyAMA0 mapping to Tx Rx of GPIO.

1. Start the serial port First check the status of the serial port startup. If the serial port has not been configured, the following results should be obtained under normal circumstances:

ls -la /dev/serial*

Raspberry Pi Documentation-GPIO30.png

    • Only serial1 -> ttyAMA0, no related mapping of ttyS0 is seen. The reason why you can see the mapping of ttyAMA0 when the serial port is not turned on is as mentioned above, Raspberry Pi 3/4B uses ttyAMA0 for onboard Bluetooth communication by default.

2. Enter raspi-config in the terminal to open the serial port (refer to the configuration to open ssh Interface Options):
3. Restart the Raspberry Pi, and after enabling the serial port in the settings, you will find that there are two in the /dev directory: serial0 -> ttyS0 and serial1 -> ttyAMA0, which means the opening is successful.

sudo reboot 

Raspberry Pi Documentation-GPIO31.png
4. Disable Bluetooth (the hardware serial port and the mini serial port mapping swap), and ttyAMA0 is released. At this time, the Raspberry Pi also automatically exchanges ttyAMA0 and ttyS0, and assigns serial0 to ttyAMA0. The purpose of the mapping swap is to apply the hardware serial port to the Tx Rx of the GPIO interface. If Bluetooth communication is used in the project, be careful when doing this step. Modify the system configuration file /boot/config.txt:

sudo nano /boot/config.txt

Add in the file:

dtoverlay=pi3-disable-bt

Note: The parameter value of Raspberry Pi 4B is also pi3-disable-bt.
5. Reboot Raspberry Pi.

sudo reboot

6. View the serial port state and whether the mapping of ttyAMA0 and ttyS0 is reversed

ls -la /dev/serial*

Raspberry Pi Documentation-GPIO32.png

    • It can be seen that in the result, the mappings of ttyAMA0 and ttyS0 are reversed.

7. Disable the serial console function. By default, the Raspberry Pi uses the serial port derived from IO as the console. When there is no network, the Raspberry Pi can be controlled and managed through the serial port. The serial port module cannot be used for communication normally. The serial console function needs to be disabled to make the serial port free for us to use. Use the following two commands to stop and disable the console function of the serial port respectively. (Because we have exchanged the mapping relationship of the serial port before, so pay attention to ttyAMA0 here.)

sudo systemctl stop [email protected]
sudo systemctl disable [email protected]

8. One last thing to remove:

sudo nano /boot/cmdline.txt

Delete or comment out in an open file:

console=serial0,115200

In this way, the serial port of the Raspberry Pi is set up, and you can send and receive messages through the serial port.
9. Install SSCOM on the Raspberry Pi:

sudo apt install minicom -y 

10. Run minicom and enter the command:

minicom -D /dev/ttyAMA0  -b 9600

11. Connect to the computer by USB TO TTL, and open File:Cktszsss32.zip to send data.
Raspberry Pi Documentation-GPIO34.png
Raspberry Pi Documentation-GPIO35.png

I2C

Introduction

  • I2C: Inter-Integrated Circuit.
  • It is a serial communication bus, using a multi-master-slave architecture, developed by Philips in the 1980s to allow motherboards and embedded systems to connect low-speed peripherals. The correct pronunciation of I2C is "I-squared-C".

I2C Hardware Connection

  • The I2C bus is very simple in physical connection, consisting of SDA (serial data line) and SCL (serial clock line) and pull-up resistors.
  • The communication principle is to generate the signals required by the I2C bus protocol for data transmission by controlling the high and low levels of SCL and SDA.
  • When the bus is idle, SCL and SDA will be pulled high by the pull-up resistor and kept high.

Through its physical connection, we can know that the I2C protocol is a serial and synchronous communication protocol.

Feature

  • Each device on the I2C bus will correspond to this unique I2C address, and some slave devices can change the I2C address through peripheral circuits.
  • The master and slave devices use this address to determine which device to communicate with.
  • Two-way data transmission is performed in units of bytes (8 bits) between the master device and the slave device on the I2C bus.

Protocol

  • The I2C protocol stipulates that the transmission of data on the bus must take a start signal as the start condition and an end signal as the stop condition of the transmission. The start and end signals are always generated by the master device (meaning that the slave device cannot initiate communication actively, all communications are initiated by the master device, the master can issue an inquiry command, and then wait for the communication from the slave device).

Raspberry Pi Documentation-GPIO50.png

  • When the bus is in an idle state, both SCL and SDA remain high. When SCL is high and SDA transitions from high to low, a start condition is generated; when the transfer is over, SCL is high and SDA is switched from a low-to-high transition indicating a stop condition.
  • After the start condition is generated, the bus is in a busy state, the master-slave device of this data transfer occupies the bus, and other I2C devices cannot access the bus; after the stop condition is generated, the master-slave device of this data transfer will release the bus, the bus Idle again.

Raspberry Pi Documentation-GPIO51.png

  • Data transfers are in bytes. The master device will transmit a data bit on the SDA line during the process of generating each clock pulse on the SCL line. When a byte is transmitted in the order of data bits from high to low, the slave device will pull down the SDA line, and return a response bit to the master device, at which time it is considered that a byte has been truly transmitted. Of course, not all byte transfers must have an acknowledged bit. For example, when the slave device can no longer receive the data sent by the master device, the slave device will not return the acknowledged bit.

Enable I2C Interface

  • The Raspberry Pi has a total of two i2c channels, namely I2C-0 (pin 3 and pin 5) and I2C-1 (pin 27 and pin 28). The method of opening I2C is as follows:
  • Enter raspi-config in the terminal to open the serial port I2C (refer to the configuration to open ssh Interface Options):
sudo raspi-config

Hardware connection

Sensor Raspberry Pi Description
Board order
VCC 5V Power input
GND GND Power ground
SDA 3 I2C data input
SCL 5 I2C clock pin

10 DOF IMU RPI C 2.jpg

i2cdetectc Test

  • Query i2c devices:
 sudo i2cdetect -y -r -a 1

Raspberry Pi Documentation-GPIO53.png

    • Parameters: -y is to execute directly ignoring interaction problems, -r is the SMBus read byte command, -a is all addresses, and 1 refers to i2c-1.
  • Scan register data:
i2cdump -y 1 0x77

Raspberry Pi Documentation-GPIO54.png

  • Register data write:
sudo i2cset -y 1 0x77 0x90 0x55
Parameters Meaning
1 represents the I2C device number
0x77 represents the I2C device address
0x90 represents the register address
0x55 represents the data written to the register
  • Register data read:
sudo i2cget -y 1 0x77 0x90
Parameters Meaning
1 represents the I2C device number
0x77 represents the I2C device address
0x90 represents the register address

Install Libraries

BCM2835

#Open the Raspberry Pi terminal and run the following command
wget http://www.airspayce.com/mikem/bcm2835/bcm2835-1.71.tar.gz
tar zxvf bcm2835-1.71.tar.gz
cd bcm2835-1.71/
sudo ./configure && sudo make && sudo make check && sudo make install
# For more information, please refer to the official website: http://www.airspayce.com/mikem/bcm2835/

wiringPi

#Open the Raspberry Pi terminal and run the following command
cd
sudo apt-get install wiringpi
#For Raspberry Pi systems after May 2019 (earlier than before, you may not need to execute), you may need to upgrade:
wget https://project-downloads.drogon.net/wiringpi-latest.deb
sudo dpkg -i wiringpi-latest.deb
gpio -v
# Run gpio -v and version 2.52 will appear. If it does not appear, the installation is wrong

#Bullseye branch system use the following command:
git clone https://github.com/WiringPi/WiringPi
cd WiringPi
./build
gpio -v
# Run gpio -v and version 2.70 will appear. If it does not appear, it means that there is an installation error

Download examples

Open a terminal of the Raspberry Pi

sudo apt-get install p7zip-full -y
sudo wget https://files.waveshare.com/upload/c/c1/10_DOF_IMU_Sensor_D_Code.7z
7z x 10_DOF_IMU_Sensor_D_Code.7z -O./10_DOF_IMU_Sensor_D_Code
cd 10_DOF_IMU_Sensor_D_Code/RaspberryPi/

Run examples

Please execute the following commands under RaspberryPi, otherwise the directory will not be indexed;

C examples

  • Recompile, the compilation process may take a few seconds

BCM2835

cd BCM2853
sudo make clean
sudo make 
sudo ./10Dof-D_Demo

wiringPi

cd wiringPi
sudo make clean
sudo make 
sudo ./10Dof-D_Demo

Note: If you have run BCM2835, please restart wiringPi before running.

Expected result

After running the program on the Raspberry Pi, it will output the following data:

10 DOF IMU RPI C 1.jpg

About the output data

Roll, Pitch, Yaw Roll(°), Pitch(°), Yaw(°)
Acceleration LSB,can be transfered to g
Gyroscope GLSB,can be transfered to °/s
Magnetic LSB, can be transfered μT
Angle Direction(°),it is equal to Yaw degree
Pressure hPa
Altitude m
Temperature

Note:
①:The acceleration output by the serial port of the sample program is the original value of the register (the value of the register). After this value is divided by 16384, it can be converted into a value in g (gravitational acceleration constant).
②:The angular velocity output by the serial port of the sample program is the original value of the register (the value of the register). After this value is divided by 32.8, it can be converted into a value in DPS (angle/second).
③:The value of the magnetic sensor output by the serial port of the sample program is the original value of the register (that is, the value of the register). This value is multiplied by 0.15 to convert it into a value in μT (10-6 Tesla).

SPI

Introduction

  • SPI stands for Serial Peripheral Interface, which is a high-speed, full-duplex, synchronous communication bus.
  • It works in a master-slave mode. In this mode, one master device usually corresponds to one or more slave devices. 4 lines are required for bidirectional data transmission, and 3 lines can be cut for unidirectional data transmission.

Description

  • The SPI bus itself consists of four physical connections: two data lines, a clock line, and a slave select line.
    • MOSI (Master Out/Slave In) – the line on which the Raspberry Pi sends data to the device (sensor).
    • MISO (Master In/Slave Out) – The line on which the device sends data to the Raspberry Pi.
    • SCLK (clock) – The clock signal line.
    • SS/CS (Slave Select/Chip Select) – The line used to select the device to send data to.
    • On the Raspberry Pi, the CS line is called the "Chip Enable" line (or CE for short). The Raspberry Pi actually has two slave select lines available, identified as CE0 and CE1.
    • Raspberry Pi MOSI is pin 19, MISO is pin 21, SCLK is pin 23, CE0 is pin 24 and CE1 pin is 26.

Working Method

  • The clock signal synchronizes the data bit output of the master device to the bit sampling of the slave device. One bit of data is transferred per clock cycle, so the speed of data transfer depends on the frequency of the clock signal. Since the host configures and generates the clock signal, SPI communication is always initiated by the host.
  • Slave selection:
    • The master can select the slave to communicate with by setting the slave's CE line to a low voltage level. In the idle, non-transmitting state, the slave select line is held at a high voltage level.
    • There are two CE pins on the Raspberry Pi, which allow multiple slaves to be connected in parallel. Multiple slaves can be daisy-chained to the master if only one CE/CS/SS pin is present.
  • Multi-Slave:
    • The SPI can be set up to operate with a single master and a single slave, and can be set up with multiple slaves controlled by a single master. Then the slaves can be connected in parallel as follows:

Raspberry Pi Documentation-GPIO60.png

  • MOSI and MISO
    • The master sends data serially to the slave over the MOSI line. The slave receives the data sent by the master through the MOSI pin. Data sent from master to slave is usually sent to MSB first.
    • The slave can also send data back to the master serially over the MISO line. Data sent from the slave back to the master is usually sent the least significant bit first.

SPI Transmission

1. Raspberry Pi output clock signal.
Raspberry Pi Documentation-GPIO61.png
2. The Raspberry Pi switches the CE pin to a low-voltage state, which activates the slave.
Raspberry Pi Documentation-GPIO62.png
3. The Raspberry Pi sends data to the slave one at a time along the MOSI line. The slave reads the received bits.
Raspberry Pi Documentation-GPIO63.png
4. If a response is required, the slave returns data one bit at a time to the Raspberry Pi along the MISO line. The Raspberry Pi reads the received bits. Raspberry Pi Documentation-GPIO64.png

Clock Polarity and Clock Phase

  • Complete timing diagram:

Raspberry Pi Documentation-GPIO65.png

  • The clock signal in SPI can be modified with the properties of clock polarity and clock phases. Together, these two properties define when a bit is an output and when it is sampled.
  • The host can set the clock polarity to allow bits to be output and sampled on the rising or falling edge of the clock cycle.
  • The master can set the clock phase to output and sample on the first or second edge of the clock cycle, regardless of whether it is rising or falling.
  • The Linux kernel uses a combination of CPOL and CPHA to represent the four working modes of the current SPI.
CPOL=0,CPHA=0		SPI_MODE_0
CPOL=0,CPHA=1		SPI_MODE_1
CPOL=1,CPHA=0		SPI_MODE_2
CPOL=1,CPHA=1		SPI_MODE_3
  • CPOL: Indicates the state of the initial level of the clock signal, 0 is a low level, and 1 is a high level.
  • CPHA: Indicates which clock edge is sampled, 0 is the first clock edge sampling, and 1 is the second clock edge sampling.
  • The waveforms of the four working modes of SPI are as follows:

Raspberry Pi Documentation-GPIO66.png

Enable SPI

  • Enter raspi-config in the terminal to open the serial port I2C (refer to the configuration to open ssh Interface Options):
sudo raspi-config
  • Test that the SPI is enabled:
ls -l /dev/spidev*

Raspberry Pi Documentation-GPIO70.png

SPI Programming

This example uses a 1.8-inch color LCD

Install Libraries

  • Install BCM2835 libraries
#Open the Raspberry Pi terminal and run the following command
wget http://www.airspayce.com/mikem/bcm2835/bcm2835-1.68.tar.gz
tar zxvf bcm2835-1.68.tar.gz
cd bcm2835-1.68/
sudo ./configure && sudo make && sudo make check && sudo make install
# For more information, please refer to the official website: http://www.airspayce.com/mikem/bcm2835/
  • Install wiringPi libraries
#Open the Raspberry Pi terminal and run the following command
sudo apt-get install wiringpi
#For Raspberry Pi systems after May 2019 (earlier than before, you may not need to execute), you may need to upgrade:
wget https://project-downloads.drogon.net/wiringpi-latest.deb
sudo dpkg -i wiringpi-latest.deb
gpio -v
# Run gpio -v and version 2.52 will appear. If it does not appear, the installation is wrong

#Bullseye branch system use the following command:
git clone https://github.com/WiringPi/WiringPi
cd WiringPi
./build
gpio -v
# Run gpio -v and version 2.60 will appear. If it does not appear, it means that there is an installation error
  • Install Python libraries
#python2
sudo apt-get update
sudo apt-get install python-pip
sudo apt-get install python-pil
sudo apt-get install python-numpy
sudo pip install RPi.GPIO
sudo pip install spidev
#python3
sudo apt-get update
sudo apt-get install python3-pip
sudo apt-get install python3-pil
sudo apt-get install python3-numpy
sudo pip3 install RPi.GPIO
sudo pip3 install spidev

Hardware Connection

  • Please connect the LCD to your Raspberry Pi with the 8PIN cable according to the table below.
  • Use the pin header or PH2.0 8PIN interface, you need to connect according to the following table.
Connect to Raspberry Pi
LCD Raspberry Pi
BCM2835 Board
VCC 3.3V 3.3V
GND GND GND
DIN MOSI 19
CLK SCLK 23
CS CE0 24
DS 25 22
RST 27 13
BL 18 12

The 1.8inch LCD uses the PH2.0 8PIN interface, which can be connected to the Raspberry Pi according to the above table: (Please connect according to the pin definition table. The color of the wiring in the picture is for reference only, and the actual color shall prevail.)
1.8-rpi.jpg

Download Program

Open the terminal of the Raspberry Pi, execute:

sudo apt-get install unzip -y
sudo wget https://files.waveshare.com/upload/8/8d/LCD_Module_RPI_code.zip
sudo unzip ./LCD_Module_RPI_code.zip -d ./LCD_Module_RPI_code/
cd LCD_Module_RPI_code/RaspberryPi/

Run the Program

Please execute the following commands under RaspberryPi, otherwise, the directory will not be indexed;

C language

  • Recompile, the compilation process may take a few seconds
cd c
sudo make
  • The test program of all screens can be called directly by entering the corresponding size:
sudo ./main screen size
  • We are using a 1.8 color LCD here, and the following commands should be entered:
sudo ./main 1.8

python

  • Enter the python program directory and run the command ls -l.
cd python/examples
ls -l

LCD rpi python examples.png

  • You can view the test programs of all screens and find our corresponding size program: 1inch8_LCD_test.py.
  • Just run the program corresponding to the screen, the program supports python2/3.
# python2
sudo python 1inch8_LCD_test.py
# python3
sudo python3 1inch8_LCD_test.py

CSI

Hardware Connection

To test the Camera, you need to connect a HDMI display or a DIS display for previewing.
The connectors of the DSI interface (display) and the CSI interface (camera) look the same, please take care of it when you connect the camera. The CSI interface is placed between the Audio jack and the HDMI port. The CSI connector of Pi zero is beside the Power interface. If you use the Compute Module, please check the actual place of the carrier board.

  • Connect to Raspberry Pi 5
Place the metal surface of the FPC cable towards the wired network port, then connect to the CSI port. The Pi5 has two CSI ports; either port can be used for connection.
Pi5-IMX219-77-details-5.jpg
  • Connect to Pi Zero Series
Place the metal surface of the FPC downward, then connect it to the CSI port.
RPi Camera Connect Zero.png
  • Connect to other Raspberry Pi boards
Place the metal side of the cable towards the HDMI port and connect to the CSI port.
RPi Camera Connect Pi4.png


About the model

Photosensitive Chip Model Supported Raspberry Pi Board Model Supported Driver Type
OV5647 All Raspberry Pi boards libcamera / Raspicam
OV9281 All Raspberry Pi boards libcamera
IMX219 (Official Raspberry Pi) All Raspberry Pi boards libcamera / Raspicam
IMX219 (Third party) Raspberry Pi Compute Module libcamera
IMX290/IMX327 All Raspberry Pi boards libcamera
IMX378 All Raspberry Pi boards libcamera
IMX477 (Official Raspberry Pi) All Raspberry Pi boards libcamera / Raspicam
IMX477 (Third party) Raspberry Pi Compute Module libcamera
IMX519 All Raspberry Pi boards libcamera (driver required)
IMX708 (Raspberry Pi Camera Module 3) All Raspberry Pi boards libcamera
IMX296 (Raspberry Pi Global Camera) All Raspberry Pi boards libcamera


Test Camera

Software Configuration

If you are using the latest Raspberry Pi Camera Module 3 or Raspberry Pi Global Shutter Camera, you need to run the following command to update the system (network connection is required).

sudo apt-get update -y
sudo apt-get upgrade-

If you do not use an official Raspberry Pi camera, you need to configure the "config.txt " file. If you use the latest Bookworm system, you need to configure /boot/firmware/config.txt.

sudo nano /boot/config.txt
#If using the bookworm system
sudo nano /boot/firmware/config.txt

Find "camera-auto-detect=1" and modify it to "camera_auto_detect=0".

At the end of the file, add the following setting statements according to the camera model.

Model Set Statement
OV9281 dtoverlay=ov9281
IMX290/IMX327 dtoverlay=imx290, clock-frequency=37125000
IMX378 dtoverlay=imx378
IMX219 dtoverlay=imx219
IMX477 dtoverlay=imx477
IMX708 dtoverlay=imx708

Binocular Camera Configuration

  • Currently, both the CM4 and Raspberry Pi 5 support the connection of two cameras.
  • If you want to simultaneously connect to two cameras, you can designate the cameras by adding 'cam0' and 'cam1' after the corresponding camera configuration statements.
    • For example, the imx219 is connected to the cam0 interface and the ov5647 camera is connected to the cam1 interface.
dtoverlay=imx219,cam0
dtoverlay=ov5647,cam1

Test Camera Commands

Enter the Raspberry Pi and enable the camera to preview:

sudo libcamera-hello -t 0

If you want to close the preview window, you can directly press the keys "Alt-F4", or click "x" to close. Also, you can return to the terminal interface and press Ctrl-c to end the demo.
Note: if using "Camera Module 3", the auto-focus function is enabled.
Test Binocular Camera

  • When testing the binocular camera, you need to add "--camera" to specify the camera. If you do not add this parameter, "cam0" is specified by default.
sudo libcamera-hello -t 0 --camera 0
sudo libcamera-hello -t 0 --camera 1

Introduction

After the Bullseye version, the underlying Raspberry Pi driver for the Raspberry Pi image has been switched from Raspicam to libcamera. Libcamera is an open-source software stack (referred to as a driver here for ease of understanding) that is convenient for third-party porting and developing their own camera drivers. As of December 11, 2023, the official pycamera2 library has been provided for libcamera, making it easier for users to call Python demos.

Call Camera

The libcamera software stack provides six instructions for users to preview and test the camera interface.

libcamera-hello

This is a simple "hello world" program that previews the camera and displays the camera image on the screen.
Example

libcamera-hello

This command will preview the camera on the screen for about 5 seconds. The user can use the "-t <duration>" parameter to set the preview time, where the unit of <duration> is milliseconds. If it is set to 0, it will keep previewing all the time. For example:

libcamerahello -t 0

Tune File
The libcamera driver of the Raspberry Pi will call a tuning file for different camera modules. The tuning file provides various parameters. When calling the camera, libcamera will call the parameters in the tuning file, and process the image in combination with the algorithm. The final output is the preview screen. Since the libcamera driver can only automatically receive the signal of the chip, the final display effect of the camera will also be affected by the entire module. The use of the tuning file is to flexibly handle the cameras of different modules and adjust to improve the image quality.
If the output image of the camera is not ideal after using the default tuning file, the user can adjust the image by calling the custom tuning file. For example, if you are using the official NOIR version of the camera, the NOIR camera may require different white balance parameters compared with the regular Raspberry Pi Camera V2. In this case, you can switch by calling the tuning file.

libcamera-hello --tuning-file /usr/share/libcamera/ipa/raspberrypi/imx219_noir.json

Users can copy the default tuning files and modify them according to their needs.
Note: The use of tuning files applies to other libcamera commands, and will not be introduced in subsequent commands.

Preview Window
Most libcamera commands will display a preview window on the screen. Users can customize the title information of the preview window through the --info-text parameter, and can also call some camera parameters through %directives and display them on the window.
For example, if you use HQ Camera: You can display the focal length of the camera on the window through --info-txe "%focus".

libcamera-hello --info-text "focus %focus".

Note: For more information on parameter settings, please refer to the following chapters.

libcamera-jpeg

libcamera-jpeg is a simple still picture shooting program, different from the complex functions of libcamera-still, libcamera-jpeg code is more concise and has many of the same functions to complete picture shooting.
Take JPEG image of full pixel

libcamera-jpeg -o test.jpg

This shooting command will display a preview serial port for about 5 seconds, and then shoot a full-pixel JPEG image and save it as test.jpg.
Users can set the preview time through the -t parameter and can set the resolution of the captured image through --width and --height. E.g:

libcamera-jpeg -o test.jpg -t 2000 --width 640 --height 480

Exposure control
All libcamera commands allow the user to set the shutter time and gain themselves, such as:

libcamera-jpeg -o test.jpg -t 2000 --shutter 20000 --gain 1.5

This command will capture an image with 20ms exposure and camera gain set to 1.5x. The gain parameter set will first set the analog gain parameter inside the photosensitive chip. If the set gain exceeds the maximum built-in analog gain value of the driver, the maximum analog gain of the chip will be set first, and then the remaining gain multiples will be used as numbers. gain to take effect.
Remarks: The digital gain is realized by ISP (image signal processing), not directly adjusting the built-in register of the chip. Under normal circumstances, the default digital gain is close to 1.0, unless there are the following three situations.

  1. Overall gain parameter requirements, that is, when the analog gain cannot meet the set gain parameter requirements, the digital gain will be needed for compensation.
  2. One of the color gains is less than 1 (the color gain is achieved by digital gain), in this case, the final gain is stabilized at 1/min(red_gain, blue_gain), that is, a uniform number is applied gain, and is the gain value for one of the color channels (not the green channel).
  3. AEC/AGC was modified. If there is a change in AEC/AGC, the numerical gain will also change to a certain extent, where does it come from to eliminate any fluctuations, this change will be quickly restored to the "normal" value.

The Raspberry Pi's AEC/AGX algorithm allows the program to specify exposure compensation, which is to adjust the brightness of the image by setting the aperture value, for example:

libcamera-jpeg --ev -0.5 -o darker.jpg
libcamera-jpeg --ev 0 -o normal.jpg
libcamera-jpeg --ev 0.5 -o brighter.jpg

libcamera-still

libcamera-still and libcamera-jpeg are very similar, the difference is that libcamera inherits more functions of raspistill. As before, the user can take a picture with the following command.
Test Command

libcamera-still -o test.jpg

Encoder
libcamea-still supports image files in different formats, can support png and bmp encoding, and also supports saving binary dumps of RGB or YUV pixels as files without encoding or in any image format. If you save RGB or YUV data directly, the program must understand the pixel arrangement of the file when reading such files.

libcamera-still -e png -o test.png
libcamera-still -e bmp -o test.bmp
libcamera-still -e rgb -o test.data
libcamera-still -e yuv420 -o test.data

Note: The format of image saving is controlled by the -e parameter. If the -e parameter is not called, it will be saved in the format of the output file name by default.
Raw Image Capture
The raw image is the image output by the direct image sensor without any ISP or CPU processing. For color camera sensors, the output format of the raw image is generally Bayer. Note that the raw image is different from the bit-encoded RGB and YUV images we said earlier, and RGB and YUV are also ISP-processed images.
Instructions to take a raw image:

libcamera-still -r -o test.jpg

The original image is generally saved in DNG (Adobe Digital Negative) format, which is compatible with most standard programs, such as dcraw or RawTherapee. The original image will be saved as a file of the same name with the .dng suffix, for example, if you run the above command, it will be saved as a test.dng, and generate a jpeg file at the same time. The DNG file contains metadata related to image acquisition, such as white balance data, ISP color matrix, etc. The following is the metadata encoding information displayed by the exiftool:

File Name                       : test.dng
Directory                       : .
File Size                       : 24 MB
File Modification Date/Time     : 2021:08:17 16:36:18+01:00
File Access Date/Time           : 2021:08:17 16:36:18+01:00
File Inode Change Date/Time     : 2021:08:17 16:36:18+01:00
File Permissions                : rw-r--r--
File Type                       : DNG
File Type Extension             : dng
MIME Type                       : image/x-adobe-dng
Exif Byte Order                 : Little-endian (Intel, II)
Make                            : Raspberry Pi
Camera Model Name               : /base/soc/i2c0mux/i2c@1/imx477@1a
Orientation                     : Horizontal (normal)
Software                        : libcamera-still
Subfile Type                    : Full-resolution Image
Image Width                     : 4056
Image Height                    : 3040
Bits Per Sample                 : 16
Compression                     : Uncompressed
Photometric Interpretation      : Color Filter Array
Samples Per Pixel               : 1
Planar Configuration            : Chunky
CFA Repeat Pattern Dim          : 2 2
CFA Pattern 2                   : 2 1 1 0
Black Level Repeat Dim          : 2 2
Black Level                     : 256 256 256 256
White Level                     : 4095
DNG Version                     : 1.1.0.0
DNG Backward Version            : 1.0.0.0
Unique Camera Model             : /base/soc/i2c0mux/i2c@1/imx477@1a
Color Matrix 1                  : 0.8545269369 -0.2382823821 -0.09044229197 -0.1890484985 1.063961506 0.1062747385 -0.01334283455 0.1440163847 0.2593136724
As Shot Neutral                 : 0.4754476844 1 0.413686484
Calibration Illuminant 1        : D65
Strip Offsets                   : 0
Strip Byte Counts               : 0
Exposure Time                   : 1/20
ISO                             : 400
CFA Pattern                     : [Blue, Green][Green, Red]
Image Size                      : 4056x3040
Megapixels                      : 12.3
Shutter Speed                   : 1/20

Long Exposure
If we want to take a super long exposure picture, we need to disable AEC/AGC and white balance, otherwise, these algorithms will cause the picture to wait for a lot of frame data when it converges. Disabling these algorithms requires another explicit value to be set. Additionally, the user can skip the preview process with the --immediate setting.
Here is the instruction to take an image with an exposure of 100 seconds:

libcamera-still -o long_exposure.jpg --shutter 100000000 --gain 1 --awbgains 1,1 --immediate

Remarks: Reference table for the longest exposure time of several official cameras.

Module Maximum exposure time (s)
V1 (OV5647) 6
V2 (IMX219) 11.76
V3 (IMX708) 112
HQ (IMX477) 670

libcamera-vid

libcamera-vid is a video recording demo that uses the Raspberry Pi hardware H.264 encoder by default. After the program runs, a preview window will be displayed on the screen, and the bitstream encoding will be output to the specified file. For example, record a 10s video.

libcamera-vid -t 10000 -o test.h264

If you want to view the video, you can use vlc to play it.

vlc test.h264

Note: The recorded video stream is unpackaged. Users can use --save-pts to set the output timestamp to facilitate the subsequent conversion of the bit stream to other video formats.

libcamera-vid -o test.h264 --save-pts timestamps.txt

If you want to output the mkv file, you can use the following command:

mkvmerge -o test.mkv --timecodes 0:timestamps.txt test.h264

Encoder
Raspberry Pi supports JPEG format and YUV420 without compression and format:

libcamera-vid -t 10000 --codec mjpeg -o test.mjpeg
libcamera-vid -t 10000 --codec yuv420 -o test.data

The --codec option sets the output format, not the output file extension.
Use the --segment parameter to split the output file into segments (unit is ms), which is suitable for JPEG files that need to split the JPEG video stream into separate short (about 1ms) JPEG files.

libcamera-vid -t 10000 --codec mjpeg --segment 1 -o test%05d.jpeg

UDP Video Streaming Transmission
UDP can be used for video streaming, and the Raspberry Pi runs (server):

libcamera-vid -t 0 --inline -o udp://<ip-addr>:<port>

Among them, <ip-addr> needs to be replaced with the actual client IP address or multicast address. On the client (client), enter the following commands to obtain and display the video stream (you can use one of the two commands);

vlc udp://@:<port> :demux=h264
vlc udp://@:<port> :demux=h264

Note: The port needs to be the same as the one you set on the Raspberry Pi.
TCP Video Streaming Transmission
You can use TCP for video streaming, and the Raspberry Pi runs (server):

libcamera-vid -t 0 --inline --listen -o tcp://0.0.0.0:<port>

The client runs:

vlc tcp/h264://<ip-addr-of-server>:<port> #Select one of the two commands
ffplay tcp://<ip-addr-of-server>:<port> -vf "setpts=N/30" -fflags nobuffer -flags low_delay -framedrop

RTSP Video Streaming Transmission
On the Raspberry Pi, vlc is usually used to process the RTSP video stream:

libcamera-vid -t 0 --inline -o - | cvlc stream:///dev/stdin --sout '#rtp{sdp=rtsp://:8554/stream1}' :demux=h264

On the playback side, you can run any of the following commands:

vlc rtsp://<ip-addr-of-server>:8554/stream1
ffplay rtsp://<ip-addr-of-server>:8554/stream1 -vf "setpts=N/30" -fflags nobuffer -flags low_delay -framedrop

In all preview commands, if you want to turn off the preview window on the Raspberry Pi, you can use the parameter -n (--nopreview) to set it. Also, pay attention to the setting of the --inline parameter. Changing the setting will force the header information of the video stream to be included in each I (intra) frame. This setting allows the client to correctly parse the video stream even if the video header is lost.
High Frame Rate Mode
If you use the libcamera-vid command to record high frame rate video (generally higher than 60fps) while reducing frame loss, you need to pay attention to the following points:

  1. The target level of H.264 needs to be set to 4.2, which can be set with the --level 4.2 parameter.
  2. The color noise reduction function must be turned off, you can use the --denoise cdn_off parameter setting.
  3. If the set frame rate is higher than 100fps, close the preview window to release more CPU resources and avoid frame loss. Can be set using the parameter -n.
  4. It is recommended to add the setting force_turbo=1 in the /boot/config.txt file to ensure that the CPU clock will not be limited during the video stream or in the middle.
  5. Adjust the ISP output resolution, use -width 1280 --height 720 to set the resolution, or set it to a lower resolution, depending on the camera model.
  6. If you are using Pi 4 or this higher-performance model, you can add the setting gpu_freq=550 or higher in the /boot/config.txt file to overclock the motherboard GPU to achieve higher performance.

For example, record 1280x720 120fps video.

libcamera-vid --level 4.2 --framerate 120 --width 1280 --height 720 --save-pts timestamp.pts -o video.264 -t 10000 --denoise cdn_off -n

libcamera-raw

Libcamera-raw is similar to a video recording demo. In different places, libcamera-raw records the Bayer format data output by the direct sensor, that is, the original image data. Libcamera-raw doesn't show a preview window. For example, record a 2-second clip of raw data.

libcamera-raw -t 2000 -o test.raw

The demo will directly dump the original frame without format information, the program will directly print the pixel format and image size on the terminal, and the user can view the pixel data according to the output data.
By default, the program will save the original frame as a file, the file is usually large, and the user can divide the file by the --segement parameter.

libcamera-raw -t 2000 --segment 1 -o test%05d.raw

If the memory is large (such as using SSD), libcamera-raw can write the official HQ Camera data (about 18MB per frame) to the hard disk at a speed of about 10 frames per second. To achieve this speed, the demo writes the unformatted raw frames, there is no way to save them as DNG files like libcamera-still does. If you want to ensure that there are no dropped frames, you can use --framerate to reduce the frame rate.

libcamera-raw -t 5000 --width 4056 --height 3040 -o test.raw --framerate 8

Common Command Setting Options

Common command setting options apply to all libcamera commands:

--help, -h

Print program help information, you can print the available setting options for each program command, and then exit.

--version

Print the software version, print the software version of libcamera and libcamera-app, then exit.

--list-cameras

Displays the recognized supported cameras. for example:

Available cameras
-----------------
0 : imx219 [3280x2464] (/base/soc/i2c0mux/i2c@1/imx219@10)
    Modes: 'SRGGB10_CSI2P': 640x480 [206.65 fps - (1000, 752)/1280x960 crop]
                             1640x1232 [41.85 fps - (0, 0)/3280x2464 crop]
                             1920x1080 [47.57 fps - (680, 692)/1920x1080 crop]
                             3280x2464 [21.19 fps - (0, 0)/3280x2464 crop]
           'SRGGB8' : 640x480 [206.65 fps - (1000, 752)/1280x960 crop]
                      1640x1232 [41.85 fps - (0, 0)/3280x2464 crop]
                      1920x1080 [47.57 fps - (680, 692)/1920x1080 crop]
                      3280x2464 [21.19 fps - (0, 0)/3280x2464 crop]
1 : imx477 [4056x3040] (/base/soc/i2c0mux/i2c@1/imx477@1a)
    Modes: 'SRGGB10_CSI2P': 1332x990 [120.05 fps - (696, 528)/2664x1980 crop]
           'SRGGB12_CSI2P': 2028x1080 [50.03 fps - (0, 440)/4056x2160 crop]
                             2028x1520 [40.01 fps - (0, 0)/4056x3040 crop]
                             4056x3040 [10.00 fps - (0, 0)/4056x3040 crop]

According to the printed information, the IMX219 camera has a suffix of 0, and the IM new 477 camera has a suffix of 1. When calling the camera, you can specify the corresponding suffix.

--camera

Specify the camera, and the corresponding suffix can refer to the print information of the command --list-camera.
For example: libcamera-hello -c config.txt
In the setting file, set parameters one line at a time, in the format of key=value:

timeout=99000
verbose=
--config,	-c

Under normal circumstances, we can directly set the camera parameters through commands. Here we use the --config parameter to specify the setting file and directly read the setting parameters in the file to set the camera preview effect.

--timeout, -t

The "-t" option sets the runtime of the libcamera demo. If the video recording command is run, the timeout option sets the recording duration. If the image capture command is run, the timeout sets the preview time before the image is captured and output.
If "timeout" is not set when running the libcamera demo, the default timeout value is 5000 (5 seconds). If the timeout is set to 0, the demo will continue to run.
Example: libcamera-hello -t 0

--preview, -p

"-p" sets the size and position of the preview window (the qualified settings are valid in both X and DRM version windows), and the format is --preview <x. y, w, h> where "x, y" sets the preview window coordinate, "w" and "h" set the width and length of the preview window.
The settings of the preview serial port will not affect the resolution and aspect ratio of the camera image preview. The demo will scale the preview image to display in the preview window and adapt it according to the original image aspect ratio.
Example: libcamera-hello -p 100,100,500,500

--fullscreen, -f

The "-f" option sets the preview window full screen, the preview window, and the border in full-screen mode. Like "-p", it does not affect the resolution and aspect ratio, and will automatically adapt.
Example: libcamera-still -f -o test.jpg

--qt-preview

Using the preview window based on the QT framework, this setting is not recommended under normal circumstances, because the preview demo will not use zero-copy buffer sharing and GPU acceleration, which will occupy more resources. The QT preview window supports X forwarding (the default preview program does not).
The Qt preview serial port does not support the "--fullscreen" setting option. If the user wants to use the Qt preview, it is recommended to keep a small preview window to avoid excessive resource usage and affecting the normal operation of the system.
Example: libcamera-hello --qt-preview

--nopreview, -n

Images are not previewed. This setting will turn off the image preview function.
Example: libcamera-hello -n

--info-text

Set the title and information display of the preview window (only available in the X graphics window) using the format --info-text <string>. When calling this option, multiple parameters can be set, and the parameters are usually called in the % command format. The demo will call the corresponding value in the graphics metadata according to the instructions.
If no window info is specified, the default --info-text is set to "#%frame (%fps fps) exp %exp ag %ag dg %dg"
Example: libcamera-hello --info-test "Focus measure: %focus
Available parameters:

Instructions Instructions
%frame Frame sequence number
%fps Instantaneous frame rate
%exp The shutter speed when capturing the image, in ms
%ag Image analog gain controlled by the sensor chip
%dg Image value gain controlled by ISP
%rg Gain of the red component of each pixel
%bg The gain of the blue component of each pixel
%focus The corner measurement of the image, the larger the value, the clearer the image
%lp Diopter of the current lens (1/distance in meters)
%afstate Autofocus state (idle, scanning, focused, failed)
--width
--height

These two parameters set the width and height of the image, respectively. For libcamera-still, libcamera-jpeg, and libcamera-vid commands, these two parameters can set the resolution of the output image/video.
If the libcamera-raw command is used, these two parameters affect the size of the obtained metadata frame. The camera has a 2 x 2 block reading mode. If the set resolution is smaller than the split mode, the camera will obtain the metadata frame according to the 2 x 2 block size.
libcamera-hello cannot specify the resolution.
Example:
libcamera-vid -o test.h264 --width 1920 --height 1080 Record 1080p video
libcamera-still -r -o test.jpg --width 2028 --height 1520 Takes a 2028 x 1520 JPEG image.

--viewfinder-width
--viewfinder-height

This setting option is also used to set the resolution of the image, the difference is only the image size of the preview. It does not affect the final output image or video resolution. The size of the preview image will not affect the size of the preview window and will be adapted according to the window.
Example: libcamera-hello --viewfinder-width 640 --viewfinder-height 480.

--rawfull

This setting forces the sensor to use the --width and --height settings to output still images and video in full-resolution read mode. This setting libcamera-hello has no effect.
With this setting, the framerate is sacrificed. In full-resolution mode, frame reading will be slower.
Example: libcamera-raw -t 2000 --segment 1 --rawfull -o test%03d.raw The example command captures multiple full-resolution images Metadata frames in rate mode. If you are using an HQ camera. The size of each frame is 18MB, and if --rawfull is not set, the HQ camera defaults to 2 x 2 mode, and the data size of each frame is only 4.5MB.

--mode

This parameter is more general than rawfull. It is used to set the camera mode. When using it, you need to specify the width, height, bit depth, and packing mode, and separate them with colons. The set value does not have to be completely accurate, the system will automatically match the closest value, and the bit depth and packing mode can be set (the default is 12 and P means packing).

  • 4056:3040:12:P - 4056x3040 resolution, 12bit per pixel, packed. Packing means that the original image data will be packed in the buffer. In this case, two pixels will only occupy 3 bytes, which can save memory.
  • 1632:1224:10 - 1632x1224 resolution, 10bit per pixel, packed by default. In 10-bit packing mode, 4-pixel data will occupy 5 bytes.
  • 2592:1944:10:U -2592x1944 resolution, 10 bits per pixel, no packing. In the case of unpacking, each speed limit will occupy 2bytes of memory, in this case, the highest 6 bits will be set to 0.
  • 3262:2448 -3264x2448 resolution, 12bits, and packing mode are used by default. However, if the camera model, such as Camera V2 (IMX219), does not support 12-bit mode, the system will automatically select 10bits mode.
--viewfinder-mode       #Specify sensor mode, given as <width>:<height>:<bit-depth>:<packing>

The --mode parameter is used to set the camera mode when recording video and shooting still images. If you want to set it when previewing, you can use the --viewfinder-mode parameter.

--lores-width
--lores-height

These two options set low-resolution images. The low-resolution data stream compresses the image, causing the aspect ratio of the image to change. When using libcamera-vid to record video, if a low resolution is set, functions such as color denoising will be disabled.
Example: libcamera-hello --lores-width 224 --lores-height 224
Note that low-resolution settings are often used in conjunction with image postprocessing, otherwise it has little effect.

--hflip #Flip the image horizontally
--vflip #Flip the image vertically
--rotation #Flip the image horizontally or vertically according to the given angle <angle>

These three options are used to flip the image. The parameters of --rotation currently only support 0 and 180, which are equivalent to --hflip and --vflip.
Example: libcamera-hello --vflip --hflip

--roi #Crop image <x, y, w, h>

"--roi" allows the user to crop the image area they want according to the coordinates from the complete image provided by the sensor, that is, digital scaling, paying attention to the coordinate value if it is in the valid range. For example --roi 0, 0, 1, 1 is an invalid instruction.
Example: libcamera-hello --roi 0.25,0.25,0.5,0.5
The example command will crop 1/4 of the image from the center of the image.

--hdr Run the camera in HDR mode (supported cameras only)

The hdr parameter is used to set the wide dynamic mode of the camera. This setting will only take effect if the camera supports a wide dynamic range. You can use --list-camera to see if the camera supports hdr mode.

--sharpness #Set the sharpness of the image <number>

Adjust the sharpness of the image by the value of <number>. If set to 0, no sharpening is applied. If you set a value above 1.0, an extra sharpening amount will be used.
Example: libcamera-still -o test.jpg --sharpness 2.0

--contrast #Set image contrast <number>

Example: libcamera-still -o test.jpg --contrast 1.5

--brightness #Set image brightness <number>

The setting range is -1.0 ~ 1.0
Example: libcamera-still -o test.jpg --brightness 0.2

--saturation #Set image color saturation <number>

Example: libcamera-still -o test.jpg --saturation 0.8

--ev #Set EV compensation <number>

Set the EV compensation of the image in aperture units, the setting range is -10 ~ 10, the default value is 0. The program works by improving the target method of the AEC/AGC algorithm.
Example: libcamera-still -o test.jpg --ev 0.3

--shutter #Set the exposure time, the unit is ms <number>

Note: If the frame rate of the camera is too fast, it may not work according to the set shutter time. If this happens, you can try to use --framerate to reduce the frame rate.
Example: libcamera-hello --shutter 30000

--gain #Set gain value (combination of numerical gain and analog gain) <number>
--analoggain #--gain synonym

--analoggain is the same as --gain, the use of analoggain is only for compatibility with raspicam programs.

--metering #Set metering mode <string>

Set the metering mode of the AEC/AGC algorithm, the available parameters are:

  • centre - Center metering (default)
  • spot - spot metering
  • average - average or full frame metering
  • custom - custom metering mode, can be set via tuning file

Example: libcamera-still -o test.jpg --metering spot

--exposure #Set exposure profile <string>

The exposure mode can be set to normal or sport. The report profile for these two modes does not affect the overall exposure of the image, but in the case of sports mode, the program will shorten the exposure time and increase the justice to achieve the same exposure effect.
Example: libcamera-still -o test.jpg --exposure sport

--awb #Set white balance mode <string>

Available white balance modes:

Mode Color Temperature
auto 2500K ~ 8000K
incadescent 2500K ~ 3000K
tungsten 3000K ~3500K
fluorescent 4000K ~ 4700K
indoor 3000K ~ 5000K
daylight 5500K ~ 6500K
cloudy 7000K ~ 8500K
custom Custom range, set via tuning file

Example: libamera-still -o test.jpg --awb tungsten

--awbgains #Set a fixed color gain <number,number>

Set red and blue gain.
Example: libcamera-still -o test.jpg --awbgains 1.5, 2.0

--denoise #Set denoising mode <string>

Supported denoising modes:

  • auto - default mode, use standard spatial denoising, if it is video, it will use fast color noise reduction and use high-quality color noise reduction when taking still pictures. The preview image will not use any color denoising.
  • off - turn off spatial denoising and color denoising.
  • cdn_off - turn off color denoising.
  • cdn_fast - use fast color denoising.
  • cdn_hq - use high-quality color denoising, not suitable for video recording.

Example: libcamera-vid -o test.h264 --denoise cdn_off

--tuning-file #Specify camera tuning file <string>

For more instructions on tuning files, you can refer to official tutorial
Example: libcamera-hello --tuning-file ~/my~camera-tuning.json

--autofocus-mode			Specify the autofocus mode <string>

Set the autofocus mode.

  • default - By default, the camera will use continuous autofocus mode, unless --lens-position or --autofocus-on-capture manual focus is set.
  • manual - manual focus mode, the focus position can be set by --lens-position.
  • auto - focus will only be done once when the camera is turned on, and will not be adjusted in other cases. (If you use the libcamera-still command, only when --autofocus-on-capture is used, it will focus once before taking a photo).
  • continuous - The camera will automatically adjust the focus position according to the scene changes.
--autofocus-range   Specify the autofocus range <string>

Set the autofocus range.

  • normal -- the default item, from nearest to infinity.
  • macro - macro mode, only focus on nearby objects.
  • full - full distance mode, adjusted to infinity for the closest object.
--autofocus-speed   Specify the autofocus speed <string>

Set the focus speed.

  • normal - default item, normal speed.
  • fast - fast focus mode.
--autofocus-window   --autofocus-window

To display the focus window, you need to set x, y, width, height, and the coordinate value setting is based on the ratio of the image. For example --autofocus-window 0.25,0.25,0.5,0.5 would set a window half the size of the image and centered.

--lens-position	    Set the lens to a given position <string>

Set the focus position.

  • 0.0 -- set the focus position to infinity
  • number -- set the focus position to 1/number number is any value you set, for example, if you set 2, it means that it will focus on the position of 0.5m.
  • default -- focus on the default position relative to the hyperfocal distance of the lens.
--output, -o #output file name <string>

Set the filename of the output image or video. In addition to setting the file name, you can also specify the output udp or tcp server address to output the image to the server. If you are interested, you can check the relevant setting instructions of the subsequent tcp and udp.
Example: libcamera-vid -t 100000 -o test.h264

--wrap #Wrap the output file counter <number>

Example: libcamera-vid -t 0 --codec mjpeg --segment 1 --wrap 100 -o image%d.jpg

--flush # Flush the output file immediately

--flush will immediately update each frame of the image to the hard disk at the same time as it is written, reducing latency.
Example: libcamera-vid -t 10000 --flush -o test.h264

Still Photo Shooting Setting Parameters

--quality, -q            #Set JPEG image quality <0 ~ 100>
--exif, -x               #Add extra EXIF flags
--timelapse              #Time interval of time-lapse photography, the unit is ms
--framestart             #Start value of frame count
--datetime               #Name output file with date format
--timestamp              #Name the output file with the system timestamp
-- restart               #Set the JPEG restart interval
--keypress, -k           #Set the enter button photo mode
--signal, -s             #Set the signal to trigger the photo
--thumb                  #Set thumbnail parameters <w:h:q>
--ebcoding, -e           #Set the image encoding type. jpg/png/bmp/rgb/yuv420
--raw, -r                #Save raw image
--latest                 #Associate symbols to the latest saved file
--autofocus-on-capture   #Set to do a focus action before taking a photo

Video Recording Image Setting Parameters

--quality, -q   #Set JPEG commands <0 - 100>
--bitrate, -b   #Set H.264 bitrate
--intra, -g     #Set the internal frame period (only supports H.264)
--profile       #Set H.264 configuration
--level         #Set H.264 level
--codec         #Set encoding type h264 / mjpeg / yuv420
--keypress, -k  #Set carriage return to pause and record
--signal, -s    #Set signal pause and record
--initial       #Start the program in the recording or paused state
--split         #Split video and save to another file
--segment       #Split video into multiple video segments
--circular      #Write video to the circular buffer
--inline        #Write header in each I frame (H.264 only)
--listen        #Wait for a TCP connection
--frames        #Set the number of frames recorded

Introduction

If you are using the Buster version of the image, the system is installed with the Raspicam driver by default, so you can turn on the camera directly and use it.
If you are using the latest Bullseye system, you need to install and configure it separately.
Applicable to OV5647, official IMX219, official IMX477.

Install Raspicam (Optional)

If you use the Bullseye image (the newest image), you need to install the Raspicam for using the legacy stack.
Note: This driver does not support the 64-bit Raspberry Pi system for now.

Open a terminal and run the following commands.

sudo apt-get update
cd
sudo apt install cmake
git clone https://github.com/raspberrypi/userland
cd userland
./buildme
cp build/bin/* ~/bin/
sudo reboot

Call the Camera

raspistill

raspistill is for taking still pictures. For example: raspistill -o cam.jpg

raspivid

raspivid is for recording video. For example: raspivid -o vid.h264

raspiyuv

The commands of raspiyuv and raspisitll have the same function. The difference is that instead of outputting standard image files such as jpgs, raspiyuv generates YUV420 or RGB888 image files from the camera's ISP output.
For the most part, it is better to shoot images and use raspistill, but if you want to use uncompressed black-and-white images, you can choose to use the raspiyuv command.
For example: raspiyuv -o cam.jpg

Command Setting Options

The raspicam command can be used with setting options to adjust the final image effect. The following is a list of the available setup options for reference.

--preview, -p  #Set the preview window<x, y, w, h>

The user can set the x, and y values to set the position of the preview window and the w, and h values to adjust the resolution of the preview image.

--fullscreen, -f  #Full screen preview window

Display the preview window in full screen.

--nopreview, -n  #No preview window displayed

Close the preview window and the command will output the image or video directly to the file.

--opacity, -op  #Set the preview window transparency

Set the transparency of the preview window, 0 is invisible, and 255 is fully transparent.

--sharpness, -sh  #Set image sharpness (-100 - 100)

The default sharpening value is 0.

--contrast. -co  #Setting Image Contrast(-100 - 100)

The default contrast is 0.

--brightness, -br  #Set Image Contrast(0 - 100)

The default brightness is 50, 0 is all black and 100 is all white.

--saturation, -sa  #Set image saturation (-100 - 100)

The default saturation is 0.

--ISO  #Setting Shutter Sensitivity (100 - 800)

Setting the sensitivity when taking pictures.

--vstab, -vs  #Enable video stabilization

Only the video recording mode is valid, with video stabilization turned on.

--ev  #Set EV compensation

Set the EV compensation value of the image, and the default is 0.

--exposure,  -ex  #Setting the exposure mode

Exposure options:

  • auto: Auto Exposure Mode
  • night: Night shooting mode
  • nightpreview
  • backlight: Backlight mode
  • spotlight
  • sports: Sports mode (the shutter time is shortened in sports mode)
  • snow: Snow mode
  • beach: Beach Mode
  • verylong: Long exposure mode
  • fixedfps: Fixed fps
  • antishake: Anti-shake mode
  • fireworks: Fireworks Mode

Note: Depending on the camera model, some modes are not available.

--flicker, -fli   #Flicker Avoidance

Configurable mode:

  • off: Turn off anti-flicker mode
  • auto: Automatic detection of injection frequency
  • 50Hz: Set the anti-flicker frequency to 50 Hz
  • 60Hz: Set the anti-flicker frequency to 60Hz
--awb,  #Set auto white balance mode
  • off: Turn off auto white balance
  • auto: Auto white balance mode (default)
  • sun: Sunny mode (5000K ~ 6500K)
  • cloud: Cloudy mode (6500K ~ 12000K)
  • shade: Shade mode
  • tungsten: Tungsten lamp mode(2500K ~ 3500K)
  • incandescent: Incandescent mode (2500K ~ 4500K)
  • flash: Flash mode
  • horizon: Horizon mode
  • greyworld: If you are using a camera without an IR filter (e.g. NoIR), you can fix the white balance imbalance caused by the lack of an IR filter.

Note: Depending on the camera model, some modes are not available.

--imfx, -ifx  #Set the image filter effect

Configurable filter effect:

  • none: No effect (default)
  • negative: Color Flip
  • solarise: Sunlight effect
  • posterise: Poster effect
  • whiteboard: Whiteboard effect
  • backboard: Blackboard effect
  • sketch: Sketch effect
  • denoise: Denoise effect
  • emboss: amboss effect
  • oilpaint: Oil paint effect
  • hatch: Hatch effect
  • gpen: Pencil sketch effect
  • pastel: Colored pencils effect
  • watercolour: Watercolor effect
  • film: Film effect
  • blur: Blur effect
  • saturation: Saturation effect

Note: Depending on the camera model, some modes are not available.

--colfx, -cfx  #Set the color effect<U:V>

The U and V parameters are set in the range of 0 ~ 255 and are used to adjust the values of the U and Y channels. For example --colfx 128:128 will set the image to a monochrome image.

--metering, -mm  #Setting the metering mode

Configurable mode:

  • average: Average or full-frame metering
  • spot: Spot metering
  • backlit: Preset a backlit image
  • matrix: Matrix metering
--rotation, -rot  #Set image rotation (0 - 359)

The image rotation angle can be set by the angle parameter.

--hflip, -hf  #Set image horizontal flip

Set image horizontal flip.

--vflip, -vf  #Set image vertical flip

Set image vertical flip.

--roi, #Crop image <x, y, w, h>

Crop the image according to the parameters, note that the parameters are planned in (0,0 ~ 1.0), for example, if you want to crop 1/4 of the image, you can use the command -roi 0.5,0.5,0.25,0.25

--shutter, --ss  Set shutter speed/time

Set the shutter time (unit:ms). The maximum shutter time that can be set varies depending on the light-sensitive chip.

Mode Maximum number(ms)
V1 (OV5647) 6000000 (6s)
V2 (IMX219) 10000000 (10s)
HQ (IMX477 200000000 (200s)
--drc, -drc  #Enable/disable dynamic range compression
  • off (Default)
  • low
  • med
  • high
--stats, -st  #Counting images by still image frames
--awbgains, -awbg

Set blue and green gain, effective when --awb off is set.

--analoggain, -ag

Set the analog gain value.

--digitalgain, -dg

Set the digital gain value.

--mode, -md

Set the sensor mode:

  • OV5647
Mode Resolution Aspect Ratio Frame Rate FoV
0 Auto-select
1 1920 x 1080 16:9 1-30fps Local
2 2592 x 1944 4:3 1-15fps Full Frame
3 2592 x 1944 4:3 0.1666 - 1fps Full Frame
4 1296 x 972 4:3 1 - 42fps Full Frame
5 1296 x 730 16:9 1- 49fps Full Frame
6 640 x 480 4:3 42.1 - 60fps Full Frame
7 640 x 480 4:3 60.1 - 90fps Full Frame
  • IMX219
Mode Resolution Aspect Ratio Frame Rate FoV
0 Auto-select
1 1920 x 1080 16:9 0.1-30fps Local
2 3280 x 2464 4:3 0. 1-15fps Full Frame
3 3280 x 2464 4:3 0.1 - 15fps Full Frame
4 1640 x 972 4:3 1 - 42fps Full Frame
5 1296 x 730 16:9 1- 49fps Full Frame
6 640 x 480 4:3 42.1 - 60fps Full Frame
7 640 x 480 4:3 60.1 - 90fps Full Frame
  • HQ Camera
Mode Resolution Aspect Ratio Frame Rate FoV
0 Auto-select
1 2028 x 1080 169:90 0.1-50fps Local
2 2028 x 1080 4:3 0. 1-50fps Full Frame
3 4056 x 3040 4:3 0.005 - 10fps Full Frame
4 1332 x 990 74:55 50.1-120 fps Local
--camselect, -cs

When the system is connected to multiple cameras, select camera, 0 or 1.

--annotate, -a #Enable/Set Comments

The parameters are represented in the metadata by means of bit masks, which can be expressed directly in additive terms. For example, 12 can represent the display time (4) and the display date (8), by adding 4+8 = 12.
Configurable options:

Value Parameters
-a 4 Time
-a 8 Date
-a 12 Time and date, actually 4 + 8
-a 16 Shutter setting
-a 32 CAF setting
-a 64 Gain setting
-a 128 Lens settings
-a 256 Animation Settings
-a 512 Frame Rate
-a 1024 Black background
-a "ABC %Y-%m-%d %X" Display text
-a 4 -a "ABC %Y-%m-%d %X" Display time/date in custom format
-a 8 -a "ABC %Y-%m-%d %X" Display time/date in custom format
--annotateex, -ae  #Set additional annotation parameters
--stereo, -3d

Set the binocular mode.

  • sbs - Side-by-side mode
  • tb: -Vertical mode
  • off -Turn off binocular mode (default)
--decimate, -dec

Halving the width and height of binocular images.

--setting, -set

Output the current camera settings.

raspistill Parameters

--width, -w  #Set image width
--height, -h  #Set image height
--quality, 0q  #Set JPEG quality <0 ~ 100>
--raw, -r  #Add the original Bayer data to the JPEG metadata
--output, -o #output file <filename>
--latest, -l  #Associating the last image frame to the file <filename>
--verbose, -v #Print Details
--timeout, -t  #Set program preview time
--timelapse, -tl  #Set up demo photography
--framestart, -fs #Save the number of the first frame
--datetime, -dt  #Naming files with date and time
--timestamp, -ts #Naming files with timestamps
--thumb, -th #Set thumbnail parameter <x:y:qulity>, default is (64:48:35)
--demo, -d  #Run demo mode <ms>
--encoding, -e #Encode in the specified format, jpg, bmp or png
--restart, -rs  #Set JPEG restart flag
--exif, -x   #Setting EXIF tags
--gpsdexif, -gps #Set real-time exif time (requires GPS Dongle access)
--fullpreview,  -fg  #Full Screen Preview
--keypress, -k  #Push button photo mode
--signal, -s  # Signal mode
--burst, -bm #Capture mode

raspivid Parameters

--width, -w #Set the video width
--height, -h #Sets the height of the video
--bitrate, -b #Sets the bitrate
--output, -o #Set output file name <filename>
--listen, -l #When using a network connection, wait for a network connection
--versbose, -v #Print details
--timeout, -t #Sets the preview time
--demo, -d #Run demo <ms>
--framerate, -fs #set frame rate
--penc, -e #Show encoded preview image
--intra, -g #Set internal refresh period
--qp, -qp #Set quantization parameters
--profile, -pf #Specify H264 profile, baseline / main / high
--level, -lev #Sets the H264 encoding level
--irefresh, -if #set H264 internal refresh type cyclic / adaptive / both / cyclicrows
--inline, -ih #insert PPS, SPS header
--spstimings, -stm #insert timing information into the SPS block
--timed, -td #Timed toggle recording and pause functions
--keypress, -k #Pause recording by keystroke
--signal, -s #Switch between pause and record according to SIGUSR1
--split, -sp #In signal and keypress mode, the file will be recreated each time you re-record
--vectors, -x #Vector output
--flush, -fl # Force a flush of the output data buffer immediately after writing video data, bypassing any OS caching of the written data and reducing latency.
--save-pts, -pts #Save timestamp information to the specified file.
--codec, -cd # Specify encoder H264 / MJPEG
--initial, -i # Set the initial state for startup
--segment, -sg # Split the video stream into multiple files
--wrap, -wr # Set the maximum value for splitting
--start, -sn #Sets the initial split encoding
--raw, -r #Sets the metadata filename
--raw-format, -rf #Specify metadata format yuv / rgb / grey

Introduction

If you are using the Buster version of the image, the Raspicam driver is installed by default in the system, you can directly turn on the camera and use it.
If you are using the latest Bullseye system, you need to install and configure it separately.

Install Raspicam (optional)

Open the Raspberry Pi terminal, and enter the following command to install the driver. Note: This driver cannot support a 64-bit Raspberry Pi system temporarily.

sudo apt-get update
cd
sudo apt install cmake
git clone https://github.com/raspberrypi/userland
cd userland
./buildme
cp build/bin/* ~/bin/

After following the need to restart the system.

sudo reboot

Call camera

raspistill

The raspistill command is used to take still pictures. Example: raspistill -o cam.jpg

raspivid

The raspivid command is used to record video. Example: raspivid -o vid.h264

raspiyuv

The raspiyuv command has the same function as raspisitll, the difference is that raspiyuv is not Su Chu. jpgs and other standard image files, but generate YUV420 or RGB888 image files from the camera's ISP output.
In most cases, it is better to use raspistill to capture images, but if you want to use uncompressed black and white images, you can choose to use the raspiyuv command. Example: raspiyuv -o cam.jpg

Instruction Setting Options

When the raspicam command is used, the final imaging effect can be adjusted by setting options. The available setting options are listed below for reference.

--preview, -p #Set the preview window <x, y, w, h>

The user can set the position of the preview window by setting the values ​​of x and y, and adjust the resolution of the preview image by setting the values ​​of w and h.

--fullscreen, -f #Fullscreen preview window

Display the preview window in full screen.

--nopreview, -n #Do not display the preview window

Close the preview window and the command will output the image or video directly to a file.

--opacity, -op #Set the transparency of the preview window

Set the transparency of the preview window, 0 is invisible, and 255 is fully transparent.

--sharpness, -sh #Set image sharpness (-100 - 100)

The default sharpening value is 0.

--contrast. -co #Set image contrast (-100 - 100)

The default contrast is 0.

--brightness, -br #Set image contrast (0 - 100)

The default brightness is 50, 0 is fully black, and 100 is full white.

--saturation, -sa #Set image saturation (-100 - 100)

The default saturation is 0.

--ISO #Set shutter sensitivity (100 - 800)

Set sensitivity when taking pictures.

--vstab, -vs #Enable video stabilization

Only the video recording mode is valid, and video stabilization is enabled.

--ev #Set EV compensation

Set the EV compensation value of the image to default 0.

--exposure, -ex #Set exposure mode

Settable exposure options:

  • auto: automatic exposure mode
  • night: night shooting mode
  • nightpreview
  • backlight: backlight mode
  • spotlight
  • sports: sports mode (the shutter time will be shortened in sports mode)
  • snow: snow mode
  • beach: beach mode
  • verylong: long exposure mode
  • fixedfps: fixed fps
  • antishake: anti-shake mode
  • fireworks: fireworks mode

Note: Depending on the camera model, some modes are not available.

--flicker, -fli #Flicker avoidance

Modes that can be set:

  • off: turn off anti-flicker mode
  • auto: auto-detect betting frequency
  • 50Hz: set the anti-flicker frequency to 50Hz
  • 60Hz: set the anti-flicker frequency to 60Hz
--awb, #Set auto white balance mode
  • off: disable auto white balance
  • auto: Auto white balance mode (default)
  • sun: sunny mode (5000K ~ 6500K)
  • cloud: cloudy mode (6500K ~ 12000K)
  • shade: shadow mode
  • tungsten: Tungsten mode (2500K ~ 3500K)
  • incadescent: Incadescent mode (2500K ~ 4500K)
  • flash: flash mode
  • horizon: horizon mode
  • greyworld: If you are using a camera without an IR filter (eg NoIR), you can fix the white balance misalignment caused by the lack of an IR filter

Note: Depending on the camera model, some modes are not available.

--imfx, -ifx #Set image filter effect

Configurable image filter effects:

  • none: no effect (default)
  • negative: color flip
  • solarise: sunlight effect
  • posterise: poster effect
  • whiteboard: whiteboard effect
  • backboard: blackboard effect
  • sketch: sketch
  • denoise: denoise
  • emboss: emboss
  • oilpaint: oil painting
  • hatch: texture
  • gpen: pencil sketch
  • pastel: colored pencils
  • watercolour: watercolor
  • film: film
  • blur: blur
  • saturation: saturation

Note: Depending on the camera model, some modes are not available.

--colfx, -cfx #Set color effect <U:V>

The setting range of the U and V parameters is 0 ~ 255, which are used to adjust the values ​​of the U and Y channels. For example --colfx 128:128 will set the image to monochrome.

--metering, -mm #Set metering mode

Settable options:

  • Average: average or full frame metering
  • spot: spot metering
  • backlit: preset a backlit image
  • matrix: matrix metering
--rotation, -rot #Set image rotation (0 - 359)

The image rotation angle can be set by the angle parameter.

--hflip, -hf #Set the image to flip horizontally

Set the image to be flipped horizontally.

--vflip, -vf #Set the image to flip vertically

Flip the image vertically.

--roi, #Crop image <x, y, w, h>

Crop the image according to the parameters, note that the parameters are all planned in (0,0 ~ 1.0), for example, if you want to crop 1/4 of the image, you can use the command - roi 0.5,0.5,0.25,0.25.

--shutter, --ss set shutter speed/time

Set the shutter time (unit: ms). Shutter time The maximum shutter time that can be set is different depending on the photosensitive chip.

Model Max Digit (ms)
V1 (OV5647) 6000000 (6s)
V2 (IMX219) 10000000 (10s)
HQ (IMX477 200000000 (200s)
--drc, -drc #Enable/disable dynamic range compression
  • off (default)
  • low
  • med
  • high
--stats, -st #Statistics images by static image frames
--awbgains, -awbg

Set blue and green gain, which takes effect if --awb off is set.

--analoggain, -ag

Set the analog gain value

--digitalgain, -dg

Set digital gain value

--mode, -md

Set sensor mode:

  • OV5647
Mode Resolution Aspect Ratio Frame Rate FoV
0 Automatic selection
1 1920 x 1080 16:9 1-30fps Partial
2 2592 x 1944 4:3 1-15fps Full Frame
3 2592 x 1944 4:3 0.1666 - 1fps Full Frame
4 1296 x 972 4:3 1 - 42fps Full Frame
5 1296 x 730 16:9 1- 49fps Full Frame
6 640 x 480 4:3 42.1 - 60fps Full Frame
7 640 x 480 4:3 60.1 - 90fps Full Frame
  • IMX219
Mode Resolution Aspect Ratio Frame Rate FoV
0 Automatic selection
1 1920 x 1080 16:9 0.1-30fps Partial
2 3280 x 2464 4:3 0.1-15fps Full Frame
3 3280 x 2464 4:3 0.1 - 15fps Full Frame
4 1640 x 972 4:3 1 - 42fps Full Frame
5 1296 x 730 16:9 1- 49fps Full Frame
6 640 x 480 4:3 42.1 - 60fps Full Frame
7 640 x 480 4:3 60.1 - 90fps Full Frame
  • HQ Camera
Mode Resolution Aspect Ratio Frame Rate FoV
0 Automatic selection
1 2028 x 1080 169:90 0.1-50fps Partial
2 2028 x 1080 4:3 0.1-50fps Full Frame
3 4056 x 3040 4:3 0.005 - 10fps Full Frame
4 1332 x 990 74:55 50.1-120 fps Partial
--camselect, -cs

When multiple cameras are connected to the system, select camera, 0 or 1.

--annotate, -a #enable/set annotations

The parameters are represented by bit masks in the metadata, which can be directly represented by addition. For example, 12 can represent the display time (4) and the display date (8), which is represented by the addition of 4+8 =12.
Configurable options

Value Parameter description
-a 4 Time
-a 8 Date
-a 12 Time and date, actually 4 + 8
-a 16 Shutter setting
-a 32 CAF settings
-a 64 Gain setting
-a 128 Lens settings
-a 256 Animation settings
-a 512 Number of frames
-a 1024 Black background
-a "ABC %Y-%m-%d %X" Display text
-a 4 -a "ABC %Y-%m-%d %X" Display time/date in custom format
-a 8 -a "ABC %Y-%m-%d %X" Display time/date in custom format
--annotateex, -ae #Set additional annotation parameters
--stereo, -3d

Set the binocular mode.

  • sbs - side-by-side mode
  • tb: - Portrait mode
  • off - turn off binocular mode (default)
--decimate, -dec

Halve the width and height of the binocular image.

--setting, -set

Output current camera settings.

raspistill setting parameters

--width, -w         #Set image width
--height, -h        #Set image height
--quality, 0q       #Set JPEG quality <0 ~ 100>
--raw, -r           #Add raw Bayer data to JPEG metadata
--output, -o        #Output file <filename>
--latest, -l        #Associate the last frame image to the file <filename>
--verbose, -v       #Print details
--timeout, -t       #Set the program preview time
--timelapse, -tl    #Set up demo photography
--framestart, -fs   #Save the number of the first frame
--datetime, -dt     #Name the file with DateTime
--timestamp, -ts    #Name files with timestamps
--thumb, -th        #Set thumbnail parameters <x:y:quility>, the default is (64:48:35)
--demo, -d          #Run demo mode <ms"
--encoding, -e      #Encode according to the specified format, jpg, BMP, or png
--restart, -rs      #Set JPEG restart flag
--exif, -x          #Set EXIF ​​flag
--gpsdexif, -gps    #Set real-time Exif time (requires GPS Dongle access)
--fullpreview, -fg  #Fullscreen preview
--keypress, -k      #Keypress camera mode
--signal, -s        #Signal mode
--burst, -bm        #Snapshot mode

raspivid setting parameters

--width, -w         #Set the video width
--height, -h        #Set the video height
--bitrate, -b       #Set bitrate
--output, -o        #Set the output filename <filename>
--listen, -l        #When using a network connection, wait for a network connection
--versbose, -v      #Print details
--timeout, -t       #Set preview time
--demo, -d          #Run demo <ms>
--framerate, -fs    #Set frame rate
--penc, -e          #Display the encoded preview image
--intra, -g         #Set the internal refresh cycle
--qp, -qp           #Set quantization parameters
--profile, -pf      #Specify H264 profile, baseline/main/high
--level, -lev       #Set H264 encoding level
--irefresh, -if     #Set H264 internal refresh type cyclic/adaptive/both/cyclicrows
--inline, -ih       #Insert PPS, SPS header
--spstimings, -stm  #Insert timing information into SPS blocks
--timed, -td        #Timed switch recording and pause function
--keypress, -k      #Keypress to pause recording
--signal, -s        #Switch pause and record state according to SIGUSR1
--split, -sp        #In signal and keypress mode, the file will be recreated every time you re-record
--vectors, -x       #Vector output
--flush, -fl        #Force the output data buffer to be flushed immediately after writing video data, bypassing any OS cache for written data and reducing latency.
--save-pts, -pts    #Save timestamp information to the specified file.
--codec, -cd        #Specify encoder H264 / MJPEG
--initial, -i       #Set the initial state of startup
--segment, -sg      #Split video stream into multiple files
--wrap, -wr         #Set the maximum value of the split
--start, -sn        #Set the initial split encoding
--raw, -r           #Set metadata file name
--raw-format, -rf   #Specify metadata format yuv/rgb/grey

USB

Test USB Camera

  • Open the Raspberry Pi terminal (Ctrl+Alt+T).
  • Edit modules file.
sudo nano /etc/modules
  • Add the following statement to the file and save it.
 bcm2835-v4l2
  • Open the Raspberry Pi terminal, and enter the command to install luvcview software.
sudo apt install luvcview -y
  • After the installation is completed, the terminal can enter the command to open the software to test the USB camera.
sudo luvcview -s 1920x1080

Raspberry Pi Documentation90.png

fswebcam

Installation

  • Open the Raspberry Pi terminal and enter the command to install the fswebcam software
sudo apt install fswebcam

Usage

  • Enter the command fswebcam followed by the file name, the photo will be taken with the USB camera and saved to the specified file name:
fswebcam image.jpg
  • This command will display the following information:
--- Opening /dev/video0...
Trying source module v4l2...
/dev/video0 opened.
No input was specified, using the first.
Adjusting resolution from 384x288 to 640x480.
--- Capturing frame...
Captured frame in 0.00 seconds.
--- Processing captured image...
Writing JPEG image to 'image.jpg'.
  • Set the resolution for the image:
fswebcam -r 1280x720 image2.jpg
  • Take photos at full resolution, without banners:
fswebcam -r 1280x720 --no-banner image3.jpg

MJPG-streamer

  • Plug in the USB camera, check if the device is found, and enter the command:
lsusb

LsusbWatermark.png

  • The USB 2.0 Camera is the camera, indicating that the USB device has been found.
  • Check whether the device driver is normal: enter the command:
ls /dev/video*

Lsvideo0watermark.png

  • where video0 is the camera driver.
  • To install the necessary libraries, enter the following commands:
sudo apt install subversion -y
sudo apt install libv4l-dev -y
sudo apt install libjpeg9-dev -y
sudo apt install cmake -y
  • Download mjpeg-stream to Raspberry Pi:
sudo git clone https://github.com/jacksonliam/mjpg-streamer.git
cd mjpg-streamer/mjpg-streamer-experimental
sudo make all
sudo make install
  • Run start.sh:
cd mjpg-streamer/mjpg-streamer-experimental/
 sudo bash start.sh 
  • Use the Firefox browser to enter http://<Raspberry Pi IP address>:8080, for example, my Raspberry Pi address is 192.168.10.20:
http://192.168.10.20:8080 

FirefoxWatermark.png

  • At this point, you should be able to see the monitoring screen of the camera.

Resource