1 of 44

챗GPT로 코딩하기

[강의교안 이용 안내]

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

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

2 of 44

Chapter

07

개발 보드의 핀 다루기

3 of 44

index

7.1​

Pin usage on development board

digital input

7.2

digital output

7. 3

analog input

7. 4

analog output

7. 5

3/42

4 of 44

Learning Objectives

  • digital Finn's How to use ( digital Understand input / output ) .
  • class Pin​ Used digital Learn input/output .
  • class ADC​ Through analog Learn to type .
  • class PWM​ Through analog Learn about output (PWM) .

4/42

5 of 44

detail outline

  • development Pin usage and connections on the board method
  • digital input Circuit and Pull-up / pull-down , debounce concept
  • digital output of power Circuit and LED control ( current sourcing / sinking )
  • analog Input (ADC, voltage distributor , potentiometer )
  • analog Output (PWM, duty Cycle , LED brightness Adjustment )

5/42

6 of 44

7.1 Development Pin Purposes on the Board

7 of 44

Key contents and references

7.1 Development Pin Purposes on the Board

  • digital Input : Determined by HIGH(1) / LOW(0)
  • digital Output : 3.3V (HIGH) and 0V (LOW) output
  • analog Input : ADC Through Voltage In numbers conversion
  • analog Output : PWM mode Through continuous value of effect avatar

core detail

Pins connected to the microcontroller exchange information in the following four ways:

  • Pin, ADC, PWM classes in the machine module of MicroPython basic offer
  • each pin Specific The constraints are Board and chip specifications reference

reference

7/42

8 of 44

7.2 Digital input

9 of 44

1. Digital input circuit

7.2 Digital input

Principles of digital input circuits

Determines the voltage applied to the pin in two stages (LOW, HIGH)

Example) Button press/release, motion sensor detection

Problems that pins can experience – Floating

  • Noise generated by external electromagnetic interference in the unlocked state
  • Solution: Configure a pull-up or pull-down circuit.

debounce treatment

Applies a delay of approximately 20ms to prevent contact bounce when pressing/releasing the button.

9/42

10 of 44

1. Digital input circuit

  • button GND and Connect it and about 10kΩ Connect the resistor to 3.3V
  • Maintain basic HIGH
  • Button LOW signal when pressed Transmission [Figure 7-1]

pull-ups circuit

  • Connect the button to 3.3V and a 10kΩ resistor. To GND connection
  • Maintain basic LOW
  • Button HIGH signal when pressed Transmission [Figure 7-2]

Pulldown circuit

7.2 Digital input

10/42

11 of 44

1. Digital input circuit

7.2 Digital input

Bounce and debounce

Bounce

A phenomenon in which the physical contacts stick and fall off several times in a very short period of time when a button is pressed or released.

debounce

About 20ms when a change in contact is detected After delaying

again Run Continue

11/42

12 of 44

2. Creating a digital input program

Circuit example

  • Connect the multi-one shield to the internal pin area of the octoboard.
  • configuration using C3 mini and button on breadboard
  • The pin to which the button is connected has an internal pull-up or pull-down circuit. Apply Securing �stable input [Figure 7-3]

target

  • Read the values of the button pins each time you press the two buttons. Outputting Create a program .
  • Each button must have an internal pull-up circuit and an internal pull-down circuit, and a debounce function must also be provided for the button .

7.2 Digital input

12/42

13 of 44

2. 디지털 입력 프로그램 만들기

7.2 디지털 입력

# 프로그램 7-3 read-potentiometer.py

