Raspberry pi programing example

Learn How to Program on the Raspberry Pi – Part 1: Introduction

Many (absolute) beginners get a Raspberry Pi as a gift, but have often little or no programming knowledge. Therefore I would like to clear that hurdle in this series of tutorials and encourage learning to program with the Raspberry Pi. The big advantage is that we can also write a hardware-related code, which allows us to use the Raspberry Pi’s GPIO pins.

We use Python as the programming language, since it is one of the easiest languages to learn for beginners and there are also usually the most references and examples available.

Required Hardware Parts

A note in advance: The tutorial series is intended to make it easier to get started with programming on the Raspberry Pi, but should not be taken as an independent course. A book is very useful for deepening your knowledge and looking things up. In particular, I can recommend one of these two books for learning:

  • pure Python basics: Python Crash Course (Eric Matthes )
  • Programming the Raspberry Pi: Getting Started with Python (Simon Monk)

Hardware

To get started, we need the following hardware parts:

  • Raspberry Pi (the model doesn’t matter – I don’t recommend Model Zero)
  • micro SD card (min. 8 GB)
  • Keyboard
  • Mouse
  • HDMI cable
  • USB power adapter + micro USB cable
  • WLAN adapter if necessary

Preparation

Before we start programming, we need to take a few steps to set up the environment. First of all, it is necessary that the Raspberry Pi gets an operating system. The Raspberry Pi Foundation provides the so-called Raspbian OS, which we need to download. Then we transfer the included file to the micro SD card. You can find detailed instructions here:

After the image is on the SD card, we insert it into the Raspberry Pi. As soon as the keyboard, mouse and display are connected via HDMI cable, we can start it. This is done simply by connecting the micro USB cable and connecting it to power. The display should now light up and a few lines of code should appear on a black background.

Shortly after, the startup process is complete and we see the desktop:

We now open the Python console, in which we can immediately enter program code. Open this by firstly clicking the Raspberry Pi symbol in the top left and then under Programming on “mu”. If you don’t see this option, you can either install it (Preferences -> Recommended Software) or also use the Thonny Python IDE.

First, you are asked for the Editor Mode. Select Python 3.

The Python console now opens and it looks like this. We will write our code in this:

Click on “REPL” on the Top bar, so that we can see our output immediately.

If you are wondering why we took Python 3 and whether you can use Python 2, the answer is that both are possible. There are a few differences between those two versions, but they do not matter to get started. The code we write is executable on both versions.
If you are interested in the differences in detail, you can read this article.

Hello World Plus

Enough words, we’re starting! In the console we want to start with a typical “Hello World” application. All you need to do is type in the following line and send it with Enter:

With that we get our first output:

Print is the function that we call here. Within the brackets, we give parameters which the function needs. Since it is a character string, we have to put also the quotation marks at the beginning and end, since other words are interpreted as variables, which we will come to in a moment.

Now it is quite boring to just print out a sentence. Therefore, we now create a so-called variable. This is sort of a placeholder that can take on different values ​​and can be addressed via its name. Would you like an example? Here:

The advantage of variables is that we can easily overwrite their value. In the next example we create two variables and add the first to the second (and save the result in the second variable – so we overwrite it):

But be careful: In addition to (integer) numbers, variables can also e.g. contain strings. An addition is not possible here and would lead to an error.

By the way: The variable can be named as you wish, but must not begin with a number. Also, no special characters (apart from the underscore) may be used. There are also no two variables that can have the same name.

Comments

Another useful feature is comments that explain the code in case someone else or you look at the code again later. Such comments are available in every programming language and can also be used to “mute” parts of the code so that they are not executed. That process is called commenting out.

