index
9.1
Using sensors in a standard way
9.2
[ Type 2] Connecting to individual pins
9.3
[ Type 3] Connecting to the I2C bus
9.4
[ Type 4] OneWire Connect to the bus
9.5
[ Type 5] Connecting to the SPI bus
9.6
[ Type 6] Connecting via UART
1/54
Learning Objectives
2/54
detail outline
3/54
9.1 Sensor standard In a way �How to use
The sensor standard In a way How to use
9.1 Sensor standard In a way How to use
Diversity of sensor connections
Sensors connected to the development board have different data types and communication methods.
Representing sensors in a standardized way (e.g., JSON format) facilitates server transmission and program integration.
Standard data representation examples
In the example, the values of the DHT22, DS18B20, and BH1750 sensors are organized into a dictionary.
Consolidate the measurements and units (e.g., temperature, humidity, and light) of each sensor into a single dictionary.
Detailed description
The sensor class reads the data and returns it with a "TempUnit" and key-value pairs for each sensor.
This standardized representation allows multiple sensor data to be processed at once or transmitted via protocols such as MQTT.
5/54
1. Development On the board Pin and The sensor Connecting method
9.1 Sensor standard In a way How to use
Type 1: Direct pin manipulation
A way to directly manipulate the digital or analog information of a pin
Type 2: Library Utilization
How to utilize a sensor connected to a pin using a specific library
Types 3-6: Utilizing communication functions
Using the communication functions built into the development board
6/54
2. Sensor's information expression Standardize
9.1 Sensor standard In a way How to use
standardization method
JSON
MQTT
7/54
3. Program Piece By pattern Register Reuse
9.1 Sensor standard In a way How to use
patterns
components
YAML
8/54
3. Program Piece By pattern Register Reuse
9.1 Sensor standard In a way How to use
pattern Register
Pattern registration
Register reusable program fragments as patterns
Patterns can add information to be used as components.
Expression form
Use YAML to easily describe information in dictionary or JSON format.
It is expressed as a 'key: value' pair, and indentation is used if the value is a dictionary.
pattern file
Collect usage patterns and store them in a separate file.
A pattern file acts as a kind of pattern dictionary.
Pattern Components
For example, the LED pattern has keys 'Description, Method, Code'
The timer pattern can only contain code
The only required elements are the codes, and the rest can be added as needed.
9/54
3. Program Piece By pattern Register Reuse
9.1 Sensor standard In a way How to use
pattern Register
Variable substitution
Items surrounded by curly brackets, such as '{{name}}', are used as specified information when using the part. Replaced
multiline string
Use the | symbol after the code to express a multi-line string
Duplicate pattern name
If the same pattern name is duplicated, only the last one is valid, so be careful.
10/54
3. Program Piece By pattern Register Reuse
9.1 Sensor standard In a way How to use
pattern Register - Prompt
Even if the prompt deviates somewhat from YAML's syntax ,
AI understands the author's intention and delivers the right result. zoom .
prompt
File name: ai-example-pattern-register.md
11/54
3. Program Piece By pattern Register Reuse
9.1 Sensor standard In a way How to use
The pattern By parts How to use
Configuring YAML Prompts
Use YAML-formatted prompts when defining parts.
You can use the pre-made pattern file in the front for common use.
Only the pattern information specified in the prompt is used, and the rest is ignored.
Define part usage
Defines the use of components by starting with components:
Each part is specified in the format - key: value
The same pattern can be used multiple times (repeated use possible)
Structure and readability
Items marked with - can be placed alongside the parent key, and indentation is omitted to improve readability.
If the source code appears in the middle, start with components: to separate it.
12/54
3. Program Piece By pattern Register Reuse
9.1 Sensor standard In a way How to use
The pattern By parts Usage - Prompt
prompt
Filename: ai-example-for-use-as-part.md
Even if the prompt deviates somewhat from YAML's syntax ,
AI understands the author's intention and delivers the right result. zoom
13/54
3. Program Piece By pattern Register Reuse
9.1 Sensor standard In a way How to use
The pattern By parts How to use - Program cord
from machine import Pin from run import Run import pinno as P run = Run() from blink import Blink led_1 = Blink(pin_instance=Pin(P.LED_1_IN, Pin.OUT), inverted=False) run.add(led_1.run) def led_toggle(): led_1.toggle() from timerrun import TimerRun timer_led = TimerRun(period=1 * 1000, callback=led_toggle) run.add(timer_led.run) def main(): while True: run.run() if __name__ == '__main__': main()
controls the LED generated using the pattern and component concepts. This is a program . I am implementing a function to blink an LED periodically using a timer .
14/54
3. Program Piece By pattern Register Reuse
9.1 Sensor standard In a way How to use
The pattern By parts Usage - YAML By pattern user intention Expressing
1
Generate concise code
Generate excellent code by simply specifying component usage in YAML.
2
Understanding the intention
AI understands the author's intent through YAML syntax and patterns: and components: keys.
3
Clear program definition
The concept of 'pattern' and 'part' can simplify and clarify program definition.
4
Leveraging common patterns
Common patterns are registered in the 'ai-patterns.md' file, and the description of the pattern itself should be checked in that file.
15/54
4. Sensor class For Template prompt
9.1 Sensor standard In a way How to use
Sensor class
This class is for using a specific sensor.
Returns the sensor values in a standardized JSON format .�
Sensor Class Template Prompt
A universal prompt for creating a class that reads the values from a sensor.
If you get an error when creating a specific sensor class, you will need to modify the prompt.
All sensor classes in this book are �Written with this prompt. �Example) DHT22, BH1750, DS18B20
prompt
Filename : ai-9-1-sensor-class-template.md
16/54
9.2 [ Type 2] �Individual On the pin Connect
1~2. Individual pin connection method and circuit diagram
9.2 [ Type 2] Individual On the pin Connect
Concept and Features
Circuit and configuration
Detailed description
18/54
3. DHT22Sensor class Making – Using Circuit
9.2 [ Type 2] Individual On the pin Connect
Circuit example
target
19/54
3. DHT22Sensor class Create - Prompts and cord
9.2 [ Type 2] Individual On the pin Connect
Generative To AI Coding
AI Printed MicroPython cord
Webpage
[ explanation ]
a class that reads temperature and humidity data in a standardized format using the DHT22 temperature and humidity sensor. Implemented
- Created by generative AI using sensor class templates Code Im
20/54
4. Parse class How to use
9.2 [ Type 2] Individual On the pin Connect
from parse import Parse data = {'DHT22': {'Temperature': 25.6, 'Humidity': 45}, 'TempUnit': 'C'} p = Parse(data) print(p.name) # 'DHT222' print(p.names) # ['DHT22'] print(p.key) # 'Humidity' print(p.keys) # ['Humidity','Temperatute'], ascending order print(p.value) # 45 print(p.values) # [45,25,6], p.keys order print(p.temp_unit) # 'C'
21/54
4. Parse 클래스 사용법
9.2 [유형 2] 개별 핀에 연결하기
class Parse:
def __init__(self, data):
self.data = data
# 기본값
self.name = None
self.names = []
self.key = None
self.keys = []
self.value = None
self.values = []
self.temp_unit = None
# TempUnit 추출
if "TempUnit" in data:
self.temp_unit = data["TempUnit"]
# 센서 이름 찾기
for k in data:
if type(data[k]) == dict:
self.names.append(k)
self.names.sort()
# 첫 번째 센서...
# 첫 번째 센서
if len(self.names):
self.name = self.names[0]
sensor_data = data[self.name]
# key 목록
self.keys = list(sensor_data.keys())
self.keys.sort()
# 첫 번째 key
if len(self.keys):
self.key = self.keys[0]
# values 생성
for k in self.keys:
self.values.append(sensor_data[k])
# 첫 번째 value
if len(self.values):
self.value = self.values[0]
def get(self, key, default=None):
if self.name is None:
return default
sensor_data = self.data[self.name]
if key in sensor_data:
return sensor_data[key]
return default
22/54
4. Parse class How to use
9.2 [ Type 2] Individual On the pin Connect
Parse class Attribute ( Property )
names
Sensor name List
name
Same as names[0]
Typically used to refer to a single sensor or the very first sensor.
keys
name of sensor data List
key
Same as keys[0]
For DHT22, ' Humidity' is sorted in ascending order. being
values
The values corresponding to the keys List
value
Same as values[0]
temp_unit
Indicates the temperature unit string
Usually 'C', 'F' or blank (' ') if there is no value . Set
OneWire related properties
ow_id, ow_ids, ow_key, ow_keys, ow_value, ow_values
To access OneWire sensor data: properties
23/54
9.3 [ Type 3] �On the I2C bus Connect
1. I2C bus connection method
9.3 [ Type 3] On the I2C bus Connect
I2C communication concept
Connect one master and multiple slaves (up to 126) with just two lines (SCL, SDA)
Sensor examples: BH1750 (light sensor), OLED display
I2C communication is an efficient communication method that can connect multiple devices using only two lines (SCL: clock, SDA: data). method
One master device (typically a microcontroller) can communicate with multiple slave devices (sensors, displays, etc. )
25/54
1. I2C bus connection method
9.3 [ Type 3] On the I2C bus Connect
Check for address conflicts
Ensure that address conflicts between components within the same I2C bus are avoided.
2
Check your PIN number
Check pin numbers when setting up the I2C bus on the ESP32 S3 mini board
Connection configuration
Connect to appropriate pins, such as SCL→GPIO36, SDA→GPIO35
When using the I2C bus, all connected devices must have a unique address. box
Also, you need to check the I2C pin number of the development board and connect it correctly. box
On the ESP32 S3 mini board, the SCL and SDA pins are assigned to specific GPIO pins. There is
26/54
2. BH1750 and OLED circuit diagram
9.3 [ Type 3] On the I2C bus Connect
I2C bus sharing
Two parts share a single I2C bus.
I2C address
The default I2C addresses for each component are 0x23(35) and 0x3c(60), respectively.
Connection method
Both devices are connected via the SCL and SDA lines. �It connects to the microcontroller .
use I2C communication. device
Since the two devices have different I2C addresses, they can be connected together on a single I2C bus .
27/54
3. On OLED Alphanumeric characters and korean Show
9.3 [ Type 3] On the I2C bus Connect
OLED Shield characteristic
screen despite their small size. Provided
The specially designed hangul.py module allows you to display Korean characters neatly, allowing you to visually present a variety of information .
hangul.py module
28/54
3. On OLED Alphanumeric characters and korean Display – Used Circuit
9.3 [ Type 3] On the I2C bus Connect
Circuit example
target
The OLED display is connected to the microcontroller via I2C communication.
This circuit allows you to display text and simple graphics . �It can be used for various purposes such as sensor data visualization and status display.
29/54
3. On OLED Alphanumeric characters and korean Show
9.3 [ Type 3] On the I2C bus Connect
This code is for OLED display Hangul and Alphanumeric characters Displaying Function Implemented
SSD1306 driver and hangul.py module By using various Text Can be displayed
- Korean and alphanumeric characters together on the OLED screen Displayed
- Readable information even on small screens
- OLED displays provide a clear screen despite their small size, making them very useful for visually displaying information in IoT projects.
- The Korean display function can provide more diverse information to users .
MicroPython cord
execution result
30/54
4. BH1750Sensor class Making – Using Circuit
9.3 [ Type 3] On the I2C bus Connect
Circuit example
target
BH1750 illumination The sensor uses I2C communication Through circumference of light Brightness Measurable It's a sensor .
This sensor By using circumference of the environment In brightness according to various Action Performing The project It can be implemented .
31/54
4. BH1750Sensor class Create - Prompts and cord
9.3 [ Type 3] On the I2C bus Connect
Generative To AI Coding
AI Printed MicroPython cord
Webpage
[ explanation ]
- This code creates a class that measures the brightness of the ambient light using the BH1750 light sensor and returns the data in a standardized format. Implemented
- Created by generative AI using sensor class templates cord
32/54
5. BH1750's illuminance The value On OLED Display – Used Circuit
9.3 [ Type 3] On the I2C bus Connect
Circuit example
target
This circuit displays the light intensity values measured by the BH1750 light sensor in real time on an OLED display. �Since both devices use I2C communication, they can be connected to the same I2C bus for efficient configuration.
33/54
5. BH1750's illuminance The value On OLED Display - Prompt and cord
9.3 [ Type 3] On the I2C bus Connect
Generative To AI Coding
AI Printed MicroPython cord
Webpage
[ explanation ]
34/54
9.4 [ Type 4] �On the I2C bus Connect
1. OneWire bus connection method
9.4 [ Type 4] On the I2C bus Connect
OneWire communication concept
One data By line Multiple DS18B20 temperatures The sensor Multidrop In a way connection
Each DS18B20 has its own unique ID Because I have several The sensor individually division possible
36/54
2. DS18B20 circuit diagram
9.4 [ Type 4] On the I2C bus Connect
Circuit diagram explanation
The DS18B20 sensor requires a 4.7kΩ �pull-up resistor on the data pin .
Connection method
connection of VCC, GND, and data pins method
The data pin is connected to VCC through a pull-up resistor.
Multi-drop configuration
Multiple DS18B20 sensors can be connected in parallel
Each sensor is identified by a unique ID . access
37/54
3. DS18B20Sensor class Create - Prompts and cord
9.4 [ Type 4] On the I2C bus Connect
Generative To AI Coding
AI Printed MicroPython cord
Webpage
[ explanation ]
- This code is for DS18B20 temperature The sensor By using Temperature Measure and Standardized In the format data Returning class Implemented
- OneWire Communication Through several The sensor Identify and individually Temperature Can read
38/54
9.5 [ Type 5] �On the SPI bus Connect
1. SPI bus connection method
9.5 [ Type 5] On the SPI bus Connect
Pin configuration
SPI consists of three common pins, SCK, MOSI, and MISO, and one SS (slave select) pin added for each slave. Composed
For example, when connecting one sensor, four �pins are required. Need
Communication method
selects a specific slave by individual pin. Communication box
Faster communication speed than I2C due to dedicated data line
Application areas
method for connecting microcontroller and flash memory Used
often adopt SPI instead of I2C for faster response speed .
SPI on ESP32
provides two SPI buses that can be used independently by the user .
40/54
2. SD card and RTC shield Circuit diagram
9.5 [ Type 5] On the SPI bus Connect
SPI vs. I2C
data Logger program
hardware composition
The SD card uses SPI communication Through fast data Save It is possible , and the RTC (Real-Time Clock) uses I2C communication. Through accurate hour Information We provide these two modules . together If you use it hour Information and together sensor Data to SD card Saving data logger It can be implemented .
41/54
3. UseSDCard class Create - Prompts and cord
9.5 [ Type 5] On the SPI bus Connect
Generative To AI Coding
AI Printed MicroPython cord
Webpage
[ explanation ]
42/54
4. Temperature and humidity Information Time and Together on the SD card Recording – Usage Circuit
9.5 [ Type 5] On the SPI bus Connect
Circuit example
target
This circuit uses a DHT22 sensor measured Temperature and humidity Data from RTC module Provided by accurate hour Information and Together on the SD card Save it .
This Through Hourly environment data Record it Analyzable data logger It can be implemented .
43/54
4. Temperature and humidity Information Time and Together on the SD card Record - Prompt and cord
9.5 [ Type 5] On the SPI bus Connect
Generative To AI Coding
AI Printed MicroPython cord
Webpage
[ explanation ]
This code is for DHT22 sensor measured Temperature and humidity Data from RTC module Provided by hour Information and Together on the SD card Save
In RTC today Time Setting up The procedure is required and once set Time is battery Lifespan I'll do it Until Maintained
accurate Time Need Every time today Time again Setting up That 's good
44/54
9.6 [ Type 6] �Connecting via UART
1. Connecting UART pins method
9.6 [ Type 6] Connecting via UART
Communication method
UART is an asynchronous serial communication method that uses TX (transmit) and RX (receive) data lines for 1:1 communication without a separate synchronization signal.
Connection structure
The TX pin of one device must be connected to the RX pin of the other device, and the data transmission speed is agreed upon in advance by both parties.
No master/slave distinction
Either device can initiate communication first, so they communicate on an equal footing.
Configuring UART on ESP32
ESP32 has three UARTs: UART0, UART1, and UART2.
UART0 is connected to the built-in USB device and is used as a MicroPython REPL, so it is better to avoid it when connecting other devices.
46/54
2. UART's data form
9.6 [ Type 6] Connecting via UART
Differences in string representation
ASCII code
Unicode
UTF-8 encoding
- In UART communication string data byte By unit Transmitting and receiving box
47/54
3. UART commands
9.6 [ Type 6] Connecting via UART
UART initialization
UART(id, baudrate, tx, rx, timeout)
UART reading
Write UART
48/54
4~5. UART1 and UART2 send information Give and Take – Usage Circuit
9.6 [ Type 6] Connecting via UART
Circuit example
target
This circuit Interconnect UART1 and UART2 within one ESP32 Connect Two-way Communication Implements . �Each UART has data Sending Receiving Role alternately and perform this Through two devices liver communication The protocol You can test it .
49/54
4~5. UART1 and UART2 send information Give and Take - Prompts and cord
9.6 [ Type 6] Connecting via UART
Generative To AI Coding
AI Printed MicroPython cord
Webpage
[ explanation ]
communication to exchange data between UART1 and UART2. Implemented
50/54
Practice Problems (1/2)
1
With RTC OLED Used clock program
These practice problems are in this chapter. learned various With sensors communication The method By utilizing Real IoT The project Implementing ability Test it .
RTC, OLED, DHT22 sensor Back In combination service Application Try making it .
51/54
Practice Problems (2/2)
2
With DHT22 sensor OLED Used Temperature and humidity Monitoring
52/54
Q&A
Copyright© 2025 Hanbit Academy, Inc.
All rights reserved.