883 views|6 replies

118

Posts

1

Resources
The OP
 

[Digi-Key Electronics Follow me Issue 3] Design of a reading light indicator based on ESP32-C3 [Copy link]

 This post was last edited by Murong Xuehua on 2023-11-11 08:36

阅读光照提醒

Core board introduction:

characteristic

Powerful CPU: ESP32-C3, 32-bit RISC-V single-core processor, running at up to 160 MHz
Complete WiFi subsystem: compliant with IEEE 802.11b/g/n protocols, supporting Station mode, SoftAP mode, SoftAP+Station mode, promiscuous mode
Bluetooth LE subsystem: supports Bluetooth 5 and Bluetooth mesh functions
Ultra-low power consumption: deep sleep power consumption is about 43μA
Better RF performance: external RF antenna can be connected
Battery charging chip: supports lithium battery charging and discharging management
Rich on-chip resources: 400KB SRAM, 4MB onboard flash memory
Ultra-small size: as small as a thumb (20x17.5mm) XIAO series classic form factor, suitable for wearable devices and small projects
Reliable security functions: cryptographic hardware accelerator supporting AES-128/256, hash, RSA, HMAC, digital signature and secure boot
Rich interfaces: 1xI2C, 1xSPI, 2xUART, 11xGPIO (PWM), 4xADC, 1xJTAG
Single-sided component layout, support surface mount design

Official Wiki: https://wiki.seeedstudio.com/XIAO_ESP32C3_Getting_Started/

The pin diagram is as follows:

Expansion board hardware resources:

https://wiki.seeedstudio.com/Seeeduino-XIAO-Expansion-Board/

https://www.seeedstudio.com/Seeeduino-XIAO-Expansion-board-p-4746.html?queryID=bd1aef586d96a08ad9a2e813c1931aa7&objectID=4746&indexName=bazaar_retailer _

Task 1: Use MicroPython system (required task)

The IDE on the computer uses THONNY. The following describes how to flash the latest MICROPYTHON firmware to C3: ESP32_GENERIC_C3-20231005-v1.21.0.bin

1. Go to Micropython official website to download the latest C3 firmware: https://micropython.org/download/ESP32_GENERIC_C3/

2. Check whether the Python version on your computer is 3.4 or above, because you will need pip to install the refresh tool next.

3. Install the esptool flash tool

pip install esptool -i https://pypi.tuna.tsinghua.edu.cn/simple some-package

Confirm whether the serial port number is installed correctly:

esptool.py --h

4. Connect the development board to the computer and confirm the serial port number

5. Clear the development board FLASH

esptool.py  --chip esp32c3 --port COM23 erase_flash

6. Flash the latest firmware to C3

esptool.py  --chip esp32c3 --port COM23 --baud 460800 write_flash -z 0x0 ESP32_GENERIC_C3-20231005-v1.21.0.bin

7. Re-plug the USB, open the THONNY software, and select ESP32 in the lower right corner
As shown in the figure above, the latest Micropython firmware has been successfully flashed, and normal Python operations can be performed!

Task 2: Drive the OLED screen on the expansion board (mandatory task)

1. Download the SSD1306 driver in THONNY IDE

2. Add relevant initialization code

from machine import Pin, I2C
from ssd1306 import SSD1306_I2C

i2c=I2C(0,sda=Pin(6), scl=Pin(7), freq=400000)
oled = SSD1306_I2C(128, 64, i2c)

oled.text("WELCOME!", 0, 0)
oled.text("This is EEWORLD", 0, 16)
oled.text("FOLLOW ME 3", 0, 32)
oled.text("JOIN US", 0, 48)
oled.show()

Precautions:

!
Before using it, it is required for me to state the software/firmware I'm using here is designed for the ESP32C3 chip. Hence when you are trying to use pin, make sure the General Purpose Input/Output instead of the pin on the board.
For example, when you are trying to use the pin in the first row on the left. Make sure it is GPIO2 instead of A0 or D0.

3. Physical effect:

4. Code: TASK2-OLED.zip (1.98 KB, downloads: 1)

Task 3: Control the buzzer to play music (mandatory task)

A passive buzzer is connected to the A3 pin on the expansion board.

By using different duty cycles and frequencies of PWM, you can control the buzzer to emit different sounds, or even play music!

# Buzzer settings
buzzer_pin = machine.Pin(5, machine.Pin.OUT)
buzzer = machine.PWM(buzzer_pin)
buzzer.freq(1047)

Below we take the relatively simple Twinkle Twinkle Little Star music score as an example to use the buzzer on the C3 expansion board to play music.

