from machine import Pin, I2C, SPI, RTC
from machine import SDCard
# import sdcard
from utime import sleep
# import os
import uos as os
import sys
import ssd1306
currentBoard=""
if(sys.platform=="esp32"):
currentBoard="esp32"
I2C_SDA =21 # GPIO21(I2C SDA)
I2C_SCL =22 # GPIO22(I2C SCL)
SPI_CS = 5 # GPIO5(SPI CS)
SPI_MOSI = 23 # GPIO23(SPI MOSI)
SPI_MISO = 19 # GPIO19(SPI MISO)
SPI_SCLK = 18 # GPIO18(SPI SCLK)
elif(sys.platform=="esp8266"):
currentBoard="esp8266"
I2C_SDA =4 # GPIO4(D2)
I2C_SCL =5 # GIPO5(D1)
SPI_CS = 15 # GPIO15(D8)(SPI CS)
SPI_MOSI = 13 # GPIO13(D7)(SPI MOSI)
SPI_MISO = 12 # GPIO12(D6)(SPI MISO)
SPI_SCLK = 14 # GPIO14(D5)(SPI SCLK)
elif(sys.platform=="rp2"):
currentBoard="Pi-Pico"
I2C_SDA =4 # GPIO4(I2C SDA)
I2C_SCL =5 # GPIO5(I2C SCL)
oled_width = 128
oled_height = 64
# Start Function
if __name__ == '__main__':
print("Hello, " + sys.platform + "!")
# ESP32 Pin assignment
i2c = I2C(0, scl=Pin(I2C_SCL), sda=Pin(I2C_SDA), freq=400000) #initializing the I2C method for ESP32
devices = i2c.scan()
if len(devices) == 0:
print("No i2c device !")
else:
print('i2c devices found:',len(devices))
for device in devices:
print("At address: ",hex(device))
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
oled.text('Hello, Wokwi!', 10, 10)
oled.show()
print("main test")
sd = SDCard(slot=2, width=1, sck=SPI_SCLK, miso=SPI_MISO, mosi=SPI_MOSI, cs=SPI_CS)
# Mount filesystem
vfs = os.VfsFat(sd)
os.mount(vfs, '/sd')
print(os.statvfs('/'))
# https://docs.micropython.org/en/latest/library/os.html
# (4096, 4096, 512, 448, 448, 0, 0, 0, 0, 255)
# 4096 * 512 is total space in bytes
# 4096 * 448 is free space in bytes
# used space = total - free
try:
os.mkdir('/sd/lib')
except Exception as e:
print('Directory created.', e)
os.chdir('/sd/lib')
print(os.listdir('/sd')) # list directory contents
print(os.getcwd()) # 顯示目前工作目錄
rtc = RTC() #建立 RTC 物件
# Create a file and write something to it
with open("/sd/test01.txt", "a") as myfile:
text_to_append = "Hello, SD World!\r\n"
timestamp = rtc.datetime()
log_entry = f"[{timestamp}] {text_to_append}\n" # 組合成一行文字
myfile.write(log_entry)
text_to_append = "This is a test\r\n"
timestamp = rtc.datetime()
log_entry = f"[{timestamp}] {text_to_append}\n" # 組合成一行文字
myfile.write(log_entry)
myfile.close()
myfile = open('hello.py', 'w')
myfile.write('print("hello!")')
myfile.close()
print(os.listdir('/sd')) # list directory contents
# Open the file we just created and read from it
with open("/sd/test01.txt", "r") as myfile:
data = myfile.read()
print(data)
myfile.close()
myfile = open('hello.py', 'r')
print(myfile.read())
myfile.close()
sys.path.append('/sd/lib')
sys.path
import hello