"""

Keyboard shortcuts (https://docs.wokwi.com/keyboard-shortcuts)

- F1 = Help menu (see all)

Simulation Control

- CTRL+ENTER = Start Simulation

- . = Stop Simulation

- , = Pause Simulation

Diagram Editing

- A = Add part

- R = Rotate part (when selected)

- D = Duplicate part (when selected)

- DELETE / BACKSPACE = Delete part

- SHIFT+CLICK = Select multiple parts

- F = Fit diagram to view

- SPACE = Pushbutton / switch (while hovering / selected)

- Select a wire, press 0-9,CLMPY to change color

- - (minus) = Zoom out

- + (plus) = Zoom in

- ? = Documentation for selected part

- ESC = Cancel action

- G = Toggle grid ruler display

Code Editing

- CTRL+/ = Toggle Comment

- CTRL+F = Find

- CTRL+H = Replace

- ALT+UP / ALT+DOWN = Move line up / down

- ALT+SHIFT+UP / ALT+SHIFT+DOWN = Duplicate line

Move wires

1. Click wire (purple handles appear)

2. Click purple handle to move wire

- Alternatively - click empty space to make "waypoints" for guided paths

No part rescaling support

"""

13/42

14 of 44

2. 디지털 입력 프로그램 만들기

7.2 디지털 입력

# c3picopinno.py --> 개발보드 \lib\pinno.py

# 내장 핀

# BUILTIN_RGB = 7

BUILTIN_BTN = 9

# 외부핀 사용

R1 = TX = 21

R2 = RX = 20

R3 = D1 = SCL = RELAY = 10

R4 = D2 = SDA = DS18B20 = WS2812B = 8

R5 = D3 = BUILTIN_RGB = PIR = BTN = 7

R6 = D4 = DHT = DHT11 = DHT22 = 6

L2 = A0 = POTENTIOMERER = 3

L3 = D0 = BUTTON_1 = 2

L4 = D5 = SCK = BUTTON_2 = 1

L5 = D6 = MISO = LED_1 = 0

L6 = D7 = MOSI = LED_2 = 4

L7 = D8 = CS = BUZZER = 5

# c3minipinno.py --> 개발보드 \lib\pinno.py

# 내장 핀

# BUILTIN_RGB = 7

BUILTIN_BTN = 9

# 외부핀 사용

R1 = TX = 21

R2 = RX = 20

R3 = D1 = SCL = RELAY = 10

R4 = D2 = SDA = DS18B20 = WS2812B = 8

R5 = D3 = BUILTIN_RGB = PIR = BTN = 7

R6 = D4 = DHT = DHT11 = DHT22 = 6

L2 = A0 = POTENTIOMERER = 3

L3 = D0 = BUTTON_1 = 2

L4 = D5 = SCK = BUTTON_2 = 1

L5 = D6 = MISO = LED_1 = 0

L6 = D7 = MOSI = LED_2 = 4

L7 = D8 = CS = BUZZER = 5

# s2minipinno.py --> 개발보드 \lib\pinno.py

# 내장 핀

BUILTIN_LED = 15

BUILTIN_BTN = 0

# 외부핀 사용

R1 = TX = 39

R2 = RX = 37

R3 = D1 = SCL = RELAY = 35

R4 = D2 = SDA = DS18B20 = WS2812B = 33

R5 = D3 = PIR = BTN = 18

R6 = D4 = DHT = DHT11 = DHT22 = 16

L2 = A0 = POTENTIOMETER =3

L3 = D0 = BUTTON_1 = 5

L4 = D5 = SCK = BUTTON_2 = 7

L5 = D6 = MISO = LED_1 = 9

L6 = D7 = MOSI = LED_2 = 11

L7 = D8 = CS = BUZZER = 12

# 내부핀 사용

R1_IN = TX_IN = 40

R2_IN = RX_IN = 38

R3_IN = D1_IN = SDA_IN = RELAY_IN = 36

R4_IN = D2_IN = SCL_IN = DS18B20_IN = WS2812B_IN = 34

R5_IN = D3_IN = PIR_IN = BTN_IN = 21

R6_IN = D4_IN = DHT_IN = DHT11_IN = DHT22_IN = 17

L1_IN = 1

L2_IN = A0_IN = POTENTIOMETER_IN = 2

L3_IN = D0_IN = BUTTON_1_IN = 4

L4_IN = D5_IN = BUTTON_2_IN = 6

L5_IN = D6_IN = LED_1_IN = 8

L6_IN = D7_IN = LED_2_IN = 10

L7_IN = D8_IN = BUZZER_IN = 13

# s3minipinno.py --> 개발보드 \lib\pinno.py

# 내장 핀

BUILTIN_RGB = 47

BUILTIN_BTN = 0

# 외부핀 사용

R1 = TX = 43

R2 = RX = 44

R3 = D1 = SCL = RELAY = 36

R4 = D2 = SDA = DS18B20 = WS2812B = 35

R5 = D3 = PIR = BTN = 18

R6 = D4 = DHT = DHT11 = DHT22 = 16

L2 = A0 = POTENTIOMETER = 2

L3 = D0 = BUTTON_1 = 4

L4 = D5 = SCK = BUTTON_2 = 12

L5 = D6 = MISO = LED_1 = 13

L6 = D7 = MOSI = LED_2 = 11

L7 = D8 = CS = BUZZER = 10

# 내부핀 사용

R1_IN = TX_IN = 33

R2_IN = RX_IN = 37

R3_IN = D1_IN = SDA_IN = RELAY_IN = 38

R4_IN = D2_IN = SCL_IN = DS18B20_IN = WS2812B_IN = 34

R5_IN = D3_IN = PIR_IN = BTN_IN = 21

R6_IN = D4_IN = DHT_IN = DHT11_IN = DHT22_IN = 17

L1_IN = 1

L2_IN = A0_IN = POTENTIOMETER_IN = 3

L3_IN = D0_IN = BUTTON_1_IN = 5

L4_IN = D5_IN = BUTTON_2_IN = 6

L5_IN = D6_IN = LED_1_IN = 7

L6_IN = D7_IN = LED_2_IN = 8

L7_IN = D8_IN = BUZZER_IN = 9

# c3pinno.py (통합 버전)

# =========================

# 내장 핀

# =========================

BUILTIN_BTN = 9

# BUILTIN_RGB = 7 # 필요 시 사용

# =========================

# 외부 R 포트 (오른쪽)

# =========================

R1 = TX = 21

R2 = RX = 20

R3 = D1 = SCL = RELAY = 10

R4 = D2 = SDA = DS18B20 = WS2812B = 8

R5 = D3 = BUILTIN_RGB = PIR = BTN = 7

R6 = D4 = DHT = DHT11 = DHT22 = 6

# =========================

# 외부 L 포트 (왼쪽)

# =========================

L2 = A0 = POTENTIOMERER = 3

# 🔥 버튼 입력용 별칭 추가 (핵심 수정)

L3 = D0 = BUTTON_1 = L3_IN = 2

L4 = D5 = SCK = BUTTON_2 = L4_IN = 1

# 출력 장치

L5 = D6 = MISO = LED_1 = 0

L6 = D7 = MOSI = LED_2 = 4

L7 = D8 = CS = BUZZER = 5

14/42

15 of 44

2. Creating a digital input program

Create a MicroPython program with the following conditions and explain the code.

from machine import …

import time

Uses two buttons.

The module pinno stores the pin number constant value.

import pinno

BUTTON_1_PIN = pinno.L3_IN

BUTTON_2_PIN = pinno.L4_IN

The first button should be PULL_UP and the second button should be PULL_DOWN.

When you start the program

Print("Try pressing button_1 and button_2.")

Next, you have to keep running.

Read the value of each button and if the value changes

Print("button_x's value changed",button_x's value)

Allow 20ms of debounce margin.

AI prompt Exercise 7-1

7.2 Digital input

15/42

16 of 44

2. 디지털 입력 프로그램 만들기

7-1의 코드 설명(1)

from machine import Pin

import time

import pinno

# 핀 번호 상수 설정

BUTTON_1_PIN = pinno.L3_IN

BUTTON_2_PIN = pinno.L4_IN

# 버튼 설정 (첫 번째는 풀업, 두 번째는 풀다운)

button_1 = Pin(BUTTON_1_PIN, Pin.IN, Pin.PULL_UP)

button_2 = Pin(BUTTON_2_PIN, Pin.IN, Pin.PULL_DOWN)

# 초기 버튼 상태 저장

button_1_prev = button_1.value()

button_2_prev = button_2.value()

# 시작 메시지 출력

print("버튼_1과 버튼_2를 눌러보세요.")

# 각 버튼의 이전 상태 저장

prev_button_1_state = button_1.value()

prev_button_2_state = button_2.value()

7.2 디지털 입력

16/42

17 of 44

2. 디지털 입력 프로그램 만들기

7.2 디지털 입력

# 메인 루프�while True:� # 버튼_1 상태 확인� current_button_1_state = button_1.value()� if current_button_1_state != prev_button_1_state:� print("버튼_1의 값이 바뀜", current_button_1_state)� prev_button_1_state = current_button_1_state # 상태 업데이트� time.sleep(0.02) # 디바운스 (20ms)�� # 버튼_2 상태 확인� current_button_2_state = button_2.value()� if current_button_2_state != prev_button_2_state:� print("버튼_2의 값이 바뀜", current_button_2_state)� prev_button_2_state = current_button_2_state # 상태 업데이트� time.sleep(0.02) # 디바운스 (20ms)�

7-1의 코드 설명(2)

17/42

18 of 44

7.3 Digital output of power

19 of 44

1. Digital output of power

7.3 Digital output of power

Principles of digital output

Outputs two levels of voltage: HIGH (3.3V) or LOW (0V) on the pin. �Example) LED on/off, motor operation control

LED Connection Method - Current Sourcing

  • Connect the anode (long leg) of the LED to a pin on the development board, and �the cathode (short leg) to GND.
  • LED on when HIGH output is made on digital pin�

LED Connection Method - Current Sinking

  • Connect the cathode of the LED to the development board pin, and the anode to 3.3V .
  • LED on when LOW output on digital pin�

caution

When using an LED, be sure to connect a resistor of about 330Ω to 560Ω in parallel to prevent overcurrent. protect

19/42

20 of 44

2. Creating a digital output program

Circuit example

  • Connect the multi-one shield to the internal pin area of the octoboard.
  • Circuit with C3 mini, button and LED on breadboard composition

target

  • When you press button_1, both LED_1 and LED_2 turn on.
  • Pressing button_2 turns off both LED_1 and LED_2 .

7.3 Digital output of power

20/42

21 of 44

2. Creating a digital output program

Create a MicroPython program with the following conditions and explain the code.

from machine import …

Use import time time.sleep_ms().

Uses 2 LEDs and buttons.

The module pinno stores the pin number constant value.

import pinno

BUTTON_1_PIN = pinno.L3_IN

BUTTON_2_PIN = pinno.L4_IN

LED_1_PIN = pinno.L5_IN

LED_2_PIN = pinno.L6_IN

The first button should be PULL_UP and the second button should be PULL_DOWN.

BUTTON_1_PRESSED_VALUE = 0

BUTTON_2_PRESSED_VALUE = 1

The first LED is connected in a current sourcing manner,

The second LED is connected in a current-sinking manner.

LED_1_ON_VALUE = 1

LED_1_OFF_VALUE = not LED_1_ON_VALUE

LED_2_ON_VALUE = 0

LED_2_OFF_VALUE = not LED_2_ON_VALUE

7.3 Digital output of power

AI prompt Practice 7-2(1)

21/42

22 of 44

2. Creating a digital output program

When you start the program

Print("on() when button_1 is pressed, off() when button_2 is pressed")

Specify two LED_x.value(LED_x_OFF_VALUE)

Here's the continuous execution:

When each button is pressed:

If button_1, then LED_x.value(LED_x.ON_VALUE) for both LEDs

If button_2, then LED_x.value(LED_x.OFF_VALUE) for both LEDs

Prints the fact that button_x is pressed and whether it is on or off.

Allow 20ms of debounce margin.

For every while loop:

prev_button_state = current_button_state

1ms pause

7.3 Digital output of power

AI prompt Practice 7-2(2)

22/42

23 of 44

2. 디지털 출력 프로그램 만들기

