# 3. Raspberry Pi Development Tutorial
## 3.1 Preparation
### 3.1.1 Wiring Instructions
When connecting the wires, make sure the 5V, GND, SDA, and SCL pins of the illuminated ultrasonic module are connected to the corresponding pins on the Raspberry Pi.
>[!Note]
>
>* **If using our lithium battery, connect the battery adapter wires to the DC port with red to+and black to-.**
>
>* **If the adapter wires are not connected to a lithium battery, do not connect them directly to the battery wires, to avoid short circuits caused by reversing the positive and negative poles.**
>
>* **Before powering on, ensure that no metal objects touch the main board, as contact with the pins on the underside may cause a short circuit and permanently damage the board.**
### 3.1.2 Environment Configuration
Install NoMachine on your computer. The installation package can be found under:**"[Remote Desktop Connection Tool](https://drive.google.com/drive/folders/1P08EEaZwiF0cLTBwIXFhv4Wh-e0CScD5?usp=sharing)"**.
For detailed instructions on using NoMachine, please refer to the corresponding directory.
Drag the program into the Raspberry Pi system image-for example, place it on the desktop. Note: The library files must be in the same directory as the program.
Open a terminal and navigate to the directory containing the program, then enter the following command:
```bash
sudo chmod a+x Sonar.py
```
## 3.2 Test Example
his example demonstrates how the glowy ultrasonic sensor displays measured values in the terminal window and changes the LED colors based on the detected distance.
### 3.2.1 Program Running
Open the terminal, and execute the command to run the program.
```bash
python3 Sonar.py
```
### 3.2.2 Program Outcome
The glowy ultrasonic module will print the detected target distance in the terminal,while the RGB LEDs on the module will change colors gradually corresponding to the measured distance.
### 3.2.3 Brief Analysis of the Example Program
* **Library Imports and Python Version Check**
```python
import os
import sys
import time
import smbus
from smbus2 import SMBus, i2c_msg
```
The program imports several libraries, including `os`, `sys`, `time`, and `smbus`, and also checks the Python version to ensure smooth execution. The purposes of these libraries are as follows:
(1) `os`: Provides functions for interacting with the operating system.
(2) `sys`: Part of the Python interpreter, used for interacting with it, such as running command-line commands or accessing program arguments.
(3) `time`: Provides time-related functions, such as setting timers or calculating time differences.
(4) `smbus`: A library for I2C communication, providing an interface to communicate with I2C devices.
* **Instantiate the Class**
```python
class Sonar:
__units = {"mm":0, "cm":1}
__dist_reg = 0
__RGB_MODE = 2
__RGB1_R = 3
__RGB1_G = 4
__RGB1_B = 5
__RGB2_R = 6
__RGB2_G = 7
__RGB2_B = 8
__RGB1_R_BREATHING_CYCLE = 9
__RGB1_G_BREATHING_CYCLE = 10
__RGB1_B_BREATHING_CYCLE = 11
__RGB2_R_BREATHING_CYCLE = 12
__RGB2_G_BREATHING_CYCLE = 13
__RGB2_B_BREATHING_CYCLE = 14
```
Instantiate the illuminated ultrasonic sensor class, while also defining its relevant properties, such as the measured distance, the RGB LED colors, and the breathing light mode.
* **Instantiate the Function**
```python
def __init__(self):
self.i2c_addr = 0x77
self.i2c = 1
self.R1 = 0
self.G1 = 0
self.B1 = 0
self.R2 = 0
self.G2 = 0
self.B2 = 0
self.RGBMode = 0
self.bus = SMBus(self.i2c)
```
Define the I²C address of the ultrasonic module, as well as the RGB LED colors and lighting modes.
* **Get Distance Function**
```python
def __getattr(self, attr):
if attr in self.__units:
return self.__units[attr]
if attr == "Distance":
return self.getDistance()
else:
raise AttributeError('Unknow attribute : %s'%attr)
```
When the conditions are met, the `getDistance` function retrieves the current measured distance to the target. Otherwise, an error message will be displayed.
* **Set the Lighting Mode for the Glowy Ultrasonic Sensor**
```python
#Set the LED mode: 0 = color mode, 1 = breathing mode
def setRGBMode(self, mode):
try:
self.bus.write_byte_data(self.i2c_addr, self.__RGB_MODE, mode)
except:
print('Sensor not connected!')
#Set the LED color
#Parameter 1: 0 = left LED, 1 = right LED
#Parameter 2: RGB color values as a tuple, range 0–255, in the order (r, g, b)
def setRGB(self, index, rgb):
start_reg = 3 if index == 1 else 6
try:
self.bus.write_byte_data(self.i2c_addr, start_reg, rgb[0])
self.bus.write_byte_data(self.i2c_addr, start_reg+1, rgb[1])
self.bus.write_byte_data(self.i2c_addr, start_reg+2, rgb[2])
except:
print('Sensor not connected!')
#Breathing light mode
#Parameter 1: 0 = left LED, 1 = right LED
#Parameter 2: Color channel: 0 = red, 1 = green, 2 = blue
#Parameter 3: Color change cycle, in milliseconds
def setBreathCycle(self, index, rgb, cycle):
start_reg = 9 if index == 1 else 12
cycle = int(cycle / 100)
try:
self.bus.write_byte_data(self.i2c_addr, start_reg + rgb, cycle)
except:
print('Sensor not connected!')
def startSymphony(self):
self.setRGBMode(1)
self.setBreathCycle(1, 0, 2000)
self.setBreathCycle(1, 1, 3300)
self.setBreathCycle(1, 2, 4700)
self.setBreathCycle(0, 0, 4600)
self.setBreathCycle(0, 1, 2000)
self.setBreathCycle(0, 2, 3400)
```
The setRGBMode function is used to set the RGB mode of the illuminated ultrasonic module, while setRGB sets the color of the corresponding LED. The indices 0 and 1 represent the left and right ultrasonic LEDs, respectively. The setBreathCycle function is used to configure the breathing light mode.
This function accepts three parameters:
(1) Index - 0 or 1,representing the left or right LED.
(2) Color channel - 0,1, or 2, representing red, green, or blue.
(3) Cycle period - the duration of the color change in milliseconds.
The main controller will attempt to write the cycle value to the device via the I2C interface. If the device is not connected, an error message will be printed in the terminal.
Next is the startSymphony function, which sets the breathing effect for the illuminated ultrasonic LEDs. It first calls setRGBMode(1) to configure the RGB mode, and then the breathing effect for the red, green, and blue LEDs is set individually. The `setBreathCycle` function is called again to define the breathing effect,with the three parameters specifying the LED index(left or right), the color channel,and the breathing cycle period.
* **Acquire Detection Distance**
```python
#Acquire the distance in mm
def getDistance(self):
dist = 5000
try:
msg = i2c_msg.write(self.i2c_addr, [0,])
self.bus.i2c_rdwr(msg)
read = i2c_msg.read(self.i2c_addr, 2)
self.bus.i2c_rdwr(read)
dist = int.from_bytes(bytes(list(read)), byteorder='little', signed=False)
if dist > 5000:
dist = 5000
except BaseException as e:
print('Sensor not connected!', e)
return dist
```
Call the getDistance function to read the I2C pins of the ultrasonic module, obtain the current distance to the target obstacle, and return the value.
* **Print the Detected Distance Data**
```python
if __name__ == '__main__':
s = Sonar()
s.setRGBMode(0)
s.setRGB(1, (35, 205, 55))
s.setRGB(0, (235, 205, 55))
s.startSymphony()
while True:
time.sleep(0.1)
print('distance: {}(mm)'.format(s.getDistance()))
```
Within the loop, the terminal will continuously print the obstacle distance data detected by the ultrasonic module.