Standard Library
# Comparison Benchmark (Thermometer)
import neopixel
import machine
import array
import time
pixels = neopixel.NeoPixel(machine.Pin(16), 25); # Matrix
N = 4096 # Sample number
samples = array.array("H", [0] * N) # Sample Buffer
sensor = machine.ADC(4) # Thermal sensor
brightness = 1
def mean(massive):
return sum(massive) / len(massive)
def map_range(inp, in_min, in_max, out_min, out_max):
return out_min + (inp - in_min) / (in_max - in_min) * (out_max - out_min)
def collect():
for i in range(N):
samples[i] = sensor.read_u16()
# Plain Python, Native, Viper
def sum_python(buf):
total = 0
for x in buf:
total += x
return total
@micropython.native
def sum_native(buf):
total = 0
for x in buf:
total += x
return total
@micropython.viper
def sum_viper(buf, n: int) -> int:
p = ptr16(buf) # raw pointer to the array's data
total = 0
for i in range(n):
total += p[i] # one load instruction per element
return total
def bench(name, fn, *args):
start = time.ticks_us()
result = fn(*args)
difference = time.ticks_diff(time.ticks_us(), start)
print(f"{name} {difference} us")
return result
def set_leds_temperature(temp, min_temp, max_temp):
r, g, b = 0, 0, 0
middle = mean([min_temp, max_temp])
if temp < middle:
r = 0
g = int(map_range(temp, min_temp, middle, 0, 255) * brightness)
b = int(map_range(temp, min_temp, middle, 255, 0) * brightness)
else:
r = int(map_range(temp, middle, max_temp, 0, 255) * brightness)
g = int(map_range(temp, middle, max_temp, 255, 0) * brightness)
b = 0
for pixel in range(25):
pixels[pixel] = (r, g, b)
pixels.write()
collect()
bench("python", sum_python, samples)
bench("native", sum_native, samples)
total = bench("viper", sum_viper, samples, N)
# --- convert to °C (formula from the RP2040 datasheet) ---
# https://datasheets.raspberrypi.com/rp2040/rp2040-datasheet.pdf - Page 563
volts = (total / N) * 3.3 / 65535
temp_c = 27 - (volts - 0.706) / 0.001721
print(f"Chip temperature: {temp_c:.1f} °C")
set_leds_temperature(temp_c, 20, 70)