MicroPython IO_Expander_Read

Here all sensor information are read out by the IOExpander via I2C. The readout is done by the function fetchSensorData(). No transfer parameters are required. The return value is a dictionary which contains the following information:

0:   Speed-Sensor Left

1:   Speed-Sensor Right

2:   LineTracking-Sensor Left

3:   LineTracking-Sensor Middle

4:   LineTracking-Sensor Right

5:   Obstacle-Sensor Left

6:   Obstacle-Sensor Right

7:   Optional Sensor

The individual parameters specify the sensor status as a boolean variable. True stands for a HIGH detection and False for a LOW detection.

Additional information: The function zfill(s, width) is used in this file. It is actually part of Python but was omitted during the port to the Micro:Bit for memory reasons. However, the function is relevant for reading sensor data and was therefore added by us. If you create your own files that read out the sensor data, this function is necessary and should also be used.

# Import of the micro:bit module
from microbit import *

# Initialization of the I2C interface
i2c.init(freq = 400000, sda = pin20, scl = pin19)

# Since the zfill function is not included in micro:bit Micropython, it must be inserted as a function
def zfill(s, width):
    return '{:0>{w}}'.format(s, w=width)

# Read out IO Expander data and store in sen_data
def fetchSensorData():
    data = "{0:b}".format(ord(i2c.read(0x38, 1))) # Read hexadecimal data and convert to binary
    data = zfill(data, 8)  # fill up the data to 8 digits if necessary
    bol_data_dict = {}  # declare bol_data_dict as dictionary
    bit_count = 7  # Counter for the loop that enters the data from data into bol_data_dict
    # Transfer data from data in bol_data_dict
    for i in data:
        if i == "0":
            bol_data_dict[bit_count] = False
            bit_count -= 1
        else:
            bol_data_dict[bit_count] = True
            bit_count -= 1
    # Transfer data to the global variable sen_data
    return bol_data_dict  # bit 0 = SpeedLeft, bit 1 = SpeedRight, bit 2 = LineTrackerLeft, bit 3 = LineTrackerMiddle, bit 4 = LineTrackerRight, bit 5 = ObstclLeft, bit 6 = ObstclRight, bit 7 = Buzzer


# while loop executes and displays the showSensorData with an interval of one second
while True:
    sen_data = fetchSensorData()
    print("\n\naus der Variable sen_data")
    print(sen_data)
    sleep(1000)
    print("\n\ndirekt aus der Funktion fetchSensorData()")
    print(fetchSensorData())
    sleep(1000)

Achtung!

Ihr Webbrowser ist veraltet. Wechseln Sie jetzt zu einem aktuellen Browser für mehr Sicherheit, Geschwindigkeit und den besten Komfort auf dieser Seite.