Category Archives: Tutorials

Using a SIM800L GSM module with the Raspberry Pi (no battery)

sim800l gsm module with raspberry pi

The SIM800L is a GSM/GPRS modem widely used in electronics due to its very low price and wide availability. It’s an affordable way to send SMS with a Raspberry Pi or an Arduino, to connect to 3G or to implement a GPS.

However, it is almost impossible to find satisfactory explanations on its use and in particular on its connection.

In this tutorial we will therefore see how to connect and power a SIM800L from a Raspberry Pi (note that this also works for an Arduino), without external power supply or battery!

Hardware

We will go into the details and explanations later in this tutorial, but be aware that to connect a SIM800L to a Raspberry some hardware is required. So, you will need:

  • SIM800L GSM Module
  • 100 µF capacitor or more
  • 1N4007 diode
  • Breadboard
  • Jumpers

Of course, you will also need a Raspberry with Raspbian installed and a SIM card with a subscription. Note, the SIM card must be in micro sim format. If yours is a smaller format (nano format), you will need an adapter.

How to use the SIM800L module with a Raspberry Pi?

The SIM800L is a modem. It is the responsible for registering with your operator’s network, etc. Overall it behaves like a phone that you could control directly from your Raspberry.

To be able to control the SIM800L, from the Raspberry, you will have to provide power to the first and physically and software connect the two using a TTL port, more often called a serial port or interface.

From there you can control the SIM800L by sending so-called Hayes commands to the serial port – we actually speak more often of AT commands – which are commands specific to the functions of a modem. For example, send an SMS, enter a PIN code, check the network status, and much more!

In theory, to use a SIM800L with the Raspberry Pi you must do like this:

  • VDD of the SIM800L to +5V on the Raspberry.
  • GND of the SIM800L to GND on the Raspberry.
  • TXD of the SIM800L to RXD of the Raspberry.
  • RXD of the SIM800L to TXD of the Raspberry.

Only here, all that is the theory, but you will see that in practice things are a little more complicated.

Why is so difficult to plug in a SIM800L?

If the theory seems simple, in reality, you will find quite a few tutorials on the internet explaining how to use the SIM800L with a Raspberry. Worse, you will essentially find incorrect tutorials which, at best, will make your installation completely unstable, why not, will damage your SIM800L.

But then, how come there are not more quality resources available for such a well-known module? Because the SIM800L is particularly difficult to power and sensitive.

1. SIM800L is designed for phones and batteries

Originally the SIM800L was designed for use in phones by manufacturers. Its use in consumer electronics is much more recent and was not considered at all by the manufacturer.

As a result of its use in telephones, the module is designed to be powered by lithium-ion batteries, which offer voltages of around 3.6 to 3.7 volts. This feature will pose a first problem for us, because in digital electronics we generally use 3.3 volts or 5 volts, but not 3.6 volts.

2. SIM800L is an energy-intensive module

The second problem, the SIM800L performs radio operations that require large, very punctual current peaks. Typically the operations involved are registering on the operator’s network, sending messages, etc. If during these phases the module does not obtain the necessary current, its behavior becomes completely unpredictable, ranging from the error message to the restart through the loss of network.

Unfortunately, the power supplies in general and the GPIO ports of the Raspberry Pi in particular have a hard time responding to this kind of consumption peaks.

In fact, the amount of energy consumed is so great and over such a short period of time that using power cables that are too long and too thin can be enough to crash the module! This is also typically the case if you connect several Dupont cables in series.

No worries, we will explain how to solve these two problems!

So, how to power a SIM800L directly from a Raspberry?

We have seen so far that two problems arise for us to power a SIM800L from a Raspberry: an incompatible voltage and peaks in power consumption.

To begin, we will tackle the tension problem.

1. Decrease the voltage supplied by the Raspberry Pi

If we read the datasheet (technical sheet) of the SIM800L, we can see that the manufacturer indicates a supply voltage between 3.4 and 4.4 volts, with an optimal voltage of 4 volts.

The Raspberry Pi have two outputs that can supply two voltages, 3.3 and 5 volts. So we should increase our tension a bit or decrease it.

Let’s eliminate the first possibility which is too complicated to implement and look at the second. We are therefore looking for a reliable, simple and very inexpensive way to reduce a voltage by at least 0.6 volts, without reducing the intensity of the current (amperes). Luckily, it turns out that there is an electronic component that does exactly that, and that in addition this component is so widespread that absolutely all electronics technicians know it: the diode.

Diodes are primarily known for passing current in one direction only. But one of their characteristics is also to cause a voltage drop, which is estimated for silicon diodes at 0.7 volts.

So we just need to insert a silicon diode, we will take a 1N4007, between the 5 volt GPIO of our Pi and the VDD (power supply) PIN of our SIM800L. And here we have a voltage of 4.3 volts, MAGICAL RIGHT!!

2. Provide a power source that can meet consumption peaks

Now that we have solved our voltage problem, there remains our consumption peak problem. This time we would need a component allowing us to “store current” and provide it very quickly when the SIM800L needs it. Again, luckily, it exists and it’s called a capacitor!

Capacitors are used in many cases, but one of the most well-known uses is power supply stabilization. They charge when there is too much current and discharge when there is not enough. We will therefore insert an electrolytic capacitor (we will take at least a 100 µF 5 V, if we have more µF or volts no problem) in parallel with the VDD and GND pins of our SIM800L.

Schematics and wiring

Now that we’ve solved our problems, let’s see what our complete assembly looks like before testing everything by sending an SMS.

To hold all our components in place and connect them together we will use a breadboard and some jumpers.

Here is the final connection diagram, the red wire goes to the VDD, the black to the GND.

A few notes on assembly:

  • unplug the power supply of your Raspberry Pi while wiring. Only plug it in after checking everything and being sure that your circuit is good to go.
  • Connect the capacitor as close as possible to the VDD and GND pins of the SIM800L, ideally as shown in the diagram.
  • Capacitors are a polarized component, you must connect theme in a precise direction, anode on the VDD, cathode on the GND. The cathode is marked by a white band on the side.
  • Just like the capacitor, the diode is a polarized component. Again the cathode is marked by a white band.

Once the assembly is complete, you will be able to insert the SIM card into the slot provided on the SIM800L.

You must tuck the card on the contact side against the printed circuit, the corner cut at an angle towards the opening (it protrudes a little). If you insert the card upside down you will get a SIM not inserted type error when using the module.

Once the assembly is finished, turn on your Raspberry Pi, we will be able to test by sending an SMS!

Your first SMS from the Raspberry with a SIM800L

To finish this tutorial, we will send a first SMS to check that everything is working. We will not go further on the use of the SIM800L, but be aware that it offers many other features. For more advanced use, refer to the AT commands guide for the SIM800.

To begin, you will have to follow our tutorial to activate the serial port of the Raspberry Pi. Once you have finished activating the serial port we can connect to the SIM800L via the serial port.

To do this, open a connection to /dev/serial0 with minicom using the command line below:

sudo minicom -b 115000 -o -D /dev/serial0

Type the AT command (often the first line is not displayed when you type, this is normal) then make a line break to validate. You should get an OK response message.

Now we are going to check that the SIM card is unlocked (the PIN code is entered). To do this type the command AT+CPIN?. You should have an answer:

+CPIN: READY
OK

If you get an answer like the one below, you need to enter your card’s PIN code.

+CPIN: SIM PIN
OK

To do this, use the command AT+CPIN=0000 replacing 0000 with your own PIN code. You should then get a response of the form:

AT+CPIN=0000
OK
+CPIN: READY
SMS Ready
Call Ready

That’s it, you are connected to your operator’s network. All we have to do is send an SMS. To do this, use the commands AT+CMGF=1 to activate the text mode (it allows us to write the SMS in a format understandable for a human), then AT+CMGS="+213XXXXXXXXX" replacing +213XXXXXXXXX by the number to which you want to send the SMS.

A character > will appear, type your SMS then once you finish, press Ctrl+Z.

In the end you should have something like this:

AT+CMGF=1
OK
AT+CMGS="+213XXXXXXXXX"
> My Fist SMS with SIM800L using Raspberry Pi
+CMGS: 29

OK

There you go, you have sent your first SMS with a Raspberry Pi and a SIM800L! if you need to see more tutorials, check this link.

Machine Vision with Raspberry Pi using TensorFlow and OpenCV4

artificial vision with raspberry pi tensorflow and opencv

Do you want to implement a CCTV camera that can identify several different elements? Or maybe optimize your robot and give it the ability to detect objects?

