meta data for this page
Differences
This shows you the differences between two versions of the page.
| code:rp2040_eth_modul_mlx90614_1 [2026/05/12 17:06] – created vamsan | code:rp2040_eth_modul_mlx90614_1 [2026/05/12 17:08] (current) – vamsan | ||
|---|---|---|---|
| Line 1: | Line 1: | ||
| - | ====== lamaPLC: RP2040_ETH_Modul: | + | ====== lamaPLC: RP2040_ETH_Modul: |
| Read [[sensor: | Read [[sensor: | ||
| Line 9: | Line 9: | ||
| <code python> | <code python> | ||
| + | import machine | ||
| + | from machine import Pin, I2C | ||
| + | import time | ||
| + | import ustruct | ||
| + | |||
| + | # I2C configuration for RP2040-ETH | ||
| + | # Default: GP4 (SDA), GP5 (SCL), I2C port 0 | ||
| + | i2c = I2C(0, sda=Pin(4), scl=Pin(5), freq=100000) | ||
| + | |||
| + | # MLX90614 Constants | ||
| + | MLX90614_I2C_ADDR = 0x5A | ||
| + | REG_AMBIENT_TEMP = 0x06 | ||
| + | REG_OBJECT_TEMP = 0x07 | ||
| + | |||
| + | def read_temp(reg): | ||
| + | """ | ||
| + | Reads 2 bytes from the sensor, converts the 16-bit value | ||
| + | to Celsius based on the MLX90614 datasheet formula. | ||
| + | Formula: (Raw * 0.02) - 273.15 | ||
| + | """ | ||
| + | try: | ||
| + | # Read 2 bytes from the specific register | ||
| + | data = i2c.readfrom_mem(MLX90614_I2C_ADDR, | ||
| + | # Unpack the 16-bit little-endian unsigned integer | ||
| + | raw_val = ustruct.unpack('< | ||
| + | | ||
| + | # Check for error flags (0xFFFF or 0x0000 often indicate wiring issues) | ||
| + | if raw_val == 0xFFFF or raw_val == 0: | ||
| + | return None | ||
| + | | ||
| + | # Convert raw to Celsius | ||
| + | celsius = (raw_val * 0.02) - 273.15 | ||
| + | return celsius | ||
| + | except Exception as e: | ||
| + | print(f" | ||
| + | return None | ||
| + | |||
| + | print(" | ||
| + | |||
| + | while True: | ||
| + | ambient = read_temp(REG_AMBIENT_TEMP) | ||
| + | obj = read_temp(REG_OBJECT_TEMP) | ||
| + | |||
| + | if ambient is not None and obj is not None: | ||
| + | # Format the output for the Serial Monitor | ||
| + | print(" | ||
| + | else: | ||
| + | print(" | ||
| + | |||
| + | time.sleep(1) # Wait 1 second between readings | ||
| + | </ | ||
| + | |||
| + | **Running example** | ||
| + | |||
| + | < | ||
| + | Ambient: 19.91C | Object: 20.65C | ||
| + | Ambient: 19.91C | Object: 26.79C | ||
| + | Ambient: 19.91C | Object: 28.11C | ||
| + | Ambient: 19.91C | Object: 28.01C | ||
| + | Ambient: 19.93C | Object: 20.67C | ||
| </ | </ | ||