1 of 26

챗GPT로 코딩하기

[강의교안 이용 안내]

  • 본 강의교안의 저작권은 양재삼한빛아카데미㈜에 있습니다.
  • 이 자료를 무단으로 전제하거나 배포할 경우 저작권법 136조에 의거하여 벌금에 처할 수 있고 �이를 병과(倂科)할 수도 있습니다.

마이크로파이썬을 활용한 사물인터넷

2 of 26

Chapter

13

전등 제어와�경보 시스템 구성하기

3 of 26

index

Creating a MicroPython Program

13.2

Creating a Node-RED Flow

13. 3

13.1

Building a circuit

3/26

4 of 26

Learning Objectives

  • BH1750 light sensor and MQ-9 gas sensor : Measure values periodically and send them to MQTT broker. Learn how .
  • PIR sensor : When motion is detected, the status is transmitted as an MQTT message and a light control signal is generated based on this. Understand the method .
  • OLED Display Control : Learn techniques for displaying sensor data alternately (e.g., configuring a 'Gas Illuminance' screen) .
  • Alarm system : When the gas concentration exceeds the threshold, an alarm is issued by a buzzer and a voice alarm is output. Implement the function ( using Node-RED's Play Audio node)
  • System Integration : Implement sensor measurements, display updates, MQTT communication, automatic control, and dashboard visualization in one system. Learn how .​​

4/26

5 of 26

13.1 Building a Circuit

6 of 26

1. Using a shield composition

13.1 Building a Circuit

purpose

To implement the lighting control and alarm system, the board is configured based on the shield. sensors and actuators at once

Shield components

  • microcontroller board : S3 mini or S2 mini
  • PIR shield : Detects the movement (action) of a nearby person and transmits the action status to MQTT.
  • OLED Shield : Display status information such as temperature, gas concentration, and illuminance on the OLED screen
  • Ambient light shield : Measure ambient brightness using the BH1750 sensor
  • MQ-9 gas sensor : Measures gas concentration and generates a signal for alarm when a threshold is exceeded.
  • Multi-One shield : Responsible for power control (connecting external power supply)

Things to consider when configuring a circuit

Each shield has a fixed board and pin layout, so the connection order and pin duplication problem (e.g. I2C pin sharing between OLED and BH1750)

6/26

7 of 26

2. Configuration using a breadboard

13.1 Building a Circuit

Alternative configuration

How to build a circuit using a breadboard and individual components without a shield

breadboard component​

Microcontroller: S3 mini, S2 mini, or C3 mini series boards

Sensor:

  • BH1750 sensor: Ambient light (illuminance) measurement (shared pins with OLED via I2C)
  • PIR module: motion detection (using pin R5)
  • MQ-9 Gas Sensor: Measuring Gas Concentration with Analog Input

Output device:

  • OLED display (SSD1306, I2C)
  • LED: Indicates light on status (330Ω resistor for overcurrent protection)

Additional components: breadboard, USB-C cable, etc.

Considerations when connecting

OLED and BH1750 use I2C communication, so be careful about pin sharing.

The PIR sensor and MQ-9 sensor have their power and signal pin connections configured precisely.

7/26

8 of 26

13.2 MicroPython �Create a program

9 of 26

MicroPython Create a program

13.2 MicroPython Create a program

Prompts and Code

Coding Generative AI

AI prompt Exercise 13-1

[ File name : ai-13-1-pir-gas.md]

MicroPython code output by AI

Program 13-1

[ File name : 13_1_pir_gas.py]

Webpage

https://iotmaker.kr/mpy-ai-13-1/

9/26

10 of 26

MicroPython Create a program

13.2 MicroPython Create a program

execution result​

connect_Wi -Fi> Start Wi-Fi (s2020)...

connect_Wi -Fi> Wi-Fi connection Completed : ('192.168.0.219', '255.255.255.0', '192.168.0.1', '61.41.153.2')

connect_mqtt > MQTT connection start

LWT> tele/ESP32-01/LWT, |Offline|, retain=True

connect_mqtt > MQTT connection complete

pub> tele/ESP32-01/LWT, |Online|, retain=True, qos =0

sub> cmnd /ESP32-01/#, qos =0

on_connect () called

pub> tele/ESP32-01/INFO, |{"TELEPERIOD": 5}|, retain=True, qos =0

on_connect_more ()...

Brightness: 471

gas: 56

pub> tele/ESP32-01/SENSOR, |{"BH1750": {"Brightness": 471}, "gas": {"value": 56}}|, retain= False, qos =0

RCV> cmnd /ESP32-01/TELEPERIOD, |10|

pub> stat/ESP32-01/TELEPERIOD, |10|, retain=True, qos =0

pub> tele/ESP32-01/INFO, |{"TELEPERIOD": "10"}|, retain=True, qos =0

TELEPERIOD has been changed to 10 seconds .

pub> tele/ESP32-01/PIR, |on|, retain=True, qos =0

PIR on

RCV> cmnd /ESP32-01/LED_1, |on|

pub> stat/ESP32-01/LED_1, |on|, retain=False, qos =0

pub> tele/ESP32-01/PIR, |off|, retain=True, qos =0

PIR off

10/26

11 of 26

MicroPython Create a program

13.2 MicroPython Create a program

program outline

Sensor data measurement

  • Measure ambient illuminance (brightness) values using the BH1750 sensor
  • Measuring gas concentration using MQ-9 gas sensor
  • Motion detection via PIR sensor

Data processing and transmission

  • After organizing the measured sensor values into a dictionary, convert it into a JSON string.
  • Send to MQTT broker
  • Transmit light control commands and alarm signals via MQTT messages

OLED display update

The gas value is displayed on the OLED with a title such as “Gas Illuminance” at 3-second intervals.

threshold and illuminance values

Automatic control function

  • If the gas sensor value exceeds the threshold, an alarm is generated through a buzzer.
  • Controls the on/off of lights (LED) according to the operation of the PIR sensor

11/26

12 of 26

MicroPython Create a program

13.2 MicroPython Create a program

program flow

Initialization and setup steps

Object creation: Create a Run object, initialize instances of each sensor (gas, BH1750, PIR) and actuator (LED, buzzer).

I2C Interface: Setting up the I2C bus for connecting the OLED and BH1750 sensors.

OLED Initialization: Initialize the OLED display, set the screen size, and set the resolution using the SSD1306 library.

Register a timer

timer_oled: Calls the display_oled function every 3 seconds to refresh the OLED screen.

timer_sensor: Reads sensor data at a default TELEPERIOD (e.g. 5 seconds) interval and sends it to the MQTT broker.

MQTT connection and event handling

After creating MQTTClient, wrap it with UseMQTTClient and set the mqtt_callback and mqtt_on_connect functions.

mqtt_on_connect: After connection, initial information such as TELEPERIOD (MQTT INFO message) is issued and additional tasks (on_connect_more) are executed.

mqtt_callback: Change TELEPERIOD according to received topic, control LED ,

Processing THRESHOLD (gas threshold) update, etc.

Sensor data transmission

read_sensors_more: Read BH1750 and MQ-9 sensor values into dictionary

Data organization

Convert the configured data into a JSON string

Publish to MQTT broker

12/26

13 of 26

13.3 Node-RED �Flow making

14 of 26

Creating a Node-RED Flow

13.3 Creating a Node-RED Flow

outline

Purpose and Role

  • Implement real-time monitoring and control functions on the dashboard by receiving sensor data and control commands transmitted from the MQTT broker.
  • Implementation of lighting control (LED on/off) and alarm system (voice alarm) based on PIR sensor, light sensor, and gas sensor data.

Core Features

  • Receive sensor data: Receive sensor data (e.g. 'tele/ESP32-01/SENSOR') as MQTT in node.
  • Light control: Issues LED on/off commands by comparing the illuminance value and the lighting threshold based on the operation of the PIR sensor.
  • Alarm System: When the MQ-9 gas sensor value exceeds the threshold, a buzzer alarm and a voice alarm output of “Alarm! Gas leak.”

component

  • MQTT in/out node : Send and receive sensor data and control commands
  • Dashboard node : Configure the user interface using widgets such as charts, text, radio groups, number inputs, and switches.
  • Conditional control nodes : Control flow according to conditions using switch, change, trigger (delay) nodes, etc.

14/26

15 of 26

1. Completed Dashboard look

13.3 Creating a Node-RED Flow

15/26

16 of 26

2. Completed Flow look

13.3 Creating a Node-RED Flow

Flow File : [ File name : flows-13-1-pir-gas.json]

16/26

17 of 26

2. Completed Flow look

13.3 Creating a Node-RED Flow

17/26

18 of 26

2. Completed Flow look

13.3 Creating a Node-RED Flow

18/26

19 of 26

3. Node Write

13.3 Creating a Node-RED Flow

sensor The value On the dashboard Expressing

  • The device reads multiple sensor values, organizes them into a dictionary, converts it into a JSON string, and sends it to the MQTT broker.
  • JSON strings in UTF-8 format are transmitted between the device and the MQTT broker, and between the MQTT broker and Node-RED.
  • Node-RED's mqtt in node automatically converts the arriving JSON string into object format.
  • In MicroPython, JSON data is processed as a dictionary data type, while in Node-RED, it is processed as an object.
  • The two environments essentially handle the same data, but have different names and Boolean notation. �(MicroPython: True/False, JSON/Node-RED: true/false)

19/26

20 of 26

3. Node Write

13.3 Creating a Node-RED Flow

sensor information Subscribe : mqtt in

  1. [ Topic ]: The topic of the sensor designation
  1. [ Output ] : Click the drop-down list
  1. [ Auto-determination ] : Automatically determines whether a JSON object, string, or binary buffer is After determining, convert Print box
  1. [ Automatic judgment ]: Automatically determines whether it is a string or binary buffer and then outputs it .
  1. [ Binary Buffer ]: For processing the contents of bytes in bit units. Data type
  1. [ string ] : as string output of power
  1. [ JSON Object ] : If the sensor data is in JSON format, then in this format �Should be converted box
  1. for processing images Data type
  1. [ Complete ]: Click the button setting Finally

20/26

21 of 26

3. Node Write

13.3 Creating a Node-RED Flow

Control lights based on PIR status and light levels

A typical example is to implement automation by comparing sensor information with pre-determined thresholds. Flow

Motion detection and light measurement

Detects movement with PIR sensor and ambient brightness with light sensor Measure​

Automatic control logic

system that turns on the lights only when motion is detected and the surroundings are dark. Implemented​

21/26

22 of 26

3. Node Write

13.3 Creating a Node-RED Flow

Control lights based on PIR status and light levels

p3)on,off

