mpython.py源码

mpython.py源码下载

   1# labplus mPython library
   2# MIT license; Copyright (c) 2018 labplus
   3# V1.0 Zhang KaiHua(apple_eat@126.com)
   4
   5# mpython buildin periphers drivers
   6
   7# history:
   8# V1.1 add oled draw function,add buzz.freq().  by tangliufeng
   9# V1.2 add servo/ui class,by tangliufeng
  10
  11from machine import I2C, PWM, Pin, ADC, TouchPad
  12from ssd1106 import SSD1106_I2C
  13import esp, math, time, network
  14import ustruct, array
  15from neopixel import NeoPixel
  16# from esp import dht_readinto
  17from time import sleep_ms, sleep_us, sleep
  18import framebuf 
  19import calibrate_img
  20from micropython import schedule,const
  21import NVS
  22import ubinascii
  23import machine
  24
  25i2c = I2C(0, scl=Pin(Pin.P19), sda=Pin(Pin.P20), freq=400000)
  26
  27if '_print' not in dir(): _print = print
  28
  29def print(_t, *args, sep=' ', end='\n'):
  30    _s = str(_t)[0:1]
  31    if u'\u4e00' <= _s <= u'\u9fff':
  32        _print(' ' + str(_t), *args, sep=sep, end=end)
  33    else:
  34        _print(_t, *args, sep=sep, end=end)
  35
  36# my_wifi = wifi()
  37#多次尝试连接wifi
  38def try_connect_wifi(_wifi, _ssid, _pass, _times):
  39    if _times < 1: return False
  40    try:
  41        print("Try Connect WiFi ... {} Times".format(_times) )
  42        _wifi.connectWiFi(_ssid, _pass)
  43        if _wifi.sta.isconnected(): return True
  44        else:
  45            time.sleep(5)
  46            return try_connect_wifi(_wifi, _ssid, _pass, _times-1)
  47    except:
  48        time.sleep(5)
  49        return try_connect_wifi(_wifi, _ssid, _pass, _times-1)
  50
  51class Font(object):
  52    def __init__(self, font_address=0x400000):
  53        self.font_address = font_address
  54        buffer = bytearray(18)
  55        esp.flash_read(self.font_address, buffer)
  56        self.header, \
  57            self.height, \
  58            self.width, \
  59            self.baseline, \
  60            self.x_height, \
  61            self.Y_height, \
  62            self.first_char,\
  63            self.last_char = ustruct.unpack('4sHHHHHHH', buffer)
  64        self.first_char_info_address = self.font_address + 18
  65
  66    def GetCharacterData(self, c):
  67        uni = ord(c)
  68        # if uni not in range(self.first_char, self.last_char):
  69        #     return None
  70        if (uni < self.first_char or uni > self.last_char):
  71            return None
  72        char_info_address = self.first_char_info_address + \
  73            (uni - self.first_char) * 6
  74        buffer = bytearray(6)
  75        esp.flash_read(char_info_address, buffer)
  76        ptr_char_data, len = ustruct.unpack('IH', buffer)
  77        if (ptr_char_data) == 0 or (len == 0):
  78            return None
  79        buffer = bytearray(len)
  80        esp.flash_read(ptr_char_data + self.font_address, buffer)
  81        return buffer
  82
  83
  84class TextMode():
  85    normal = 1
  86    rev = 2
  87    trans = 3
  88    xor = 4
  89
  90
  91class OLED(SSD1106_I2C):
  92    """ 128x64 oled display """
  93
  94    def __init__(self):
  95        super().__init__(128, 64, i2c)
  96        self.f = Font()
  97        if self.f is None:
  98            raise Exception('font load failed')
  99
 100    def DispChar(self, s, x, y, mode=TextMode.normal, auto_return=False):
 101            row = 0
 102            str_width = 0
 103            if self.f is None:
 104                return
 105            for c in s:
 106                data = self.f.GetCharacterData(c)
 107                if data is None:
 108                    if auto_return is True:
 109                        x = x + self.f.width
 110                    else:
 111                        x = x + self.width
 112                    continue
 113                width, bytes_per_line = ustruct.unpack('HH', data[:4])
 114                # print('character [%d]: width = %d, bytes_per_line = %d' % (ord(c)
 115                # , width, bytes_per_line))
 116                if auto_return is True:
 117                    if x > self.width - width:
 118                        str_width += self.width - x
 119                        x = 0
 120                        row += 1
 121                        y += self.f.height
 122                        if y > (self.height - self.f.height)+0:
 123                            y, row = 0, 0
 124                for h in range(0, self.f.height):
 125                    w = 0
 126                    i = 0
 127                    while w < width:
 128                        mask = data[4 + h * bytes_per_line + i]
 129                        if (width - w) >= 8:
 130                            n = 8
 131                        else:
 132                            n = width - w
 133                        py = y + h
 134                        page = py >> 3
 135                        bit = 0x80 >> (py % 8)
 136                        for p in range(0, n):
 137                            px = x + w + p
 138                            c = 0
 139                            if (mask & 0x80) != 0:
 140                                if mode == TextMode.normal or \
 141                                        mode == TextMode.trans:
 142                                    c = 1
 143                                if mode == TextMode.rev:
 144                                    c = 0
 145                                if mode == TextMode.xor:
 146                                    c = self.buffer[page * (self.width if auto_return is True else 128) + px] & bit
 147                                    if c != 0:
 148                                        c = 0
 149                                    else:
 150                                        c = 1
 151                                super().pixel(px, py, c)
 152                            else:
 153                                if mode == TextMode.normal:
 154                                    c = 0
 155                                    super().pixel(px, py, c)
 156                                if mode == TextMode.rev:
 157                                    c = 1
 158                                    super().pixel(px, py, c)
 159                            mask = mask << 1
 160                        w = w + 8
 161                        i = i + 1
 162                x = x + width + 1
 163                str_width += width + 1
 164            return (str_width-1,(x-1, y))
 165
 166    def DispChar_font(self, font, s, x, y, invert=False):
 167        """
 168        custom font display.Ref by , https://github.com/peterhinch/micropython-font-to-py
 169        :param font:  use font_to_py.py script convert to `py` from `ttf` or `otf`.
 170        """
 171        screen_width = self.width
 172        screen_height = self.height
 173        text_row = x
 174        text_col = y
 175        text_length = 0
 176        if font.hmap():
 177            font_map = framebuf.MONO_HMSB if font.reverse() else framebuf.MONO_HLSB
 178        else:
 179            raise ValueError('Font must be horizontally mapped.')
 180        for c in s:
 181            glyph, char_height, char_width = font.get_ch(c)
 182            buf = bytearray(glyph)
 183            if invert:
 184                for i, v in enumerate(buf):
 185                    buf[i] = 0xFF & ~ v
 186            fbc = framebuf.FrameBuffer(buf, char_width, char_height, font_map)
 187            if text_row + char_width > screen_width - 1:
 188                text_length += screen_width-text_row
 189                text_row = 0
 190                text_col += char_height
 191            if text_col + char_height > screen_height + 2:
 192                text_col = 0
 193
 194            super().blit(fbc, text_row, text_col)
 195            text_row = text_row + char_width+1
 196            text_length += char_width+1
 197        return (text_length-1, (text_row-1, text_col))
 198
 199# display
 200if 60 in i2c.scan():
 201    oled = OLED()
 202    display = oled
 203else:
 204    print("oled init error!")
 205
 206class MOTION(object):
 207    def __init__(self):
 208        self.i2c = i2c
 209        addr = self.i2c.scan()
 210        if 38 in addr:
 211            MOTION.chip = 1  # MSA300
 212            MOTION.IIC_ADDR = 38
 213        elif 107 in addr:
 214            MOTION.chip = 2  # QMI8658
 215            MOTION.IIC_ADDR = 107
 216        else:
 217            raise OSError("MOTION init error")
 218        if(MOTION.chip == 1):
 219            pass
 220        elif(MOTION.chip == 2):
 221            MOTION._writeReg(0x60, 0x01) # soft reset regist value.
 222            time.sleep_ms(20)
 223            MOTION._writeReg(0x02, 0x60) # Enabe reg address auto increment auto
 224            MOTION._writeReg(0x08, 0x03) # Enable accel and gyro
 225            MOTION._writeReg(0x03, 0x1c) # accel range:4g ODR 128HZ
 226            MOTION._writeReg(0x04, 0x40) # gyro ODR 8000HZ, FS 256dps
 227            MOTION._writeReg(0x06, 0x55) # Enable accel and gyro Low-Pass Filter
 228        # print('Motion init finished!')
 229
 230    # @staticmethod
 231    def _readReg(reg, nbytes=1):
 232        return i2c.readfrom_mem(MOTION.IIC_ADDR, reg, nbytes)
 233
 234    # @staticmethod
 235    def _writeReg(reg, value):
 236        i2c.writeto_mem(MOTION.IIC_ADDR, reg, value.to_bytes(1, 'little'))
 237
 238    def get_fw_version(self):
 239        if(self.chip==1):
 240            pass
 241        elif(self.chip==2):
 242            MOTION._writeReg(0x0a, 0x10) # send ctrl9R read FW cmd
 243            while True:
 244                if (MOTION._readReg(0x2F, 1)[0] & 0X01) == 0X01:
 245                    break
 246            buf = MOTION._readReg(0X49, 3)
 247            # print(buf[0])
 248            # print(buf[1])
 249            # print(buf[2])
 250        
 251    class Accelerometer():
 252        """MSA300"""
 253        # Range and resolustion
 254        RANGE_2G = const(0)
 255        RANGE_4G = const(1)
 256        RANGE_8G = const(2)
 257        RANGE_16G = const(3)
 258        RES_14_BIT = const(0) 
 259        RES_12_BIT = const(1)
 260        RES_10_BIT = const(2)
 261        # Event
 262        TILT_LEFT = const(0)
 263        TILT_RIGHT = const(1)
 264        TILT_UP = const(2)
 265        TILT_DOWN = const(3)
 266        FACE_UP = const(4)
 267        FACE_DOWN = const(5)
 268        SINGLE_CLICK = const(6)
 269        DOUBLE_CLICK = const(7)
 270        FREEFALL = const(8)
 271
 272        """QMI8658C"""
 273        # Range and resolustion
 274        # QMI8658C_RANGE_2G = const(0x00)
 275        # QMI8658C_RANGE_4G = const(0x10)
 276        # QMI8658C_RANGE_8G = const(0x20)
 277        # QMI8658C_RANGE_16G = const(0x40)
 278
 279        def __init__(self):
 280            if(MOTION.chip==1):
 281                self.set_resolution(MOTION.Accelerometer.RES_10_BIT)
 282                self.set_range(MOTION.Accelerometer.RANGE_2G)
 283                MOTION._writeReg(0x12, 0x03)               # polarity of y,z axis,
 284                MOTION._writeReg(0x11, 0)                  # set power mode = normal
 285                # interrupt
 286                MOTION._writeReg(0x16, 0x70)      # int enabled: Orient | S_TAP | D_TAP 
 287                MOTION._writeReg(0x17, 0x08)      # int enabled: Freefall
 288                MOTION._writeReg(0x19, 0x71)      # int1 map to: Orient, S_TAP, D_TAP, Freefall
 289                MOTION._writeReg(0x20, 0x02)      # int1 active level = 0, output = OD
 290                MOTION._writeReg(0x21, 0x0C)      # int tempoary latched 25ms
 291                # freefall:
 292                #   single mode: |acc_x| < Threshold && |acc_y| < Threshold && |acc_z| < Threshold, at least time > Duration
 293                #   sum mode: |acc_x| + |acc_y| + |acc_z| < Threshold, at least time > Duration
 294                MOTION._writeReg(0x22, 20)    # Freefall Duration:(n+1)*2ms, range from 2ms to 512ms
 295                MOTION._writeReg(0x23, 48)    # Freefall Threshold: n*7.81mg
 296                MOTION._writeReg(0x24, 0x01)  # Freefall mode = 0-singlemode;hysteresis = n*125mg
 297                # tap:
 298                MOTION._writeReg(0x2A, 0x06)  # Tap duration:quit = 30ms, shock=50ms, time window for secent shock=500ms
 299                MOTION._writeReg(0x2B, 0x0A)  # Tap threshold = 10*[62.5mg@2G | 125mg@4G | 250mg@8G | 500mg@16g]
 300                # Orient
 301                MOTION._writeReg(0x2C, 0x18)  # Orient hysteresis= 1*62.5mg; 
 302                                            #        block mode = 10 z_axis blocking or slope in any axis > 0.2g;
 303                                            #        orient mode = 00-symetrical
 304                MOTION._writeReg(0x2D, 8)     # Z-axis block
 305                # int pin irq register
 306                self.int = Pin(37, Pin.IN)
 307                self.int.irq(trigger=Pin.IRQ_FALLING, handler=self.irq)
 308                # event handler 
 309                self.event_tilt_up = None
 310                self.event_tilt_down = None
 311                self.event_tilt_left = None
 312                self.event_tilt_right = None
 313                self.event_face_up = None
 314                self.event_face_down = None
 315                self.event_single_click = None
 316                self.event_double_click = None
 317                self.event_freefall = None
 318            elif(MOTION.chip==2):
 319                # 设置偏移值
 320                self.x_offset = 0
 321                self.y_offset = 0
 322                self.z_offset = 0
 323                self.get_nvs_offset()
 324                try:
 325                    id =  MOTION._readReg(0x0, 2)
 326                except:
 327                    pass
 328                self.set_range(MOTION.Accelerometer.RANGE_2G) #设置默认分辨率+-2g
 329                self.int = Pin(37, Pin.IN)
 330                self.int.irq(trigger=Pin.IRQ_FALLING, handler=self.irq)
 331                # event handler 
 332                self.wom = None
 333            
 334
 335        def irq(self, arg):
 336            if(MOTION.chip==1):
 337                reg_int = MOTION._readReg(0x09)[0]
 338                reg_orent = MOTION._readReg(0x0C)[0]
 339                # orient_int
 340                if (reg_int & 0x40):
 341                    if ((reg_orent & 0x30) == 0x00 and self.event_tilt_left is not None):
 342                        schedule(self.event_tilt_left, self.TILT_LEFT)
 343                    if ((reg_orent & 0x30) == 0x10 and self.event_tilt_right is not None):
 344                        schedule(self.event_tilt_right, self.TILT_RIGHT)
 345                    if ((reg_orent & 0x30) == 0x20 and self.event_tilt_up is not None):
 346                        schedule(self.event_tilt_up, self.TILT_UP)
 347                    if ((reg_orent & 0x30) == 0x30 and self.event_tilt_down is not None):
 348                        schedule(self.event_tilt_down, self.TILT_DOWN)
 349                    if ((reg_orent & 0x40) == 0x00 and self.event_face_up):
 350                        schedule(self.event_face_up, self.FACE_UP)
 351                    if ((reg_orent & 0x40) == 0x40 and self.event_face_down):
 352                        schedule(self.event_face_down, self.FACE_DOWN)
 353                # single tap
 354                if (reg_int & 0x20):
 355                    if (self.event_single_click is not None):
 356                        schedule(self.event_single_click, self.SINGLE_CLICK)
 357                # double tap
 358                if (reg_int & 0x10):
 359                    if (self.event_double_click is not None):
 360                        schedule(self.event_double_click, self.DOUBLE_CLICK)
 361                # freefall
 362                if (reg_int & 0x01):
 363                    if (self.event_freefall is not None):
 364                        schedule(self.event_freefall, self.FREEFALL)
 365                # print("acc sensor interrupt, because 0x%2x, orient = 0x%2x" % (reg_int, reg_orent))
 366            elif(MOTION.chip==2):  
 367                flag = MOTION._readReg(0x2F, 1)[0]
 368                if (flag & 0x04) == 0x04:
 369                    print('wom int trigged.')
 370
 371        def wom_config(self):
 372            if(MOTION.chip==1):
 373                pass
 374            elif(MOTION.chip==2):
 375                MOTION._writeReg(0x60, 0x01) # soft reset regist value.
 376                time.sleep_ms(20)
 377                MOTION._writeReg(0x08, 0x0) # disable all sensor
 378                MOTION._writeReg(0x03, 0x1c) # accel range:4g ODR 128HZ
 379                MOTION._writeReg(0x0B, 0xfF) # CAL_L WoM Threshold(1mg/LSB resolution)
 380                MOTION._writeReg(0x0C, 0x8F) # CAL_H WoM (INT1 blank time 0x1f)
 381                MOTION._writeReg(0x0A, 0x08)
 382                while True:
 383                    if (MOTION._readReg(0x2F, 1)[0] & 0X01) == 0X01:
 384                        break
 385                MOTION._writeReg(0x08, 0x01) # enable accel
 386
 387        def set_resolution(self, resolution):# set data output rate
 388            if(MOTION.chip==1):
 389                format = MOTION._readReg(0x0f, 1)
 390                format = format[0] & ~0xC
 391                format |= (resolution << 2)
 392                MOTION._writeReg(0x0f, format)
 393            elif(MOTION.chip==2):
 394                self.odr = resolution
 395                format = MOTION._readReg(0x03, 1)
 396                format = format[0] & 0xf0
 397                format |= (resolution & 0x0f)
 398                MOTION._writeReg(0x03, format)
 399                
 400        def set_range(self, range):
 401            if(MOTION.chip==1):
 402                self.range = range
 403                format = MOTION._readReg(0x0f, 1)
 404                format = format[0] & ~0x3
 405                format |= range
 406                MOTION._writeReg(0x0f, format)
 407            elif(MOTION.chip==2):
 408                if(range==3):
 409                    range = 64 #0x40
 410                else:
 411                    range = range << 4
 412                self.FS = 2*(2**(range >> 4))
 413                format = MOTION._readReg(0x03, 1)
 414                format = format[0] & 0x8F
 415                format |= range
 416                MOTION._writeReg(0x03, format)
 417
 418        def set_offset(self, x=None, y=None, z=None):
 419            if(MOTION.chip==1):
 420                for i in (x, y, z):
 421                    if i is not None:
 422                        if i < -1 or i > 1:
 423                            raise ValueError("out of range,only offset 1 gravity")
 424                if x is not None:
 425                    MOTION._writeReg(0x39, int(round(x/0.0039)))
 426                elif y is not None:
 427                    MOTION._writeReg(0x38, int(round(y/0.0039)))
 428                elif z is not None:
 429                    MOTION._writeReg(0x3A, int(round(z/0.0039)))
 430            elif(MOTION.chip==2):
 431                for i in (x, y, z):
 432                    if i is not None:
 433                        if i < -16 or i > 16:
 434                            raise ValueError("超出调整范围!!!")
 435                if x is not None:
 436                    self.x_offset = x
 437                    self.set_nvs_offset("x", x)
 438                if y is not None:
 439                    self.y_offset = y
 440                    self.set_nvs_offset("y", y)
 441                if z is not None:
 442                    self.z_offset = z
 443                    self.set_nvs_offset("z", z)
 444                
 445        def get_x(self):
 446            if(MOTION.chip==1):
 447                retry = 0
 448                if (retry < 5):
 449                    try:
 450                        buf = MOTION._readReg(0x02, 2)
 451                        x = ustruct.unpack('h', buf)[0]
 452                        return x / 4 / 4096 * 2**self.range
 453                    except:
 454                        retry = retry + 1
 455                else:
 456                    raise Exception("i2c read/write error!")
 457            elif(MOTION.chip==2):
 458                buf = MOTION._readReg(0x35, 2)
 459                x = ustruct.unpack('<h', buf)[0]
 460                return (x * self.FS) / 32768 + self.x_offset
 461
 462        def get_y(self):
 463            if(MOTION.chip==1):
 464                retry = 0
 465                if (retry < 5):
 466                    try:
 467                        buf = MOTION._readReg(0x04, 2)
 468                        y = ustruct.unpack('h', buf)[0]
 469                        return y / 4 / 4096 * 2**self.range
 470                    except:
 471                        retry = retry + 1
 472                else:
 473                    raise Exception("i2c read/write error!")
 474            elif(MOTION.chip==2):
 475                buf = MOTION._readReg(0x37, 2)
 476                y = ustruct.unpack('<h', buf)[0]
 477                return (y * self.FS) / 32768  + self.y_offset
 478
 479        def get_z(self):
 480            if(MOTION.chip==1):
 481                retry = 0
 482                if (retry < 5):
 483                    try:
 484                        buf = MOTION._readReg(0x06, 2)
 485                        z = ustruct.unpack('h', buf)[0]
 486                        return z / 4 / 4096 * 2**self.range
 487                    except:
 488                        retry = retry + 1
 489                else:
 490                    raise Exception("i2c read/write error!")
 491            elif(MOTION.chip==2):
 492                buf = MOTION._readReg(0x39, 2)
 493                z = ustruct.unpack('<h', buf)[0]
 494                return (z * self.FS) / 32768 + self.z_offset
 495                # return -(z * self.FS) / 32768
 496     
 497        def roll_pitch_angle(self):
 498            x, y, z = self.get_x(), self.get_y(), -self.get_z()
 499            # vector normalize
 500            mag = math.sqrt(x ** 2 + y ** 2+z ** 2)
 501            x /= mag
 502            y /= mag
 503            z /= mag
 504            roll = math.degrees(-math.asin(y))
 505            pitch = math.degrees(math.atan2(x, z))
 506
 507            return roll, pitch
 508        
 509        def get_nvs_offset(self):
 510            try:
 511                tmp = NVS("offset_a")
 512                self.x_offset = round(tmp.get_i32("x")/1e5, 5)
 513                self.y_offset = round(tmp.get_i32("y")/1e5, 5)
 514                self.z_offset = round(tmp.get_i32("z")/1e5, 5)
 515            except OSError as e:
 516                # print('Accelerometer get_nvs_offset:',e)
 517                # self.x_offset = 0
 518                # self.y_offset = 0
 519                # self.z_offset = 0
 520                self.set_offset(0,0,0)
 521        
 522        def set_nvs_offset(self, key, value):
 523            try:
 524                nvs = NVS("offset_a")
 525                nvs.set_i32(key, int(value*1e5))
 526                nvs.commit()
 527            except OSError as e:
 528                print('Gyroscope set_nvs_offset error:',e)
 529
 530    class Gyroscope():
 531        # gyro full scale
 532        RANGE_16_DPS =  const(0x00)
 533        RANGE_32_DPS =  const(0x10)
 534        RANGE_64_DPS =  const(0x20)
 535        RANGE_128_DPS =  const(0x30)
 536        RANGE_256_DPS =  const(0x40)
 537        RANGE_512_DPS =  const(0x50)
 538        RANGE_1024_DPS = const(0x60)
 539        RANGE_2048_DPS = const(0x70)
 540
 541        def __init__(self):
 542            if(MOTION.chip==1):
 543                pass
 544            elif(MOTION.chip==2):
 545                # 设置偏移值
 546                self.x_offset = 0
 547                self.y_offset = 0
 548                self.z_offset = 0
 549                self.get_nvs_offset()
 550                self.set_range(MOTION.Gyroscope.RANGE_256_DPS)
 551
 552        def set_range(self, range):
 553            if(MOTION.chip==1):
 554                pass
 555            elif(MOTION.chip==2):
 556                self.FS = 16*(2**(range >> 4))        
 557                format = MOTION._readReg(0x04, 1)
 558                format = format[0] & 0x8F
 559                format |= range
 560                MOTION._writeReg(0x04, format)
 561
 562        def set_ODR(self, odr):  # set data output rate
 563            if(MOTION.chip==1):
 564                pass
 565            elif(MOTION.chip==2):
 566                self.odr = odr
 567                format = MOTION._readReg(0x04, 1)
 568                format = format[0] & 0xF0
 569                format |= odr
 570                MOTION._writeReg(0x04, format)
 571
 572        def get_x(self):
 573            if(MOTION.chip==1):
 574                pass
 575            elif(MOTION.chip==2):
 576                buf = MOTION._readReg(0x3b, 2)
 577                x = ustruct.unpack('<h', buf)[0]
 578                return (x * self.FS) / 32768 + self.x_offset
 579
 580        def get_y(self):
 581            if(MOTION.chip==1):
 582                pass
 583            elif(MOTION.chip==2):
 584                buf = MOTION._readReg(0x3d, 2)
 585                y = ustruct.unpack('<h', buf)[0]
 586                return (y * self.FS) / 32768 + self.y_offset
 587
 588        def get_z(self):
 589            if(MOTION.chip==1):
 590                pass
 591            elif(MOTION.chip==2):
 592                buf = MOTION._readReg(0x3f, 2)
 593                z = ustruct.unpack('<h', buf)[0]
 594                return (z * self.FS) / 32768 + self.z_offset
 595        
 596        def set_offset(self, x=None, y=None, z=None):
 597            if(MOTION.chip==1):
 598                pass
 599            elif(MOTION.chip==2):
 600                for i in (x, y, z):
 601                    if i is not None:
 602                        if i < -4096 or i > 4096:
 603                            raise ValueError("超出调整范围!!!")
 604                if x is not None:
 605                    self.x_offset = x
 606                    self.set_nvs_offset("x", x)
 607                if y is not None:
 608                    self.y_offset = y
 609                    self.set_nvs_offset("y", y)
 610                if z is not None:
 611                    self.z_offset = z
 612                    self.set_nvs_offset("z", z)
 613
 614        def get_nvs_offset(self):
 615            if(MOTION.chip==1):
 616                pass
 617            elif(MOTION.chip==2):
 618                try:
 619                    tmp = NVS("offset_g")
 620                    self.x_offset = round(tmp.get_i32("x")/1e5, 5)
 621                    self.y_offset = round(tmp.get_i32("y")/1e5, 5)
 622                    self.z_offset = round(tmp.get_i32("z")/1e5, 5)
 623                except OSError as e:
 624                    # print('Gyroscope get_nvs_offset:',e)
 625                    self.set_offset(0,0,0)
 626                    # self.x_offset = 0
 627                    # self.y_offset = 0
 628                    # self.z_offset = 0
 629
 630        def set_nvs_offset(self, key, value):
 631            try:
 632                nvs = NVS("offset_g")
 633                nvs.set_i32(key, int(value*1e5))
 634                nvs.commit()
 635            except OSError as e:
 636                print('Gyroscope set_nvs_offset error:',e)
 637
 638    
 639motion = MOTION()
 640accelerometer = motion.Accelerometer()
 641gyroscope = motion.Gyroscope()
 642
 643class Magnetic(object):
 644    """ MMC5983MA driver """
 645    """ MMC5603NJ driver 20211028替换"""
 646    def __init__(self):
 647        self.addr = 48
 648        self.i2c = i2c
 649        self._judge_id()
 650        time.sleep_ms(5)
 651        if (self.product_ID==48):
 652            pass  # MMC5983MA
 653        elif (self.product_ID==16):
 654            pass  # MMC5603NJ
 655        else:
 656            raise OSError("Magnetic init error")
 657        """ MMC5983MA driver """
 658        # 传量器裸数据,乘0.25后转化为mGS
 659        self.raw_x = 0.0
 660        self.raw_y = 0.0
 661        self.raw_z = 0.0
 662        # 校准后的偏移量, 基于裸数据
 663        self.cali_offset_x = 0.0 
 664        self.cali_offset_y = 0.0
 665        self.cali_offset_z = 0.0
 666        # 去皮偏移量,类似电子秤去皮功能,基于裸数据。
 667        self.peeling_x = 0.0
 668        self.peeling_y = 0.0
 669        self.peeling_z = 0.0
 670        self.is_peeling = 0
 671        if (self.chip==1):
 672            self.i2c.writeto(self.addr, b'\x09\x20\xbd\x00', True)
 673        """ MMC5603NJ driver """
 674        if (self.chip==2):
 675            self._writeReg(0x1C, 0x80)#软件复位
 676            time.sleep_ms(100)
 677            self._writeReg(0x1A, 255)
 678            self._writeReg(0x1B, 0b10100001)
 679            # self._writeReg(0x1C, 0b00000011)
 680            self._writeReg(0x1C, 0b00000000)
 681            self._writeReg(0x1D, 0b10010000)
 682            time.sleep_ms(100)
 683
 684    def _readReg(self, reg, nbytes=1):
 685        return i2c.readfrom_mem(self.addr, reg, nbytes)
 686
 687    def _writeReg(self, reg, value):
 688        i2c.writeto_mem(self.addr, reg, value.to_bytes(1, 'little')) 
 689
 690    def _set_offset(self):
 691        if(self.chip == 1):
 692            self.i2c.writeto(self.addr, b'\x09\x08', True)  #set
 693            self.i2c.writeto(self.addr, b'\x09\x01', True)
 694            while True:
 695                self.i2c.writeto(self.addr, b'\x08', False)
 696                buf = self.i2c.readfrom(self.addr, 1)
 697                status = ustruct.unpack('B', buf)[0]
 698                if(status & 0x01):
 699                    break
 700            self.i2c.writeto(self.addr, b'\x00', False)
 701            buf = self.i2c.readfrom(self.addr, 6)
 702            data = ustruct.unpack('>3H', buf)
 703
 704            self.i2c.writeto(self.addr, b'\x09\x10', True)  #reset
 705
 706            self.i2c.writeto(self.addr, b'\x09\x01', True)
 707            while True:
 708                self.i2c.writeto(self.addr, b'\x08', False)
 709                buf = self.i2c.readfrom(self.addr, 1)
 710                status = ustruct.unpack('B', buf)[0]
 711                if(status & 0x01):
 712                    break
 713            self.i2c.writeto(self.addr, b'\x00', False)
 714            buf = self.i2c.readfrom(self.addr, 6)
 715            data1 = ustruct.unpack('>3H', buf)
 716
 717            self.x_offset = (data[0] + data1[0])/2
 718            self.y_offset = (data[1] + data1[1])/2
 719            self.z_offset = (data[2] + data1[2])/2
 720        elif(self.chip == 2):
 721            pass
 722    
 723    def _get_raw(self):
 724        if (self.chip == 1):
 725            retry = 0
 726            if (retry < 5):
 727                try:
 728                    self.i2c.writeto(self.addr, b'\x09\x08', True)  #set
 729
 730                    self.i2c.writeto(self.addr, b'\x09\x01', True)
 731                    while True:
 732                        self.i2c.writeto(self.addr, b'\x08', False)
 733                        buf = self.i2c.readfrom(self.addr, 1)
 734                        status = ustruct.unpack('B', buf)[0]
 735                        if(status & 0x01):
 736                            break
 737                    self.i2c.writeto(self.addr, b'\x00', False)
 738                    buf = self.i2c.readfrom(self.addr, 6)
 739                    data = ustruct.unpack('>3H', buf)
 740
 741                    self.i2c.writeto(self.addr, b'\x09\x10', True)  #reset
 742
 743                    self.i2c.writeto(self.addr, b'\x09\x01', True)
 744                    while True:
 745                        self.i2c.writeto(self.addr, b'\x08', False)
 746                        buf = self.i2c.readfrom(self.addr, 1)
 747                        status = ustruct.unpack('B', buf)[0]
 748                        if(status & 0x01):
 749                            break
 750                    self.i2c.writeto(self.addr, b'\x00', False)
 751                    buf = self.i2c.readfrom(self.addr, 6)
 752                    data1 = ustruct.unpack('>3H', buf)
 753
 754                    self.raw_x = -((data[0] - data1[0])/2)
 755                    self.raw_y = -((data[1] - data1[1])/2)
 756                    self.raw_z = -((data[2] - data1[2])/2)
 757                    # print(str(self.raw_x) + "   " + str(self.raw_y) + "  " + str(self.raw_z))
 758                except:
 759                    retry = retry + 1
 760            else:
 761                raise Exception("i2c read/write error!")     
 762        elif(self.chip == 2):
 763            retry = 0
 764            if (retry < 5):
 765                try:
 766                    _raw_x = 0.0
 767                    _raw_y = 0.0
 768                    _raw_z = 0.0
 769
 770                    # self.i2c.writeto(self.addr, b'\x1B\x08', True)  #set
 771                    # self.i2c.writeto(self.addr, b'\x1B\x01', True)
 772                    
 773                    # while True:
 774                    #     buf = self._readReg(0x18, 1)
 775                    #     status = buf[0]
 776                    #     if(status & 0x40):
 777                    #         break
 778
 779                    # _buf = self._readReg(0x00, 9)
 780
 781                    self.i2c.writeto(self.addr, b'\x1B\x08', True)  #set
 782                    # self.i2c.writeto(self.addr, b'\x1B\x80', True)
 783                    self.i2c.writeto(self.addr, b'\x1B\x01', True)
 784                    
 785                    while True:
 786                        sleep_ms(25)
 787                        buf = self._readReg(0x18, 1)
 788                        status = buf[0]
 789                        if(status & 0x40):
 790                            break
 791
 792                    buf = self._readReg(0x00, 9)
 793
 794                    _raw_x = (buf[0] << 12) | (buf[1] << 4) | (buf[6] >> 4)
 795                    _raw_y = (buf[2] << 12) | (buf[3] << 4) | (buf[7] >> 4)
 796                    _raw_z = (buf[4] << 12) | (buf[5] << 4) | (buf[8] >> 4)
 797
 798                    self.raw_x = _raw_x
 799                    self.raw_y = _raw_y
 800                    self.raw_z = _raw_z
 801                except:
 802                    retry = retry + 1
 803            else:
 804                raise Exception("i2c read/write error!")
 805
 806    def peeling(self):
 807        '''
 808        去除磁场环境
 809        '''
 810        self._get_raw()
 811        self.peeling_x = self.raw_x
 812        self.peeling_y = self.raw_y
 813        self.peeling_z = self.raw_z
 814        self.is_peeling = 1
 815
 816    def clear_peeling(self):
 817        self.peeling_x = 0.0
 818        self.peeling_y = 0.0
 819        self.peeling_z = 0.0
 820        self.is_peeling = 0
 821
 822    def get_x(self):
 823        if (self.chip == 1):
 824            self._get_raw()
 825            return self.raw_x * 0.25
 826        if (self.chip == 2):
 827            self._get_raw()
 828            if(self.cali_offset_x):
 829                return -0.0625 * (self.raw_x - self.cali_offset_x)
 830            else:
 831                return -0.0625 * (self.raw_x - 524288)
 832            # return -(self.raw_x - 524288)/16384
 833
 834    def get_y(self):
 835        if (self.chip == 1):
 836            self._get_raw()
 837            return self.raw_y * 0.25
 838        if (self.chip == 2):
 839            self._get_raw()
 840            if(self.cali_offset_y):
 841                return -0.0625 * (self.raw_y - self.cali_offset_y)
 842            else:
 843                return -0.0625 * (self.raw_y - 524288)
 844            # return -(self.raw_y - 524288)/16384
 845
 846    def get_z(self):
 847        if (self.chip == 1):
 848            self._get_raw()
 849            return self.raw_z * 0.25 
 850        if (self.chip == 2):
 851            self._get_raw()
 852            if(self.cali_offset_z):
 853                return 0.0625 * (self.raw_z - self.cali_offset_z)
 854            else:
 855                return 0.0625 * (self.raw_z - 524288)
 856            # return (self.raw_z - 524288)/16384
 857
 858    def get_field_strength(self):
 859        if(self.chip==1):
 860            self._get_raw()
 861            if self.is_peeling == 1:
 862                return (math.sqrt((self.raw_x - self.peeling_x)*(self.raw_x - self.peeling_x) + (self.raw_y - self.peeling_y)*(self.raw_y - self.peeling_y) + (self.raw_z - self.peeling_z)*(self.raw_z - self.peeling_z)))*0.25
 863            return (math.sqrt(self.raw_x * self.raw_x + self.raw_y * self.raw_y + self.raw_z * self.raw_z))*0.25
 864        elif(self.chip==2):
 865            self._get_raw()
 866            if self.is_peeling == 1:
 867                return (math.sqrt(math.pow(self.raw_x - self.peeling_x, 2) + pow(self.raw_y - self.peeling_y, 2) + pow(self.raw_z - self.peeling_z , 2)))*0.0625
 868            return (math.sqrt(math.pow(self.get_x(), 2) + pow(self.get_y(), 2) + pow(self.get_z(), 2)))
 869
 870    def calibrate(self):
 871        oled.fill(0)
 872        oled.DispChar("步骤1:", 0,0,1)
 873        oled.DispChar("如图",0,26,1)
 874        oled.DispChar("转几周",0,43,1)
 875        oled.bitmap(64,0,calibrate_img.rotate,64,64,1)
 876        oled.show()
 877        self._get_raw()
 878        min_x = max_x = self.raw_x
 879        min_y = max_y = self.raw_y
 880        min_z = max_z = self.raw_z
 881        ticks_start = time.ticks_ms()
 882        while (time.ticks_diff(time.ticks_ms(), ticks_start) < 15000) :
 883            self._get_raw()
 884            min_x = min(self.raw_x, min_x)
 885            min_y = min(self.raw_y, min_y)
 886            max_x = max(self.raw_x, max_x)
 887            max_y = max(self.raw_y, max_y)
 888            time.sleep_ms(100)
 889        self.cali_offset_x = (max_x + min_x) / 2
 890        self.cali_offset_y = (max_y + min_y) / 2
 891        print('cali_offset_x: ' + str(self.cali_offset_x) + '  cali_offset_y: ' + str(self.cali_offset_y))
 892        oled.fill(0)
 893        oled.DispChar("步骤2:", 85,0,1)
 894        oled.DispChar("如图",85,26,1)
 895        oled.DispChar("转几周",85,43,1)
 896        oled.bitmap(0,0,calibrate_img.rotate1,64,64,1)
 897        oled.show()
 898        ticks_start = time.ticks_ms()
 899        while (time.ticks_diff(time.ticks_ms(), ticks_start) < 15000) :
 900            self._get_raw()
 901            min_z = min(self.raw_z, min_z)
 902            max_z = max(self.raw_z, max_z)
 903            time.sleep_ms(100)
 904        self.cali_offset_z = (max_z + min_z) / 2
 905  
 906        print('cali_offset_z: ' + str(self.cali_offset_z))
 907
 908        oled.fill(0)
 909        oled.DispChar("校准完成", 40,24,1)
 910        oled.show()
 911        oled.fill(0)
 912
 913    def get_heading(self):
 914        if(self.chip==1):
 915            self._get_raw()
 916            temp_x = self.raw_x - self.cali_offset_x
 917            temp_y = self.raw_y - self.cali_offset_y
 918            # temp_z = self.raw_z - self.cali_offset_z
 919            heading = math.atan2(temp_y, -temp_x) * (180 / 3.14159265) + 180 + 3
 920            return heading
 921        else:
 922            if(self.cali_offset_x):
 923                self._get_raw()
 924                temp_x = -(self.raw_x - self.cali_offset_x)
 925                temp_y = -(self.raw_y - self.cali_offset_y)
 926                heading = math.atan2(temp_y, -temp_x) * (180 / 3.14159265) + 180 + 3
 927            else:
 928                heading = math.atan2(self.get_y(), -self.get_x()) * (180 / 3.14159265) + 180 + 3
 929            return heading
 930        
 931    def _get_temperature(self):
 932        if(self.chip==1):
 933            retry = 0
 934            if (retry < 5):
 935                try:
 936                    self.i2c.writeto(self.addr, b'\x09\x02', True)
 937                    while True:
 938                        self.i2c.writeto(self.addr, b'\x08', False)
 939                        buf = self.i2c.readfrom(self.addr, 1)
 940                        status = ustruct.unpack('B', buf)[0]
 941                        if(status & 0x02):
 942                            break
 943                    self.i2c.writeto(self.addr, b'\x07', False)
 944                    buf = self.i2c.readfrom(self.addr, 1)
 945                    temp = (ustruct.unpack('B', buf)[0])*0.8 -75
 946                    # print(data)
 947                    return temp
 948                except:
 949                    retry = retry + 1
 950            else:
 951                raise Exception("i2c read/write error!")   
 952        elif(self.chip == 2):
 953            pass
 954
 955    def _get_id(self):
 956        if (self.chip==1):
 957            retry = 0
 958            if (retry < 5):
 959                try:
 960                    self.i2c.writeto(self.addr, bytearray([0x2f]), False)
 961                    buf = self.i2c.readfrom(self.addr, 1, True)
 962                    print(buf)
 963                    id = ustruct.unpack('B', buf)[0]
 964                    return id
 965                except:
 966                    retry = retry + 1
 967            else:
 968                raise Exception("i2c read/write error!")
 969        elif (self.chip==2):
 970            retry = 0
 971            if (retry < 5):
 972                try:
 973                    self.i2c.writeto(self.addr, bytearray([0x39]), False)
 974                    buf = self.i2c.readfrom(self.addr, 1, True)
 975                    id = ustruct.unpack('B', buf)[0]
 976                    return id
 977                except:
 978                    retry = retry + 1
 979            else:
 980                raise Exception("i2c read/write error!")
 981
 982    def _judge_id(self):
 983        """
 984        判断product_ID
 985        """
 986        retry = 0
 987        if (retry < 5):
 988            try:
 989                self.i2c.writeto(self.addr, bytearray([0x39]), False)
 990                buf = self.i2c.readfrom(self.addr, 1, True)
 991                id = ustruct.unpack('B', buf)[0]
 992                if(id == 16):
 993                    self.chip = 2
 994                    self.product_ID = 16
 995                else:
 996                    self.chip = 1
 997                    self.product_ID = 48
 998            except:
 999                retry = retry + 1