Below is the relationship between the notes and frequencies of C:

# 定义音调频率
tones = {'1': 262, '2': 294, '3': 330, '4': 349, '5': 392, '6': 440, '7': 494, '-': 0}
# 定义小星星旋律
melody = "1155665-4433221-5544332-5544332-1155665-4433221"

while True:
    # Play the song
    for tone in melody:
        freq = tones[tone]
        if freq:
        # 调整PWM的频率,使其发出指定的音调
            buzzer.duty(1000)  # Set duty cycle for sound
            buzzer.freq(freq)  # Set frequency of the note
        else:
            buzzer.duty(0)  # 空拍时一样不上电
        # 停顿一下 (四四拍每秒两个音,每个音节中间稍微停顿一下)
        time.sleep_ms(400)
        buzzer.duty(0)  # 设备占空比为0,即不上电
        time.sleep_ms(100)

Physical display:

f154877482b2cfdc32d08855d9893029

Code: TASK3-BUZZER-MUSIC-V2.py (1.21 KB, downloads: 0)

Task 4: Connect to WiFi network (mandatory task)

Connecting to a network using Micropython is relatively simple:

def scan_and_connect():
    station = network.WLAN(network.STA_IF)
    station.active(True)

    print("Scanning for WiFi networks, please wait...")
    for ssid, bssid, channel, RSSI, authmode, hidden in station.scan():
        print("* {:s}".format(ssid))
        print("   - Channel: {}".format(channel))
        print("   - RSSI: {}".format(RSSI))
        print("   - BSSID: {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}".format(*bssid))
        print()

    while not station.isconnected():
        print("Connecting...")
        station.connect(wifi_ssid, wifi_password)
        time.sleep(10)

    print("Connected!")
    print("My IP Address:", station.ifconfig()[0])

After the connection is successful, the console outputs the corresponding IP address:

* TP-LINK_2804
   - Channel: 6
   - RSSI: -92
   - BSSID: 34:96:72:c2:28:04

* Hi32003Y7A1102300133002447F41513
   - Channel: 6
   - RSSI: -92
   - BSSID: 08:31:8b:62:7f:41

Connected!
My IP Address: 192.168.0.104

Next, I will access Xinzhi Weather through the URL and obtain the local weather information in Shanghai. Among them, Xinzhi Weather returns the data in json format:

url = "https://api.seniverse.com/v3/weather/now.json?key=请替换自己的KEY&location=shanghai&language=zh-Hans&unit=c"
while True:
    # Perform HTTP GET request on a non-SSL web
    response = urequests.get(url)
    # Check if the request was successful
    if response.status_code == 200:
        # Parse the JSON response
        weather = ujson.loads(response.text)
        print(weather)
        # Extract the "datetime" field for New York
        current_weather = weather["results"][0]["now"]

        # Get the Temperature
        current_temperature = current_weather["temperature"]
        
        # Clear the OLED display
        oled.fill(0)
        
        # Display the New York date and time on separate lines
        oled.text("Shanghai Temperature:", 0, 0)
        oled.text(current_temperature, 0, 10)
        # Update the display
        oled.show()
    else:
        oled.text("Failed to get the weather")
        # Update the display
        oled.show()
    time.sleep(30)

The console output is as follows:

{'results': [{'location': {'name': '\u4e0a\u6d77', 'path': '\u4e0a\u6d77,\u4e0a\u6d77,\u4e2d\u56fd', 'timezone': 'Asia/Shanghai', 'timezone_offset': '+08:00', 'id': 'WTW3SJ5ZBJUY', 'country': 'CN'}, 'last_update': '2023-11-10T18:30:32+08:00', 'now': {'text': '\u591a\u4e91', 'code': '4', 'temperature': '14'}}]}

Physical display:

获取天气

Code: TASK4-ConnectToWiFi-V2 - eeworld.py (2.14 KB, downloads: 0)

Task 5: Using External Sensors (Required)

This time we drive the temperature and humidity sensor AHT20:

install driver:

Core code:

from ahtx0 import AHT20

# Oled init
i2c=machine.I2C(0,sda=Pin(6), scl=Pin(7), freq=400000)
oled = SSD1306_I2C(128, 64, i2c)

oled.text("This is TASK5", 0, 0)
oled.text("aht20", 0, 16)
oled.text("Temp:", 0, 32)
oled.text("Humi:", 0, 48)
oled.show()

#aht20
aht = AHT20(i2c)