The Raspberry Pi 4 offers enough performance to perform machine learning. In this tutorial you will see the steps to get TensorFlow working on your Raspberry Pi 4, as well as a demonstration of detecting objects with a PI Camera or USB Webcam.

Required Hardware/software

  • Raspberry Pi 4.
  • 3000mA power supply with its USB-C cable.
  • micro-SD card (minimum 32 GB).
  • Picamera (or USB webcam).

What is TensorFlow ?

TensorFlow is an open source machine learning framework for solving complex mathematical problems. It allows researchers to develop experimental learning architectures and turn them into software. TensorFlow was developed by Google Brain team in 2011 and made open source in 2015. Since then it has gone through more than 21000 changes and upgraded to version 1.0 in February 2017. Currently version 2.8.0 is available on the TensorFlow website.

This library notably makes it possible to train and run neural networks for the classification of handwritten digits, image recognition, models for machine translation, and natural language processing. An application’s code is written in Python but executed in high-performance C++. Here, the raspberry and its camera will be able to detect a hundred different objects! In addition, good results are obtained at night with an IR camera equipped with LEDs.

On the software side, the micro-SD has been flashed with the latest version of Raspbian Buster downloadable from the official website. Python3 is installed there by default, to launch a program from the command line, you will have to type in a terminal:

$ python3 my_program.py

Here, the Object_detection_picamera.py program will need several elements to work:

  • The mscoco_label_map.pbtext file corresponding to the list of 100 detectable objects, it is located in the data folder.
  • The “ssdlite_mobilenet_v2_coco_2018_05_09” folder where the training model files are stored.
  • The utils folder (utilities) containing the classification modules for the various objects.

Installing TensorFlow

Start by updating the Raspberry Pi:

sudo apt-get update
sudo apt-get dist-upgrade

Next, install TensorFlow with the pip3 command.

sudo pip3 install tensorflow

TensorFlow needs a library named Atlas, type the following command:

sudo apt-get install libatlas-base-dev

Finally, it will be necessary to install the dependencies necessary for the detection of objects.

sudo pip3 install pillow lxml jupyter matplotlib cython
sudo apt-get install python-tk

That’s it for TensorFlow. Let’s move on to OpenCV.

Installing OpenCV

TensorFlow’s object detection examples typically use matplotlib to display images, but OpenCV is preferred because it’s easier to use and less error-prone. The object detection scripts in the GitHub repository in this guide use OpenCV. To make OpenCV work on the Raspberry Pi, many dependencies need to be installed via apt-get.

sudo apt-get install libjpeg-dev libtiff5-dev libjasper-dev libpng12-dev 
sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev 
sudo apt-get install libxvidcore-dev libx264-dev 
sudo apt-get install qt4-dev-tools libatlas-base-dev
sudo pip3 install opencv-python

If all went well, OpenCV is installed on your Raspberry.

You can check if the installation is successful and the installed version. Open a terminal and launch the Python3 interpreter.

The TensorFlow object detection API uses Protobuf, a package that implements Google’s Protocol Buffer data format. Before, you had to compile the Protobuf source code (a bit tedious), but now the installation is very simple, thanks to the multiple contributions of the community.

sudo apt-get install protobuf-compiler

In order to check the version installed, run the command:

protoc --version

You should have in response libprotoc v3.20.0 (latest version.)
Create a TensorFlow directory and navigate to it (/home/pi/tensorflow).

mkdir tensorflow
cd tensorflow

Download the TensorFlow repository from GitHub by typing:

git clone --depth 1 https://github.com/tensorflow/models.git

Next, you need to modify the PYTHONPATH environment variable to point to certain directories in the TensorFlow repository you just downloaded. PYTHONPATH needs to be set each time a terminal is opened, so the .bashrc file needs to be edited.

sudo nano ~/.bashrc

Go to the end of the file, and add this line:

export PYTHONPATH=$PYTHONPATH:/home/pi/tensorflow/models/research:/home/pi/tensorflow/models/research/slim

Now we need to use protoc to compile the Protocol Buffer (.proto) files used by the Object Detection API. The .proto files are in /research/object_detection/protos, but we need to run the command from the /research directory.

