[Diao Ye Learns Programming] MicroPython Manual WiPy I2C Bus

Insert image description here
MicroPython is a lightweight version of the interpreter designed for running the Python 3 programming language in embedded systems. Compared with regular Python, the MicroPython interpreter is small (only about 100KB) and is compiled into a binary Executable file to run, resulting in higher execution efficiency. It uses a lightweight garbage collection mechanism and removes most of the Python standard library to accommodate resource-constrained microcontrollers.

The main features of MicroPython include:
1. The syntax and functions are compatible with standard Python, making it easy to learn and use. Supports most of Python's core syntax.
2. Directly access and control hardware, control GPIO, I2C, SPI, etc. like Arduino.
3. Powerful module system, providing file system, network, graphical interface and other functions.
4. Support cross-compilation to generate efficient native code, which is 10-100 times faster than the interpreter.
5. The amount of code is small and the memory usage is small. It is suitable for running on MCU and development boards with small memory.
6. Open source license, free to use. The Shell interactive environment provides convenience for development and testing.
7. The built-in I/O driver supports a large number of microcontroller platforms, such as ESP8266, ESP32, STM32, micro:bit, control board and PyBoard, etc. There is an active community.

MicroPython application scenarios include:
1. Rapidly build prototypes and user interactions for embedded products.
2. Make some small programmable hardware projects.
3. As an educational tool, it helps beginners learn Python and IoT programming.
4. Build smart device firmware to achieve advanced control and cloud connectivity.
5. Various microcontroller applications such as Internet of Things, embedded intelligence, robots, etc.

Things to note when using MicroPython:
1. Memory and Flash space are limited.
2. The explanation and execution efficiency is not as good as C language.
3. Some library functions are different from the standard version.
4. Optimize the syntax for the platform and correct the differences with standard Python.
5. Use memory resources rationally and avoid frequently allocating large memory blocks.
6. Use native code to improve the performance of speed-critical parts.
7. Use abstraction appropriately to encapsulate underlying hardware operations.

Generally speaking, MicroPython brings Python into the field of microcontrollers, which is an important innovation that not only lowers the programming threshold but also provides good hardware control capabilities. It is very suitable for the development of various types of Internet of Things and intelligent hardware.
Insert image description here
WiPy is a MicroPython-based wireless microcontroller module that provides a complete hardware and software solution designed to simplify the development and deployment of Internet of Things (IoT) devices.

1. Microcontroller module: WiPy is a microcomputer module that integrates a processor, memory, wireless communication module and other necessary components. It is designed to provide a compact, low-power hardware platform capable of running high-level programming languages ​​​​such as MicroPython and having the ability to connect to the Internet and other devices.
2. MicroPython: MicroPython is a streamlined version of the Python programming language, specially developed for embedded systems and microcontroller design. It provides the core functions and syntax of the Python language, allowing developers to use familiar Python syntax for hardware control and IoT application development. As the operating environment of MicroPython, WiPy can directly interpret and execute MicroPython code.
3. Internet of Things (IoT): The Internet of Things refers to a network that connects various physical devices (such as sensors, actuators, embedded systems, etc.) through the Internet to achieve intelligence and interconnection. As a wireless microcontroller module, WiPy has wireless communication capabilities and can be connected to other devices and cloud platforms in the Internet of Things to achieve remote control and data exchange.
4. Wireless communication module: WiPy has one or more built-in wireless communication modules, common ones including Wi-Fi, Bluetooth, LoRa, etc. These wireless communication modules enable WiPy to communicate with other devices through wireless networks to achieve data transmission, remote control, cloud connection and other functions. Developers can choose appropriate wireless communication modules based on specific needs.
5. Development and deployment: WiPy provides a set of convenient development tools and development environment, allowing developers to quickly develop, debug and test applications. Once developed, WiPy can be deployed directly into actual IoT devices to communicate and interact with other devices. WiPy's compact design and low power consumption make it ideal for deployment in embedded systems and IoT devices.

Insert image description here
MicroPython's WiPy I2C (Inter-Integrated Circuit) bus is an interface technology used for serial communication.

main feature:

Simplified hardware connection: WiPy I2C bus uses a two-wire connection method, including data line (SDA) and clock line (SCL). Compared with other serial communication buses, such as the SPI bus, its hardware connection is simpler and only requires two wires to achieve communication.
Multi-device support: The WiPy I2C bus supports the connection of multiple devices, each with a unique address. Through the device address and chip select mechanism, communication with multiple devices can be achieved, with high flexibility.
Low power consumption: The WiPy I2C bus adopts the master-slave mode during the transmission process. The master device initiates communication and controls the timing of the transmission. When the slave device is not working, it can be set to low power mode to save energy.
Software programmable: The WiPy I2C bus can be configured and controlled through software, including the setting of device address, transmission rate, clock frequency and other parameters. This software programmability allows the WiPy I2C bus to adapt to a variety of different application needs.