# 핀 설정: LED는 출력, 버튼은 입력(PULL_UP, PULL_DOWN)�from machine import Pin�import time�import pinno��# 핀 번호 상수 설정�BUTTON_1_PIN = pinno.L3_IN�BUTTON_2_PIN = pinno.L4_IN�LED_1_PIN = pinno.L5_IN�LED_2_PIN = pinno.L6_IN��# 버튼이 눌린 값 설정�BUTTON_1_PRESSED_VALUE = 0 # 버튼_1 눌림�BUTTON_2_PRESSED_VALUE = 1 # 버튼_2 눌림��# LED의 ON/OFF 값 설정�LED_1_ON_VALUE = 1 # 전류 소싱 방식으로 연결된 LED_1 ON�LED_1_OFF_VALUE = not LED_1_ON_VALUE�LED_2_ON_VALUE = 0 # 전류 싱킹 방식으로 연결된 LED_2 ON�LED_2_OFF_VALUE = not LED_2_ON_VALUE�

7.3 디지털 출력

7-2의 코드 설명(1)

23/42

24 of 44

2. 디지털 출력 프로그램 만들기

# 핀 설정: LED는 출력, 버튼은 입력(PULL_UP, PULL_DOWN)�led_1 = Pin(LED_1_PIN, Pin.OUT)�led_2 = Pin(LED_2_PIN, Pin.OUT)�button_1 = Pin(BUTTON_1_PIN, Pin.IN, Pin.PULL_UP)�button_2 = Pin(BUTTON_2_PIN, Pin.IN, Pin.PULL_DOWN)��# 초기 LED 상태 설정: OFF�led_1.value(LED_1_OFF_VALUE)�led_2.value(LED_2_OFF_VALUE)��# 시작 메시지 출력�print("버튼_1을 누르면 on(), 버튼_2를 누르면 off()")��# 버튼 상태 추적�prev_BUTTON_1_state = button_1.value()�prev_BUTTON_2_state = button_2.value()�

7.3 디지털 출력

7-2의 코드 설명(2)

24/42

25 of 44

2. 디지털 출력 프로그램 만들기

while True:� # 현재 버튼 상태 읽기� current_BUTTON_1_state = button_1.value()� current_BUTTON_2_state = button_2.value()�� # 버튼_1이 눌렸는지 확인� if current_BUTTON_1_state == BUTTON_1_PRESSED_VALUE and \� prev_BUTTON_1_state != current_BUTTON_1_state:� # LED_1, LED_2 켜기� led_1.value(LED_1_ON_VALUE)� led_2.value(LED_2_ON_VALUE)� print("버튼_1 누름, 두 LED on")� time.sleep_ms(20) # 디바운스 시간�� # 버튼_2가 눌렸는지 확인� if current_BUTTON_2_state == BUTTON_2_PRESSED_VALUE and \� prev_BUTTON_2_state != current_BUTTON_2_state:� # LED_1, LED_2 끄기� led_1.value(LED_1_OFF_VALUE)� led_2.value(LED_2_OFF_VALUE)� print("버튼_2 누름, 두 LED off")� time.sleep_ms(20) # 디바운스 시간�� # 상태 갱신� prev_BUTTON_1_state = current_BUTTON_1_state� prev_BUTTON_2_state = current_BUTTON_2_state�� # CPU 사용량 줄이기 위해 1ms 중지� time.sleep_ms(1)

7.3 디지털 출력

7-2의 코드 설명(3)

25/42

26 of 44

7.4 Analog Input

27 of 44

1. Analog input circuit

Basic concepts of analog input

  • Converts the continuous voltage applied to the pin into a number using an analog-to-digital converter (ADC).
  • ESP32 mainly uses 12-bit resolution (0 to 4095)

voltage distribution circuit

  • Two resistors are used to lower high voltages such as 5V to below 3.3V. circuit
  • When 5V is applied to Vin (input side), a voltage of 3.3V is output to Vout (output side).

Uses of potentiometers

  • When you turn the knob, the values of the two resistors change, and the output voltage changes between 0V and 3.3V.
  • This value can be read through the ADC and converted to a specific percentage for use [Fig 7-9]

7.4 Analog Input

27/42

28 of 44

2. Analog input Create a program