In Python, comments begin with a hashtag (#). The rest of the line is then no longer executed. Here’s an example:

As you can see, only line 1 and line 3 are output because we commented out the middle command.

First Queries

As already said, variables can have different values. So that we can query them again, there is also a possibility for this. We can do this with if .. else . Here is an example:

There is a lot to consider here:

  1. At the end of the if , elif or else line there must be a colon because we are saying that the condition has ended. We can also link several conditions.
  2. For queries, the following options exist == (equality), (smaller), > (larger), (smaller/equal), >= (larger/equal). When checking for equality, the simple equal sign must not be used, since this only assigns variables.
  3. The commands that are executed if the condition is true must be indented with spaces. Everything must be on the same level or indented equally. The default is 4 spaces to indent.

I will now show an extended example so that the syntax is a bit easier to understand (fictitious person with a date of birth on July 30, 1980):

As you can see, it is very easy to nest queries. It is only important that you always keep an eye on the indentations, otherwise, you will get an error (or the program will be executed incorrectly).

Loops

Now we go one step further and look at so-called loops. Basically, these represent simple repetitions, whereby after each repetition (also called iteration) it is checked whether the specified condition is (still) true.

The two types of loops are called ForLoop and WhileLoop. The while loop initially checks whether the query is true. Here’s an example:

In each repetition, it is initially checked whether x is less than 5 and if so, the indented part is executed. We output the number once and then add 1 to x. The numbers 0 to 4 are thus output.

In contrast, the structure of the for loop is a little different. In Python, its definition is for .. in .. : where the first parameter is a variable (which is available within the loop) and the second parameter is e.g. a list. We have the following options for outputting the numbers from 0 to 4:

As you can see, a for loop is better for easy counting.

Outsourcing the Code in Files

As a final step of this tutorial, I want to show you how to write the code into a file and execute it. Since you usually write whole blocks of code, you also want to have them executed sequentially. The so-called compiler, which translates the readable (human-understandable) code into machine code, can execute individual commands or entire files.

Click on the folder symbol in the navigation bar and right-click on the free space. Under “Create New”> “Empty File” you can create a new file:

Name them e.g. “program1.py” (without quotes). Don’t forget the “.py” extension, so it is clear that it is a Python script.

You can open the created file with a double click. Here you can write your code and save it via the menu. I pasted the code from above:

After saving, we can already start the file. This happens via the terminal/console. To do this, click the icon to the right of the folder in the taskbar. A black window opens in which you can enter something.

Here you write the following (send with Enter):

The program will now run from start to finish. All queries are executed until the program has reached the end where there are no further commands. Then it terminates.

This was it with the first part of my little overview to get started with programming with the Raspberry Pi. In the next part, we will focus on reading and writing the GPIO pins, which we can use to control electronic components such as LEDs and read buttons.

PS: No Python code can be seen in the entry picture since it should only be a symbol picture 🙂

PPS: Comments/suggestions (especially from beginners) are welcome so that I can adapt the other parts accordingly.

Источник

Программирование Raspberry Pi Pico с помощью C/C ++ SDK

Сегодня существует множество встраиваемых платформ с разной производительностью. Многие устройства имеют одинаковые функциональные возможности. Таким образом, разработчика, привыкшего к разноообразию аппаратных платформ, очень сложно удивить чем-то действительно новым.

Чем же может нас удивить новая плата Raspberry Pi Pico на базе собственного чипа RP2040?

Raspberry Pi Pico — это не такая высокопроизводительная платформа, как другие платы Raspberry Pi, но намного дешевле их. Производительность Pico можно сравнить с Arduino Due или ESP32.

Это действительно очень интересное устройство, основанное на двух ядрах Cortex M0 + с уникальным модулем PIO, который работает как контакты FPGA и может быть запрограммирован на языке Assembler (я бы сказал упрощенный Assembler).

Поддержка Raspberry Pi Pico впечатляет. Можно использовать разные языки программирования, такие как Assembler, C, C ++ и Python, для программирования Raspberry Pi Pico.

Raspberry Pi Pico также можно запрограммировать в среде Arduino IDE.

Чип RP2040 и плата Raspberry Pi Pico хорошо документированы, документация содержит дейташиты для микроконтроллера и платы, руководство по разработке своего железа на основе RP2040, руководство для быстрого начала работы с платой Raspberry Pi Pico.

Raspberry Pi Foundation предоставляет два SDK для разработки приложений на Python и C / C ++.

Начнем с основных характеристик платы:

  • Микроконтроллер RP2040, разработанный Raspberry Pi в Великобритании
  • Двухъядерный процессор Arm Cortex M0 + с тактовой частотой до 133 МГц
  • 264 КБ SRAM и 2 МБ встроенной флэш-памяти
  • Благодаря контактам по периметру модуля Pico его можно запаять на несущую плату
  • USB 1.1 с поддержкой профилей устройства и хоста
  • Режимы сна и ожидания с низким энергопотреблением
  • Программирование методом копирования файла прошивки на внешнее запоминающее устройство через USB
  • 26 × многофункциональных контактов GPIO
  • 2 × SPI, 2 × I2C, 2 × UART, 3 × 12-битных АЦП, 16 × управляемых каналов ШИМ
  • Точные часы и таймер на кристалле
  • Датчик температуры
  • Библиотеки для выполнения операций с плавающей запятой
  • 8 конечных автоматов программируемого ввода-вывода (PIO) для поддержки настраиваемых периферийных устройств

Техническая спецификация Raspberry Pi Pico доступна по ссылке https://datasheets.raspberrypi.org/pico/pico-datasheet.pdf

Она также содержит электрическую принципиальную схему Raspberry Pi Pico.

Если взглянуть на распиновку, то можно увидеть на плате SWD-разъем для отладки, пользовательский светодиод, разъем micro-USB, кнопку BOOTSEL и 2х20 контактов расширения.

Прежде всего необходимо прочитать «Getting started with Raspberry Pi Pico» https://datasheets.raspberrypi.org/pico/getting-started-with-pico.pdf , следуя указанным там инструкциям.

Если вы собираетесь использовать плату RPi 4B или RPi 400 для разработки приложений для RPi Pico, развернуть среду разработки там очень просто.

На Raspberry Pi 4B / 400 необходимо выполнить следующие действия (убедитесь, что у вас есть подключение к Интернету):

  1. Скачайте установочный скрипт
  1. Добавьте разрешения на выполнение скрипта

$ chmod +x pico_setup.sh

  1. Запустите установочный скрипт
  1. Перезагрузите вашу операционную систему

В противном случае процесс установки зависит от операционной системы, установленной на вашем компьютере. Я использую Ubuntu 20.04 LTS, поэтому мне пришлось прочитать «Chapter 2. SDK».

Пользователи Windows и OSX должны прочитать «Chapter 9. Building on other platforms» из руководства «Getting started with RPi Pico».

Автор документации предпочитает, чтобы мы использовали Visual Studio Code. Если вы не привыкли разрабатывать в Visual Studio Code, то можете выбрать что-нибудь другое, например Eclipse или Clion.

После установки необходимых инструментов пора помигать светодиодом на плате Raspberry Pi Pico. Выполните в терминале следующие команды:

$ mkdir build && cd build

Вот и все. Теперь мы можем загрузить прошивку в плату Raspberry Pi Pico.

Обновление и отладка прошивки

Если вы, как и я, используете десктопную версию Ubuntu 20.04 LTS, Raspberry Pi Pico должен автоматически примонтироваться к файловой системе как запоминающее устройство USB. Вы можете просто перетащить blink.uf2 на запоминающее устройство. RP2040 перезагрузится, размонтируется как запоминающее устройство и начнет запускать прошитый код. В следующий раз, когда вы захотите обновить прошивку, вам нужно будет нажать кнопку BOOT перед включением Raspberry Pi Pico, чтобы войти в режим обновления.

Если ваше приложение не работает или вы хотите понять, как оно работает, вы можете использовать внутрисхемную отладку через разъем SWD, но для этого необходимо иметь какой-то аппаратный адаптер JTAG / SWD, например J-Link, DAP-Link или плату Raspberry Pi с разъемом расширения контактов.

Использование Picoprobe

Из документации «Getting started with RPi Pico» я узнал, что можно использовать вторую плату Raspberry Pi Pico в качестве адаптера SWD (см. «Appendix A. Using Picoprobe»).

Это очень интересная возможность, учитывая невысокую стоимость платы. Давайте попробуем.

Если я не ошибаюсь, picoprobe — это прошивка DAP-Link, основанная на открытом стандарте CMSIS-DAP для микроконтроллеров Cortex-M, которая обеспечивает два преобразователя: USB-UART и USB-SWD.

Все, что нам нужно сделать, это загрузить специальную прошивку (picoprobe) во вторую плату Pico. После этого мы получим полноценный отладчик SWD по цене Pico.

Кстати, вы можете использовать его и для отладки других микроконтроллеров Cortex-M.

Вы должны прочитать «Appendix A. Using Picoprobe», чтобы узнать, что вам нужно сделать для начала использования picoprobe.

Это дублирующее документацию описание действий под Linux, поскольку я использую Ubuntu 20.04 LTS.

Для работы picoprobe необходимо собрать openocd с включенным драйвером picoprobe:

Пора собрать и прошить picoprobe:

/pico && git clone https://github.com/raspberrypi/picoprobe.git

$ mkdir build && cd build

$ cmake .. && make -j$(nproc)

Включите плату Raspberry Pi Pico, которую вы собираетесь использовать в качестве отладчика, с нажатой кнопкой BOOTSEL и перетащите файл picoprobe.uf2.

В итоге мы получили отладчик с двумя интерфейсами, один из которых — SWD, другой — UART для работы в качестве адаптера USB-UART независимо от первого.

Подключение между двумя платами Pico показано в следующей таблице:

Pico A (picoprobe) Pico B (dev board)
GND GND
GP2 SWCLK
GP3 SWDIO
GP4/UART1 TX GP1/UART0 RX
GP5/UART1 RX GP0/UART0 TX

На ярко-оранжевом фоне это выглядит так:

Чтобы использовать UART picoprobe, вы можете задействовать любую терминальную утилиту, например minicom.

Сначала добавьте себя в группу пользователей dialout и перезагрузитесь:

$ sudo usermod -a -G dialout $USER

После этого проверьте, находитесь ли вы в группе dialout, выполнив следующую команду:

Если да, запустим minicom:

$ minicom -D /dev/ttyACM0 -b 115200

Использование OpenOCD и GDB

Чтобы использовать отладку через SWD, вам необходимо запустить openocd как сервер и gdb как клиент:

$ openocd -f interface/picoprobe.cfg -f target/rp2040.cfg -s tcl

Open On-Chip Debugger 0.10.0+dev-g18b4c35-dirty (2021-08-12-18:55)

Licensed under GNU GPL v2

For bug reports, read http://openocd.org/doc/doxygen/bugs.html

Info : only one transport option; autoselect ‘swd’

Warn : Transport «swd» was already selected adapter speed: 5000 kHz

Info : Hardware thread awareness created

Info : Hardware thread awareness created

Info : RP2040 Flash Bank Command

Info : Listening on port 6666 for tcl connections

Info : Listening on port 4444 for telnet connections

Info : clock speed 5000 kHz

Info : SWD DPIDR 0x0bc12477

Info : SWD DLPIDR 0x00000001

Info : SWD DPIDR 0x0bc12477

Info : SWD DLPIDR 0x10000001

Info : rp2040.core0: hardware has 4 breakpoints, 2 watchpoints

Info : rp2040.core1: hardware has 4 breakpoints, 2 watchpoints

Info : starting gdb server for rp2040.core0 on 3333

Info : Listening on port 3333 for gdb connections

$ sudo apt install gdb-multiarch -y

(gdb) target remote loacalhost:3333

Конечно же вы можете отлаживать свое приложение в своей любимой IDE, в этом случае IDE работает как клиент.

Автоматическая генерация проекта

Для автоматического создания нового проекта вы можете использовать скрипт Python, который может работать как в режиме графического интерфейса пользователя, так и в режиме командной строки.

Чтобы воспользоваться этим, вам нужно будет клонировать скрипт создания проекта из Git репозитория :

/pico && git clone https://github.com/raspberrypi/pico-project-generator.git

Не забудьте установить библиотеку TKInter для использования GUI:

$ sudo apt-get install python3-tk

Затем его можно запустить в графическом режиме:

Добавление Pico в Arduino IDE

Также можно запрограммировать Raspberry Pi Pico в Arduino IDE. Была выпущена даже новая версия Arduino Nano на базе чипа RP 2040.

Если вы решите работать с Raspberry Pi Pico в Arduino IDE, вам сначала нужно будет добавить поддержку платы. Для этого выберите в Arduino IDE пункт меню File-> Preferences, затем заполните «Additional Board Manager URLs» ссылкой https://github.com/earlephilhower/arduino-pico/releases/download/global/package_rp2040_index.json

После этого выберите пункт меню «Board:« Arduino Uno »-> Board Manager …», введите «raspberry pi pico» и установите пакет «Raspberry Pi Pico / RP2040», который уже установлен на моей картинке.

Когда пакет установлен, нам нужно выбрать плату в пункте меню «Tools->Boards: «Arduino Uno»->Raspberry Pi RP2040 Boards(1.9.4)->Raspberry Pi Pico». Информация о плате появится в меню «Tools».

Процесс разработки в C/C ++ SDK

В этом разделе я покажу вам, что программирование Raspberry Pi Pico с использованием C/C++ SDK не сложнее, чем в Arduino IDE. Даже в том случае, если вы используете командную оболочку Linux.

Добавьте путь к pico-project-generator в ваш файл конфигурации .bashrc :

Потом перезагрузите систему:

После этого вы можете запускать pico_project.py из любого каталога.

Давайте создадим новый каталог для наших экспериментов:

/pico && mkdir pico-workspace && cd pico-workspace

Выберите имя и расположение проекта, затем нажмите кнопку ОК.

Мигание светодиодом

Теперь мы можем открыть автоматически сгенерированный C файл, отредактировать его:

Источник