1000        else:
1001            raise Exception("i2c read/write error!") 
1002
1003# Magnetic
1004if 48 in i2c.scan():
1005    magnetic = Magnetic()
1006else:
1007    print("magnetic init error!")
1008
1009class BME280(object):
1010    def __init__(self):
1011        self.addr = 119
1012        # The “ctrl_hum” register sets the humidity data acquisition options of the device
1013        # 0x01 = [2:0]oversampling ×1
1014        i2c.writeto(self.addr, b'\xF2\x01')
1015        # The “ctrl_meas” register sets the pressure and temperature data acquisition options of the device.
1016        # The register needs to be written after changing “ctrl_hum” for the changes to become effective.
1017        # 0x27 = [7:5]Pressure oversampling ×1 | [4:2]Temperature oversampling ×4 | [1:0]Normal mode
1018        i2c.writeto(self.addr, b'\xF4\x27')
1019        # The “config” register sets the rate, filter and interface options of the device. Writes to the “config”
1020        # register in normal mode may be ignored. In sleep mode writes are not ignored.
1021        i2c.writeto(self.addr, b'\xF5\x00')
1022
1023        i2c.writeto(self.addr, b'\x88', False)
1024        bytes = i2c.readfrom(self.addr, 6)
1025        self.dig_T = ustruct.unpack('Hhh', bytes)
1026
1027        i2c.writeto(self.addr, b'\x8E', False)
1028        bytes = i2c.readfrom(self.addr, 18)
1029        self.dig_P = ustruct.unpack('Hhhhhhhhh', bytes)
1030
1031        i2c.writeto(self.addr, b'\xA1', False)
1032        self.dig_H = array.array('h', [0, 0, 0, 0, 0, 0])
1033        self.dig_H[0] = i2c.readfrom(self.addr, 1)[0]
1034        i2c.writeto(self.addr, b'\xE1', False)
1035        buff = i2c.readfrom(self.addr, 7)
1036        self.dig_H[1] = ustruct.unpack('h', buff[0:2])[0]
1037        self.dig_H[2] = buff[2]
1038        self.dig_H[3] = (buff[3] << 4) | (buff[4] & 0x0F)
1039        self.dig_H[4] = (buff[5] << 4) | (buff[4] >> 4 & 0x0F)
1040        self.dig_H[5] = buff[6]
1041
1042    def temperature(self):
1043        retry = 0
1044        if (retry < 5):
1045            try:
1046                i2c.writeto(self.addr, b'\xFA', False)
1047                buff = i2c.readfrom(self.addr, 3)
1048                T = (((buff[0] << 8) | buff[1]) << 4) | (buff[2] >> 4 & 0x0F)
1049                c1 = (T / 16384.0 - self.dig_T[0] / 1024.0) * self.dig_T[1]
1050                c2 = ((T / 131072.0 - self.dig_T[0] / 8192.0) * (T / 131072.0 - self.dig_T[0] / 8192.0)) * self.dig_T[2]
1051                self.tFine = c1 + c2
1052                return self.tFine / 5120.0
1053            except:
1054                retry = retry + 1
1055        else:
1056            raise Exception("i2c read/write error!")
1057
1058    def pressure(self):
1059        retry = 0
1060        if (retry < 5):
1061            try:
1062                self.temperature()
1063                i2c.writeto(self.addr, b'\xF7', False)
1064                buff = i2c.readfrom(self.addr, 3)
1065                P = (((buff[0] << 8) | buff[1]) << 4) | (buff[2] >> 4 & 0x0F)
1066                c1 = self.tFine / 2.0 - 64000.0
1067                c2 = c1 * c1 * self.dig_P[5] / 32768.0
1068                c2 = c2 + c1 * self.dig_P[4] * 2.0
1069                c2 = c2 / 4.0 + self.dig_P[3] * 65536.0
1070                c1 = (self.dig_P[2] * c1 * c1 / 524288.0 + self.dig_P[1] * c1) / 524288.0
1071                c1 = (1.0 + c1 / 32768.0) * self.dig_P[0]
1072                if c1 == 0.0:
1073                    return 0
1074                p = 1048576.0 - P
1075                p = (p - c2 / 4096.0) * 6250.0 / c1
1076                c1 = self.dig_P[8] * p * p / 2147483648.0
1077                c2 = p * self.dig_P[7] / 32768.0
1078                p = p + (c1 + c2 + self.dig_P[6]) / 16.0
1079                return p
1080            except:
1081                retry = retry + 1
1082        else:
1083            raise Exception("i2c read/write error!")
1084
1085    def humidity(self):
1086        retry = 0
1087        if (retry < 5):
1088            try:
1089                self.temperature()
1090                i2c.writeto(self.addr, b'\xFD', False)
1091                buff = i2c.readfrom(self.addr, 2)
1092                H = buff[0] << 8 | buff[1]
1093                h = self.tFine - 76800.0
1094                h = (H - (self.dig_H[3] * 64.0 + self.dig_H[4] / 16384.0 * h)) * \
1095                    (self.dig_H[1] / 65536.0 * (1.0 + self.dig_H[5] / 67108864.0 * h * \
1096                    (1.0 + self.dig_H[2] / 67108864.0 * h)))
1097                h = h * (1.0 - self.dig_H[0] * h / 524288.0)
1098                if h > 100.0:
1099                    return 100.0
1100                elif h < 0.0:
1101                    return 0.0
1102                else:
1103                    return h
1104            except:
1105                retry = retry + 1
1106        else:
1107            raise Exception("i2c read/write error!")
1108
1109# bm280
1110# if 119 in i2c.scan():
1111#     bme280 = BME280()
1112
1113class PinMode(object):
1114    IN = 1
1115    OUT = 2
1116    PWM = 3
1117    ANALOG = 4
1118    OUT_DRAIN = 5
1119
1120
1121pins_remap_esp32 = (33, 32, 35, 34, 39, 0, 16, 17, 26, 25, 36, 2, -1, 18, 19, 21, 5, -1, -1, 22, 23, -1, -1, 27, 14, 12,
1122                    13, 15, 4)
1123
1124
1125class MPythonPin():
1126    def __init__(self, pin, mode=PinMode.IN, pull=None):
1127        if mode not in [PinMode.IN, PinMode.OUT, PinMode.PWM, PinMode.ANALOG, PinMode.OUT_DRAIN]:
1128            raise TypeError("mode must be 'IN, OUT, PWM, ANALOG,OUT_DRAIN'")
1129        if pin == 4:
1130            raise TypeError("P4 is used for light sensor")
1131        if pin == 10:
1132            raise TypeError("P10 is used for sound sensor")
1133        try:
1134            self.id = pins_remap_esp32[pin]
1135        except IndexError:
1136            raise IndexError("Out of Pin range")
1137        if mode == PinMode.IN:
1138            # if pin in [3]:
1139            #     raise TypeError('IN not supported on P%d' % pin)
1140            self.Pin = Pin(self.id, Pin.IN, pull)
1141        if mode == PinMode.OUT:
1142            if pin in [2, 3]:
1143                raise TypeError('OUT not supported on P%d' % pin)
1144            self.Pin = Pin(self.id, Pin.OUT, pull)
1145        if mode == PinMode.OUT_DRAIN:
1146            if pin in [2, 3]:
1147                raise TypeError('OUT_DRAIN not supported on P%d' % pin)
1148            self.Pin = Pin(self.id, Pin.OPEN_DRAIN, pull)
1149        if mode == PinMode.PWM:
1150            if pin not in [0, 1, 5, 6, 7, 8, 9, 11, 13, 14, 15, 16, 19, 20, 23, 24, 25, 26, 27, 28]:
1151                raise TypeError('PWM not supported on P%d' % pin)
1152            self.pwm = PWM(Pin(self.id), duty=0)
1153        if mode == PinMode.ANALOG:
1154            if pin not in [0, 1, 2, 3, 4, 10]:
1155                raise TypeError('ANALOG not supported on P%d' % pin)
1156            self.adc = ADC(Pin(self.id))
1157            self.adc.atten(ADC.ATTN_11DB)
1158        self.mode = mode
1159
1160    def irq(self, handler=None, trigger=Pin.IRQ_RISING):
1161        if not self.mode == PinMode.IN:
1162            raise TypeError('the pin is not in IN mode')
1163        return self.Pin.irq(handler, trigger)
1164
1165    def read_digital(self):
1166        if not self.mode == PinMode.IN:
1167            raise TypeError('the pin is not in IN mode')
1168        return self.Pin.value()
1169
1170    def write_digital(self, value):
1171        if self.mode not in [PinMode.OUT, PinMode.OUT_DRAIN]:
1172            raise TypeError('the pin is not in OUT or OUT_DRAIN mode')
1173        self.Pin.value(value)
1174
1175    def read_analog(self):
1176        if not self.mode == PinMode.ANALOG:
1177            raise TypeError('the pin is not in ANALOG mode')
1178        return self.adc.read()
1179        
1180
1181    def write_analog(self, duty, freq=1000):
1182        if not self.mode == PinMode.PWM:
1183            raise TypeError('the pin is not in PWM mode')
1184        self.pwm.freq(freq)
1185        self.pwm.duty(duty)
1186
1187
1188'''
1189# to be test
1190class LightSensor(ADC):
1191    
1192    def __init__(self):
1193        super().__init__(Pin(pins_remap_esp32[4]))
1194        # super().atten(ADC.ATTN_11DB)
1195    
1196    def value(self):
1197        # lux * k * Rc = N * 3.9/ 4096
1198        # k = 0.0011mA/Lux
1199        # lux = N * 3.9/ 4096 / Rc / k
1200        return super().read() * 1.1 / 4095 / 6.81 / 0.011
1201    
1202'''
1203
1204
1205class wifi:
1206    def __init__(self):
1207        self.sta = network.WLAN(network.STA_IF)
1208        self.ap = network.WLAN(network.AP_IF)
1209
1210    def connectWiFi(self, ssid, passwd, timeout=10):
1211        if self.sta.isconnected():
1212            self.sta.disconnect()
1213        self.sta.active(True)
1214        list = self.sta.scan()
1215        for i, wifi_info in enumerate(list):
1216            try:
1217                if wifi_info[0].decode() == ssid:
1218                    self.sta.connect(ssid, passwd)
1219                    wifi_dbm = wifi_info[3]
1220                    break
1221            except UnicodeError:
1222                self.sta.connect(ssid, passwd)
1223                wifi_dbm = '?'
1224                break
1225            if i == len(list) - 1:
1226                raise OSError("SSID invalid / failed to scan this wifi")
1227        start = time.time()
1228        print("Connection WiFi", end="")
1229        while (self.sta.ifconfig()[0] == '0.0.0.0'):
1230            if time.ticks_diff(time.time(), start) > timeout:
1231                print("")
1232                raise OSError("Timeout!,check your wifi password and keep your network unblocked")
1233            print(".", end="")
1234            time.sleep_ms(500)
1235        print("")
1236        print('WiFi(%s,%sdBm) Connection Successful, Config:%s' % (ssid, str(wifi_dbm), str(self.sta.ifconfig())))
1237
1238    def disconnectWiFi(self):
1239        if self.sta.isconnected():
1240            self.sta.disconnect()
1241        self.sta.active(False)
1242        print('disconnect WiFi...')
1243
1244    def enable_APWiFi(self, essid, password=b'',channel=10):
1245        self.ap.active(True)
1246        if password:
1247            authmode=4
1248        else:
1249            authmode=0
1250        self.ap.config(essid=essid,password=password,authmode=authmode, channel=channel)
1251
1252    def disable_APWiFi(self):
1253        self.ap.active(False)
1254        print('disable AP WiFi...')
1255
1256
1257# 3 rgb leds
1258rgb = NeoPixel(Pin(17, Pin.OUT), 3, 3, 1, brightness=0.3)
1259rgb.write()
1260
1261# light sensor
1262light = ADC(Pin(39))
1263light.atten(light.ATTN_11DB)
1264
1265# sound sensor
1266sound = ADC(Pin(36))
1267sound.atten(sound.ATTN_11DB)
1268
1269# buttons
1270class Button:
1271    def __init__(self, pin_num, reverse=False):
1272        self.__reverse = reverse
1273        (self.__press_level, self.__release_level) = (0, 1) if not self.__reverse else (1, 0)
1274        self.__pin = Pin(pin_num, Pin.IN, pull=Pin.PULL_UP)
1275        self.__pin.irq(trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING, handler=self.__irq_handler)
1276        # self.__user_irq = None
1277        self.event_pressed = None
1278        self.event_released = None
1279        self.__pressed_count = 0
1280        self.__was_pressed = False
1281        # print("level: pressed is {}, released is {}." .format(self.__press_level, self.__release_level))
1282    
1283
1284    def __irq_handler(self, pin):
1285        irq_falling = True if pin.value() == self.__press_level else False
1286        # debounce
1287        time.sleep_ms(10)
1288        if self.__pin.value() == (self.__press_level if irq_falling else self.__release_level):
1289            # new event handler
1290            # pressed event
1291            if irq_falling:
1292                if self.event_pressed is not None:
1293                    schedule(self.event_pressed, self.__pin)
1294                # key status
1295                self.__was_pressed = True
1296                if (self.__pressed_count < 100):
1297                    self.__pressed_count = self.__pressed_count + 1
1298            # release event
1299            else:
1300                if self.event_released is not None:
1301                    schedule(self.event_released, self.__pin)
1302
1303                
1304    def is_pressed(self):
1305        if self.__pin.value() == self.__press_level:
1306            return True
1307        else:
1308            return False
1309
1310    def was_pressed(self):
1311        r = self.__was_pressed
1312        self.__was_pressed = False
1313        return r
1314
1315    def get_presses(self):
1316        r = self.__pressed_count
1317        self.__pressed_count = 0
1318        return r
1319
1320    def value(self):
1321        return self.__pin.value()
1322    
1323    def status(self):
1324        val = self.__pin.value()
1325        if(val==0):
1326            return 1
1327        elif(val==1):
1328            return 0
1329
1330    def irq(self, *args, **kws):
1331        self.__pin.irq(*args, **kws)
1332
1333
1334
1335class Touch:
1336
1337    def __init__(self, pin):
1338        self.__touch_pad = TouchPad(pin)
1339        self.__touch_pad.irq(self.__irq_handler)
1340        self.event_pressed = None
1341        self.event_released = None
1342        self.__pressed_count = 0
1343        self.__was_pressed = False
1344        self.__value = 0
1345
1346    def __irq_handler(self, value):
1347        # when pressed
1348        if value == 1:
1349            if self.event_pressed is not None:
1350                self.event_pressed(value)
1351            self.__was_pressed = True
1352            self.__value = 1
1353            if (self.__pressed_count < 100):
1354                self.__pressed_count = self.__pressed_count + 1
1355        # when released
1356        else:
1357            self.__value = 0
1358            if self.event_released is not None:
1359                self.event_released(value)
1360            
1361    def config(self, threshold):
1362        self.__touch_pad.config(threshold)
1363
1364    def is_pressed(self):
1365        if self.__value:
1366            return True
1367        else:
1368            return False
1369
1370    def was_pressed(self):
1371        r = self.__was_pressed
1372        self.__was_pressed = False
1373        return r
1374
1375    def get_presses(self):
1376        r = self.__pressed_count
1377        self.__pressed_count = 0
1378        return r
1379
1380    def read(self):
1381        return self.__touch_pad.read()
1382
1383
1384# button_a = Pin(0, Pin.IN, Pin.PULL_UP)
1385# button_b = Pin(2, Pin.IN, Pin.PULL_UP)
1386button_a = Button(0)
1387button_b = Button(2)
1388
1389
1390# touchpad
1391touchpad_p = touchPad_P = Touch(Pin(27))
1392touchpad_y = touchPad_Y = Touch(Pin(14))
1393touchpad_t = touchPad_T = Touch(Pin(12))
1394touchpad_h = touchPad_H = Touch(Pin(13))
1395touchpad_o = touchPad_O = Touch(Pin(15))
1396touchpad_n = touchPad_N = Touch(Pin(4))
1397
1398from gui import *
1399
1400
1401def numberMap(inputNum, bMin, bMax, cMin, cMax):
1402    outputNum = 0
1403    outputNum = ((cMax - cMin) / (bMax - bMin)) * (inputNum - bMin) + cMin
1404    return outputNum
1405
1406
1407"""
1408uuid
1409"""
1410def uuid():
1411    uuid = ''
1412    try:
1413        uuid = ubinascii.hexlify(machine.unique_id_custom()).decode().upper()
1414    except Exception as e:
1415        uuid = ubinascii.hexlify(machine.unique_id()).decode().upper()
1416    
1417    if(uuid=='ffffffffffff'.upper()):
1418        uuid = ubinascii.hexlify(machine.unique_id()).decode().upper()
1419
1420    return uuid