Circuit example

  • Connect the multi-one shield to the internal pin area of the octoboard.
  • mini on breadboard Potentiometer​ circuit composition �(In the picture below, C3 mini and Putten Show Me Terman use

target

  • Read the value of the potentiometer every 0.5 seconds,
  • If the difference from the previous value is more than 0.5%, the read value is 4095 . �The percentage Print it out

7.4 Analog Input

28/42

29 of 44

2. Analog input Create a program

AI prompt Exercise 7-3

MicroPython The program next On the condition according to Create and code Explain it to me.

from machine import …

import time time.sleep ()

instead Use time.sleep_ms () .

module pinno is a pin number constant The value Saved There is .

import pinno

POTENTIOMETER_PIN = pinno.L2_IN

Potentiometer's Voltage reads up to 3.3V .

program When you start

print(" potentiometer's The knob Please turn it around .")

first = True

Next is sequence It's running :

0.5 second increments Potentiometer's The value Read .

first is True or prev_value and current_value If the difference is more than 0.5% of 4095

Read For values and 4095 The percentage Printer box .

7.4 Analog Input

29/42

30 of 44

2. 아날로그 입력 프로그램 만들기

from machine import ADC, Pin�import time�import pinno��# 핀 번호 상수 설정�POTENTIOMETER_PIN = pinno.L2_IN��# ADC 설정: 퍼텐쇼미터 입력 핀을 ADC로 사용�potentiometer = ADC(Pin(POTENTIOMETER_PIN))��# ADC 분해능 설정 (기본 12비트, 최대 4095)�potentiometer.atten(ADC.ATTN_11DB) # 최대 3.3V까지 측정 가능��# 퍼텐쇼미터 읽기 및 값 비교에 필요한 변수�prev_value = 0�first = True�THRESHOLD = 4095 * 0.005 # 0.5% 변화 임계값��# 프로그램 시작 메시지�print("퍼텐쇼미터의 노브를 돌려보세요.")�

7.4 아날로그 입력

7-3의 코드 설명(1)

30/40

31 of 44

2. 아날로그 입력 프로그램 만들기

while True:� # 퍼텐쇼미터 값 읽기� current_value = potentiometer.read()�� # first가 True이거나, 값이 0.5% 이상 변했을 경우 출력� if first or abs(current_value - prev_value) > THRESHOLD:� # 4095에 대한 백분율 계산� percentage = (current_value / 4095) * 100� print(f"퍼텐쇼미터 값: {current_value}, 백분율: {percentage:.2f}%")� � # 첫 번째 출력 후 first를 False로 설정� first = False� prev_value = current_value # 이전 값 갱신�� # 1ms 대기� time.sleep_ms(1)� � # 0.5초 간격으로 퍼텐쇼미터 값을 읽음� time.sleep(0.5)�

7.4 아날로그 입력

7-3의 코드 설명(2)

31/40

32 of 44

7.5 Analog Output

33 of 44

1. Analog Output circuit

Analog output implementation

  • Real Voltage Adjusting Instead , the PWM (Pulse Width Modulation) technique use
  • Change the average voltage by repeating ON/OFF for a short period of time effect

Duty cycle concept

The ratio of the time that the PWM signal is ON of the LED or the speed of the motor

Example) 75% duty cycle →Approximately 3.3 V × 0.75 ≒ 2.5 V effect [Fig 7-10]

Program example

  • Controlling LED with machine.PWM class,
  • Specify a range of 0 to 1023 with the method *duty()*
  • brightness according to potentiometer input
  • Regulating cord avatar

7.5 Analog Output

33/42

34 of 44

2. Analog Creating an output program

Circuit example

  • Connect the multi-one shield to the internal pin area of the octoboard.
  • Circuit configuration with C3 mini on breadboard [Figure 7-9]

target

  • Pressing button_1 turns on both LEDs, and pressing button_2 turns off both LEDs.
  • When turning on the LED, the brightness is determined by the value of the potentiometer.
  • the LED is on, turn the potentiometer knob to adjust the brightness .

7.5 Analog Output

34/42

35 of 44

2. Analog Creating an output program