def ahtxx():
    temp = aht.temperature
    humi = aht.relative_humidity
    
    print("\n")
    print(temp)
    print("\n")
    print(humi)
    
    #print("\n");
    #print('{:.2f}'.format(humi))
    oled.fill_rect(50,32,40,30,0) # 局部清屏
    oled.text('{:.2f}'.format(temp), 50, 32)
    oled.text('{:.2f}'.format(humi), 50, 48)
    oled.show()   
    time.sleep(1)

Physical display:

Physical display:

1ad2087c64b309fd3f4a281e58dea393_raw

Code: TASK5-AHT20.py (1.15 KB, downloads: 1)

Task 6: Subtask 3: Light-on reminder
Monitor the ambient light intensity. If the light is too dim, remind the user to turn on the light through the screen and buzzer to protect eyesight.

  • Grove Light Sensor v1.2 is an analog light sensor with a maximum of 350 lux corresponding to ADC 4095
  • There is also a red LED and Grove interface, which is very convenient to use
  • oled is used to display the current lux value. If the light brightness is lower than 50, it means it is very dark. The buzzer alarms and the red LED lights up and the OLED screen outputs a warning: TOO DARK!

Main code:

#led
led_red = machine.Pin(20, Pin.OUT)
led_red.off()

#adc
adc = machine.ADC(Pin(2))
adc.atten(machine.ADC.ATTN_11DB)
adc.width(machine.ADC.WIDTH_12BIT)  #4095

# Buzzer settings
buzzer_pin = machine.Pin(5, machine.Pin.OUT)
buzzer = machine.PWM(buzzer_pin)
buzzer.freq(1047)

def lightSensor():
    
    temp = adc.read()
    print("\n")
    print("lightsensor value: ")
    print(temp)
    
    lux_float = temp*350*1.0/4095;
    oled.fill_rect(50,32,77,30,0) # 局部清屏
    oled.text('{:.2f}'.format(lux_float), 50, 32)
    if lux_float < 50:
        oled.text("Too dark!", 50, 48)
        buzzer.duty(512)  # Turn off the sound
        led_red.on()
    else:
        buzzer.duty(0)  # Turn off the sound
        led_red.off()
        
    oled.show()
    
    time.sleep(1)

Physical display:

cffaf02510560984a05834e543dcae18_raw

Code: TASK6-lightSensor-V2.py (1.12 KB, downloads: 1)

Summarize:

I am very happy to participate in this FOLLOW ME event. Through this event, I flashed the micropython firmware into esp32c3, drove OLED, connected to the Internet, obtained weather information, and drove the aht20 temperature and humidity sensor, and finally made a simple reading reminder. I learned a lot and improved my knowledge. I hope the follow me event will get better and better!

Reference Documents:

1. https://wiki.seeedstudio.com/XIAO_ESP32C3_Getting_Started/

2. https://wiki.seeedstudio.com/XIAO_ESP32C3_MicroPython/

This post is from DigiKey Technology Zone

Latest reply

You can try to update Thonny to version 4.1.4 or just copy the ssd1306.py file and drop it in.   Details Published on 2023-11-22 10:43
 
 

164

Posts

2

Resources
2
 

It's too curly. I just soldered the pins today.

This post is from DigiKey Technology Zone

Comments

I did the welding yesterday morning.  Details Published on 2023-11-11 18:47
 
 
 

6822

Posts

11

Resources
3
 
ssd1306, can your library be downloaded? I tried N times but it didn't work.
This post is from DigiKey Technology Zone

Comments

Some magic  Details Published on 2023-11-22 10:43
Some magic  Details Published on 2023-11-11 18:46
 
 
 

118

Posts

1

Resources
4
 
lugl4313820 posted on 2023-11-11 10:14 ssd1306, can your library be downloaded? I tried N times but it didn't work.

Some magic

This post is from DigiKey Technology Zone
 
 
 

118

Posts

1

Resources
5
 
EPTmachine posted on 2023-11-11 09:58 It's too curly, I just soldered the pins today

I did the welding yesterday morning.

This post is from DigiKey Technology Zone
 
 
 

725

Posts

4

Resources
6
 

Thanks for the technical sharing provided by the host. I will collect and study it first and then express my personal opinion.

This post is from DigiKey Technology Zone
 
 
 

24

Posts

3

Resources
7
 
lugl4313820 posted on 2023-11-11 10:14 ssd1306, can your library be downloaded? I tried N times but it didn't work.

You can try to update Thonny to version 4.1.4 or just copy the ssd1306.py file and drop it in.

This post is from DigiKey Technology Zone
 
 
 

Guess Your Favourite
Just looking around
Find a datasheet?

EEWorld Datasheet Technical Support

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京B2-20211791 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号
快速回复 返回顶部 Return list