andrewb

yvonne2.py - MicroPython

Jul 19th, 2020
415
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.64 KB | None | 0 0
  1. from m5stack import *
  2. import machine
  3. from os import listdir, mount, remove
  4. import utime as time
  5. import random
  6.  
  7.  
  8. # Sets up the SD Card. MUST be in try/catch because even when it works mount throws an exception.
  9. try:
  10.     sd = machine.SDCard(slot=2, miso=19, mosi=23, sck=18, cs=4)
  11.     mount(sd, '/sd')
  12. except:
  13.     pass
  14.  
  15.  
  16. def change_counter(value, change, minval=0, maxval=None):
  17.     """Chain, chain, chain! Chain of ints"""
  18.     value += change
  19.     if value < minval:
  20.         return maxval
  21.     if value > maxval:
  22.         return minval
  23.     return value
  24.  
  25.  
  26. def copy_image(img_path):
  27.     """My M5Stack Core won't read images from the SD card so they have to be copied to the flash memory"""
  28.     remove(IMG_NAME)
  29.     fr = open(img_path)
  30.     fw = open(IMG_NAME, "wb")
  31.     fw.write(fr.read())
  32.     fr.close()
  33.     fw.close()
  34.  
  35.  
  36. def set_image(action=None):
  37.     """Performs the prescribed action to select the image then displays it on the screen"""
  38.     global IMG_COUNTER
  39.     if action:
  40.         IMG_COUNTER = change_counter(IMG_COUNTER, action, 0, len(IMG_LIST) - 1)
  41.     else:
  42.         IMG_COUNTER = random.randint(0, len(IMG_LIST) - 1)
  43.     copy_image(IMG_DIR + '/' + IMG_LIST[IMG_COUNTER])
  44.     lcd.image(0, 0, IMG_NAME, 0, lcd.JPG)
  45.  
  46.  
  47. # This is bad form and bad MicroPython. These should be local and set within a main() function.
  48. IMG_COUNTER = 0
  49. IMG_DIR = '/sd/yvonne'
  50. IMG_LIST = listdir(IMG_DIR)
  51. IMG_NAME = "/flash/yvonne.jpg"
  52.  
  53. lcd.clear(lcd.WHITE)
  54. set_image()
  55.  
  56. while True:
  57.     if btnA.isPressed():
  58.         set_image(-1)
  59.     if btnB.isPressed():
  60.         set_image()
  61.     if btnC.isPressed():
  62.         set_image(1)
  63.     time.sleep(0.1)
Add Comment
Please, Sign In to add comment