AI prompt Practice 7-4(1)

Create a MicroPython program and explain the code.

from machine import…

import time

Use time.sleep_ms().

Uses 2 LEDs and 2 buttons.

The module pinno stores the pin number constant value.

import pinno

POTENTIOMETER_PIN = pinno.L2_IN

BUTTON_1_PIN = pinno.L3_IN

BUTTON_2_PIN = pinno.L4_IN

LED_1_PIN = pinno.L5_IN

LED_2_PIN = pinno.L6_IN

About the POTENTIOMETER:

Method atten(): Specifies to read up to 3.3V

Method width(): 12-bit resolution

potentiometer_percent = (POTENTIOMETER reading value / 4095 * 100) integer

The first button should be PULL_UP and the second button should be PULL_DOWN.

BUTTON_1_PRESSED_VALUE = 0

BUTTON_2_PRESSED_VALUE = 1

7.5 Analog Output

35/42

36 of 44

2. Analog Creating an output program

AI prompt Practice 7-4(2)

The first LED is connected in a current sourcing manner,

The second LED is connected in a current-sinking manner.

led_1_on_percent = potentiometer_percent %

led_1_off_percent = 0 %

led_2_on_percent = (100 - potentiometer_percent) %

led_2_off_percent = 100%

When turning on the LED, PWM is based on led_x_on_percent.

When turning off the LED, PWM is set to led_x_off_percent.

About PWM:

Use the method duty().

Method freq(): 1000

led_on_off_state = False

prev_potentiometer = 0

When you start the program:

Print("on() when button_1 is pressed, off() when button_2 is pressed")

Print("When the light comes on, turn the knob to adjust the brightness")

Turn off both LEDs

7.5 Analog Output

36/42

37 of 44

2. Analog Creating an output program

AI prompt Practice 7-4(3)

Next is sequence It's running :

current_potentiometer and prev_potentiometer's If the difference is more than 2% :

prev_potentiometer = current_potentiometer

If led_on_off_state = True :

both LEDs (PWM: led_x_on_percent )

print(" Brightness Adjustment : {led_1_on_percent}%")

current_button_state != prev_button_state :

Debounce 20ms

button_1 is PRESSED :

Turn on both LEDs

print("on(): {led_1_on_percent}%")

button_2 is PRESSED :

Turn off both LEDs

print("off()")

In every while loop about :

prev_button_state = current_button_state

1ms pause

7.5 Analog Output

37/42

38 of 44

2. 아날로그 출력 프로그램 만들기

from machine import Pin, ADC, PWM�import time�import pinno��# 핀 번호 상수 설정�POTENTIOMETER_PIN = pinno.L2_IN�BUTTON_1_PIN = pinno.L3_IN�BUTTON_2_PIN = pinno.L4_IN�LED_1_PIN = pinno.L5_IN�LED_2_PIN = pinno.L6_IN��# 상수 설정�BUTTON_1_PRESSED_VALUE = 0�BUTTON_2_PRESSED_VALUE = 1�PWM_FREQ = 1000��# 핀 객체 설정�potentiometer = ADC(Pin(POTENTIOMETER_PIN))�potentiometer.atten(ADC.ATTN_11DB) # 3.3V까지 읽을 수 있도록 설정�potentiometer.width(ADC.WIDTH_12BIT) # 12비트 해상도 설정��BUTTON_1 = Pin(BUTTON_1_PIN, Pin.IN, Pin.PULL_UP)�BUTTON_2 = Pin(BUTTON_2_PIN, Pin.IN, Pin.PULL_DOWN)��led_1 = PWM(Pin(LED_1_PIN))�led_2 = PWM(Pin(LED_2_PIN))�

7.5 아날로그 출력

7-4의 코드 설명(1)

38/40

39 of 44

2. 아날로그 출력 프로그램 만들기