Application scenarios:

Sensor to Microcontroller Communication: WiPy I2C bus is widely used for communication between sensors and microcontrollers. For example, it can interact with temperature sensors, humidity sensors, accelerometers and other sensors to realize functions such as environmental monitoring and object positioning.
Expansion module connection: WiPy I2C bus can be used to connect various expansion modules, such as display modules, expansion storage modules, etc. Through the I2C bus, data exchange and control operations with these modules can be realized.
Multi-device control: The WiPy I2C bus supports the connection of multiple devices, so it is suitable for application scenarios that require controlling multiple devices at the same time. For example, a controller in a smart home system can communicate and control multiple sensors, actuators and other devices through the I2C bus.
Real-time clock (RTC) module: The WiPy I2C bus is often used to connect real-time clock modules to provide accurate time information. This is important for applications that require timestamp logging or time synchronization.

Precautions:

Hardware compatibility: When using the WiPy I2C bus, you need to ensure hardware compatibility between the external device and WiPy. Check parameters such as voltage and signal levels of your devices to ensure they are connecting and communicating correctly.
Device address conflict: When connecting multiple devices to the WiPy I2C bus, you need to pay attention to the uniqueness of the device address. Make sure each device has a different address to avoid address conflicts causing communication errors.
Power and ground connections: When connecting WiPy to external devices, power and ground connections need to be made correctly. Make sure the power supply is stable and reliable, and keep the ground wire well connected to avoid power noise and signal interference.

To summarize, MicroPython's WiPy I2C bus is an interface technology used for serial communication. It features simplified hardware connectivity, multi-device support, low power consumption and software programmability. The WiPy I2C bus plays an important role in application scenarios such as sensor and microcontroller communication, expansion module connection, and multi-device control. When using the WiPy I2C bus, you need to pay attention to hardware compatibility, device address conflicts, and power and ground connection to ensure the reliability and stability of communication.

Insert image description here
Case 1: Reading SMBus sensor data using I2C bus

import machine  
import smbus  
  
# 设置I2C总线参数  
I2C = machine.I2C(scl=machine.Pin(22), sda=machine.Pin(21), freq=400000)  
  
# 初始化SMBus传感器  
sensor = smbus.SMBus(I2C)  
  
# 读取传感器数据  
sensor_address = 0x50  # 传感器地址,根据实际传感器设置。  
register_address = 0x00  # 传感器寄存器地址,根据实际传感器设置。  
data = sensor.read_byte_data(sensor_address, register_address)  
  
# 打印传感器数据  
print("传感器数据:", data)

Case 2: Using I2C bus to control LED lights

import machine  
import utime  
  
# 设置I2C总线参数  
I2C = machine.I2C(scl=machine.Pin(22), sda=machine.Pin(21), freq=400000)  
  
# 初始化LED灯  
led = machine.Pin(5, machine.Pin.OUT)  
  
# 循环控制LED灯闪烁  
while True:  
    led.toggle()  
    utime.sleep(1)

Case 3: Using I2C bus to control Raspberry Pi light sensor

import machine  
import time  
import sensor  # 导入树莓派光感器库  
  
# 设置I2C总线参数  
I2C = machine.I2C(scl=machine.Pin(22), sda=machine.Pin(21), freq=400000)  
  
# 初始化光感器  
sens = sensor.TCS34725()  # 假设使用TCS34725光感器芯片  
sens.setup()  # 初始化光感器芯片  
sens.set_gain(3)  # 设置增益,这里设置为3倍。  
sens.set_integration_time(14)  # 设置积分时间,这里设置为14ms。  
sens.enable(True)  # 启用光感器。  
  
# 循环读取光感器数据  
while True:  
    data = sens.read()  # 读取光感器数据。  
    print("光感器数据:", data)  # 打印光感器数据。  
    time.sleep(1)  # 等待1秒。

Case 4: Reading I2C data using MicroPython

from machine import I2C, Pin
import time

i2c = I2C(scl=Pin(5), sda=Pin(4))

while True:
    # 读取I2C数据
    data = i2c.readfrom(0x3f)
    print("Received data: {0}".format(data))
    time.sleep(1)  # 延时1秒

Case 5: Using MicroPython to send I2C data

from machine import I2C, Pin
import time

i2c = I2C(scl=Pin(5), sda=Pin(4))

while True:
    # 发送字符串数据
    i2c.writeto(0x3f, "Hello, world!")
    time.sleep(1)  # 延时1秒

Case 6: Use MicroPython to control the brightness of LED lights

from machine import Pin, PWM
import time

