Skip to content

Implementation of example with VL6180X sensor #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 21 commits into from
Mar 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
bc3ce2b
Implementation of VL6180X sensor
tomekmalek Nov 18, 2022
90f4f9e
Improvement of information message when GPIO is not present.
tomekmalek Nov 29, 2022
ad27dbb
Creation of class for VL6180X in hal.py. Adding support for ESP8266 a…
tomekmalek Dec 6, 2022
937c46d
Adding function recognizing I2C interface. Unification of range measu…
tomekmalek Dec 8, 2022
ddfa77e
Improved version working on PC@Ubuntu, Raspberry Pi, ESP32, GPy, LoPy…
tomekmalek Dec 9, 2022
7e6c638
Version with own library vl6180x_micro.py working on ESP8266 (and pro…
tomekmalek Dec 9, 2022
9b1b886
Correction of get_i2c()
tomekmalek Dec 9, 2022
f71c7a2
Correction of get_i2c()
tomekmalek Dec 9, 2022
9014e02
Introducing customized VL6180X library.
tomekmalek Dec 14, 2022
7f01c93
Merge remote-tracking branch 'origin/mod_vl6180x'
tomekmalek Dec 14, 2022
55a938c
Improving message regarding I2C.
tomekmalek Dec 14, 2022
69edca9
Using default VL6180X address (0x29)
tomekmalek Dec 15, 2022
8d7d541
Improvement of VL6180X library.
tomekmalek Dec 15, 2022
bcb19bb
Implementation of default value of gain for function responsible for …
tomekmalek Dec 16, 2022
15a1b97
Adding libraries for micropython.
tomekmalek Dec 16, 2022
a015a6a
Readme for Python updating.
tomekmalek Dec 16, 2022
904bee3
Readme for microPython updating.
tomekmalek Dec 16, 2022
0e4488e
Readme update with wiring.
tomekmalek Dec 19, 2022
a573905
Adding "model" to MQTT payload to improve LO line chart dashboard.
tomekmalek Feb 1, 2023
8e12c06
Adding new pair SDA, SCL in hal.py.
tomekmalek Feb 7, 2023
07fe0e0
README.md update
tomekmalek Mar 12, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions 7_distance_and_light_sensor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#
# Copyright (C) Orange
#
# This software is distributed under the terms and conditions of the 'MIT'
# license which can be found in the file 'LICENSE.md' in this package distribution
import sys
import time
import LiveObjects

# Create LiveObjects
lo = LiveObjects.Connection()
sensor = LiveObjects.SensorVL6180X()

MESSAGE_RATE = 5

# Main program
lo.connect() # Connect to LiveObjects
last = uptime = time.time()

while True:
if (time.time()) >= last + MESSAGE_RATE:
lo.add_to_payload("distance", sensor.range)
lo.add_to_payload("ambient_light", sensor.amb_light())
lo.send_data() # Sending data to cloud
last = time.time()
lo.loop() # Check for incoming messages and if connection is still active
1 change: 1 addition & 0 deletions LiveObjects/Connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,7 @@ def get_parameter(self, name):
return 0

def add_to_payload(self, name, val):
self.add_model("Orange")
self.__payload[self.__value][name] = val

def set_object_as_payload(self, val):
Expand Down
62 changes: 61 additions & 1 deletion LiveObjects/hal.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,10 +210,70 @@ def get_client_id(self):
return self.get_lang_str() + ':' + get_mac()


class BoardsFactory:
class RaspberryPi(Linux):
pass


def is_raspberrypi():
try:
with open('/proc/device-tree/model') as f:
return f.read().startswith('Raspberry')
except FileNotFoundError:
return False


class BoardsFactory:
def __new__(cls, net_type):
s = sys.platform
sn = s[0].upper() + s[1:] # capitalize first letter
if sn == 'Linux':
sn = 'RaspberryPi' if is_raspberrypi() else 'Linux'
board = eval(sn)(net_type) # instance of board w/ net type: WiFi, LTE, etc.
return board


MAX_DEV_NB = 20


def get_i2c():
import machine
typical_gpio = ([22, 23], [5, 4], [22, 21], [23, 18])
for gpio in typical_gpio:
scl, sda = gpio
i2c = None
try: # MicroPython 1.19.1 20220618-v1.19.1
i2c = machine.SoftI2C(scl=machine.Pin(scl), sda=machine.Pin(sda), freq=100000)
if i2c.scan() and len(i2c.scan()) < MAX_DEV_NB:
return i2c
except ValueError: # next sda, scl
pass
except AttributeError: # Pycom MicroPython 1.20.2.r6 [v1.11-c5a0a97] on 2021-10-28
i2c = machine.I2C(0)
return i2c
del i2c
raise RuntimeError("No I2C devices found. Check SDA and SCL lines and add respective GPIO to 'typical_gpio'.")


class SensorVL6180X:
def __new__(cls):
try: # Python@RPi
import busio
import adafruit_vl6180x
import board

class VL6180X(adafruit_vl6180x.VL6180X):
def amb_light(self):
"""Implementing default gain"""
return self.read_lux(gain=0x06) # ALS_GAIN_1

i2c = busio.I2C(board.SCL, board.SDA)
return VL6180X(i2c)

except ImportError: # microPython
import vl6180x_micro
i2c = get_i2c()
return vl6180x_micro.Sensor(i2c)

except NotImplementedError: # if no I2C device
print("No GPIO present.")
sys.exit()
104 changes: 99 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Prototype with Orange using Live Objects
### Discover Orange [**Live Objects**](https://liveobjects.orange-business.com) using dedicated SDK for **Python and uPython compatible** boards and systems.
### Discover Orange [**Live Objects**](https://liveobjects.orange-business.com) using dedicated SDK for **Python 3 and uPython compatible** boards and systems.

This code wraps all the functions necessary to make your object work with Live Objects.

Expand All @@ -23,7 +23,7 @@ Code uses MQTT connection to exchange data with Live objects under the hood to k
This code needs a few libraries to run:
- Python needs [paho-mqtt](https://pypi.org/project/paho-mqtt/)
- Python for Windows needs [python-certifi-win32](https://pypi.org/project/python-certifi-win32/)
- uPython needs [umqttsimple, umqttrobust and ssl](https://github.com/micropython/micropython-lib)
- uPython needs [umqttsimple](https://github.com/micropython/micropython-lib/blob/master/micropython/umqtt.simple/umqtt/simple.py) and [umqttrobust](https://github.com/micropython/micropython-lib/blob/master/micropython/umqtt.robust/umqtt/robust.py)

## How to use ##

Expand Down Expand Up @@ -236,12 +236,55 @@ You need to override specific methods - e.g. `connect` which is depended on type
All specific functions are placed in `services.py`.
If your board needs function supporting its equipment you need to put it in this file.

## VL6180X Sensor use-case ##

We can connect sensor using I<sup>2</sup>C to board supporting Python like **Raspberry Pi**.

The [VL6180X](https://www.st.com/en/imaging-and-photonics-solutions/vl6180x.html) is the latest product based on ST’s patented FlightSense™technology.
This is a ground-breaking technology allowing absolute distance to be measured independent of target reflectance.
Instead of estimating the distance by measuring the amount of light reflected back from the object (which is significantly influenced by color and surface),
the VL6180X precisely measures the time the light takes to travel to the nearest object and reflect back to the sensor (Time-of-Flight).
Description from st.com.

### Prerequisites ###

#### Enabling I<sup>2</sup>C ####
Enable (if needed) **I<sup>2</sup>C** interface on your Raspberry Pi using terminal and command:
```bash
sudo raspi-config
```
and selecting: **3 Interface Options** -> **P5 I2C** -> **\<Yes\>**

![I2C_Enabling](image/enable_I2C.png)

#### Wiring ####
![Wiring](https://www.raspberrypi-spy.co.uk/wp-content/uploads/2012/06/Raspberry-Pi-GPIO-Header-with-Photo-768x512.png "Mapping")

<br>

Example of development module using VL6180X you can find [here](https://kamami.pl/en/kamod-kamami-peripheral-modules/559362-kamodvl6180x-a-module-with-distance-gesture-and-als-sensor.html). Below diagram shows how to connect it to Raspberry Pi.

![Schematics](image/RPi_VL6180X.png "Schematics")

#### Adding VL6180X Python module ####
Necessary module by [Adafruit](https://learn.adafruit.com/adafruit-vl6180x-time-of-flight-micro-lidar-distance-sensor-breakout/python-circuitpython) can be installed using `pip`
```bash
pip3 install adafruit-circuitpython-vl6180x
```

#### How to use ####
To run you need to use below command:
```bash
python3 7_distance_and_light_sensor.py
```

---

# Installation guide for uPython #
## Example for ESP32 / ESP8266 ##
### Requirements ###
1. [ampy](https://learn.adafruit.com/micropython-basics-load-files-and-run-code/install-ampy)
2. [umqttsimple, umqttrobust and ssl](https://github.com/micropython/micropython-lib)
2. [umqttsimple, umqttrobust and ssl](https://github.com/micropython/micropython-lib) (for your convenience they are included in `micropython` folder)
3. [PuTTY](https://www.putty.org/) (for Windows)

### Installation steps ###
Expand All @@ -264,6 +307,7 @@ You can use one of example ones (`1_send_data.py`, ...) renaming it to `main.py`
> ampy -pCOMXX put main.py
```


4. Connect to device and check if it's working using PuTTY

Ctrl + D soft resets device
Expand All @@ -274,25 +318,75 @@ You can use one of example ones (`1_send_data.py`, ...) renaming it to `main.py`

After all steps content of the device should look like below:
```commandline
> ampy -pCOMXX ls
> ampy --port COMx ls
/LiveObjects
/boot.py
/main.py
/umqttrobust.py
/simple.py

> ampy -pCOMXX ls LiveObjects
> ampy --port COMx ls LiveObjects
/LiveObjects/Connection.py
/LiveObjects/__init__.py
/LiveObjects/hal.py
/LiveObjects/credentials.py
/LiveObjects/services.py
```
where COMx means port on your computer (e.g. COM8) with connected microPython board.

## Example for LoPy / GPy ##

You can do the steps as above but better is to use [Pymakr plug-in](https://pycom.io/products/supported-networks/pymakr/) for **Visual Studio Code** or **Atom** delivered by [Pycom](https://pycom.io/).
Plug-in supports code development, its upload to the board and communication with board.

## VL6180X Sensor use-case ##

Sensor described in this [section](#vl6180x-sensor-use-case) can be used on boards supporting microPython.

### Prerequisites ###

#### Wiring ####
You need to connect I<sup>2</sup>C interface (SCL & SDA) and power lines on the board with corresponding pins on the sensor.
You need to be aware that **boards can use different GPIOs for I<sup>2</sup>C** purposes. Set of typical pairs is placed
in function `get_i2c()` in file `hal.py`. If your board uses other GPIO pins, you need to add them to the tuple `typical_gpio`.
```Python
def get_i2c():
import machine
typical_gpio = ([22, 23], [5, 4], [22, 21])
...
```
![ESP32_sch](image/ESP32_VL6180X_sch.png)

Example of wiring ESP32 board with GPIO22 and GPIO21 (_source: https://randomnerdtutorials.com/esp32-pinout-reference-gpios/_)

![ESP32](image/ESP32_VL6180X.jpg)

#### How to use ####
1. You need to upload additional library for VL6180X support (it is placed in `micropython` folder):
```commandline
> ampy -pCOMXX put vl6180x_micro.py
```
2. Copy `7_distance_and_light_sensor.py` as `main.py` and upload it into board.

After above operations you can see:
```commandline
> ampy --port COMx ls
/LiveObjects
/boot.py
/main.py
/umqttrobust.py
/simple.py
/vl6180x_micro.py

> ampy --port COMx ls LiveObjects
/LiveObjects/Connection.py
/LiveObjects/__init__.py
/LiveObjects/hal.py
/LiveObjects/credentials.py
/LiveObjects/services.py
```
3. Connect to device and check if it's working using PuTTY.


## Troubleshooting ##
If you are getting 'MQTT exception: 5' check your api key
Binary file added image/ESP32_VL6180X.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added image/ESP32_VL6180X_sch.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added image/RPi_VL6180X.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added image/enable_I2C.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading