初始化提交

This commit is contained in:
王立帮
2024-07-19 10:16:00 +08:00
parent 4c7b571f20
commit 4a2d56dcc4
7084 changed files with 741212 additions and 63 deletions

View File

@@ -0,0 +1,289 @@
"""
MINI_WCH
Micropython library for the MINI_WCH(TOUCH*2, MIC*1, Buzzer*1, PWM*2, Matrix8x12)
=======================================================
@dahanzimin From the Mixly Team
"""
import time
from esp import flash_read
from micropython import const
from framebuf import FrameBuffer, MONO_VLSB
_BOT035_ADDRESS = const(0x13)
_BOT5_TOUCH = const(0x01)
_BOT035_MIC = const(0x05)
_BOT035_SPK = const(0x07)
_BOT035_PWM = const(0x0B)
_BOT035_FLAG = const(0x0F)
_BOT035_LEDS = const(0x10)
_BOT035_PGA = const(0x20)
_FONT_W = const(5)
_FONT_H = const(8)
_LEDS_W = const(12)
_LEDS_H = const(8)
_FONT5x8_CODE = const(b'\x05\x08\x00\x00\x00\x00\x00\x00\x00_\x00\x00\x00\x07\x00\x07\x00\x14\x7f\x14\x7f\x14$*\x7f*\x12#\x13\x08db6IV P\x00\x08\x07\x03\x00\x00\x1c"A\x00\x00A"\x1c\x00*\x1c\x7f\x1c*\x08\x08>\x08\x08\x00\x80p0\x00\x08\x08\x08\x08\x08\x00\x00``\x00 \x10\x08\x04\x02>QIE>\x00B\x7f@\x00rIIIF!AIM3\x18\x14\x12\x7f\x10\'EEE9<JII1A!\x11\t\x076III6FII)\x1e\x00\x00\x14\x00\x00\x00@4\x00\x00\x00\x08\x14"A\x14\x14\x14\x14\x14\x00A"\x14\x08\x02\x01Y\t\x06>A]YN|\x12\x11\x12|\x7fIII6>AAA"\x7fAAA>\x7fIIIA\x7f\t\t\t\x01>AAQs\x7f\x08\x08\x08\x7f\x00A\x7fA\x00 @A?\x01\x7f\x08\x14"A\x7f@@@@\x7f\x02\x1c\x02\x7f\x7f\x04\x08\x10\x7f>AAA>\x7f\t\t\t\x06>AQ!^\x7f\t\x19)F&III2\x03\x01\x7f\x01\x03?@@@?\x1f @ \x1f?@8@?c\x14\x08\x14c\x03\x04x\x04\x03aYIMC\x00\x7fAAA\x02\x04\x08\x10 \x00AAA\x7f\x04\x02\x01\x02\x04@@@@@\x00\x03\x07\x08\x00 TTx@\x7f(DD88DDD(8DD(\x7f8TTT\x18\x00\x08~\t\x02\x18\xa4\xa4\x9cx\x7f\x08\x04\x04x\x00D}@\x00 @@=\x00\x7f\x10(D\x00\x00A\x7f@\x00|\x04x\x04x|\x08\x04\x04x8DDD8\xfc\x18$$\x18\x18$$\x18\xfc|\x08\x04\x04\x08HTTT$\x04\x04?D$<@@ |\x1c @ \x1c<@0@<D(\x10(DL\x90\x90\x90|DdTLD\x00\x086A\x00\x00\x00w\x00\x00\x00A6\x08\x00\x02\x01\x02\x04\x02<&#&<')
_Uincode_ADDR = const(0x3A0000)
class BOT035(FrameBuffer):
def __init__(self, i2c_bus, brightness=0.8):
self._i2c= i2c_bus
self._buffer = bytearray(12)
self._brightness = brightness
self._touchs = [self.touch(0), self.touch(1)]
super().__init__(self._buffer, _LEDS_W, _LEDS_H, MONO_VLSB)
self.reset()
self.show()
def _chardata(self, ch):
'''Ascall code font reading data'''
if 0x20 <= ord(ch) <= 0x7f:
char_index = 2 + (ord(ch)-32) * _FONT_W
return _FONT5x8_CODE[char_index : char_index + _FONT_W]
def _uincode(self, ch):
'''uincode code font reading data'''
uni = ord(ch)
if 0x20 <= uni <= 0x2642 :
_address = 0x28 + (uni - 0x20) * 4
elif 0x3001 <= uni <= 0x9fa0 :
_address = 0x98b4 + (uni - 0x3001) * 4
elif 0xff01 <= uni <= 0xffe5 :
_address = 0x25734 + (uni - 0xff01) * 4
else:
return None, 0
buffer = bytearray(4)
flash_read(_Uincode_ADDR + _address, buffer)
font_info = buffer[3] << 24 | buffer[2] << 16 | buffer[1] << 8 | buffer[0]
font_address = font_info & 0X3FFFFFF
font_width = font_info >> 26
buffer = bytearray( 12 * (font_width // 8 + 1))
flash_read(_Uincode_ADDR + font_address, buffer)
return buffer, font_width
def shift(self, x, y, rotate=False):
"""Shift pixels by x and y"""
if x > 0: # Shift Right
for _ in range(x):
for row in range(0, _LEDS_H):
last_pixel = self.pixel(_LEDS_W - 1, row) if rotate else 0
for col in range(_LEDS_W - 1, 0, -1):
self.pixel(col, row, self.pixel(col - 1, row))
self.pixel(0, row, last_pixel)
elif x < 0: # Shift Left
for _ in range(-x):
for row in range(0, _LEDS_H):
last_pixel = self.pixel(0, row) if rotate else 0
for col in range(0, _LEDS_W - 1):
self.pixel(col, row, self.pixel(col + 1, row))
self.pixel(_LEDS_W - 1, row, last_pixel)
if y > 0: # Shift Up
for _ in range(y):
for col in range(0, _LEDS_W):
last_pixel = self.pixel(col, _LEDS_H - 1) if rotate else 0
for row in range(_LEDS_H - 1, 0, -1):
self.pixel(col, row, self.pixel(col, row - 1))
self.pixel(col, 0, last_pixel)
elif y < 0: # Shift Down
for _ in range(-y):
for col in range(0, _LEDS_W):
last_pixel = self.pixel(col, 0) if rotate else 0
for row in range(0, _LEDS_H - 1):
self.pixel(col, row, self.pixel(col, row + 1))
self.pixel(col, _LEDS_H - 1, last_pixel)
self.show()
def shift_right(self, num, rotate=False):
"""Shift all pixels right"""
self.shift(num, 0, rotate)
def shift_left(self, num, rotate=False):
"""Shift all pixels left"""
self.shift(-num, 0, rotate)
def shift_up(self, num, rotate=False):
"""Shift all pixels up"""
self.shift(0, -num, rotate)
def shift_down(self, num, rotate=False):
"""Shift all pixels down"""
self.shift(0, num, rotate)
def map_invert(self, own):
"""Graph invert operation"""
result = bytearray()
for i in range(len(own)):
result.append(~ own[i])
return result
def map_add(self, own, other):
"""Graph union operation"""
result = bytearray()
for i in range(min(len(own), len(other))):
result.append(own[i] | other[i])
return result
def map_sub(self, own, other):
"""Graphic subtraction operation"""
result = bytearray()
for i in range(min(len(own), len(other))):
result.append((own[i] ^ other[i]) & own[i])
return result
def set_buffer(self, buffer):
for i in range(len(buffer)):
self._buffer[i] = self._buffer[i] | buffer[i]
def _ascall_bitmap(self, buffer, x=0):
if -_FONT_W <= x <= _LEDS_W:
for _x in range(_FONT_W):
for _y in range(_FONT_H):
if (buffer[_x] >> _y) & 0x1:
self.pixel(x + _x, _y, 1)
def _uincode_bitmap(self, buffer, x=0):
_buffer, width = buffer
if -width < x < _LEDS_H:
for _y in range(12):
for _x in range(width):
if _buffer[_y * ((width + 7) // 8) + _x // 8] & (0x80 >> (_x & 7)):
self.pixel(_y, _LEDS_H - (x + _x), 1)
def shows(self, data, space=1, center=True):
"""Display character"""
if data is not None:
self.fill(0)
if type(data) in [bytes, bytearray]:
self.set_buffer(data)
self.show()
else:
data = str(data)
x = (_LEDS_W - len(data) * (_FONT_W + space) + space) // 2 if center else 0
for char in data:
self._ascall_bitmap(self._chardata(char), x)
x = _FONT_W + x + space
self.show()
def frame(self, data, delay=500):
"""Display one frame per character"""
if data is not None:
data = str(data)
for char in data:
self.fill(0)
self._ascall_bitmap(self._chardata(char), (_LEDS_W - _FONT_W) // 2)
self.show()
time.sleep_ms(delay)
def scroll(self, data, space=0, speed=100):
"""Scrolling characters"""
if data is not None:
data = str(data)
uincode = False
for char in data:
if ord(char) >= 0xff:
uincode =True
break
if uincode:
font_buffer = []
str_len = 0
for c in data:
_buffer = self._uincode(c)
font_buffer.append(_buffer)
str_len = str_len + _buffer[1] + space
for i in range(str_len + _LEDS_H - space):
x = _LEDS_H - i
self.fill(0)
for buffer in font_buffer:
self._uincode_bitmap(buffer, x)
x = buffer[1] + x + space
self.show()
time.sleep_ms(speed)
else:
str_len = len(data) * (_FONT_W + space) - space
for i in range(str_len + _LEDS_W + 1):
x = _LEDS_W -i
self.fill(0)
for char in data:
self._ascall_bitmap(self._chardata(char), x)
x = _FONT_W + x + space
self.show()
time.sleep_ms(speed)
def _wreg(self, reg, val):
'''Write memory address'''
self._i2c.writeto_mem(_BOT035_ADDRESS, reg, val.to_bytes(1, 'little'))
def _rreg(self, reg, nbytes=1):
'''Read memory address'''
self._i2c.writeto(_BOT035_ADDRESS, reg.to_bytes(1, 'little'))
return self._i2c.readfrom(_BOT035_ADDRESS, nbytes)[0]
def reset(self):
"""Reset SPK, PWM registers to default state"""
self._i2c.writeto_mem(_BOT035_ADDRESS, _BOT035_SPK, b'\x0A\x00\x00\x00\x20\x4E\x64\x64')
def get_brightness(self):
return self._brightness
def set_brightness(self, brightness):
if not 0.0 <= brightness <= 1.0:
raise ValueError("Brightness must be a decimal number in the range: 0.0-1.0")
self._brightness = brightness
self._wreg(_BOT035_FLAG, _BOT035_PGA | round(10 * brightness))
def show(self):
self._i2c.writeto_mem(_BOT035_ADDRESS, _BOT035_LEDS, self._buffer)
def buzzer(self, duty=None, freq=None):
if duty is not None:
duty = max(min(duty, 100), 0)
self._wreg(_BOT035_SPK + 2, int(duty))
if freq is not None:
freq = max(min(freq, 65535), 10)
self._wreg(_BOT035_SPK, freq & 0xFF)
self._wreg(_BOT035_SPK + 1, freq >> 8)
if freq is None and duty is None:
return self._rreg(_BOT035_SPK + 2), self._rreg(_BOT035_SPK) | self._rreg(_BOT035_SPK + 1) << 8
def usben(self, index=1, duty=None, freq=None):
index = max(min(index, 2), 1) - 1
if duty is not None:
duty = max(min(duty, 100), 0)
self._wreg(_BOT035_PWM + index + 2, int(duty))
if freq is not None:
freq = max(min(freq, 65535), 10)
self._wreg(_BOT035_PWM, freq & 0xFF)
self._wreg(_BOT035_PWM + 1, freq >> 8)
if freq is None and duty is None:
return self._rreg(_BOT035_PWM + index + 2), self._rreg(_BOT035_PWM) | self._rreg(_BOT035_PWM + 1) << 8
def touch(self, index, value=None):
index = max(min(index, 1), 0)
touch = 4095 - (self._rreg(_BOT5_TOUCH + index * 2) | self._rreg(_BOT5_TOUCH + index * 2 + 1) << 8)
return touch > value if value else touch
def touched(self, index, value=600):
return self.touch(index, value)
def touch_slide(self):
values = []
for i in range(30):
values.append((self.touch(1) - self._touchs[1]) - (self.touch(0) - self._touchs[0]))
return round(sorted(values)[15] / 10)
def soundlevel(self):
values = []
for i in range(50):
values.append(self._rreg(_BOT035_MIC) | self._rreg(_BOT035_MIC + 1) << 8)
values = sorted(values)
return values[-10] - values[10]
"""Graph module"""
HEART=b'\x00\x0c\x1e?~\xfc~?\x1e\x0c\x00\x00'
HEART_SMALL=b'\x00\x00\x0c\x1e<x<\x1e\x0c\x00\x00\x00'
HAPPY=b'\x00\x06\x06\x10 @@ \x10\x06\x06\x00'
SAD=b'\x04\x02\x02B \x10\x10 B\x02\x02\x04'
SMILE=b'\x04\x02\x02$@\x80\x80@$\x02\x02\x04'
ANGRY=b'\x01\x02\x84B!\x10\x10!B\x84\x02\x01'
NO=b'\x00\x00\x00B$\x18\x18$B\x00\x00\x00'
YES=b'\x00\x00\x10 @@ \x10\x08\x04\x02\x00'

View File

@@ -0,0 +1,239 @@
"""
ME GO -Onboard resources
MicroPython library for the ME GO (Smart Car base for MixGo Mini)
=======================================================
@dahanzimin From the Mixly Team
"""
import time, gc, math
from tm1931 import TM1931
from machine import Pin, SoftI2C, ADC
'''i2c-onboard'''
onboard_i2c = SoftI2C(scl=Pin(10), sda=Pin(18), freq=400000)
onboard_i2c_scan = onboard_i2c.scan()
'''Version judgment'''
if 0x50 in onboard_i2c_scan:
version = 1
else:
version = 0
'''Judging the type of external motor'''
Mi2c = 0
for addr in onboard_i2c_scan:
if addr in [0x30, 0x31, 0x32, 0x33]:
Mi2c = addr
break
'''i2c-motor'''
def i2c_motor(speed):
i2c.writeto(Mi2c, b'\x00\x00' + speed.to_bytes(1, 'little') + b'\x00')
'''TM1931-Expand'''
class CAR(TM1931):
'''Infrared line patrol obstacle avoidance mode'''
CL=0 #Turn off infrared to reduce power consumption
OA=1 #Obstacle avoidance mode only
LP=2 #Line patrol mode only
LS=3 #Light seeking mode only
AS=4 #Automatic mode switching
'''TM1931 port corresponding function definition'''
OAOU=5 #obstacle avoidance
LPOU=4 #Line patrol control
LSOU=3 #Light control
WLED=12 #Headlamp port
GLED=(17,8,6,15) #Green LED port
RLED=(16,7,9,18) #Red LED port
UCOU=(1,2) #Typec external port
MOTO=((13,14),(10,11),(1,2)) #Motor port
def __init__(self, i2c_bus):
super().__init__(i2c_bus)
self._mode = self.CL
self.atten = 0.82 if version else 1
self.adc0 = ADC(Pin(3), atten=ADC.ATTN_11DB)
self.adc1 = ADC(Pin(4), atten=ADC.ATTN_11DB)
self.adc2 = ADC(Pin(1), atten=ADC.ATTN_11DB)
self.adc3 = ADC(Pin(2), atten=ADC.ATTN_11DB)
def ir_mode(self,select=0):
'''Infrared line patrol obstacle avoidance mode'''
self._mode=select
if select==self.CL:
self.pwm(self.OAOU,0)
self.pwm(self.LPOU,0)
self.pwm(self.LSOU,0)
if select==self.OA:
self.pwm(self.OAOU,255)
self.pwm(self.LPOU,0)
self.pwm(self.LSOU,0)
if select==self.LP:
self.pwm(self.OAOU,0)
self.pwm(self.LPOU,255)
self.pwm(self.LSOU,0)
if select==self.LS:
self.pwm(self.OAOU,0)
self.pwm(self.LPOU,0)
self.pwm(self.LSOU,255)
time.sleep_ms(2)
def obstacle(self):
'''Read the obstacle avoidance sensor'''
if self._mode==self.AS:
self.pwm(self.OAOU,255)
self.pwm(self.LPOU,0)
self.pwm(self.LSOU,0)
time.sleep_ms(2)
if self._mode==self.OA or self._mode==self.AS :
return self.adc2.read_u16(),self.adc1.read_u16(),self.adc0.read_u16(),self.adc3.read_u16()
else:
raise ValueError('Mode selection error, obstacle avoidance data cannot be read')
def patrol(self):
'''Read the line patrol sensor'''
if self._mode==self.AS:
self.pwm(self.OAOU,0)
self.pwm(self.LPOU,255)
self.pwm(self.LSOU,0)
time.sleep_ms(2)
if self._mode==self.LP or self._mode==self.AS:
return self.adc3.read_u16(),self.adc2.read_u16(),self.adc1.read_u16(),self.adc0.read_u16()
else:
raise ValueError('Mode selection error, line patrol data cannot be read')
def light(self):
'''Read the light seeking sensor'''
if self._mode==self.AS:
self.pwm(self.OAOU,0)
self.pwm(self.LPOU,0)
self.pwm(self.LSOU,255)
time.sleep_ms(2)
if self._mode==self.LS or self._mode==self.AS:
return self.adc3.read_u16(),self.adc2.read_u16(),self.adc1.read_u16(),self.adc0.read_u16()
else:
raise ValueError('Mode selection error, light seeking data cannot be read')
def motor(self, index, action, speed=0):
speed = round(max(min(speed, 100), -100) * self.atten)
if action=="N":
if (index == [1, 2]) and Mi2c:
i2c_motor(0)
else:
self.pwm(index[0], 255)
self.pwm(index[1], 255)
elif action=="P":
if (index == [1, 2]) and Mi2c:
i2c_motor(0)
else:
self.pwm(index[0], 0)
self.pwm(index[1], 0)
elif action=="CW":
if (index == [1, 2]) and Mi2c:
i2c_motor(speed)
else:
if speed >= 0:
self.pwm(index[0], speed * 255 // 100)
self.pwm(index[1], 0)
else:
self.pwm(index[0], 0)
self.pwm(index[1], - speed * 255 // 100)
elif action=="CCW":
if (index == [1, 2]) and Mi2c:
i2c_motor(- speed)
else:
if speed >= 0:
self.pwm(index[0], 0)
self.pwm(index[1], speed * 255 // 100)
else:
self.pwm(index[0], - speed * 255 // 100)
self.pwm(index[1], 0)
def move(self,action,speed=100):
if action=="N":
self.motor(self.MOTO[0],"N")
self.motor(self.MOTO[1],"N")
elif action=="P":
self.motor(self.MOTO[0],"P")
self.motor(self.MOTO[1],"P")
elif action=="F":
self.motor(self.MOTO[0],"CCW",speed)
self.motor(self.MOTO[1],"CW",speed)
elif action=="B":
self.motor(self.MOTO[0],"CW",speed)
self.motor(self.MOTO[1],"CCW",speed)
elif action=="L":
self.motor(self.MOTO[0],"CW",speed)
self.motor(self.MOTO[1],"CW",speed)
elif action=="R":
self.motor(self.MOTO[0],"CCW",speed)
self.motor(self.MOTO[1],"CCW",speed)
def setbrightness(self,index,val):
self.pwm(index, max(min(val, 100), 0))
def getrightness(self,index):
return self.duty(index)
def setonoff(self,index,val):
if val == -1:
if self.getrightness(index) < 50:
self.setbrightness(index,100)
else:
self.setbrightness(index,0)
elif val == 1:
self.setbrightness(index,100)
elif val == 0:
self.setbrightness(index,0)
def getonoff(self,index):
return True if self.getrightness(index)>0 else False
try :
car=CAR(onboard_i2c) #Including LED,motor,patrol,obstacle
except Exception as e:
print("Warning: Failed to communicate with TM1931 (ME GO CAR) or", e)
'''2Hall_HEP'''
class HALL:
_pulse_turns=1/480 if version else 1/400 #圈数= 1/(减速比*磁极)
_pulse_distance=_pulse_turns*math.pi*4.4 #距离= 圈数*π*轮胎直径
def __init__(self, pin):
self.turns = 0
self.distance = 0 #cm
self._speed = 0 #cm/s
self._on_receive = None
self._time = time.ticks_ms()
Pin(pin, Pin.IN).irq(handler=self._receive_cb, trigger = (Pin.IRQ_RISING | Pin.IRQ_FALLING))
def _receive_cb(self, event_source):
self.turns += self._pulse_turns
self.distance += self._pulse_distance
self._speed += self._pulse_distance
if self._on_receive:
self._on_receive(round(self.turns,2),round(self.distance,2))
def irq_cb(self, callback):
self._on_receive = callback
def initial(self,turns=None,distance=None):
if turns is not None:
self.turns = turns
if distance is not None:
self.distance = distance
@property
def speed(self):
value=self._speed/time.ticks_diff(time.ticks_ms(), self._time)*1000 if self._speed>0 else 0
self._time = time.ticks_ms()
self._speed=0
return round(value, 2)
hall_A = HALL(5)
hall_B = HALL(6)
'''Reclaim memory'''
gc.collect()

View File

@@ -0,0 +1,176 @@
"""
mixgo_mini onboard resources
Micropython library for the mixgo_mini onboard resources
=======================================================
#Preliminary composition 20240618
@dahanzimin From the Mixly Team
"""
import time, gc
from esp32 import mcu_temperature
from machine import Pin, ADC, RTC, SoftI2C
'''Reclaim memory'''
gc.collect()
'''RTC'''
rtc_clock = RTC()
'''I2C-onboard'''
onboard_i2c = SoftI2C(scl=Pin(10), sda=Pin(18), freq=400000)
onboard_i2c_scan = onboard_i2c.scan()
'''ACC-Sensor'''
try :
import sc7a20
onboard_acc = sc7a20.SC7A20(onboard_i2c)
except Exception as e:
print("Warning: Failed to communicate with SC7A20H (ACC) or",e)
'''ALS_PS-Sensor'''
try :
import ap3216c
onboard_als = ap3216c.AP3216C(onboard_i2c)
except Exception as e:
print("Warning: Failed to communicate with AP3216C (ALS&PS) or",e)
'''BOT035-Sensor'''
try :
import mini_bot
onboard_bot = mini_bot.BOT035(onboard_i2c)
onboard_matrix = onboard_bot
except Exception as e:
print("Warning: Failed to communicate with BOT035 (Coprocessor) or",e)
'''BPS-Sensor'''
if 0x77 in onboard_i2c_scan:
try :
import spl06_001
onboard_bps = spl06_001.SPL06(onboard_i2c)
except Exception as e:
print("Warning: Failed to communicate with SPL06-001 (BPS) or",e)
'''THS-Sensor'''
if 0x70 in onboard_i2c_scan:
try :
import shtc3
onboard_ths = shtc3.SHTC3(onboard_i2c)
except Exception as e:
print("Warning: Failed to communicate with GXHTC3 (THS) or",e)
'''MGS-Sensor'''
if 0x30 in onboard_i2c_scan:
try :
import mmc5603
onboard_mgs = mmc5603.MMC5603(onboard_i2c)
except Exception as e:
print("Warning: Failed to communicate with MMC5603 (MGS) or",e)
'''MCU_temperature'''
def onboard_temperature():
return mcu_temperature()
'''2RGB_WS2812'''
from ws2812x import NeoPixel
onboard_rgb = NeoPixel(Pin(9), 2)
'''1Buzzer-Music'''
from musicx import MIDI
onboard_music = MIDI(onboard_bot)
'''5KEY_Sensor'''
class KEYSensor:
def __init__(self, pin, range):
self.pin = pin
self.adc = ADC(Pin(pin), atten=ADC.ATTN_0DB)
self.range = range
self.flag = True
def _value(self):
values = []
for _ in range(50):
values.append(self.adc.read())
time.sleep_us(2)
return (self.range-200) < min(values) < (self.range+200)
def get_presses(self, delay = 1):
last_time,presses = time.time(), 0
while time.time() < last_time + delay:
time.sleep_ms(50)
if self.was_pressed():
presses += 1
return presses
def is_pressed(self):
return self._value()
def was_pressed(self):
if(self._value() != self.flag):
self.flag = self._value()
if self.flag :
return True
else:
return False
def irq(self, handler, trigger):
Pin(self.pin, Pin.IN).irq(handler = handler, trigger = trigger)
'''1KEY_Button'''
class Button(KEYSensor):
def __init__(self, pin):
self.pin = pin
self.key = Pin(pin, Pin.IN)
self.flag = True
def _value(self):
return not self.key.value()
B1key = Button(9)
B2key = KEYSensor(0,0)
A1key = KEYSensor(0,2100)
A2key = KEYSensor(0,1500)
A3key = KEYSensor(0,800)
A4key = KEYSensor(0,2700)
'''2LED-Multiplex RGB'''
class LED:
def __init__(self, rgb, num=2, color=3):
self._rgb = rgb
self._col = [color] * num
self._color = ((0, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1), (1, 1, 0), (0, 1, 1), (1, 0, 1), (1, 1, 1))
def setbrightness(self, index, value):
self._rgb[index - 1] = (value if self._color[self._col[index-1]][0] else 0,
value if self._color[self._col[index-1]][1] else 0,
value if self._color[self._col[index-1]][2] else 0)
self._rgb.write()
def getbrightness(self, index):
color = self._rgb[index - 1]
return color[0] | color[1] | color[2]
def setonoff(self, index, value):
if value == -1:
if self.getbrightness(index) < 50:
self.setbrightness(index, 100)
else:
self.setbrightness(index, 0)
elif value == 1:
self.setbrightness(index, 100)
elif value == 0:
self.setbrightness(index, 0)
def getonoff(self, index):
return True if self.getbrightness(index) > 50 else False
def setcolor(self, index, color):
self._col[index-1] = color
def getcolor(self, index):
return self._col[index-1]
onboard_led = LED(onboard_rgb)
'''Reclaim memory'''
gc.collect()

View File

@@ -0,0 +1,121 @@
"""
Music buzzer(BOT)
Micropython library for the Music buzzer(Coprocessor I2C communication)
=======================================================
@dahanzimin From the Mixly Team
"""
from time import sleep_ms
normal_tone = {
'A1': 55, 'B1': 62, 'C1': 33, 'D1': 37, 'E1': 41, 'F1': 44, 'G1': 49,
'A2': 110, 'B2': 123, 'C2': 65, 'D2': 73, 'E2': 82, 'F2': 87, 'G2': 98,
'A3': 220, 'B3': 247, 'C3': 131, 'D3': 147, 'E3': 165, 'F3': 175, 'G3': 196,
'A4': 440, 'B4': 494, 'C4': 262, 'D4': 294, 'E4': 330, 'F4': 349, 'G4': 392,
'A5': 880, 'B5': 988, 'C5': 523, 'D5': 587, 'E5': 659, 'F5': 698, 'G5': 784,
'A6': 1760, 'B6': 1976, 'C6': 1047, 'D6': 1175, 'E6': 1319, 'F6': 1397, 'G6': 1568,
'A7': 3520, 'B7': 3951, 'C7': 2093, 'D7': 2349, 'E7': 2637, 'F7': 2794, 'G7': 3135,
'A8': 7040, 'B8': 7902, 'C8': 4186, 'D8': 4699, 'E8': 5274, 'F8': 5588, 'G8': 6271,
'A9': 14080, 'B9': 15804 }
Letter = 'ABCDEFG#R'
class MIDI():
def __init__(self, bus, volume=100):
self.reset()
self._bus = bus
self._volume = volume // 5
def set_volume(self, volume):
self._volume = max(min(volume, 100), 0) // 5
def set_tempo(self, ticks=4, bpm=120):
self.ticks = ticks
self.bpm = bpm
self.beat = 60000 / self.bpm / self.ticks
def set_octave(self, octave=4):
self.octave = octave
def set_duration(self, duration=4):
self.duration = duration
def get_tempo(self):
return (self.ticks, self.bpm)
def get_octave(self):
return self.octave
def get_duration(self):
return self.duration
def reset(self):
self.set_duration()
self.set_octave()
self.set_tempo()
def parse(self, tone, dict):
time = self.beat * self.duration
pos = tone.find(':')
if pos != -1:
time = self.beat * int(tone[(pos + 1):])
tone = tone[:pos]
freq, tone_size = 1, len(tone)
if 'R' in tone:
freq = 400000
elif tone_size == 1:
freq = dict[tone[0] + str(self.octave)]
elif tone_size == 2:
freq = dict[tone]
self.set_octave(tone[1:])
return int(freq), int(time)
def midi(self, tone):
pos = tone.find('#')
if pos != -1:
return self.parse(tone.replace('#', ''), normal_tone)
pos = tone.find('B')
if pos != -1 and pos != 0:
return self.parse(tone.replace('B', ''), normal_tone)
return self.parse(tone, normal_tone)
def set_default(self, tone):
pos = tone.find(':')
if pos != -1:
self.set_duration(int(tone[(pos + 1):]))
tone = tone[:pos]
def play(self, tune, duration=None):
if duration is None:
self.set_default(tune[0])
else:
self.set_duration(duration)
for tone in tune:
tone = tone.upper()
if tone[0] not in Letter:
continue
midi = self.midi(tone)
self._bus.buzzer(self._volume, midi[0])
sleep_ms(midi[1])
self._bus.buzzer(0)
sleep_ms(1)
sleep_ms(10)
def pitch(self, freq):
self._bus.buzzer(self._volume, int(freq))
def pitch_time(self, freq, delay):
self._bus.buzzer(self._volume, int(freq))
sleep_ms(delay)
self._bus.buzzer(0)
def stop(self):
self._bus.buzzer(0)
BA_DING=('b5:1','e6:3')
JUMP_UP=('c5:1','d','e','f','g')
JUMP_DOWN=('g5:1','f','e','d','c')
POWER_UP=('g4:1','c5','e4','g5:2','e5:1','g5:3')
POWER_DOWN=('g5:1','d#','c','g4:2','b:1','c5:3')
DADADADUM=('r4:2','g','g','g','eb:8','r:2','f','f','f','d:8')
BIRTHDAY=('c4:4','c:1','d:4','c:4','f','e:8','c:3','c:1','d:4','c:4','g','f:8','c:3','c:1','c5:4','a4','f','e','d','a#:3','a#:1','a:4','f','g','f:8')

View File

@@ -0,0 +1,94 @@
"""
Radio-ESP-NOW(ESP32-C2)
Micropython library for the Radio-ESP-NOW(ESP32-C2)
=======================================================
@dahanzimin From the Mixly Team
"""
import espnow
from ubinascii import hexlify,unhexlify
import network
class ESPNow(espnow.ESPNow):
def __init__(self,channel=1,txpower=20):
super().__init__()
self.active(True)
self._channel = channel
self._txpower = txpower
self._nic = network.WLAN(network.STA_IF)
self._nic.active(True)
self._nic.config(channel=self._channel,txpower=self._txpower)
def send(self,peer,msg):
'''Send data after error reporting and effective processing'''
try:
_peer=unhexlify(peer)
return super().send(_peer, str(msg))
except OSError as err:
if len(err.args) < 2:
raise err
if err.args[1] == 'ESP_ERR_ESPNOW_NOT_INIT':
raise OSError("Radio(ESPNOW) is not activated, unable to transmit data")
elif err.args[1] == 'ESP_ERR_ESPNOW_IF':
self._nic.active(True)
elif err.args[1] == 'ESP_ERR_ESPNOW_NOT_FOUND':
self.add_peer(_peer)
return super().send(_peer, str(msg))
elif err.args[1] == 'ESP_ERR_ESPNOW_NO_MEM':
raise OSError("internal ESP-NOW buffers are full")
elif err.args[1] == 'ESP_ERR_ESPNOW_ARG':
raise OSError("invalid argument")
else:
raise err
def recv(self):
'''Receive data'''
if self.any():
host, msg = super().recv()
return hexlify(host).decode(),msg.decode()
else :
return None,None
def set_channel(self,channel=None,txpower=None):
self._channel = self._channel if channel is None else channel
self._nic.config(channel=self._channel, txpower=self._txpower if txpower is None else txpower)
def _cb_handle(self, ee):
'''Callback processing conversion'''
host, msg = super().recv()
if self._on_handle:
if isinstance(self._on_handle, list):
for func in self._on_handle:
cmd = func.__name__.rfind('__')
if cmd != -1:
cmd=func.__name__[cmd+2:]
if cmd == str(msg.decode()):
func(hexlify(host).decode(), msg.decode())
else:
func(hexlify(host).decode(), msg.decode())
else:
self._on_handle(hexlify(host).decode(), msg.decode())
def recv_cb(self, recv_cbs):
'''Receive callback'''
self._on_handle = recv_cbs
if recv_cbs:
self.irq(self._cb_handle)
def info(self):
'''Get the paired Mac and rssi'''
_info=[]
for i in self.peers_table:
_info.append((hexlify(i).decode(),self.peers_table[i][0]))
return _info
@property
def mac(self):
'''Get mac address'''
return hexlify(self._nic.config('mac')).decode()
@property
def channel(self):
'''Get mac address'''
return self._nic.config('channel')

View File

@@ -0,0 +1,72 @@
"""
WS2812 RGB
Micropython library for the WS2812 NeoPixel-RGB
=======================================================
@dahanzimin From the Mixly Team
"""
from time import sleep, sleep_us
from machine import bitstream
class NeoPixel:
def __init__(self, pin, n, bpp=3, timing=1, ORDER=(1, 0, 2, 3)):
self.pin = pin
self.bpp = bpp
self.rgbs = n
self.ORDER = ORDER
self.rgb_buf = bytearray(self.rgbs * bpp)
self.timing = (((350, 850, 800, 400) if timing else (800, 1700, 1600, 900)) if isinstance(timing, int) else timing)
self.write()
def __len__(self):
return self.rgbs
def __setitem__(self, n, v):
for i in range(self.bpp):
self.rgb_buf[n * self.bpp + self.ORDER[i]] = v[i]
def __getitem__(self, n):
return tuple(self.rgb_buf[n* self.bpp + self.ORDER[i]] for i in range(self.bpp))
def fill(self, v):
for i in range(self.bpp):
j = self.ORDER[i]
while j < self.rgbs * self.bpp:
self.rgb_buf[j] = v[i]
j += self.bpp
def write(self):
self.pin.init(self.pin.OUT)
bitstream(self.pin, 0, self.timing, self.rgb_buf)
sleep_us(50)
bitstream(self.pin, 0, self.timing, self.rgb_buf)
self.pin.init(self.pin.IN)
def color_chase(self,R, G, B, wait):
for i in range(self.rgbs):
self.__setitem__(i,(R, G, B))
self.write()
sleep(wait/1000)
def rainbow_cycle(self, wait, clear=True):
for j in range(255):
for i in range(self.rgbs):
rc_index = (i * 256 // self.rgbs) + j
self.__setitem__(i,self.wheel(rc_index & 255))
self.write()
sleep(wait / 1000 / 256)
if clear:
self.fill((0, 0, 0))
self.write()
def wheel(self,pos):
if pos < 0 or pos > 255:
return (0, 0, 0)
elif pos < 85:
return (pos * 3, 255 - pos * 3, 0)
elif pos < 170:
pos -= 85
return (255 - pos * 3, 0, pos * 3)
else:
pos -= 170
return (0, pos * 3, 255 - pos * 3)