Divide it into on or off depending on the output value of the 'p1)tele/ESP32-01/PIR' node. Branch​

p4)If it's dark

When the PIR value is on, the flow to this node Connected​

illuminance value (flow.light) is less than the lighting threshold (flow.light_threshold) ( if it is dark ) , go to port 1 . Branch and turn on LED_1 If the illuminance value is higher than the lighting threshold, nothing happens.

Control execution

to the MQTT broker to turn the LED on or off based on conditions. Sent​

22/26

23 of 26

3. Node Write

13.3 Creating a Node-RED Flow

trigger Node How to use

  1. [Transmission data ] : This is the value output as msg.payload when the node starts. It is �usually set to on, but it is not needed here, so it is set to 'none'. Set
  1. [Post-transmission processing ] : After sending a message, select the ‘Wait for a specified time’ option. Used ( �You can also choose the Wait until initialization option )
  1. [ atmosphere Time ] : Specifies 10 seconds as the waiting time.
  1. Extend new message delay ] : Set to extend the existing delay when a new message arrives, so that �the delay is reset through 'p5)msg.reset' in the previous flow. Processed
  1. [ specify msg.delay ] : You can replace the 10-second waiting time with the value specified in msg.delay. Options
  1. [Retransmission data ] : msg.payload value to output when the specified waiting time has elapsed
  1. Use second port ] : Initial transmission and retransmission after waiting can be output separately to ports 1 and 2, but only retransmission data is used here , so no separate designation is made. No
  1. Set initialization condition, msg.reset ] : If the msg object has a reset property �Set the waiting time to the default value (10 seconds) Reset
  1. [Initialization condition, msg.payload is the following value] : Wait time is set to the value specified in msg.payload. Reset
  1. [ Processing Target ] : Can be processed as a group of 'all messages' or individually for 'each msg.topic'.
  1. [ Name ] : The name of the node to be displayed in the dashboard editing window or layout. Designated​
  1. [ Complete ] : Click the button to complete the setup.

23/26

24 of 26

3. Node Write

13.3 Creating a Node-RED Flow

Voice alarm based on gas concentration

g7), g8) gas.value

The value of the gas sensor is retrieved through the switch node 'g7)gas.value' and the change node 'g8)gas.value'. Extract​

g11) If the concentration is high

In this node, a conditional expression is used to check whether there is a gas leak or not. Judgement​

24/26

25 of 26

3. Node Write

13.3 Creating a Node-RED Flow

Alarm By voice Send

  1. [TTS Voice] : Type of output voice Select ( here Korean is the default value ) ( specified )
  1. [ Name ] : The node name displayed in the dashboard editing window or dashboard layout. Designated​
  1. [ Complete ] : Click the button Finish setting​

25/26

26 of 26

Q&A

Copyright© 2025 Hanbit Academy, Inc.

All rights reserved.