Category Archives: CircuitPython

ESP32S2, CircuitPython and BIPES: Franzininho WiFi

Franzininho WiFi (https://github.com/Franzininho/Franzininho-WIFI) is a Brazilian Open Hardware project based on the ESP32-S2 SoC from Espressif (https://www.espressif.com/en/products/socs/esp32-s2). It was created by the Brazilian hardware designer and embedded systems enthusiast Fábio Souza.

Franzininho WiFi supports CircuitPython (a project supported by Adafruit Industries) and is available on the official CircuitPython repository:

https://circuitpython.org/board/franzininho_wifi_wroom/

or

https://circuitpython.org/board/franzininho_wifi_wrover/

BIPES is a free and open-source platform for block-based embedded systems, IoT programming, and more (https://bipes.net.br/). BIPES generates code for CircuitPython and is entirely web-based, so no software install is needed. BIPES can be used as an IDE to program using CircuitPython using text-based programming, blocks, and other features.

Although this post is focused on the Franzininho WiFi with the ESP32S2, BIPES works perfectly with MicroPython based boards and should work with other boards based on CircuitPython.

This post shows some possibilities using BIPES + Franzininho WiFi + CircuitPython!

Moreover, this post is based on: https://docs.franzininho.com.br/docs/franzininho-wifi/franzininho-wifi

Our intention is to revisit the examples and instructions presented by Fábio and Diana (on the link above), but now, using BIPES (https://bipes.net.br/). The board must already have the CircuitPython installed to follow the activities, as explained by Fábio and Diana in the Franzinho WiFi documentation mentioned above. Considering CircuitPython is already installed on the board, no additional software or configuration needs to be done. Just access the BIPES and program / control your Franzininho WiFi board. It is recommended to use Google Chrome.

Hello World – Blinking an LED

Based on: https://docs.franzininho.com.br/docs/franzininho-wifi/exemplos-circuitpython/hello-world by Fábio Souza e Diana Santos.

The objective of this first program is to test the connections, USB port access, send commands to Franzininho WiFi, and control an output pin (GPIO) to flash an external LED. USB connection is possible due to Web Serial API.

franzininho-wifi-hello-world

To create a program to blink the LED by BIPES, access BIPES (https://bipes.net.br/ide/) and choose the board on the top right area of the screen:

Next, try to connect to the board using the connect button:

After clicking on the USB port symbol, select Serial:

A list of devices will be shown. Select your Franzininho WiFi, which is powered by the ESP32-S2:

Click on the BIPES Console tab and try to send some Python commands to the board through this Console / Serial Terminal in the web browser:

With board connected, create the following program:

Use the left blocks toolboxes: Loops, Logic, Timing, and Machine ==> In/Out Pins.

You can also access the above program directly by clicking on the link below:

https://bipes.net.br/beta2/ui/#an9f6p

Try running and stopping the program using the Play button and the Stop button or the keyboard hotkeys Ctrl+Shift+R to run and Ctrl+Shift+S to halt the program:

You can also refine the program a little more:

Direct link to the program: https://bipes.net.br/beta2/ui/#ohqz9r

Run the program and check the result on the Console tab:

Serial Console

Based on: https://docs.franzininho.com.br/docs/franzininho-wifi/exemplos-circuitpython/serial-console by Ewerton Leandro de Sousa.

Objective: control Neopixel RGB LED at GPIO18, asking parameters from the user using the Console.

franzininho-wifi-serial-console

The Franzininho WiFi board has a Nexopixel RGB LED on GPIO18. We can start by testing this LED with an example application: a traffic light.

Direct link to the program: https://bipes.net.br/beta2/ui/#3o9e3a

And the result is:

But we can also ask the user for the desired values ​​for the LED control through the Console:

Direct link to the program: https://bipes.net.br/beta2/ui/#ysxszk

And the result can be seen at the Console:

Digital Inputs and Outputs

Based on: https://docs.franzininho.com.br/docs/franzininho-wifi/exemplos-circuitpython/entradas-saidas-digitais by Fábio Souza.

Purpose: read a digital input and control a digital output based on the state of the digital information.

Circuito Entrada e Saida digital

Program:

Direct link to the program: https://bipes.net.br/beta2/ui/#ghxagh

Analog Input (Analog to Digital Conversion – ADC)

Based on: https://docs.franzininho.com.br/docs/franzininho-wifi/exemplos-circuitpython/entradas-analogicas by Fábio Souza and Diana Santos.

Purpose: Read an analog input of the ESP32S2 and plot the reading graphically using BIPES. Moreover, turn the LED on if the digital input is greater than 2.5 Volts.

Circuito

Let’s start reading the analog input:

Direct link to the program: https://bipes.net.br/beta2/ui/#3qhnpe

Result:

Now let’s convert the raw reading from the analog input to Volts:

Direct link to the program: https://bipes.net.br/beta2/ui/#j4ami7

BIPES also allows you to plot data through an IoT dashboard, thanks to freeboard (https://github.com/Freeboard/freeboard). Use the “Show on IoT tab” block and the IoT tab. You can use this block multiple times and plot multiple values ​​simultaneously:

Direct link to the program: https://bipes.net.br/beta2/ui/#58h7xv

Go to the IoT tab:

And add a DATASOURCE of type “BIPES Serial, USB or Bluetooth. Define the datasource as ADC1, message ID 1, and refresh every 0.1 seconds:

After that, add some panes using the option ADD PANE:

Next, click on the + icon on the top right area of each pane and select the type you prefer. For this example, we used Gauge and typed datasources[“ADC1”] on the value field. Note that you can click on + DATASOURCE so that freeboard will help you enter the value with auto-completion. Also, define the Unit, minimum and maximum values.

We have also added a Timeseries (highchart) widget to another pane, with input values from the same datasource (ADC1), which allows a single (or multi) line real-time plot to be shown. And the result is:

Important notes

Timing and synchrony

BIPES used a queue data structure to send data from the Console to the IoT tab. In that way, note that the program sleeps for 0.2 seconds after each data is sent from the board to the console and to the IoT tab. Next, note that the freeboard datasource has the parameter refresh every 0.1 seconds. This gives freeboard time to consume data faster than it arrives. If these values are mismatched, you may have strange delays on the IoT tab visualization.

JavaScript support on freeboard

freeboard has another powerful feature: the possibility of entering/mixing JavaScript code with datasources to compute values, enter expressions or adjust values. On the last test, for example, there were so many decimal plates for the ADC (5 decimal plates to be precise):

We can change the VALUE field of this widget and add a JavaScript call to format the number of decimal plates. So, the VALUE field will be changed from datasources[“ADC1”] to datasources[“ADC1”].toFixed(2), which will format the number to 2 decimal plates, like this:

Other JavaScript expressions could be added to this field or using the JavaScript editor of freeboard. For example: (5+(datasources[“ADC1”]*3)).toFixed(2).

Finally, note that all data has been transferred and plotted using the USB cable. You can take your board anywhere, open the BIPES program by URL, and plot the data right where you are, even without an Internet connection, as BIPES works offline.

Direct link to the program, with the dashboard, included: https://bipes.net.br/beta2/ui/#9qwdh7.

By the way, we have been sharing BIPES programs here since the first example. So, if you want to share yours, simply click on the share button:

An Internet link will be generated with everything you created: block-based program, board definition, language, and IOT tab datasources and widgets.

BIPES EasyMQTT Bridge

Even without the board being connected to the Internet, BIPES offers a feature called EasyMQTT Bridge, which publishes the board’s data, received over USB, to the BIPES MQTT server. To do so, define a session (by clicking on the gear) and activate the “EasyMQTT Bridge” button on the Console tab:

When you click on the gear, you have the option of defining the EasyMQTT Session ID. Type one ID. Next, you can view the session. Click on “View EasyMQTT Session”, and you will have access to the link:

http://bipes.net.br/easymqtt/?session=5001

Activate the bridge to send data from the Console to the EasyMQTT server:

On the EasyMQTT tab, with the program running, you should see data arriving on the EasyMQTT session:

The link http://bipes.net.br/easymqtt/?session=5001 can be shared with anyone who will have access to the published data from anywhere. EasyMQTT, a BIPES module by Caio Silva (https://github.com/caioasilva), also offers an integration API. For more details, check EasyMQTT implementation documentation here: https://bipes.net.br/wp/publications/ and the BIPES Book here: https://bipes.net.br/wp/book-livro/.

File Manager

CircuitPython offers the nice feature of a file system based on the ESP32S2 flash memory, so we can add files with data, programs, and other contents. In the “normal” mode, the device is detected and used as a USB thumb drive. Files copied to the CIRCUITPY USB thumb drive are available for the CircuitPython environment using file operations calls, so your CircuitPython programs can use these files.

BIPES brings an additional way to manage files on the board: a file manager based on the browser that exchanges file commands to the board using a USB port (thanks to Web Serial API used by BIPES). Thus, BIPES can manage files on the Franzininho WiFi board with CircuitPython. Furthermore, BIPES also offers an editor in its own IDE in the web browser. Just use the Files tab. It is possible to upload files to the board, download files from the board, delete files, edit files through the text editor and run Python programs recorded in files on the board. As said, all these operations take place via USB.

Important: By default, the FLASH filesystem of CircuitPython is mounted read-only, as the board provides the CIRCUITYPY thumb drive.

BIPES will remount the filesystem on write mode with the command storage.remount(“/”, False). However, first, you must EJECT / SAFELY REMOVE / UMOUNT the CIRCUITPY USB Drive, so the BIPES file manager and your programs can write to files on the FLASH Memory.

After the filesystem is correctly mounted, you can go to the files tab and click on Refresh to update the file list:

And the file list will be updated on the left part of the screen:

Note that CircuitPython, by default, runs code.py automatically when the board boots. It is possible to click on this file, edit it, save and Run with the Run button, and, of course, it will run when the board boots.

Connecting to the Internet

You can use BIPES blocks to list available WiFi networks on the toolbox “Network and Internet“:

The result will give details about the available networks, like this:

We can also connect to the Internet:

And the result can be seen on the Console. For the example, the network selected is “Termometro”:

Web: HTTP Client

Once connected to the Internet, you can make HTTP GET requests. For example, we made the URL http://bipes.net.br/test.txt available for testing convenience. Here is an example that accesses this web page:

And the result would be similar to:


But we can use HTTP GET requests for dozens of powerful features using integration with other services using APIS. For example, we could check the weather using the OpenWeatherMap free web service and change the NeoPixel LED color according to the weather. Here is one possible program to do that:

Direct link to the program: https://bipes.net.br/beta2/ui/#wszbbc

To use the program, you must create an account on http://openweathermap.org/api and generate an API key. Then copy the generated API key and paste on YOUR KEY text on the block that defines the URL to be accessed.

We have made a test with the Boston city, but you can change ?q=Boston by any town you want. OpenWeatherMap responds with a JavaScript Object Notation (JSON), similar to:

{"coord":{"lon":-71.0598,"lat":42.3584},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10n"}],"base":"stations","main":{"temp":278.01,"feels_like":275.39,"temp_min":275.34,"temp_max":279.79,"pressure":1011,"humidity":80},"visibility":10000,"wind":{"speed":3.13,"deg":280,"gust":6.71},"rain":{"1h":0.14},"clouds":{"all":100},"dt":1641770969,"sys":{"type":2,"id":2013408,"country":"US","sunrise":1641730368,"sunset":1641763771},"timezone":-18000,"id":4930956,"name":"Boston","cod":200}

Then we manipulate this response to get only the contents of “description”, which is “light rain”. There are several methods for this text parsing, so we present one simple and basic approach to this program.

The following image shows the result seen on the Console, step by step. The program first prints the complete response, then each step of the parsing process until the program gets the weather description: light rain. Next, we execute some conditional statements, checking if the description is light rain. If it is, we light the NeoPixel LED in blue color. If we have a storm, we light the red LED. You can adjust other variations, for sure!

Console:

The Franzininho WiFi board can be connected to a USB power bank and act as a weather indicator device:

Check more details and explanations on the BIPES Book here:

https://bipes.net.br/wp/book-livro/

Web: HTTP Server

BIPES also offers blocks to create an HTTP Web Server. Here is an example:

Direct link to the program: https://bipes.net.br/beta2/ui/#bco3js

Run the program and use the Console to check if the server started and the IP you can connect to the webserver.

When you access this IP using a web browser, you get:

We can also create HTTP links and actions at our web server with BIPES by verifying the contents of the block requested page. The following example offers some options to control the NeoPixel LED color.

Direct link to the program: https://bipes.net.br/beta2/ui/#icpec6

The resulting page is seen on the web browser:

Monitoring requests using the Console:

When RED is clicked:

When OFF is clicked:

We could also ask for user input. For example:

In this example, the HTLM text input from the user is used to control the RED LED color intensity:

Direct link to the program: https://bipes.net.br/beta2/ui/#d3i7j7

IoT Dashboard using EasyMQTT

Using web request blocks (HTTP GET), we can publish sensor data to the BIPES MQTT server and create dashboards that can be easily shared for access from other devices, with responsive technology, for visualization on mobile phones, again, using freeboard.

To accomplish that, we can use an URL to publish data to the BIPES EasyMQTT Server. For example, considering session 5001 and topic Topic1, we can publish the value 1:

http://bipes.net.br/easymqtt/publish.php?session=5001&topic=Topic1&value=1

As already mentioned, data published to session 5001 can be seen using this URL:

http://bipes.net.br/easymqtt/?session=5001

Now we can publish data. For example, the Analog reading of pin AN1 every 5 seconds:

Next, go to the IoT tab and configure a datasource for this EasyMQTT session and topic.

Create a pane and include a Gauge widget:

Include also a time-series. One possible result is:

While the program is running, the Console tab can be used to monitor each HTTP request to the server that posts data:

Direct link to the program, including the dashboard: https://bipes.net.br/beta2/ui/#ibgpa6

The IoT tab has the option “Share board”, which generates a link and a QR-Code for direct access to the dashboard:

This option will share the dashboard without the program for visualization only operation.

A link similar to this one will be generated:

http://bipes.net.br/freeboard#fqngjd

This QR-Code can be read by a smartphone, which will open the URL to show the dashboard with real-time updates:

Book

BIPES offers several other options, including custom Python code inside blocks, creating functions, and much more. If you are new to BIPES, you can check out the BIPES book at https://bipes.net.br/wp/book-livro/. You can also learn more about BIPES at the project GitHub repository and interact at the BIPES discussion forum. Both are available at the link: https://github.com/BIPES/BIPES/.

Thanks

Thanks for the interest in the BIPES project and in this text. Hope it’s been helpful for you.


[Post in Portuguese] Franzininho Wifi e BIPES

Este post é baseado na documentação do Franzininho WiFi (https://github.com/Franzininho/Franzininho-WIFI) preparado pelo Fábio Souza e Diana Santos:

https://docs.franzininho.com.br/docs/franzininho-wifi/franzininho-wifi

Nossa intenção é revisitar os exemplos e instruções apresentados pelo Fábio e Diana através do BIPES (https://bipes.net.br/). Para seguir, a placa já deve possuir o CircuitPython instalado, conforme explicado pelo Fábio e Diana na documentação do Franzininho WiFi citada acima. Considerando o CircuitPython já instalado na placa, nenhum software ou configuração adicional precisam ser feitos. Basta acessar o BIPES e programar / controlar sua Franzininho WiFi. Recomenda-se o uso do Google Chrome.

Hello World – Piscando um LED

Baseado em : https://docs.franzininho.com.br/docs/franzininho-wifi/exemplos-circuitpython/hello-world por Fábio Souza e Diana Santos.

O objetivo deste primeiro programa é testar as conexões, enviar comandos para a Franzininho WiFi e controlar um pino de saída (GPIO) para piscar um LED externo.

franzininho-wifi-hello-world

Para piscar o LED pelo BIPES, acesse o BIPES (https://bipes.net.br/ide/) e escolha a placa:

Em seguida, tente conectar na placa, usando o botão conectar:

Após clicar no símbolo da porta USB, selecione Serial:

Uma lista de dispositivos será mostrada. Selecione sua Franzininho WiFi:

Clique na guia Console do BIPES e tente enviar alguns comandos Python para a placa através deste Console / Terminal Serial no navegador web:

Com placa conectada, crie o seguinte programa:

Utilize blocos das opções: Laços, Lógica, Temporização e Máquina -> In/Out Pins

Você também pode acessar o programa acima diretamente ao clicar no link abaixo:

https://bipes.net.br/beta2/ui/?lang=pt-br#an9f6p

Tente executar e interromper o programa utilizando o botão Play e Stop ou as teclas de atalho Ctrl+Shift+R para executar e Ctrl+Shift+S para parar o programa:

Você também pode sofisticar o programa um pouco mais:

Link para acesso direto ao programa: https://bipes.net.br/beta2/ui/?lang=pt-br#pcjebw

Resultado:

Serial Console

Baseado em: https://docs.franzininho.com.br/docs/franzininho-wifi/exemplos-circuitpython/serial-console por Ewerton Leandro de Sousa.

Objetivo: controlar o LED RGB Nexopixel no GPIO18 através do Console.

franzininho-wifi-serial-console

A placa Franzininho WiFi possui um LED RGB Nexopixel no GPIO18. Podemos começar testando este LED com uma aplicação de exemplo: um semáforo:

Link pra acesso direto ao programa: https://bipes.net.br/beta2/ui/?lang=pt-br#3ueqpe

Resultado:

Mas também podemos perguntar ao usuário os valores desejados para o controle do LED, através do Console:

Resultado no Console:

Link pra acesso direto ao programa: https://bipes.net.br/beta2/ui/?lang=pt-br#5dwn6r

Entradas e Saídas Digitais

Baseado em: https://docs.franzininho.com.br/docs/franzininho-wifi/exemplos-circuitpython/entradas-saidas-digitais por Fábio Souza.

Objetivo: ler uma entrada digital e controlar uma saída digital a partir do estado da entrada digital.

Circuito Entrada e Saida digital

Programa:

Link para acesso direto ao programa: https://bipes.net.br/beta2/ui/?lang=pt-br#e9y9bu

Entrada Analógica

Baseado em: https://docs.franzininho.com.br/docs/franzininho-wifi/exemplos-circuitpython/entradas-analogicas por Fábio Souza e Diana Santos.

Objetivo: Ler uma entrada analógica da ESP32S2, plotar a leitura de forma gráfica e acionar o LED se a entrada for maior que 2.5 Volts.

Circuito

Vamos começar lendo valores da entrada analógica:

Link direto para o programa: https://bipes.net.br/beta2/ui/?lang=pt-br#8j3cur

Resultado:

Agora vamos converter a leitura digital para Volts:

Link direto para o programa: https://bipes.net.br/beta2/ui/?lang=pt-br#bt4tfw

O BIPES também permite plotar dados através de um dashboard IoT. Para isso, utilize o bloco “Show on IoT tab” e a aba IoT. Você pode usar este bloco várias vezes e plotar vários valores simultaneamente:

Link direto para o programa: https://bipes.net.br/beta2/ui/?lang=pt-br#ht655f

Na aba IOT, adicione um datasource:

Depois adicione panels e widgets conforme você preferir. Por exemplo:

Resultado:

Note que esta transferência de dados ocorreu via USB.

Link direto para o programa, com o dashboard incluído: https://bipes.net.br/beta2/ui/?lang=pt-br#9qwdh7

Mesmo sem a placa estar conectada na Internet, o BIPES oferece um recurso chamado EasyMQTT Bridge, que publica os dados da placa no servidor MQTT do BIPES. Para tanto, defina uma sessão (clicando na engrenagem) e ative o botão “EasyMQTT Bridge”:

Ao clicar no botão “View this EasyMQTT Session”, você terá acesso ao link:

http://bipes.net.br/easymqtt/?session=5001

Com o envio de dados ativado:

Você verá os dados no link mencionado:

O link http://bipes.net.br/easymqtt/?session=5001 pode ser compartilhado com qualquer pessoa, que terá acesso aos dados, a partir de qualquer lugar. O EasyMQTT também oferece uma API para integração com outros sistemas. Para detalhes, verifique a documentação do EasyMQTT aqui: https://bipes.net.br/wp/publications/

Gerenciador de arquivos

Você pode usar o BIPES para gerenciar arquivos na placa Franzininho WiFi. Além disso, o BIPES também oferece um editor em sua própria IDE no navegador Web. Basta utilizar a guia Arquivos. A partir dela é possível enviar arquivos para a placa, baixar arquivos da placa, apagar arquivos, editar arquivos pelo editor de textos e executar programas Python gravados em arquivos na placa. Todas estas operações ocorrem via USB.

Nota: Como os arquivos da placa estão em um sistema de arquivos compartilhado com dispositivo de armazenamento em massa USB, é preciso ejetar o dispositivo de armazenamento USB do seu PC para que o BIPES consiga gravar arquivos na placa.

Utilize o botão refreh para atualizar os arquivos:

Conectando na Internet

Você pode usar blocos do BIPES para listar redes WiFi disponíveis a partir dos blocos disponíveis em “Rede e Internet”:

E também conectar na Internet:

O resultado pode ser visto no Console:

Cliente HTTP Web

Uma vez conectado na Internet, você pode fazer requisições HTTP, acessando sites ou serviços web (webservices). Por exemplo:

Resultado:


Note que o texto exibido foi obtido da URL: http://bipes.net.br/test.txt

Servidor HTTP Web

O BIPES também oferece a opção de iniciar um servidor web (HTTP) no Franzininho WiFi:

Link direto para o programa: https://bipes.net.br/beta2/ui/?lang=pt-br#qckmaf

Verifique o IP obtido no Console e acesse por um navegador web:

Resultado, ao acessar pelo navegador web:

Também podemos criar links e ações em nosso servidor web:

Link direto para o programa: https://bipes.net.br/beta2/ui/?lang=pt-br#zu2sq2

E é possível acompanhar as requisições pelo Console:

EasyMQTT e dashboard IoT

Utilizando os blocos de requisições web (HTTP GET), podemos publicar dados de sensores para o servidor MQTT do BIPES e criar dashboards que podem ser compartilhados facilmente para acesso a partir de outros dispositivos, inclusive com tecnologia responsiva, para visualização em celulares.

Para tanto, usaremos a URL de publicação de dados no servidor EasyMQTT. Exemplo:

http://bipes.net.br/easymqtt/publish.php?session=5001&topic=Topic1&value=1

Como já mencionado, os dados publicados podem ser vistos em:

http://bipes.net.br/easymqtt/?session=5001

Agora podemos criar um programa que publica dados nestes servidor:

Link direto para o programa: https://bipes.net.br/beta2/ui/?lang=pt-br#wvkbim

Agora podemos configurar um datasource para este tópico do EasyMQTT:

Crie um componente widget -> Gauge:

Resultado:

Você pode acessar o programa completo já com o dashboard IoT por este link:

https://bipes.net.br/beta2/ui/?lang=pt-br#mwhsz9

Na aba IoT, também temos a opção “Share board”:

Este recurso permite compartilhar apenas o painel (dashboard) de visualização de dados, em tempo real, com qualquer usuário, mas sem o programa:

Um link deste tipo será gerado:

http://bipes.net.br/freeboard#fqngjd

Este QR-Code pode ser lido em um smartphone, possibilitando visualizar o dashboard:

Bugs

Algumas implementações ainda são beta e podem oferecer bugs. Por exemplo, o servidor web e cliente web podem dar erro de “Out of Sockets”. Este bug está relacionado com o código do CircuitPython. Estamos trabalhando para reduzir estes bugs.