# 初始化引脚12为PWM输出模式
led = PWM(Pin(12), duty=50)

while True:
    # 设置占空比为75%
    led.duty(75)
    time.sleep(1)  # 延时1秒
    # 设置占空比为25%
    led.duty(25)
    time.sleep(1)  # 延时1秒

Case 7: Reference code example for connecting an LCD display using the I2C bus:

# 导入必要的模块
from machine import I2C, Pin
from lcd160cr import LCD160CR # 从 https://github.com/micropython/micropython/tree/master/drivers/display 下载

# 初始化I2C总线和LCD对象
i2c = I2C(0, mode=I2C.MASTER, baudrate=1000000, polarity=0, phase=0)
lcd = LCD160CR('X') # LCD160CR显示屏连接到X端口

# 清除屏幕
lcd.erase()
lcd.show()

# 显示一些文本
lcd.set_font(1, 0) # 设置字体为1号,颜色为黑色
lcd.set_pos(0, 0) # 设置光标位置为左上角
lcd.write('Hello from WiPy') # 写入文本
lcd.show()

# 显示一些图形
lcd.rect(10, 30, 140, 100, lcd.rgb(255, 0, 0), lcd.rgb(0, 255, 0)) # 画一个红色边框绿色填充的矩形
lcd.circle(80, 80, 40, lcd.rgb(0, 0, 255), lcd.rgb(255, 255, 255)) # 画一个蓝色边框白色填充的圆形
lcd.line(40, 40, 120, 120, lcd.rgb(255, 255, 0)) # 画一条黄色的直线
lcd.show()

:

Case 8: Reference code case for connecting an MPU6050 gyroscope acceleration sensor using the I2C bus:

# 导入必要的模块
from machine import I2C, Pin
from mpu6050 import MPU6050 # 从 https://github.com/adamjezek98/MPU6050-ESP8266-MicroPython 下载
import network
import time
import ubinascii
from umqtt.simple import MQTTClient

# 初始化I2C总线和MPU6050对象
i2c = I2C(0, mode=I2C.MASTER, baudrate=1000000, polarity=0, phase=0)
mpu = MPU6050(i2c)

# 连接到WLAN网络
wlan = network.WLAN(mode=network.WLAN.STA)
wlan.connect('your_ssid', auth=(network.WLAN.WPA2, 'your_password'))
while not wlan.isconnected():
    time.sleep_ms(50)

# 创建一个MQTT客户端对象,并连接到MQTT服务器
client_id = ubinascii.hexlify(machine.unique_id())
client = MQTTClient(client_id, 'your_mqtt_server')
client.connect()

# 定义姿态数据主题和间隔时间(秒)
topic_accel = b'wipy/acceleration'
topic_gyro = b'wipy/gyroscope'
interval = 1

# 循环读取并发送姿态数据
while True:
    try:
        # 读取加速度和角速度数据,返回值是三轴的元组(单位分别是g和度/秒)
        accel = mpu.get_accel_data()
        gyro = mpu.get_gyro_data()
        print('Acceleration: {} g'.format(accel))
        print('Gyroscope: {} deg/s'.format(gyro))

        # 将姿态数据转换为字节串,并发送到MQTT服务器
        client.publish(topic_accel, str(accel))
        client.publish(topic_gyro, str(gyro))

        # 等待一段时间
        time.sleep(interval)

    except Exception as e:
        # 如果发生异常,打印异常信息,并重试
        print(e)
        time.sleep(1)

Case 9: Reference code example for connecting an EEPROM chip using the I2C bus:

# 导入必要的模块
from machine import I2C, Pin
import time

# 初始化I2C总线和EEPROM对象
i2c = I2C(0, mode=I2C.MASTER, baudrate=1000000, polarity=0, phase=0)
eeprom = 0x50 # EEPROM的I2C地址

# 定义一个辅助函数,用于将16位的地址转换为两个8位的字节
def addr_to_bytes(addr):
    return bytes([addr >> 8, addr & 0xff])

# 写入一些数据到EEPROM的指定地址(假设为0x0000)
data = b'Hello from WiPy'
i2c.writeto_mem(eeprom, 0x0000, data)
time.sleep_ms(10) # 等待写入完成

# 从EEPROM的指定地址读取相同长度的数据
data = i2c.readfrom_mem(eeprom, 0x0000, len(data))
print(data) # 打印读取到的数据

Please note that the above cases are only for expanding ideas and may contain errors or inapplicability. Different hardware platforms, usage scenarios and MicroPython versions may lead to different usage methods. In actual programming, you need to adjust it according to your hardware configuration and specific needs, and conduct multiple actual tests. It is important to ensure that the hardware is connected correctly and to understand the specifications and characteristics of the sensors and devices used.

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_41659040/article/details/133412431