"Instrumentation and measurement": ADC and Timer
1. API Function for adc
import time
from machine import Pin, ADC
# using pin 26
adc = ADC(Pin(26))
# get the adc value
# resolutions:12 bits, return value 0-4095
val = adc.read()
# Attenuation
# ADC_ATTN_2_5DB(2.5dB:Maximum input: 1.34 V)、
# ADC_ATTN_6DB(6dB: Maximum input 2 V)
# ADC_ATTN_11DB(11dB: Maximum input 3.3 V)
adc.atten(ADC.ATTN_11DB)
2. Pins and GPIO
from machine import Pin p0 = Pin(0, Pin.OUT) # create output pin on GPIO0 p0.on() # set pin to "on" (high) level p0.off() # set pin to "off" (low) level p0.value(1) # set pin to on/high p2 = Pin(2, Pin.IN) # create input pin on GPIO2 print(p2.value()) # get value, 0 or 1 p4 = Pin(4, Pin.IN, Pin.PULL_UP) # enable internal pull-up resistor p5 = Pin(5, Pin.OUT, value=1) # set pin high on creation p6 = Pin(6, Pin.OUT, drive=Pin.DRIVE_3) # set maximum drive strength
3. Timer
from machine import Timer tim0 = Timer(0) tim0.init(period=5000, mode=Timer.ONE_SHOT, callback=lambda t:print(0)) tim1 = Timer(1) tim1.init(period=2000, mode=Timer.PERIODIC, callback=lambda t:print(1))
import time
from machine import Pin, Timer
# 定义 Pin 控制引脚
led_1 = Pin(2, Pin.OUT)
led_2 = Pin(4, Pin.OUT)
# 定义定时器中断的回调函数
def timer_irq(timer_pin):
led_1.value(not led_1.value())
# 定义定时器
timer = Timer(0)
# 初始化定时器
timer.init(period=500, mode=Timer.PERIODIC, callback=timer_irq)
while True:
led_2.value(not led_2.value())
time.sleep(1)