1+ #
2+ # This file is part of the micropython-esp32-ulp project,
3+ # https://github.com/micropython/micropython-esp32-ulp
4+ #
5+ # SPDX-FileCopyrightText: 2018-2023, the micropython-esp32-ulp authors, see AUTHORS file.
6+ # SPDX-License-Identifier: MIT
7+
8+
9+ """
10+ Example for: ESP32-S2
11+
12+ Example showing how to use the TSENS instruction from the ULP
13+ and access temperature data from the main CPU.
14+
15+ Note that the temperature sensor clock needs to be enabled for the TSENS instruction to complete.
16+
17+ """
18+
19+ from esp32 import ULP
20+ from machine import mem32
21+ from esp32_ulp import src_to_binary
22+ from time import sleep
23+
24+ source = """\
25+ # constants from:
26+ # https://github.com/espressif/esp-idf/blob/v5.0.2/components/soc/esp32s2/include/soc/reg_base.h
27+ #define DR_REG_SENS_BASE 0x3f408800
28+
29+ # constants from:
30+ # https://github.com/espressif/esp-idf/blob/v5.0.2/components/soc/esp32s2/include/soc/sens_reg.h
31+ #define SENS_SAR_TSENS_CTRL2_REG (DR_REG_SENS_BASE + 0x0054)
32+ #define SENS_TSENS_CLKGATE_EN_M (BIT(15))
33+
34+ .set token, 0xACED
35+
36+ .text
37+ magic: .long 0
38+ temperature_data: .long 0
39+
40+ .global entry
41+ entry:
42+ move r3, magic
43+ ld r0, r3, 0
44+ jumpr start, token, eq #check if we have already initialized
45+
46+ init:
47+ # Set SENS_TSENS_CLKGATE_EN to enable temperature sensor clock.
48+ WRITE_RTC_REG(SENS_SAR_TSENS_CTRL2_REG, SENS_TSENS_CLKGATE_EN_M, 1, 1)
49+
50+ # Store temperature_data memory location in r2
51+ move r2, temperature_data
52+
53+ # store that we're done with initialisation
54+ move r0, token
55+ st r0, r3, 0
56+
57+ start:
58+ tsens r0, 1000 # make measurement for 1000 clock cycles
59+ st r0, r2, 0 # store the temperature in memory to be read by main CPU
60+ halt # go back to sleep until next wakeup period
61+ """
62+
63+ binary = src_to_binary (source , cpu = "esp32s2" ) # cpu is esp32 or esp32s2
64+
65+ load_addr , entry_addr = 0 , 8
66+
67+ ULP_MEM_BASE = 0x50000000
68+ ULP_DATA_MASK = 0xffff # ULP data is only in lower 16 bits
69+
70+ ulp = ULP ()
71+ ulp .set_wakeup_period (0 , 500000 ) # use timer0, wakeup after 500000usec (0.5s)
72+ ulp .load_binary (load_addr , binary )
73+
74+ ulp .run (entry_addr )
75+
76+ while True :
77+ magic_token = hex (mem32 [ULP_MEM_BASE + load_addr ] & ULP_DATA_MASK )
78+ current_temperature = 0.4386 * (mem32 [ULP_MEM_BASE + load_addr + 4 ] & ULP_DATA_MASK )- 20.52
79+ print (magic_token , current_temperature )
80+ sleep (0.5 )
0 commit comments