cd /home/pi/tensorflow1/models/research
protoc object_detection/protos/*.proto --python_out=.

Next, move into the object_detection directory:

cd /home/pi/tensorflow/models/research/object_detection

Now download the SSD_Lite model. Google teams have developed a series of pre-trained object detection files, with varying levels of speed and accuracy. The Raspberry Pi has a relatively weak processor for the recognition application, so a model should be used that takes less processing power. Here we will use SSDLite-MobileNet, which remains well suited for our Raspberry Pi. Download the file and unzip it into the object_detection directory.

wget http://download.tensorflow.org/models/object_detection/ssdlite_mobilenet_v2_coco_2018_05_09.tar.gz
tar -xzvf ssdlite_mobilenet_v2_coco_2018_05_09.tar.gz

Finally, copy/paste the python program from this Github link in a file named Object_detection_picamera.py

If you want to port the application to other Raspberry Pi with OpenCV and TensorFlow installed, simply download the .ZIP of the necessary files available on GitHub.

Your application is now ready to work!

Conclusion

Once your application is operational, all possibilities are open. For an autonomous application, based on solar panels, it would suffice to perform a calculation of the power consumed by the entire installation, and to determine the appropriate type of battery.

Still at the battery level, the Lion-i technology seems well suited, because of its small size and its autonomy, the price is higher than a lead battery, but offers good results in an environment subject to cold or heat. heat.

Programming Arduino with Visual Studio Code

program arduino with vscode

Every hobbyist generally start programming on Arduino using its official IDE. For advanced programmers, it may be interesting to change the code editor to have access to a larger number of features. In this article, you will learn how to program your Arduino using of the Visual Studio Code software which is a nice alternative to the Arduino IDE.

Introducing Visual Studio Code

Visual Studio Code is an extensible and lightweight code editor developed by Microsoft. VSCode brings many features compared to the Arduino IDE:

  • Auto-completion.
  • Syntax highlighting.
  • Debug functionality.
  • Programming in several languages (C++, C#, Java, Python, PHP, etc.).
  • Project management.
  • Git repository management.

It is open source and available on Windows, Linux and MacOS platforms.

Installing Visual Studio Code

Go to the Visual Studio Code download page and download the latest version corresponding to your OS. Launch the installer and follow the usual steps.

Communicating with Arduino

To be able to communicate with Arduino, you must install the corresponding extension.

Click on the “Extensions” icon it the left of your screen or use the shortcut (Ctrl+Shift+X).

Then search for Arduino and select “Arduino for Visual Studio Code”.

install it then Restart VSCode.

Setting up VSCode for Arduino

Click on the Manage icon (gear icon on the bottom left) and select “Command Palette”. You can use the shortcut (Ctrl+Shift+P).

Search for Arduino, then you have access to several commands related to Arduino.

Select Arduino Board Config then select board type.

At the bottom right, click on Select Serial Port, then select the serial port corresponding to the Arduino (here, COM5).

At the bottom right, click on Select Programmer then select “AVRISP mkII”.

Code compilation and upload

In the command palette (Ctrl+Shift+P), search for “Arduino: Examples” then choose “Blink” or another example.

You can then upload the code by pressing “Upload” in the top right.

The console indicates if the code is loading and you can verify that the code is loaded on the Arduino board by looking at the status of the LED.

By modifying the code a bit we send text to the serial monitor.

int led = 13;

// the setup routine runs once when you press reset:
void setup() {
  Serial.begin(115200);
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  Serial.println("Led is High");
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  Serial.println("Led is Low");

  delay(1000);               // wait for a second
}

Upload the modified code to the Arduino board.

To open the serial monitor, press the Serial Monitor icon just to the right of the board type at the bottom right.

You can then select the desired Baudrate in the Arduino board configuration bar at the bottom right (115200).

Send commands to the serial monitor

Just like the Arduino IDE, it is possible to send commands via the Serial port.

In the Arduino command palette, search for “Send text to Serial Port”. An input bar appears.

It is possible to create a keyboard shortcut to open this command more easily. Press the gear icon to the right of the control.

Under the Keybinding tab, you can customize your shortcut.

Now you are ready to use use VSCode with your Arduino boards.

Raspberry Pi Pico and MPU6050 with MicroPython

Raspberry Pi Pico and MPU6050 with MicroPython

The MPU6050 is an inertial unit that combines an accelerometer and a gyroscope. It is used to measure acceleration, inclination and angular velocity. In this tutorial, we will try to explain how to use an MPU6050 with a Raspberry Pi Pico using MicroPython.

The accelerometer makes it possible to know the acceleration and/or the gravitational field according to 3 axes: x, y and z. If you take a closer look, you can see a drawing of the x and the y axes on the module, while the z axis is perpendicular to the plane of the module. When the module is stationary, flat on a table, it will measure an acceleration of 1 g along the z axis, due to the force of gravity acting downwards. If the measured acceleration is zero along the 3 axes, the MPU-6050 module is in free fall!

The gyroscope measures the angular speed along the 3 axes. When the module is immobile, the 3 components of the angular velocity are, in principle, zero (a calibration is however necessary for the result to be exact).

Connections

The MPU-6050 module has 8 connectors, but only 4 of them are necessary for its operation (2 for power supply, and 2 for data transmission by I2C):

  • VCC pin (MPU-6050) => 3.3V output pin (Raspberry Pi Pico).
  • GND pin (MPU-6050) => GND pin (Raspberry Pi Pico).
  • SCL pin (MPU-6050) => GP9 pin (Raspberry Pi Pico).
  • SDA pin (MPU-6050) => GP8 pin (Raspberry Pi Pico).

Installing imu.py and vector3d.py libraries

You can find the necessary libraries on this Github repository. Also, you need to copy the “imu.py” and “vector3d.py” files to the flash memory of the Raspberry Pi Pico.

First script

This script displays the measurements from the accelerometer and the gyroscope. From the data of the accelerometer, the script tries to determine if one of the 3 axes (x, y or z) approaches the vertical. Based on the data from the gyroscope, the script indicates whether the MPU-6050 module is spinning.

Run this script, and orient the MPU-6050 module in different ways to see how the displayed values vary.

'''
Using the MPU6050 inertial unit (accelerometer + gyrometer) with a Raspberry Pi Pico.
For more info:
bekyelectronics.com/raspberry-pi-pico-and-mpu-6050-micropython/
'''

from imu import MPU6050  # https://github.com/micropython-IMU/micropython-mpu9x50
import time
from machine import Pin, I2C

i2c = I2C(0, sda=Pin(8), scl=Pin(9), freq=400000)
imu = MPU6050(i2c)

# Temperature display
print("Temperature: ", round(imu.temperature,2), "°C")

while True:
    # reading values
    acceleration = imu.accel
    gyroscope = imu.gyro
    
    print ("Acceleration x: ", round(acceleration.x,2), " y:", round(acceleration.y,2),
           "z: ", round(acceleration.z,2))

    print ("gyroscope x: ", round(gyroscope.x,2), " y:", round(gyroscope.y,2),
           "z: ", round(gyroscope.z,2))

# data interpretation (accelerometer)

    if abs(acceleration.x) > 0.8:
        if (acceleration.x > 0):
            print("The x axis points upwards")
        else:
            print("The x axis points downwards")

    if abs(acceleration.y) > 0.8:
        if (acceleration.y > 0):
            print("The y axis points upwards")
        else:
            print("The y axis points downwards")

    if abs(acceleration.z) > 0.8:
        if (acceleration.z > 0):
            print("The z axis points upwards")
        else:
            print("The z axis points downwards")

# data interpretation (gyroscope)

    if abs(gyroscope.x) > 20:
        print("Rotation around the x axis")

    if abs(gyroscope.y) > 20:
        print("Rotation around the y axis")

    if abs(gyroscope.z) > 20:
        print("Rotation around the z axis")
    
    time.sleep(0.2)

Second script

In this second example, the Raspberry Pi Pico’s built-in LED lights up when you shake the MPU6050 module.

'''
Using the MPU6050 inertial unit (accelerometer + gyroscope) with a Raspberry Pi Pico.
The Pico LED lights up when the MPU6050 is shaken.
For more info:
bekyelectronics.com/raspberry-pi-pico-and-mpu-6050-micropython/
'''

from imu import MPU6050  # https://github.com/micropython-IMU/micropython-mpu9x50
import time
from machine import Pin, I2C

i2c = I2C(0, sda=Pin(8), scl=Pin(9), freq=400000)
imu = MPU6050(i2c)

# LED initially off
Pin(25, Pin.OUT).value(0)

while True:
    # acceleration reading
    acceleration = imu.accel.magnitude
    print (acceleration)
    
    # value at rest is 1
    if abs(acceleration - 1) > 0.1:
        print("It is moving!")   
        Pin(25, Pin.OUT).value(1) # turn on the LED
    else: 
        Pin(25, Pin.OUT).value(0) # turn off the LED
        
    time.sleep(0.2)

That’s it, this is how you can use the MCU6050 unit with your Paspberry Pi Pico. You can check other tutorials from this link. If you want to establish wireless communication between two of your Picos using NRF24L01, click here.

Raspberry Pi Pico with nRF24L01 using MicroPython

Raspberry Pi Pico with nRF24L01 using MicroPython

In this tuturial, we will establish a wireless communication between two Raspberry Pi Pico equipped with an nRF24L01 module each. We will use the MicroPython languge to program our Raspberry Pi Pico.

nRF24L01 modules are designed to transmit the information at a 2.4 GHz radio frequency. Each module can transmit and receive signals. The range can be a few tens of meters.

Connections

You need to have a pair of nRF24L01 modules. Depending on their brand, you may find:

  • Green modules with 10 clearly marked pins
  • Black modules with 8 pins that have no identification.

Wire each of your Raspberry Pi Pico to an nRF24L01 module as follows:

  • VCC (nRF24L01) => 3.3V output (Raspberry Pi Pico).
  • GND (nRF24L01) => GND (Raspberry Pi Pico).
  • SCK (nRF24L01) => GP6 (Raspberry Pi Pico).
  • MOSI (nRF24L01) => GP7 (Raspberry Pi Pico).
  • MISO (nRF24L01) => GP4 (Raspberry Pi Pico).
  • IRQ (nRF24L01) => not connected
  • CE (nRF24L01) => GP12 (Raspberry Pi Pico).
  • CSN (nRF24L01) => GP5 (Raspberry Pi Pico).

We highly recommend that you add a 10 µF capacitor between the GND and VCC pins of the nRF24L01 module. This is a solution to consider if you notice erratic operation.

Installing the nrf24l01.py library

After downloading the nrf24l01.py library, it is important to install the nrf24l01.py file in the flash memory of the Raspberry Pi Pico (using, for example, Thonny).

This library is accompanied by a very well done program called “nrf24l01test.py”. To use it with the Raspberry Pi Pico, however, you will need to change the pin numbers at the start of the program.
Based on this example, you’ll find two separate scripts below. These scripts was designed to be used simultaneously on two different Raspberry Pi Picos. The first script is for the transmitter, and the other one is for the receiver.

The transmitter’s script

Each second, this Raspberry Pi Pico increments an integer number and sends it to the nRF24L01 module. It then checks whether it receives a response from the receiver.

"""
nRF24L01 transmitter
Raspberry Pi Pico and nRF24L01 module
Once per second, a numerical value is sent, and we
checks if we receive a response.
For more info:
www.bekyelectronics.com/raspberry-pico-nrf25l01-micropython/
"""
import ustruct as struct
import utime
from machine import Pin, SPI
from nrf24l01 import NRF24L01

# pin definition for the Raspberry Pi Pico:
myPins = {"spi": 0, "miso": 4, "mosi": 7, "sck": 6, "csn": 5, "ce": 12}

# Addresses (little endian)
pipes = (b"\xe1\xf0\xf0\xf0\xf0", b"\xd2\xf0\xf0\xf0\xf0")

print("NRF24L01 transmitter")

csn = Pin(myPins["csn"], mode=Pin.OUT, value=1)
ce = Pin(myPins["ce"], mode=Pin.OUT, value=0)
nrf = NRF24L01(SPI(myPins["spi"]), csn, ce, payload_size=8)

nrf.open_tx_pipe(pipes[0])
nrf.open_rx_pipe(1, pipes[1])
nrf.start_listening()

counter = 0  # Increase the value by 1 with each emission

while True:
    # Stop listening, time to send a message
    nrf.stop_listening()
    
    counter = counter + 1 # preparing the message to send
    print("sending:",  counter)
    
    try:
        nrf.send(struct.pack("i",  counter)) # sending the message
    except OSError:
        pass

    # Listen if the other Pico answers us
    nrf.start_listening()

    # Wait for 250ms max
    start_time = utime.ticks_ms()
    timeout = False
    while not nrf.any() and not timeout:
        if utime.ticks_diff(utime.ticks_ms(), start_time) > 250:
            timeout = True

    if timeout:  # no response received
        print("failure, no response")

    else:  # a response has been received
        (response,) = struct.unpack("i", nrf.recv())
        print ("response recue:", response)

    # Wait a second before sending the next message
    utime.sleep_ms(1000)

The receiver’s script

If this Raspberry Pi Pico receives a message from the transmitter, it calculates the modulo of the number received and returns the result to the transmitter. It therefore returns the number “0” when it receives an even number, and the number “1” when it receives an odd number.

"""
nRF24L01 receiver
Raspberry Pi Pico and nRF24L01 module.
If an integer is received, it is acknowledged by flipping its modulo.
For more info:
www.bekyelectronics.com/raspberry-pico-nrf25l01-micropython/
"""
import ustruct as struct
import utime
from machine import Pin, SPI
from nrf24l01 import NRF24L01
from micropython import const

# delay between receiving a message and waiting for the next message
POLL_DELAY = const(15)
# Delay between receiving a message and sending the response
# (so that the other pico has time to listen)
SEND_DELAY = const(10)

# Pico pin definition:
myPins = {"spi": 0, "miso": 4, "mosi": 7, "sck": 6, "csn": 5, "ce": 12}

# Addresses
pipes = (b"\xe1\xf0\xf0\xf0\xf0", b"\xd2\xf0\xf0\xf0\xf0")

csn = Pin(myPins["csn"], mode=Pin.OUT, value=1)
ce = Pin(myPins["ce"], mode=Pin.OUT, value=0)
nrf = NRF24L01(SPI(myPins["spi"]), csn, ce, payload_size=8)

nrf.open_tx_pipe(pipes[1])
nrf.open_rx_pipe(1, pipes[0])
nrf.start_listening()

print("nRF24L01 receiver; waiting for the first post...")

while True:
    if nrf.any(): # we received something
        while nrf.any():
            buf = nrf.recv()
            counter = struct.unpack("i", buf)
            print("message received:", counter[0])
            utime.sleep_ms(POLL_DELAY) # delay before next listening
            
        response = counter[0]%2 # preparing the response

        utime.sleep_ms(SEND_DELAY) # Give the other Pico a brief time to listen
        nrf.stop_listening()
        try:
            nrf.send(struct.pack("i", response))
        except OSError:
            pass
        print("reply sent:", response)
        nrf.start_listening()

That’s it, this is how you establish wireless communication between your Picos using NRF24L01. I hope this tutorial was helpful for you. You can check other tutorials from this link.

Twister: the brilliant OS for Raspberry Pi

Twister: the brilliant OS for Raspberry Pi

Since 2012, Raspberry Pi OS, formerly Raspbian, has been the go-to operating system for Raspberry Pi enthusiasts. Raspberry Pi OS is not the only operating system and a recent addition is Twister OS, which is based on Raspberry Pi OS, but it offers a larger selection of pre-installed apps and a choice of themes, some of which provide a Windows/macOS experience for the humble Pi.

In this tutorial, we will install Twister OS on a Raspberry Pi 4, then change the theme to suit Windows 10 and macOS. We’ll also take a look at the additional features of this excellent operating system, such as streaming media (Netflix, Amazon Prime, Hulu, Disney+) and games.

You can also use this OS with the Raspberry Pi 3B+. But for best performance, we recommend using a Raspberry Pi 4.

How to install Twister OS on the raspberry pi?

  • Download the latest version of Twister OS from this link which at the time of writing this article is v2.1.2.
  • Download balenaEtcher from here and install it.
  • Insert a micro SD card into your computer to install the OS on it.
  • Open balenaEtcher, select the Twister OS image, select the microSD card then click Flash to write the image.
  • Now, you can boot your Raspberry Pi from the microSD card.

On the first boot, you will see the Twister OS in all its glory. Stunning wallpaper and aesthetics that use the XFCE window manager to great effect. Twister OS is based on the latest version of Raspberry Pi OS (formerly Raspbian) and features all the applications found in a typical Raspberry Pi OS installation. Additional applications and themes provided by Twister OS are maintained and fixed by the Twister OS team.

Screenshot of the twister OS

Updating Twister OS

  • Check your internet connectivity.
  • From the main menu, select System >> Twister OS Patcher.
  • Follow the instructions to update and restart your Raspberry Pi.

Add a Windows or MacOS theme to your Twister OS

Twister OS is a chameleon, it can change its appearance in just a few clicks. If you want your OS to look like a Windows or Apple device, you can. The themes offered are of superb quality and really give the impression that we are using this OS.

To change the theme of your Twister OS just follow these steps:

  • On your desktop, Double-click on ThemeTwister.
  • Click Next to enter the theme selection screen.
  • Click the button below each theme to select it. A terminal window will appear and ask you to press Enter to restart.

Play with your Twister OS

Twister OS comes with a lot of gaming options. One can play classic PC games using DOSBOX x86Box, installable through PiKiss. Steam support is built into Twister OS, but don’t expect to rip demons in Doom Eternal, prefer simple 2D indie games.

Retro game players can play their game collections using RetroPie.

  • Install all the ROMs you have in /home/pi/RetroPie/roms selecting the correct system for each of the ROMs.
  • Connect a USB/Bluetooth gamepad
  • Double-click the RetroPie desktop icon and follow the on-screen instructions to set up your controller.
  • Choose the system for which you installed ROMs, and press the B button on your gamepad to select it.
  • Browse the game list and press B to play.

You can install the listed games in the Games Menu using PiKISS. Try AM2R: Return of Samus, an original game based on the Metroid series.

Play media files

There are several options for playing the videos and audio files. VLC and Parole media players allow playback through the desktop.

Kodi comes pre-installed on Twister OS and works exactly as you expect. Now enjoy loading up your media and streaming services on the big screen.

If you use streaming services like Amazon Prime Video, Netflix, Hulu, you can use the Chromium (Media Edition) version in the Internet menu to watch your favorite shows.

Control your Android device

The scrcpy app provides a way to interact with your Android device via USB debugging and it works remarkably well. It gives you the ability to control the device using a mouse and keyboard.

To set this up, follow these steps:

  • On your Android device, go to Settings >> About Phone and tap on Build Number until you enable the Developer Mode.
  • In Settings, find USB Debugging and select the first option.
  • Use the slider to enable USB debugging.
  • In Twister OS, click on the My Android icon. This will trigger a query on your Android device. Allow the request and your Android device will appear on the screen.

Using the keyboard and mouse, you can interact with the device now.

for other uses of the Raspberry Pi, check this link.

Launch a Python script when starting your Raspberry Pi

Launch a Python script when starting your Raspberry Pi

There are many projects where, to work, you had to run a Python script. For example for a control station, a Jukebox with RFID chip, or a security alarm system.

The problem is that it is quite annoying to have to launch it by hand each time the Raspberry Pi starts… Because that means always having a keyboard, a mouse and a screen plugged in, or logging in by SSH to launch it.

One solution is to start the Python script as soon as the Raspberry Pi boots up, and we’ll see how to do that in this article.

Don’t know what a raspberry pi is? check this link.

Create a shell script

In the user folder, you have to create a shell file that will contain the commands to run to launch the Python script.

cd /home/pi
nano launch.sh

Code explanation:

The first line “cd /home/pi” allows you to move into your user directory.

The command “nano launch.sh” will create the file “launch.sh” and will open the nano text editor so that we can write in the file.

In the file, write the commands to run your Python script:

cd /home/pi/my-program
python3 my-program.py

Save the file by pressing ”Ctrl + X”, confirm by pressing “O” and validate you choice by pressing Enter.

Make the file executable

Before you can use this shell file, you have to make it executable:

chmod 755 launch.sh

Test your file and check that your python script is launched with the command:

sh launch.sh

If everything works, you can move on to the next step.

Create a log file

In your user directory, create a “logs” folder which will contain the various log files of your programs. They will be used to have a written trace in you have an error in your program.

mkdir /home/pi/logs

Add your file to crontab

crontab is a process for running scripts in the background. It will execute scripts and commands at specific times or during specific events.

To add a new command in crontab:

sudo crontab -e

At the bottom of the file, add the line:

@reboot sh /home/pi/launch.sh > /home/pi/logs/log.txt 2>&1

This line will allow you executing the command “sh /home/pi/launch.sh” when starting the Raspberry Pi, and will save error messages and logs in the file “/home/pi/logs/log.txt ”.

Save with the shortcut “Ctrl + X“.

Check that everything is working

Reboot your Raspberry Pi:

reboot

If your program did not launch or there is a problem, check the log file to see if any errors have occurred.

That’s the end of this tutorial, I hope that tutorial could help you!

Write a comment below and tell us what will you use this script for?