| 1 |
# TinyS2 MicroPython Helper Library |
| 2 |
# 2021 Seon Rozenblum - Unexpected Maker |
| 3 |
# |
| 4 |
# Project home: |
| 5 |
# https://tinys2.io |
| 6 |
# |
| 7 |
# 2021-Apr-10 - v0.1 - Initial implementation |
| 8 |
|
| 9 |
# Import required libraries |
| 10 |
from micropython import const |
| 11 |
from machine import Pin, SPI, ADC |
| 12 |
import machine, time |
| 13 |
|
| 14 |
# TinyS2 Hardware Pin Assignments |
| 15 |
|
| 16 |
# Sense Pins |
| 17 |
VBUS_SENSE = const(21) |
| 18 |
VBAT_SENSE = const(3) |
| 19 |
|
| 20 |
|
| 21 |
# RGB LED Pins |
| 22 |
RGB_DATA = const(1) |
| 23 |
RGB_PWR = const(2) |
| 24 |
|
| 25 |
# SPI |
| 26 |
SPI_MOSI = const(35) |
| 27 |
SPI_MISO = const(36) |
| 28 |
SPI_CLK = const(37) |
| 29 |
|
| 30 |
# I2C |
| 31 |
I2C_SDA = const(8) |
| 32 |
I2C_SCL = const(9) |
| 33 |
|
| 34 |
# DAC |
| 35 |
DAC1 = const(17) |
| 36 |
DAC2 = const(18) |
| 37 |
|
| 38 |
|
| 39 |
# Helper functions |
| 40 |
def set_pixel_power(state): |
| 41 |
"""Enable or Disable power to the onboard NeoPixel to either show colour, or to reduce power for deep sleep.""" |
| 42 |
Pin(RGB_PWR, Pin.OUT).value(state) |
| 43 |
|
| 44 |
|
| 45 |
def get_battery_voltage(): |
| 46 |
""" |
| 47 |
Returns the current battery voltage. If no battery is connected, returns 4.2V which is the charge voltage |
| 48 |
This is an approximation only, but useful to detect if the charge state of the battery is getting low. |
| 49 |
""" |
| 50 |
adc = ADC(Pin(VBAT_SENSE)) # Assign the ADC pin to read |
| 51 |
measuredvbat = adc.read() # Read the value |
| 52 |
measuredvbat /= 8192 # divide by 8192 as we are using the default ADC voltage range of 0-1V |
| 53 |
measuredvbat *= 4.2 # Multiply by 4.2V, our reference voltage |
| 54 |
return round(measuredvbat, 2) |
| 55 |
|
| 56 |
|
| 57 |
def get_vbus_present(): |
| 58 |
"""Detect if VBUS (5V) power source is present""" |
| 59 |
return Pin(VBUS_SENSE, Pin.IN).value() == 1 |
| 60 |
|
| 61 |
|
| 62 |
# NeoPixel rainbow colour wheel |
| 63 |
def rgb_color_wheel(wheel_pos): |
| 64 |
"""Color wheel to allow for cycling through the rainbow of RGB colors.""" |
| 65 |
wheel_pos = wheel_pos % 255 |
| 66 |
|
| 67 |
if wheel_pos < 85: |
| 68 |
return 255 - wheel_pos * 3, 0, wheel_pos * 3 |
| 69 |
elif wheel_pos < 170: |
| 70 |
wheel_pos -= 85 |
| 71 |
return 0, wheel_pos * 3, 255 - wheel_pos * 3 |
| 72 |
else: |
| 73 |
wheel_pos -= 170 |
| 74 |
return wheel_pos * 3, 255 - wheel_pos * 3, 0 |
| 75 |
|
| 76 |
|
| 77 |
# Go into deep sleep but shut down the RGB LED first to save power |
| 78 |
# Use this if you want lowest deep sleep current |
| 79 |
def go_deepsleep(t): |
| 80 |
"""Deep sleep helper that also powers down the on-board NeoPixel.""" |
| 81 |
set_pixel_power(False) |
| 82 |
machine.deepsleep(t) |