meta data for this page
  •  

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

code:rp2040_eth_modul_mlx90614_1 [2026/05/12 17:06] – created vamsancode:rp2040_eth_modul_mlx90614_1 [2026/05/12 17:08] (current) vamsan
Line 1: Line 1:
-====== lamaPLC: RP2040_ETH_Modul: MLX90614 ======+====== lamaPLC: RP2040_ETH_Modul: MLX90614 simple ======
 Read [[sensor:mlx90614|MLX90614 (GY-906) infrared non-contact thermometer sensor]] to serial.  Read [[sensor:mlx90614|MLX90614 (GY-906) infrared non-contact thermometer sensor]] to serial. 
  
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, reg, 2)
 +        # Unpack the 16-bit little-endian unsigned integer
 +        raw_val = ustruct.unpack('<H', data)[0]
 +        
 +        # 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"Error reading I2C: {e}")
 +        return None
 +
 +print("--- MLX90614 Temperature Reader ---")
 +
 +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("Ambient: {:.2f}C | Object: {:.2f}C".format(ambient, obj))
 +    else:
 +        print("Failed to read from sensor. Check wiring.")
 +
 +    time.sleep(1) # Wait 1 second between readings
 +</code>
 +
 +**Running example**
 +
 +<code>
 +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
 </code> </code>