초기 설정�led_1.freq(PWM_FREQ)�led_2.freq(PWM_FREQ)��led_on_off_state = False�prev_potentiometer = 0�prev_BUTTON_1_state = BUTTON_1.value()�prev_BUTTON_2_state = BUTTON_2.value()��# 초기 메시지 출력�print("버튼_1을 누르면 on(), 버튼_2를 누르면 off()")�print("불이 켜지면 너브를 돌려서 밝기를 조절하세요")��# 두 LED를 끔�led_1.duty(0)�led_2.duty(1023)�

7.5 아날로그 출력

7-4의 코드 설명(2)

39/40

40 of 44

2. 아날로그 출력 프로그램 만들기

while True:� # 현재 퍼텐쇼미터 값을 읽음� current_potentiometer = potentiometer.read()� potentiometer_percent = int(current_potentiometer / 4095 * 100)�� # 퍼텐쇼미터 값이 2% 이상 변했는지 확인� if abs(current_potentiometer - prev_potentiometer) > (4095 * 0.02):� prev_potentiometer = current_potentiometer� � # LED가 켜져 있을 때 밝기 조절� if led_on_off_state:� led_1_on_percent = potentiometer_percent� led_2_on_percent = 100 - potentiometer_percent� � led_1.duty(int(led_1_on_percent / 100 * 1023))� led_2.duty(int(led_2_on_percent / 100 * 1023))� � print(f"밝기 조절: {led_1_on_percent}%")�� # 버튼 상태 확인� current_BUTTON_1_state = BUTTON_1.value()� current_BUTTON_2_state = BUTTON_2.value()�

7.5 아날로그 출력

7-4의 코드 설명(3)

40/40

41 of 44

2. 아날로그 출력 프로그램 만들기

# while True: 연결됨� # 버튼 상태가 변경되었는지 확인 (디바운스 적용)� if current_BUTTON_1_state != prev_BUTTON_1_state or \� current_BUTTON_2_state != prev_BUTTON_2_state:� time.sleep_ms(20) # 디바운스 시간� � # 버튼_1이 눌렸을 때� if BUTTON_1.value() == BUTTON_1_PRESSED_VALUE:� led_on_off_state = True� led_1.duty(int(potentiometer_percent / 100 * 1023))� led_2.duty(int((100 - potentiometer_percent) / 100 * 1023))� print(f"on(): {potentiometer_percent}%")� � # 버튼_2가 눌렸을 때� if BUTTON_2.value() == BUTTON_2_PRESSED_VALUE:� led_on_off_state = False� led_1.duty(0)� led_2.duty(1023)� print("off()")� � # 이전 버튼 상태 업데이트� prev_BUTTON_1_state = current_BUTTON_1_state� prev_BUTTON_2_state = current_BUTTON_2_state� � # 1ms 중지� time.sleep_ms(1)�

7-4의 코드 설명(4)

41/40

42 of 44

Practice Problems (1/2)

1

this chapter Used program The example has two buttons or 2 LEDs Use it There is . Because of this Button's Enter Processing and LED's Output In charge of similar There are two codes . List If you use it similar Function of The code One by one To be able to unify because The code It's simplified . Next together List To use prompt Edit it The results Please derive it .

(a) [AI prompt [Practice 7-1] List To use prompt Fix it , MicroPython Code and its explanation Please write .

(b) [AI prompt [Practice 7-2] List To use prompt Fix it , MicroPython Code and its explanation Please write .

(c) [AI prompt [Practice 7-3] List To use prompt Fix it , MicroPython Code and its explanation Please write .

(d) [AI prompt [Practice 7-4] List To use prompt Fix it , MicroPython Code and its explanation Please write .

42/42

43 of 44

Practice Problems (2/2)

2

[AI prompt In [Practice 7-2] , when button 1 is pressed, two LEDs are turned on. On and when you press button_2, both LEDs off . This prompt next On the condition To fit Fix it , MicroPython The code Create and of the code Description Please write .

  • Button and LED is To the list We will handle it .
  • When you press button_1 , both LEDs Adjust the brightness from 0% to 100% in 5 seconds , and then from 100% to 0% in the next 5 seconds . I repeat .
  • When you press button_2 , both LEDs Turn it off .

43/42

44 of 44

Q&A

Copyright© 2025 Hanbit Academy, Inc.

All rights reserved.