andrewb icon

yvonne2.py - MicroPython

andrewb | PRO | 07/19/20 10:53:47 AM UTC | 0 ⭐ | 842 👁️ | Never ⏰ | []
Python |

1.64 KB

|

None

|

0 👍

/

0 👎

from m5stack import *
import machine
from os import listdir, mount, remove
import utime as time
import random
 
 
# Sets up the SD Card. MUST be in try/catch because even when it works mount throws an exception.
try:
    sd = machine.SDCard(slot=2, miso=19, mosi=23, sck=18, cs=4)
    mount(sd, '/sd')
except:
    pass
 
 
def change_counter(value, change, minval=0, maxval=None):
    """Chain, chain, chain! Chain of ints"""
    value += change
    if value < minval:
        return maxval
    if value > maxval:
        return minval
    return value
 
 
def copy_image(img_path):
    """My M5Stack Core won't read images from the SD card so they have to be copied to the flash memory"""
    remove(IMG_NAME)
    fr = open(img_path)
    fw = open(IMG_NAME, "wb")
    fw.write(fr.read())
    fr.close()
    fw.close()
 
 
def set_image(action=None):
    """Performs the prescribed action to select the image then displays it on the screen"""
    global IMG_COUNTER
    if action:
        IMG_COUNTER = change_counter(IMG_COUNTER, action, 0, len(IMG_LIST) - 1)
    else:
        IMG_COUNTER = random.randint(0, len(IMG_LIST) - 1)
    copy_image(IMG_DIR + '/' + IMG_LIST[IMG_COUNTER])
    lcd.image(0, 0, IMG_NAME, 0, lcd.JPG)
 
 
# This is bad form and bad MicroPython. These should be local and set within a main() function.
IMG_COUNTER = 0
IMG_DIR = '/sd/yvonne'
IMG_LIST = listdir(IMG_DIR)
IMG_NAME = "/flash/yvonne.jpg"
 
lcd.clear(lcd.WHITE)
set_image()
 
while True:
    if btnA.isPressed():
        set_image(-1)
    if btnB.isPressed():
        set_image()
    if btnC.isPressed():
        set_image(1)
    time.sleep(0.1)

Comments