Beispiel #1
0
    def __init__(self, ledNumber=1, brightness=100, dataPin='P22'):
        """
        Params:
        * ledNumber = count of LEDs
        * brightness = light brightness (integer : 0 to 100%)
        * dataPin = pin to connect data channel (LoPy only)
        """
        self.ledNumber = ledNumber
        self.brightness = brightness

        # Prepare SPI data buffer (8 bytes for each color)
        self.buf_length = self.ledNumber * 3 * 8
        self.buf = bytearray(self.buf_length)

        # SPI init
        # Bus 0, 8MHz => 125 ns by bit, 8 clock cycle when bit transfert+2 clock cycle between each transfert
        # => 125*10=1.25 us required by WS2812
        if uname().sysname == 'LoPy':
            self.spi = SPI(0, SPI.MASTER, baudrate=8000000, polarity=0, phase=1, pins=(None, dataPin, None))
             # Enable pull down
	    Pin(dataPin, mode=Pin.OUT, pull=Pin.PULL_DOWN)
	else: #WiPy
            self.spi = SPI(0, SPI.MASTER, baudrate=8000000, polarity=0, phase=1)
            # Enable pull down
            Pin('GP16', mode=Pin.ALT, pull=Pin.PULL_DOWN)
        
        # Turn LEDs off
        self.show([])
Beispiel #2
0
class WS2812:
    # values to put inside the SPI register for each bit of color
    bits = (0xE0, 0xFC)

    def __init__(self, nleds=1):
        # params: * nleds = number of LEDs

        self.buf = bytearray(nleds * 3 * 8)  # 1 byte per bit
        # spi init
        # bus 0, 8MHz => 125 ns by bit, each transfer is 10 cycles long due to the
        # CC3200 spi dead cycles, therefore => 125*10=1.25 us as required by the
        # WS2812. Don't do the automatic pin assigment since we only need MOSI
        self.spi = SPI(0, SPI.MASTER, baudrate=8000000, pins=None)
        Pin('GP16', mode=Pin.ALT, pull=Pin.PULL_DOWN, alt=7)
        # turn all the LEDs off
        self.show([])

    def _send(self):
        # send the buffer over SPI.

        disable_irq()
        self.spi.write(self.buf)
        enable_irq()

    def show(self, data):
        # show RGB data on the LEDs. Expected data = [(R, G, B), ...] where
        # R, G and B are the intensities of the colors in the range 0 to 255.
        # the number of tuples may be less than the number of connected LEDs.

        self.fill(data)
        self._send()

    def update(self, data, start=0):
        # fill a part of the buffer with RGB data.
        # Returns the index of the first unfilled LED.

        buf = self.buf
        bits = self.bits
        idx = start * 24
        for colors in data:
            for c in (1, 0, 2): # the WS2812 requires GRB
                color = colors[c]
                for bit in range (0, 8):
                    buf[idx + bit] = bits[color >> (7 - bit) & 0x01]
                idx += 8
        return idx // 24

    def fill(self, data):
        # fill the buffer with RGB data.
        # all the LEDs after the data are turned off.

        end = self.update(data)
        buf = self.buf
        off = self.bits[0]
        for idx in range(end * 24, len(self.buf)):
            buf[idx] = off
Beispiel #3
0
class LedStrip:
    """
    Driver for APA102C ledstripes (Adafruit Dotstars) on the Wipy
    Connect
    CLK <---> GP14 (yellow cable)
    DI  <---> GP16 (green cable)
    """

    def __init__(self, leds):
        """
        :param int leds: number of LEDs on strio
        """
        self.ledcount = leds
        self.buffersize = self.ledcount * 4
        self.buffer = bytearray(self.ledcount * 4)
        self.emptybuffer = bytearray(self.ledcount * 4)
        for i in range(0, self.buffersize, 4):
            self.emptybuffer[i] = 0xFF
            self.emptybuffer[i + 1] = 0x0
            self.emptybuffer[i + 2] = 0x0
            self.emptybuffer[i + 3] = 0x0
        self.startframe = bytes([0x00, 0x00, 0x00, 0x00])
        self.endframe = bytes([0xFF, 0xFF, 0xFF, 0xFF])
        self.spi = SPI(0, mode=SPI.MASTER, baudrate=4000000, polarity=0, phase=0, bits=8, firstbit=SPI.MSB)
        self.clear()

    def clear(self):
        self.buffer = self.emptybuffer[:]

    def set(self, led, red=0, green=0, blue=0, bri=0x1F):
        """
        :param int led: Index of LED
        :param int red, green, blue: 0-255
        :param int bri: Brightness 0-31
        """
        if led > self.ledcount:
            led %= self.ledcount

        if led < 0:
            led += self.ledcount

        frameheader = (0x07 << 5) | bri

        offset = led * 4
        self.buffer[offset] = frameheader
        self.buffer[offset + 1] = blue
        self.buffer[offset + 2] = green
        self.buffer[offset + 3] = red

    def send(self):
        self.spi.write(self.startframe + self.buffer)
Beispiel #4
0
    def __init__(self, debug=False, baud=100000):
        # From datasheet
        # Bit rate – up to 12 MHz1
        # ▪ Polarity – CPOL = 1; clock transition high-to-low on the leading edge and low-to-high on the
        #   trailing edge
        # ▪ Phase – CPHA = 1; setup on the leading edge and sample on the trailing edge
        # ▪ Bit order – MSB first
        # ▪ Chip select polarity – active low
        self.spi = SPI(0)
        try:
            self.spi.init(mode=SPI.MASTER, baudrate=baud, bits=8,
                          polarity=1, phase=1, firstbit=SPI.MSB,
                          pins=('GP31', 'GP16', 'GP30')) # CLK, MOSI, MISO
        except AttributeError:
            self.spi.init(baudrate=baud, bits=8,
                          polarity=1, phase=1, firstbit=SPI.MSB,
                          pins=('GP31', 'GP16', 'GP30')) # CLK, MOSI, MISO

        # These are all active low!
        self.tc_en_bar = Pin('GP4', mode=Pin.OUT)

        self.disable()

        self.tc_busy_bar = Pin('GP5', mode=Pin.IN)
        self.tc_busy_bar.irq(trigger=Pin.IRQ_RISING) # Wake up when it changes
        self.tc_cs_bar = Pin('GP17', mode=Pin.ALT, alt=7)

        self.debug = debug
Beispiel #5
0
    def __init__(self, nleds=1):
        # params: * nleds = number of LEDs

        self.buf = bytearray(nleds * 3 * 8)  # 1 byte per bit
        # spi init
        # bus 0, 8MHz => 125 ns by bit, each transfer is 10 cycles long due to the
        # CC3200 spi dead cycles, therefore => 125*10=1.25 us as required by the
        # WS2812. Don't do the automatic pin assigment since we only need MOSI
        self.spi = SPI(0, SPI.MASTER, baudrate=8000000, pins=None)
        Pin('GP16', mode=Pin.ALT, pull=Pin.PULL_DOWN, alt=7)
        # turn all the LEDs off
        self.show([])
Beispiel #6
0
class DotStars:


    def __init__(self, leds):
        self.ledcount = leds
        self.buffersize = self.ledcount * 4
        self.buffer = bytearray(self.ledcount * 4)
        self.emptybuffer = bytearray(self.ledcount * 4)
        for i in range(0, self.buffersize, 4):
            self.emptybuffer[i] = 0xff
            self.emptybuffer[i + 1] = 0x0
            self.emptybuffer[i + 2] = 0x0
            self.emptybuffer[i + 3] = 0x0   
        self.startframe = bytes([0x00, 0x00, 0x00, 0x00])
        self.endframe   = bytes([0xff, 0xff, 0xff, 0xff])
        self.spi = SPI(0, mode=SPI.MASTER, baudrate=8000000, polarity=0, phase=0,bits=8, firstbit=SPI.MSB)
        self.clearleds()

       
    #init empty self.buffer
    def clearleds(self):
        self.buffer = self.emptybuffer[:]

    def setled(self, led, red=0, green=0, blue=0, bri=0x1f):
        if (led > self.ledcount):
            led=led % self.ledcount
        
        if (led < 0):
            led = self.ledcount + led
        
        frameheader = (0x07 << 5) | bri
        offset = led * 4
        self.buffer[offset] = frameheader
        self.buffer[offset + 1] = blue
        self.buffer[offset + 2] = green
        self.buffer[offset + 3] = red

    def send(self):
        #self.spi.write(self.startframe + self.buffer + self.endframe)
        self.spi.write(self.startframe + self.buffer)
	def __init__(self, sck, mosi, miso, rst, cs):

		self.sck = Pin(sck, Pin.OUT)
		self.mosi = Pin(mosi, Pin.OUT)
		self.miso = Pin(miso)
		self.rst = Pin(rst, Pin.OUT)
		self.cs = Pin(cs, Pin.OUT)

		self.rst.value(0)
		self.cs.value(1)

		if uname()[0] == 'WiPy':
			self.spi = SPI(0)
			self.spi.init(SPI.MASTER, baudrate=1000000, pins=(self.sck, self.mosi, self.miso))
		elif uname()[0] == 'esp8266':
			self.spi = SPI(baudrate=100000, polarity=0, phase=0, sck=self.sck, mosi=self.mosi, miso=self.miso)
			self.spi.init()
		else:
			raise RuntimeError("Unsupported platform")

		self.rst.value(1)
		self.init()
Beispiel #8
0
 def __init__(self, leds):
     self.ledcount = leds
     self.buffersize = self.ledcount * 4
     self.buffer = bytearray(self.ledcount * 4)
     self.emptybuffer = bytearray(self.ledcount * 4)
     for i in range(0, self.buffersize, 4):
         self.emptybuffer[i] = 0xff
         self.emptybuffer[i + 1] = 0x0
         self.emptybuffer[i + 2] = 0x0
         self.emptybuffer[i + 3] = 0x0   
     self.startframe = bytes([0x00, 0x00, 0x00, 0x00])
     self.endframe   = bytes([0xff, 0xff, 0xff, 0xff])
     self.spi = SPI(0, mode=SPI.MASTER, baudrate=8000000, polarity=0, phase=0,bits=8, firstbit=SPI.MSB)
     self.clearleds()
Beispiel #9
0
  def __init__(self, spd=1000000):
    # first assign CLK, MISO, MOSI, CS to the correct pins
    self.pin_clk = Pin(self.CLK, mode=Pin.OUT)    # CLK
    self.pin_miso = Pin(self.MISO)    # MISO
    self.pin_mosi = Pin(self.MOSI, mode=Pin.OUT)    # MOSI
    self.pin_cs = Pin(self.CS, mode=Pin.OUT)    # NSS/CS
    self.pin_reset = Pin(self.RESET, mode=Pin.OUT)

    self.pin_reset.value(0)
    self.pin_cs.value(1)

    self.spi = SPI(0)
    self.spi.init(mode=SPI.MASTER, baudrate=spd, pins=(self.CLK, self.MOSI, self.MISO))
    
    self.pin_reset.value(1)

    self.MFRC522_Init()
Beispiel #10
0
 def __init__(self, leds):
     """
     :param int leds: number of LEDs on strio
     """
     self.ledcount = leds
     self.buffersize = self.ledcount * 4
     self.buffer = bytearray(self.ledcount * 4)
     self.emptybuffer = bytearray(self.ledcount * 4)
     for i in range(0, self.buffersize, 4):
         self.emptybuffer[i] = 0xFF
         self.emptybuffer[i + 1] = 0x0
         self.emptybuffer[i + 2] = 0x0
         self.emptybuffer[i + 3] = 0x0
     self.startframe = bytes([0x00, 0x00, 0x00, 0x00])
     self.endframe = bytes([0xFF, 0xFF, 0xFF, 0xFF])
     self.spi = SPI(0, mode=SPI.MASTER, baudrate=4000000, polarity=0, phase=0, bits=8, firstbit=SPI.MSB)
     self.clear()
Beispiel #11
0
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.pages = self.height // 8
        self.buffer = bytearray(self.pages * self.width)
        self.framebuf = framebuf.FrameBuffer(self.buffer, self.width, self.height, framebuf.MONO_VLSB)

        self.spi = SPI(0)
        # chip select
        self.cs = Pin("P16", mode=Pin.OUT, pull=Pin.PULL_UP)
        # command
        self.dc = Pin("P17", mode=Pin.OUT, pull=Pin.PULL_UP)
        
        # initialize all pins high
        self.cs.high()
        self.dc.high()

        self.spi.init(baudrate=8000000, phase=0, polarity=0)

        self.init_display()
    def __init__(self, controller="XPT2046", asyn=False, *, confidence=5, margin=50, delay=10, calibration=None, spi = None):
        if spi is None:
            self.spi = SPI(-1, baudrate=1000000, sck=Pin("X12"), mosi=Pin("X11"), miso=Pin("Y2"))
        else:
            self.spi = spi
        self.recv = bytearray(3)
        self.xmit = bytearray(3)
# set default values
        self.ready = False
        self.touched = False
        self.x = 0
        self.y = 0
        self.buf_length = 0
        cal = TOUCH.DEFAULT_CAL if calibration is None else calibration
        self.asynchronous = False
        self.touch_parameter(confidence, margin, delay, cal)
        if asyn:
            self.asynchronous = True
            import uasyncio as asyncio
            loop = asyncio.get_event_loop()
            loop.create_task(self._main_thread())
Beispiel #13
0
    def __init__(self, ledNumber=1, brightness=100):
        """
        Params:
        * ledNumber = count of LEDs
        * brightness = light brightness (integer : 0 to 100%)
        """
        self.ledNumber = ledNumber
        self.brightness = brightness

        # Prepare SPI data buffer (8 bytes for each color)
        self.buf_length = self.ledNumber * 3 * 8
        self.buf = bytearray(self.buf_length)

        # SPI init
        # Bus 0, 8MHz => 125 ns by bit, 8 clock cycle when bit transfert+2 clock cycle between each transfert
        # => 125*10=1.25 us required by WS2812
        self.spi = SPI(0, SPI.MASTER, baudrate=8000000, polarity=0, phase=1)
        # Enable pull down
        Pin('GP16', mode=Pin.ALT, pull=Pin.PULL_DOWN)
        
        # Turn LEDs off
        self.show([])
Beispiel #14
0
class WS2812:
    """
    Driver for WS2812 RGB LEDs. May be used for controlling single LED or chain
    of LEDs.

    Example of use:

        chain = WS2812(ledNumber=4)
        data = [
            (255, 0, 0),    # red
            (0, 255, 0),    # green
            (0, 0, 255),    # blue
            (85, 85, 85),   # white
        ]
        chain.show(data)

    Version: 1.0
    """
    # Values to put inside SPi register for each color's bit
    buf_bytes = (0xE0E0, 0xFCE0, 0xE0FC, 0xFCFC)

    def __init__(self, ledNumber=1, brightness=100, dataPin='P22'):
        """
        Params:
        * ledNumber = count of LEDs
        * brightness = light brightness (integer : 0 to 100%)
        * dataPin = pin to connect data channel (LoPy only)
        """
        self.ledNumber = ledNumber
        self.brightness = brightness

        # Prepare SPI data buffer (8 bytes for each color)
        self.buf_length = self.ledNumber * 3 * 8
        self.buf = bytearray(self.buf_length)

        # SPI init
        # Bus 0, 8MHz => 125 ns by bit, 8 clock cycle when bit transfert+2 clock cycle between each transfert
        # => 125*10=1.25 us required by WS2812
        if uname().sysname == 'LoPy':
            self.spi = SPI(0, SPI.MASTER, baudrate=8000000, polarity=0, phase=1, pins=(None, dataPin, None))
             # Enable pull down
	    Pin(dataPin, mode=Pin.OUT, pull=Pin.PULL_DOWN)
	else: #WiPy
            self.spi = SPI(0, SPI.MASTER, baudrate=8000000, polarity=0, phase=1)
            # Enable pull down
            Pin('GP16', mode=Pin.ALT, pull=Pin.PULL_DOWN)
        
        # Turn LEDs off
        self.show([])

    def show(self, data):
        """
        Show RGB data on LEDs. Expected data = [(R, G, B), ...] where R, G and B
        are intensities of colors in range from 0 to 255. One RGB tuple for each
        LED. Count of tuples may be less than count of connected LEDs.
        """
        self.fill_buf(data)
        self.send_buf()

    def send_buf(self):
        """
        Send buffer over SPI.
        """
        disable_irq()
        self.spi.write(self.buf)
        enable_irq()
        gc.collect()

    def update_buf(self, data, start=0):
        """
        Fill a part of the buffer with RGB data.

        Order of colors in buffer is changed from RGB to GRB because WS2812 LED
        has GRB order of colors. Each color is represented by 4 bytes in buffer
        (1 byte for each 2 bits).

        Returns the index of the first unfilled LED

        Note: If you find this function ugly, it's because speed optimisations
        beated purity of code.
        """

        buf = self.buf
        buf_bytes = self.buf_bytes
        brightness = self.brightness

        index = start * 24
        for red, green, blue in data:
            red = int(red * brightness // 100)
            green = int(green * brightness // 100)
            blue = int(blue * brightness // 100)

            buf[index] = buf_bytes[green >> 6 & 0x03]
            buf[index+2] = buf_bytes[green >> 4 & 0x03]
            buf[index+4] = buf_bytes[green >> 2 & 0x03]
            buf[index+6] = buf_bytes[green & 0x03]

            buf[index+8] = buf_bytes[red >> 6 & 0x03]
            buf[index+10] = buf_bytes[red >> 4 & 0x03]
            buf[index+12] = buf_bytes[red >> 2 & 0x03]
            buf[index+14] = buf_bytes[red & 0x03]

            buf[index+16] = buf_bytes[blue >> 6 & 0x03]
            buf[index+18] = buf_bytes[blue >> 4 & 0x03]
            buf[index+20] = buf_bytes[blue >> 2 & 0x03]
            buf[index+22] = buf_bytes[blue & 0x03]

            index += 24

        return index // 24

    def fill_buf(self, data):
        """
        Fill buffer with RGB data.

        All LEDs after the data are turned off.
        """
        end = self.update_buf(data)

        # Turn off the rest of the LEDs
        buf = self.buf
        off = self.buf_bytes[0]
        for index in range(end * 24, self.buf_length):
            buf[index] = off
            index += 2
            
    def set_brightness(self, brightness):
        """
        Set brighness of all leds
        """
        self.brightness = brightness
Beispiel #15
0
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import gc
from machine import Pin, SPI
from codepage import cp437_chr, cp437_pal, cp437_pic
from gd import Gameduino, RAM_CHR, RAM_PAL

# See the Gameduino General test for all MicroPython plateform support
spi = SPI(2)  # MOSI=Y8, MISO=Y7, SCK=Y6, SS=Y5
spi.init(SPI.MASTER, baudrate=2000000, phase=0, polarity=0)
# We must manage the SS signal ourself
ss = Pin(Pin.board.Y5, Pin.OUT)

# Gameduino Lib
gd = Gameduino(spi, ss)
print("Initializing...")
gd.begin()
print("Uncompressing to RAM_CHR")
gd.uncompress(RAM_CHR, cp437_chr)
print("Uncompressing to RAM_PAL")
gd.uncompress(RAM_PAL, cp437_pal)


def atxy(x, y):
Beispiel #16
0
from network import Bluetooth

# Timing variables
Irrigation_Delay_Sec_On = 30  # watering time in seconds
Irrigation_Delay_Sec_Off = 43200  # wait time in seconds
Irrigation_Delay_Count = 0  # functions need to count down, not up
Solenoid_Status = False

# Initialise LED
pycom.heartbeat(False)
pycom.rgbled(0x0000ff)  # blue

# Pin and Com definitions
_SPI_Ref = SPI(0,
               mode=SPI.MASTER,
               baudrate=100000,
               polarity=0,
               phase=0,
               firstbit=SPI.MSB)  # baud rate was 100000
_I2C_Ref = I2C(0, I2C.MASTER, baudrate=10000, pins=('P21', 'P20'))  # SDA, SCL
_LCD_CS_Ref = Pin('P9', mode=Pin.OUT)
_Solenoid = Pin('P19', mode=Pin.OUT)

# Calling Constructors
_LCDScreen = LCDBackend(_SPI_Ref, _LCD_CS_Ref)
_Clock = RTCBackend(_I2C_Ref)
_BT_UART = UART(1, baudrate=9600, pins=('P7', 'P6'))  # TX, RX

#_Clock.SetTime(0, 31, 15, 6, 25, 4, 20) # s,m,h,dow,d,m,y

# SD stuff
sd = SD()
Beispiel #17
0
# Project home: https://github.com/mchobby/esp8266-upy/tree/master/ili934x
#
# This use the font file veram_m15.bin available on the FreeType_generator Project
# located at https://github.com/mchobby/freetype-generator
#
# In this sample we will:
# * Use the font drawer on the ILI934x driver, This approach is quite slower
#   compare to the print() function because is draws to the LCD pixel per pixel
#
from machine import SPI, Pin
from ili934x import *
from fdrawer import *

# PYBStick config (idem with PYBStick-Feather-Face)
spi = SPI(1, baudrate=40000000)
cs_pin = Pin("S15")
dc_pin = Pin("S13")
rst_pin = None

# r in 0..3 is rotation, r in 4..7 = rotation+miroring
# Use 3 for landscape mode
lcd = ILI9341(spi, cs=cs_pin, dc=dc_pin, rst=rst_pin, w=320, h=240, r=0)
lcd.erase()
lcd.rect(2, 2, lcd.width - 4, lcd.height - 4, WHITE)

fd = FontDrawer(frame_buffer=lcd, font_name='veram_m15')
fd.color = GREEN
fd.print_str("Font Demo", 10, 10)

fd.print_char("#", 10, 50)
Beispiel #18
0
strWLAN = str(wlan.ifconfig())
strWLAN = strWLAN[2:strWLAN.find(',',2)-1]

# synchronize with time-server
rtc = RTC()
rtc.ntp_sync('pool.ntp.org')
time.sleep(2)

# create LoRa-socket
lora = LoRa(mode=LoRa.LORA, region=LoRa.EU868)
s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)

# the display is a SHARP Memory Display Breakout - 1.3" 96x96 Silver Monochrome
# https://www.exp-tech.de/displays/lcd/5090/sharp-memory-display-breakout-1.3-96x96-silver-monochrome
# this uses the Lopys SPI default pins for CLK, MOSI and MISO (``P10``, ``P11`` and ``P14``)
spi = SPI(0, mode=SPI.MASTER, baudrate=2000000, polarity=0, phase=0)
# define a dedicated pin for CS
scs = Pin('P9', mode=Pin.OUT)

# pass in the display size, width and height, as well
display = adafruit_sharpmemorydisplay.SharpMemoryDisplay(spi, scs, 96, 96)

# set the display rotation (possible values: 0, 1, 2, 3)
display.rotation = 0

def recLoRa(delay, id, dataArray):
    print("now listening ...")
    # check lora-interface for sensor-data
    s.setblocking(False)
    data = ""
    # listen as long as the received data-length is lower 8 byte
Beispiel #19
0
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import gc
from machine import Pin, SPI
from gd import Gameduino, RAM_CHR, RAM_PAL

# Initialize the SPI Bus (on Pyboard)
spi = SPI(2) # MOSI=Y8, MISO=Y7, SCK=Y6, SS=Y5
spi.init( baudrate=2000000, phase=0, polarity=0 )
# We must manage the SS signal ourself
sel = Pin( Pin.board.Y5, Pin.OUT )

# Gameduino Lib
gd = Gameduino( spi, sel )
print( "Initializing...")
gd.begin()
print( "Initializing ASCII...")
gd.ascii()

# Print a string
gd.putstr( 5 ,  0, "  *** DEMOs ***" )
gd.putstr( 5 ,  1, "04_demo/ascii/dump.py" )
gd.putstr( 10, 10, "MicroPython goes VGA !" )
Beispiel #20
0
import cmath
import utime
import uos
from writer import Writer, CWriter
from nanogui import Label, Meter, LED, Dial, Pointer, refresh
# SHT30 IMPORT
from sht3x import SHT3X

if sys.platform == 'esp32':
    print('1.4 inch TFT screen test on ESP32')
    sck = Pin(18)
    miso= Pin(19)
    mosi= Pin(23)
    SPI_CS = 26
    SPI_DC = 5
    spi = SPI(2, baudrate=32000000, sck=sck, mosi=mosi, miso=miso)

st7735 =Display(spi,SPI_CS,SPI_DC)    
# Fonts
import fonts.arial10 as arial10
import fonts.freesans20 as freesans20

GREEN = color565(0, 255, 0)
RED = color565(255, 0, 0)
BLUE = color565(0, 0, 255)
YELLOW = color565(255, 255, 0)
BLACK = 0
CWriter.set_textpos(st7735, 0, 0)  # In case previous tests have altered it
wri = CWriter(st7735, arial10, GREEN, BLACK, verbose=False)
wri.set_clip(True, True, False)
import struct

from machine import Pin, I2C, SPI, Timer
import sdcard

import dht12
import sht30

binary_struct = b"<I4f"
binary_struct_len = struct.calcsize(binary_struct)

i2c = I2C(scl=Pin(5), sda=Pin(4))
dht_sens = dht12.DHT12(i2c)
sht_sens = sht30.SHT30(i2c)

sd = sdcard.SDCard(SPI(1), Pin(15))
assert sd.csd_version == 2
buffer_4096 = bytearray(512)
pointer = 0
buffer_cursor = 0  # in lba size units
SD_LBA_SIZE = const(512)

last_measurements = None
last_measurements_time = 0
measurements_store_time_limit_sec = 2.5


def _get_measures():
    global last_measurements_time, last_measurements
    if time.time(
    ) < last_measurements_time + measurements_store_time_limit_sec:
Beispiel #22
0
import time
import json

Wifissid = 'yuhan888888'
Wifipasswd = 'yuhan123456'
SERVER = "47.103.121.23"
CLIENT_ID = "L9ZPRGlt6Bl7P8FXYRRd"
TOPIC = "v1/devices/me/telemetry"
username = '******'
passwd = ''

# 采用默认的SPI引脚
# spi = SPI(1);
spi = SPI(baudrate=10000000,
          polarity=1,
          phase=0,
          sck=Pin(2, Pin.OUT),
          mosi=Pin(0, Pin.OUT),
          miso=Pin(12))
# D0-CLK/sck D1-MOSI 采用自定义的SPI引脚
display = SSD1306_SPI(128, 64, spi, Pin(5), Pin(4), Pin(16))
# 采用自定义的DC  RES  CS 引脚


def wifi_connect(essid, password):
    if essid == None or essid == '':
        raise BaseException('essid can not be null')
    if password == None or password == '':
        raise BaseException('password can not be null')
    sta_if = network.WLAN(network.STA_IF)
    if not sta_if.active():
        #print("set sta active")
Beispiel #23
0
rel = Pin(pinout.RELAY_PIN, Pin.OUT)

isLed7 = True  # SPI
isOLED = False  # I2C
isLCD = False  # I2C
isSD = False  # UART

print("setup displays: >")

# SPI max 8x7 segment
try:
    #spi.deinit()
    #print("spi > close")
    spi = SPI(1,
              baudrate=10000000,
              polarity=1,
              phase=0,
              sck=Pin(pinout.SPI_CLK_PIN),
              mosi=Pin(pinout.SPI_MOSI_PIN))
    ss = Pin(pinout.SPI_CS0_PIN, Pin.OUT)
except:
    print("SPI.Err")

if isLed7:
    from lib.max7219_8digit import Display
    d7 = Display(spi, ss)
    d7.write_to_buffer('octopus')
    d7.display()

LCD_ADDRESS = 0x27
LCD_ROWS = 2
LCD_COLS = 16
Beispiel #24
0
from machine import SPI, Pin
import time
import framebuf

def load_image(name):
    "takes a filename, returns a framebuffer"
    f = open(name, 'rb')
    if b'P4\n' != f.readline():                         # Magic number
        raise ImportError("Invalid file")
    f.readline()                                       # Creator comment
    width, height = list(int(j) for j in f.readline()[:-1].decode().split(" ")) # Dimensions
    data = bytearray(f.read())
    return framebuf.FrameBuffer(data, width, height, framebuf.MONO_HLSB)


d = ssd1306.SSD1306_SPI(128, 64, SPI(1),
        dc=Pin("B1", Pin.OUT),
        res=Pin("C9", Pin.OUT),
        cs=Pin("A8", Pin.OUT),
        external_vcc=False, mirror_v=True, mirror_h=True)



while 1:
    d.text("Hello world!", 0, 0, 1)
    d.framebuf.line(127, 0, 0, 63, 1)
    d.show()
    time.sleep(1)

    d.framebuf.blit(load_image("test.pbm"), 0, 0)
    d.show()
def master():
    csn = Pin(cfg['csn'], mode=Pin.OUT, value=1)
    ce = Pin(cfg['ce'], mode=Pin.OUT, value=0)
    if cfg['spi'] == -1:
        spi = SPI(-1,
                  sck=Pin(cfg['sck']),
                  mosi=Pin(cfg['mosi']),
                  miso=Pin(cfg['miso']))
        nrf = NRF24L01(spi, csn, ce, payload_size=8)
    else:
        nrf = NRF24L01(SPI(cfg['spi']), csn, ce, payload_size=8)

    nrf.open_tx_pipe(pipes[0])
    nrf.open_rx_pipe(1, pipes[1])
    nrf.start_listening()

    num_needed = 16
    num_successes = 0
    num_failures = 0
    led_state = 0

    print('NRF24L01 master mode, sending %d packets...' % num_needed)

    while num_successes < num_needed and num_failures < num_needed:
        # stop listening and send packet
        nrf.stop_listening()
        millis = utime.ticks_ms()
        led_state = max(1, (led_state << 1) & 0x0f)
        print('sending:', millis, led_state)
        try:
            nrf.send(struct.pack('ii', millis, led_state))
        except OSError:
            pass

        # start listening again
        nrf.start_listening()

        # wait for response, with 250ms timeout
        start_time = utime.ticks_ms()
        timeout = False
        while not nrf.any() and not timeout:
            if utime.ticks_diff(utime.ticks_ms(), start_time) > 250:
                timeout = True

        if timeout:
            print('failed, response timed out')
            num_failures += 1

        else:
            # recv packet
            got_millis, = struct.unpack('i', nrf.recv())

            # print response and round-trip delay
            print('got response:', got_millis, '(delay',
                  utime.ticks_diff(utime.ticks_ms(), got_millis), 'ms)')
            num_successes += 1

        # delay then loop
        utime.sleep_ms(250)

    print('master finished sending; successes=%d, failures=%d' %
          (num_successes, num_failures))
Beispiel #26
0
MCHobby investit du temps et des ressources pour écrire de la
documentation, du code et des exemples.
Aidez nous à en produire plus en achetant vos produits chez MCHobby.

------------------------------------------------------------------------

History:
  08 march 2021 - Dominique - initial writing
"""

from machine import SPI, Pin
from lcd12864 import SPI_LCD12864
import time

# PYBStick: S19=mosi, S23=sck, S26=/ss
spi = SPI(1)
spi.init(polarity=0, phase=1)
cs = Pin('S26', Pin.OUT, value=0)

HEART_ICON = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
              [0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0],
              [0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0],
              [0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0],
              [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
              [0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0],
              [0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0],
              [0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0],
              [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
              [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

Beispiel #27
0
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
from machine import Pin, SPI
from time import sleep_ms

# UEXT wiring on the Pyboard.
# https://github.com/mchobby/pyboard-driver/tree/master/UEXT
spi = SPI(2) # MOSI=Y8, MISO=Y7, SCK=Y6, SS=Y5
spi.init( baudrate=5000000, phase=0, polarity=0 )
# We must manage the SS signal ourself
ss = Pin( Pin.board.Y5, Pin.OUT )

# Start a new SPI transaction
ss.value( 1 )
sleep_ms( 10 )
ss.value( 0 )


print( "Write a A on the screen" )
spi.send( bytes([0x80,0x00,0x41]) )

sleep_ms( 500 )
Beispiel #28
0
#
# Copyright (c) 2006-2019, RT-Thread Development Team
#
# SPDX-License-Identifier: MIT License
#
# Change Logs:
# Date           Author       Notes
# 2019-06-13     SummerGift   first version
#

from machine import Pin, SPI

PIN_CLK  = 26
PIN_MOSI = 27   
PIN_MISO = 28   

clk = Pin(("clk", PIN_CLK), Pin.OUT_PP)          # Select the PIN_CLK pin device as the clock
mosi = Pin(("mosi", PIN_MOSI), Pin.OUT_PP)       # Select the PIN_MOSI pin device as the mosi
miso = Pin(("miso", PIN_MISO), Pin.IN)           # Select the PIN_MISO pin device as the miso

spi = SPI(-1, 500000, polarity=0, phase=0, bits=8, firstbit=0, sck=clk, mosi=mosi, miso=miso)
print(spi)
spi.write("hello rt-thread!")
spi.read(10)
Beispiel #29
0
from machine import Pin, SPI
from ST7735 import TFT
from sysfont import sysfont
from time import sleep_ms

#led_r = Pin(13, Pin.OUT, value=0)
#led_g = Pin(14, Pin.OUT, value=0)
#led_b = Pin(15, Pin.OUT, value=0)

spi = SPI(0, 1000000, polarity=1, phase=1, sck=Pin(18), mosi=Pin(19))
#spi = machine.SPI(0)
print(spi)
tft = TFT(spi, 22, 21, 20)  # DC, RST, CS
tft.initr()
tft.rgb()
tft.rotation(2)
tft.fill(TFT.BLACK)


def tft_draw_char(string, px, py):
    long = len(string)
    for x in range(long):
        c = string[x]
        tft.text((px, py), str(c), TFT.GREEN, sysfont, 1)
        sleep_ms(120)
        px = px + 6


while True:
    tft.fill(TFT.BLACK)
    sleep_ms(1200)
Beispiel #30
0
class ILI9341:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.pages = self.height // 8
        self.buffer = bytearray(self.pages * self.width)
        self.framebuf = framebuf.FrameBuffer(self.buffer, self.width, self.height, framebuf.MONO_VLSB)

        self.spi = SPI(0)
        # chip select
        self.cs = Pin("P16", mode=Pin.OUT, pull=Pin.PULL_UP)
        # command
        self.dc = Pin("P17", mode=Pin.OUT, pull=Pin.PULL_UP)
        
        # initialize all pins high
        self.cs.high()
        self.dc.high()

        self.spi.init(baudrate=8000000, phase=0, polarity=0)

        self.init_display()
        

    def init_display(self):
        time.sleep_ms(500)
        
        self.write_cmd(0x01)
        
        time.sleep_ms(200)
    
        self.write_cmd(0xCF)
        self.write_data(bytearray([0x00, 0x8B, 0x30]))
    
        self.write_cmd(0xED)
        self.write_data(bytearray([0x67, 0x03, 0x12, 0x81]))

        self.write_cmd(0xE8)
        self.write_data(bytearray([0x85, 0x10, 0x7A]))
    
        self.write_cmd(0xCB)
        self.write_data(bytearray([0x39, 0x2C, 0x00, 0x34, 0x02]))
    
        self.write_cmd(0xF7)
        self.write_data(bytearray([0x20]))

        self.write_cmd(0xEA)
        self.write_data(bytearray([0x00, 0x00]))

        # Power control
        self.write_cmd(0xC0)
        # VRH[5:0]
        self.write_data(bytearray([0x1B]))
        
        # Power control
        self.write_cmd(0xC1)
        # SAP[2:0];BT[3:0]
        self.write_data(bytearray([0x10]))
        
        # VCM control
        self.write_cmd(0xC5)
        self.write_data(bytearray([0x3F, 0x3C]))
    
        # VCM control2
        self.write_cmd(0xC7)
        self.write_data(bytearray([0xB7]))
    
        # Memory Access Control
        self.write_cmd(0x36)
        self.write_data(bytearray([0x08]))
    
        self.write_cmd(0x3A)
        self.write_data(bytearray([0x55]))
    
        self.write_cmd(0xB1)
        self.write_data(bytearray([0x00, 0x1B]))
        
        # Display Function Control
        self.write_cmd(0xB6)
        self.write_data(bytearray([0x0A, 0xA2]))
    
        # 3Gamma Function Disable
        self.write_cmd(0xF2)
        self.write_data(bytearray([0x00]))
        
        # Gamma curve selected
        self.write_cmd(0x26)
        self.write_data(bytearray([0x01]))
    
        # Set Gamma
        self.write_cmd(0xE0)
        self.write_data(bytearray([0x0F, 0x2A, 0x28, 0x08, 0x0E, 0x08, 0x54, 0XA9, 0x43, 0x0A, 0x0F, 0x00, 0x00, 0x00, 0x00]))
    
        # Set Gamma
        self.write_cmd(0XE1)
        self.write_data(bytearray([0x00, 0x15, 0x17, 0x07, 0x11, 0x06, 0x2B, 0x56, 0x3C, 0x05, 0x10, 0x0F, 0x3F, 0x3F, 0x0F]))
        
        # Exit Sleep
        self.write_cmd(0x11)
        time.sleep_ms(120)
        
        # Display on
        self.write_cmd(0x29)
        time.sleep_ms(500)
        self.fill(0)

    def show(self):
        # set col
        self.write_cmd(0x2A)
        self.write_data(bytearray([0x00, 0x00]))
        self.write_data(bytearray([0x00, 0xef]))
        
        # set page 
        self.write_cmd(0x2B)
        self.write_data(bytearray([0x00, 0x00]))
        self.write_data(bytearray([0x01, 0x3f]))

        self.write_cmd(0x2c);

        num_of_pixels = self.height * self.width

        for row in range(0, self.pages):
            for pixel_pos in range(0, 8):
                for col in range(0, self.width):
                    compressed_pixel = self.buffer[row * 240 + col]
                    if ((compressed_pixel >> pixel_pos) & 0x1) == 0:
                        self.write_data(bytearray([0x00, 0x00]))
                    else:
                        self.write_data(bytearray([0xFF, 0xFF]))

    def fill(self, col):
        self.framebuf.fill(col)

    def pixel(self, x, y, col):
        self.framebuf.pixel(x, y, col)

    def scroll(self, dx, dy):
        self.framebuf.scroll(dx, dy)

    def text(self, string, x, y, col=1):
        self.framebuf.text(string, x, y, col)

    def write_cmd(self, cmd):
        self.dc.low()
        self.cs.low()
        self.spi.write(bytearray([cmd]))
        self.cs.high()
        
    def write_data(self, buf):
        self.dc.high()
        self.cs.low()
        self.spi.write(buf)
        self.cs.high()

i2c = I2C(-1, Pin(SCL), Pin(SDA))

p=ms5837.MS5837(model='MODEL_30BA',i2c=i2c)
t=tsys01.TSYS01(i2c)

p.init()



sck=Pin(16)
mosi=Pin(4)
miso=Pin(17)
cs = Pin(15, Pin.OUT)
spi2=SPI(2,baudrate=5000000,sck=sck,mosi=mosi,miso=miso)

#sd = sdcard.SDCard(spi2, cs)
#os.mount(sd,'/sd')
#output=os.listdir('/sd')
#print(output)

#f=open('/sd/data.txt','a')

DISPLAY=True

if DISPLAY:
    import ssd1306
    from machine import I2C
    #i2c_display = I2C(-1, Pin(SCL), Pin(SDA))
    oled = ssd1306.SSD1306_I2C(128, 64, i2c)
Beispiel #32
0
12 | 10
 G | 27
'''

print("Welcome to MicroPython!")
fm.register(20, fm.fpioa.GPIO5, force=True)
cs = GPIO(GPIO.GPIO5, GPIO.OUT)
#cs.value(0)
#utime.sleep_ms(2000)

print(os.listdir())
spi = SPI(SPI.SPI1,
          mode=SPI.MODE_MASTER,
          baudrate=400 * 1000,
          polarity=0,
          phase=0,
          bits=8,
          firstbit=SPI.MSB,
          sck=21,
          mosi=8,
          miso=15)  #使用程序配置了 cs0 则无法读取 W25QXX
print(os.listdir())
print(spi)

while True:
    fm.register(21, fm.fpioa.SPI1_SCLK, force=True)
    fm.register(8, fm.fpioa.SPI1_D0, force=True)
    fm.register(15, fm.fpioa.SPI1_D1, force=True)
    cs.value(0)
    write_data = bytearray([0x90, 0x00, 0x00, 0x00])
    spi.write(write_data)
    id_buf = bytearray(2)
Beispiel #33
0
def main():
    global p
    p = [7,6,5,4,0,1,2,3]
    
    global mcp3008_spi
    global mcp3008_cs
    global mcp3008_out_buf
    global mcp3008_in_buf
    # initialize
    mcp3008_spi = SPI(0, sck=Pin(2),mosi=Pin(3),miso=Pin(4), baudrate=10000)
    mcp3008_cs = Pin(5, Pin.OUT)
    mcp3008_cs.value(1) # disable chip at start

    mcp3008_cs.value(1) # ncs on
    mcp3008_out_buf = bytearray(3)
    mcp3008_out_buf[0] = 0x01
    mcp3008_in_buf = bytearray(3)
    
    global ox1_freq
    global ox1_duty
    global ox2_freq
    global ox2_duty
    ox1_freq = 0
    ox1_duty = 0
    ox2_freq = 0
    ox2_duty = 0
    s1_shift = 0
    s2_shift = 0
    signal_freq = 0
    
    pwm1=PIOPWM(0, 14, 100_000, 10000)
    pwm2=PIOPWM(1, 15, 100_000, 10000)
    
    ox1_ox2_timer = Timer()
    signal_shift_timer = Timer()
    signal_freq_timer = Timer()
    
    bound = [0]*65
    for i in range(65):
        bound[i]=int((1024/(64-1))*(i-1))

    print(bound[2])

    def calc_option(option, value):
        direction = 0
        if (value >= (bound[option+1]+10)):
            direction = 1
        if (value <= (bound[option]-10)):
            direction = -1
        option = option+direction
        m_v = value//16
        direction2 = 0
        if option-m_v>2:
            direction2 = m_v-option
        if option-m_v<-2:
                direction2 = m_v-option
        option = option+direction2
        return option

    def tick_ox1_ox2(timer):
        t0 = ticks_ms()
        global ox1_freq
        global ox1_duty
        global ox2_freq
        global ox2_duty
        #global mcp3008_cs
        #global mcp3008_out_buf
        #global mcp3008_in_buf
        #global mcp3008_spi
        #global p
        m4 = mcp3008_read(p[4])
        m5 = mcp3008_read(p[5])
        m6 = mcp3008_read(p[6])
        m7 = mcp3008_read(p[7])
        #print(m)
        #so = co(so, m)
        new_ox1_freq = calc_option(ox1_freq, m4)
        new_ox1_duty = calc_option(ox1_duty, m5)
        new_ox2_freq = calc_option(ox2_freq, m6)
        new_ox2_duty = calc_option(ox2_duty, m7)
        
        diff = int(new_ox1_freq != ox1_freq)+int(new_ox1_duty != ox1_duty)+int(new_ox2_freq != ox2_freq)+int(new_ox2_duty != ox2_duty)
        #print(diff)
        if (diff != 0):
            t1 = ticks_ms()
            #print(so,m1, ticks_diff(t1, t0))
            #print((new_ox1_freq, ticks_diff(t1, t0)), m4, m4//16)
            if new_ox1_duty != ox1_duty:
                duty=int((new_ox1_duty*10000)/63)
                #duty=min(9000,duty)
                #duty=max(1000,duty)
                #print(duty)
                print("duty_1: {}".format(duty))
                if duty==0:
                    duty=-1
                pwm1._set(duty)
            print((diff, ticks_diff(t1, t0)),(new_ox1_freq, new_ox1_duty, new_ox2_freq, new_ox2_duty))
            ox1_freq = new_ox1_freq
            ox1_duty = new_ox1_duty
            ox2_freq = new_ox2_freq
            ox2_duty = new_ox2_duty
        
    
    print("a1")
    ox1_ox2_timer.init(freq=10, mode=Timer.PERIODIC, callback=tick_ox1_ox2)
    print("a2")
    sleep(90)
    ox1_ox2_timer.deinit()
Beispiel #34
0
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
from machine import Pin, SPI
from time import sleep_ms

# UEXT wiring on the Pyboard.
# https://github.com/mchobby/pyboard-driver/tree/master/UEXT
spi = SPI(2) # MOSI=Y8, MISO=Y7, SCK=Y6, SS=Y5
spi.init( baudrate=5000000, phase=0, polarity=0 )
# We must manage the SS signal ourself
ss = Pin( Pin.board.Y5, Pin.OUT )

# Start a new SPI transaction
ss.value( 1 )
sleep_ms( 10 )
ss.value( 0 )

print( "Read IDCode from GameDuino (0x6d expected)" )
spi.send( bytes([0x28,0x00]) )

buf = bytearray(1)
spi.recv( buf ) # read 1 byte
'''
''' pre setting about OLED screen buttons '''
# When the button A,B,C on OLED is pressed, OLED Pin A,B,C will generate a LOW voltage
switchA = Pin(2, Pin.IN)  # GPIO#2 has a pullup resistor connected to it
switchB = Pin(13, Pin.IN)  # GPIO#13 is the same as the MOSI 'SPI' pin
switchC = Pin(0, Pin.IN)  # GPIO#0 does not have an internal pullup
# We have to give Pin0 Pin13 a outer pullup resistor, but be aware the maximum current drawn per pin is 12mA
# minimum resistor is 250 ohm
switchA.irq(trigger=Pin.IRQ_FALLING,
            handler=Interrupt)  # use falling edge as interupt
''' pre setting about accelerator sensor '''
# The maximum SPI clock speed is 5 MHz with 100 pF maximum loading, and the timing scheme follows clock polarity (CPOL) = 1 and clock phase (CPHA) = 1
spi = SPI(-1,
          baudrate=100000,
          polarity=1,
          phase=1,
          sck=Pin(14),
          mosi=Pin(13),
          miso=Pin(12),
          bits=8)
cs = Pin(16, Pin.OUT, value=1)  # chip select
spi.init(baudrate=100000)
''' pre setting about OLED screen '''
i2c = I2C(-1, scl=Pin(5), sda=Pin(4))  # initialize access to the I2C bus
i2c.scan()
oled = ssd1306.SSD1306_I2C(128, 32, i2c)  # the width=128 and height=32
''' pre setting about alarm LED '''
redLED = Pin(15, Pin.OUT, value=0)
''' pre setting about real time clock '''
rtc = RTC()

Beispiel #36
0
                self._buf[index * 2] = self._colormap[c * 2]
                self._buf[index * 2 + 1] = self._colormap[c * 2 + 1]
        rest = w * h - written
        if rest != 0:
            mv = memoryview(self._buf)
            self._data(mv[:rest * 2])


if OPEN_AXP202:
    a = axp202.PMU()
    a.setChgLEDMode(axp202.AXP20X_LED_BLINK_1HZ)
    a.enablePower(axp202.AXP202_LDO2)
    a.setLDO2Voltage(3300)
bl = Pin(TFT_LED_PIN, Pin.OUT)
bl.value(1)

spi = SPI(baudrate=40000000,
          miso=Pin(TFT_MISO_PIN),
          mosi=Pin(TFT_MOSI_PIN, Pin.OUT),
          sck=Pin(TFT_CLK_PIN, Pin.OUT))

display = ST7789(spi, cs=Pin(TFT_CS_PIN), dc=Pin(TFT_DC_PIN), rst=None)

while True:
    display.fill_rectangle(0, 0, display.width, display.height, 0x0000)
    time.sleep(1)
    display.fill_rectangle(0, 0, display.width, display.height, 0xFF00)
    time.sleep(1)
    display.fill_rectangle(0, 0, display.width, display.height, 0xF800)
    time.sleep(1)
Beispiel #37
0
from machine import Pin, SPI
from tft import TFT_GREEN
gc.collect()
import font
import network, socket

# DC       - RS/DC data/command flag
# CS       - Chip Select, enable communication
# RST/RES  - Reset
dc = Pin(4, Pin.OUT)
cs = Pin(2, Pin.OUT)
rst = Pin(5, Pin.OUT)
# SPI Bus (CLK/MOSI/MISO)
# check your port docs to see which Pins you can use
spi = SPI(1, baudrate=8000000, polarity=1, phase=0)

# TFT object, this is ST7735R green tab version
tft = TFT_GREEN(128, 160, spi, dc, cs, rst, rotate=90)

# init TFT
tft.init()

#Network
sta = network.WLAN(network.STA_IF)
ap = network.WLAN(network.AP_IF)
sta.active(True)
sta.connect("YOUR_SSID_HERE", "YOUR_PASSWORD_HERE")
while not sta.isconnected():
    pass
print(sta.ifconfig())
Beispiel #38
0
from machine import Pin, SPI
import time
import ubinascii
hspi = SPI(1, baudrate=1000000, polarity=0, phase=0)
# hspi.init()
while 1:
    hspi.write(b'\x05')     # write 5 bytes on MOSI
    time.sleep(1)
Beispiel #39
0
'''
SPI test for the CC3200 based boards.
'''

from machine import SPI
import os

mch = os.uname().machine
if 'LaunchPad' in mch:
    spi_pins = ('GP14', 'GP16', 'GP30')
elif 'WiPy' in mch:
    spi_pins = ('GP14', 'GP16', 'GP30')
else:
    raise Exception('Board not supported!')

spi = SPI(0, SPI.MASTER, baudrate=2000000, polarity=0, phase=0, firstbit=SPI.MSB, pins=spi_pins)
print(spi)
spi = SPI(baudrate=5000000)
print(spi)
spi = SPI(0, SPI.MASTER, baudrate=200000, bits=16, polarity=0, phase=0)
print(spi)
spi = SPI(0, SPI.MASTER, baudrate=10000000, polarity=0, phase=1)
print(spi)
spi = SPI(0, SPI.MASTER, baudrate=5000000, bits=32, polarity=1, phase=0)
print(spi)
spi = SPI(0, SPI.MASTER, baudrate=10000000, polarity=1, phase=1)
print(spi)
spi.init(baudrate=20000000, polarity=0, phase=0)
print(spi)
spi=SPI()
print(spi)
Beispiel #40
0
class EPD(object):
    MAX_READ = 45
    SW_NORMAL_PROCESSING = 0x9000
    EP_FRAMEBUFFER_SLOT_OVERRUN = 0x6a84 # too much data fed in
    EP_SW_INVALID_LE = 0x6c00 # Wrong expected length
    EP_SW_INSTRUCTION_NOT_SUPPORTED = 0x6d00 # bad instr
    EP_SW_WRONG_PARAMETERS_P1P2 = 0x6a00
    EP_SW_WRONG_LENGTH = 0x6700

    DEFAULT_SLOT=0 # always the *oldest*, should wear-level then I think

    def __init__(self, debug=False, baud=100000):
        # From datasheet
        # Bit rate – up to 12 MHz1
        # ▪ Polarity – CPOL = 1; clock transition high-to-low on the leading edge and low-to-high on the
        #   trailing edge
        # ▪ Phase – CPHA = 1; setup on the leading edge and sample on the trailing edge
        # ▪ Bit order – MSB first
        # ▪ Chip select polarity – active low
        self.spi = SPI(0)
        try:
            self.spi.init(mode=SPI.MASTER, baudrate=baud, bits=8,
                          polarity=1, phase=1, firstbit=SPI.MSB,
                          pins=('GP31', 'GP16', 'GP30')) # CLK, MOSI, MISO
        except AttributeError:
            self.spi.init(baudrate=baud, bits=8,
                          polarity=1, phase=1, firstbit=SPI.MSB,
                          pins=('GP31', 'GP16', 'GP30')) # CLK, MOSI, MISO

        # These are all active low!
        self.tc_en_bar = Pin('GP4', mode=Pin.OUT)

        self.disable()

        self.tc_busy_bar = Pin('GP5', mode=Pin.IN)
        self.tc_busy_bar.irq(trigger=Pin.IRQ_RISING) # Wake up when it changes
        self.tc_cs_bar = Pin('GP17', mode=Pin.ALT, alt=7)

        self.debug = debug

    def enable(self):
        self.tc_en_bar.value(0) # Power up
        time.sleep_ms(5)
        while self.tc_busy_bar() == 0:
            machine.idle() # will it wake up here?
        # /tc_busy goes high during startup, low during init, then high when not busy

    def disable(self):
        self.tc_en_bar.value(1) # Off

    def send_command(self, ins, p1, p2, data=None, expected=None):

        # These command variables are always sent
        cmd = struct.pack('3B', ins, p1, p2)

        # Looks like data is only sent with the length (Lc)
        if data:
            assert len(data) <= 251 # Thus speaks the datasheet
            cmd += struct.pack('B', len(data))
            cmd += data

        # Expected data is either not present at all, 0 for null-terminated, or a number for fixed
        if expected is not None:
            cmd += struct.pack('B', expected)

        if self.debug:
            print("Sending: " + hexlify(cmd).decode())

        self.spi.write(cmd)

        # Wait for a little while
        time.sleep_us(15) # This should take at most 14.5us
        while self.tc_busy_bar() == 0:
            machine.idle()

        # Request a response
        if expected is not None:
            if expected > 0:
                result_bytes = self.spi.read(2 + expected)
            else:
                result_bytes = self.spi.read(EPD.MAX_READ)
                strlen = result_bytes.find(b'\x00')
                result_bytes = result_bytes[:strlen] + result_bytes[strlen+1:strlen+3]
        else:
            result_bytes = self.spi.read(2)

        if self.debug:
            print("Received: " + hexlify(result_bytes).decode())

        (result,) = struct.unpack_from('>H', result_bytes[-2:])

        if result != EPD.SW_NORMAL_PROCESSING:
            raise ValueError("Bad result code: 0x%x" % result)

        return result_bytes[:-2]

    @staticmethod
    def calculate_checksum(data, skip=16):
        """
        Initial checksum value is 0x6363

        :param data:
        :param skip: Skip some data as slices are expensive
        :return:
        """
        acc = 0x6363
        for byte in data:
            if skip > 0:
                skip -= 1
            else:
                acc ^= byte
                acc = ((acc >> 8) | (acc << 8)) & 0xffff
                acc ^= ((acc & 0xff00) << 4) & 0xffff
                acc ^= (acc >> 8) >> 4
                acc ^= (acc & 0xff00) >> 5
        return acc

    def get_sensor_data(self):
        # GetSensorData
        val = self.send_command(0xe5, 1, 0, expected=2)
        (temp,) = struct.unpack(">H", val)
        return temp

    def get_device_id(self):
        return self.send_command(0x30, 2, 1, expected=0x14)

    def get_system_info(self):
        return self.send_command(0x31, 1, 1, expected=0)

    def get_system_version_code(self):
        return self.send_command(0x31, 2, 1, expected=0x10)

    def display_update(self, slot=0, flash=True):
        cmd = 0x86
        if flash:
            cmd = 0x24
        self.send_command(cmd, 1, slot)

    def reset_data_pointer(self):
        self.send_command(0x20, 0xd, 0)

    def image_erase_frame_buffer(self, slot=0):
        self.send_command(0x20, 0xe, slot)

    def get_checksum(self, slot):
        cksum_val = self.send_command(0x2e, 1, slot, expected=2)
        (cksum,) = struct.unpack(">H", cksum_val)
        return cksum

    def upload_image_data(self, data, slot=0, delay_us=1000):
        self.send_command(0x20, 1, slot, data)
        time.sleep_us(delay_us)

    def upload_whole_image(self, img, slot=0):
        """
        Chop up chunks and send it
        :param img: Image to send in EPD format
        :param slot: Slot framebuffer number to use
        :param delay_us: Delay between packets? 450us and the Tbusy line never comes back
        :return:
        """
        total = len(img)
        idx = 0
        try:
            while idx < total - 250:
                chunk = img[idx:idx+250]
                self.upload_image_data(chunk, slot)
                del chunk
                idx += 250
            self.upload_image_data(img[idx:], slot)
        except KeyboardInterrupt:
            print("Stopped at user request at position: %d (%d)" % (idx, (idx // 250)))
        except ValueError as e:
            print("Stopped at position: %d (%d) - %s" % (idx, (idx // 250), e))
from ST7789 import TFT
# from sysfont import sysfont
from machine import SPI, Pin
import time
import math

spi = SPI(2,
          baudrate=20000000,
          polarity=0,
          phase=0,
          sck=Pin(14),
          mosi=Pin(13),
          miso=Pin(12))
tft = TFT(spi, 16, 2, 15)
tft.initr()
tft.rgb(True)


def testlines(color):
    tft.fill(TFT.BLACK)
    for x in range(0, tft.size()[0], 6):
        tft.line((0, 0), (x, tft.size()[1] - 1), color)
    for y in range(0, tft.size()[1], 6):
        tft.line((0, 0), (tft.size()[0] - 1, y), color)

    tft.fill(TFT.BLACK)
    for x in range(0, tft.size()[0], 6):
        tft.line((tft.size()[0] - 1, 0), (x, tft.size()[1] - 1), color)
    for y in range(0, tft.size()[1], 6):
        tft.line((tft.size()[0] - 1, 0), (0, y), color)
Beispiel #42
0
def main():
    """Initialize display."""
    # Baud rate of 14500000 seems about the max
    spi = SPI(2, baudrate=14500000, sck=Pin(14), mosi=Pin(13))
    display = Display(spi, dc=Pin(2), cs=Pin(15), rst=Pin(16))

    while True:
        # Draw background image
        display.draw_image('images/Arkanoid_Border128x118.raw', 0, 10, 128,
                           118)

        # Initialize ADC on VP pin 36
        # adc = ADC(Pin(36))
        # Set attenuation 0-2V (Will use resistor to limit pot to 2V).
        # adc.atten(ADC.ATTN_6DB)

        # Seed random numbers
        seed(ticks_us())

        # Generate bricks
        MAX_LEVEL = const(9)
        level = 1
        bricks = load_level(level, display)

        # Initialize paddle
        paddle = Paddle(display)

        # Initialize score
        score = Score(display)

        # Initialize balls
        balls = []
        # Add first ball
        balls.append(Ball(59, 111, -2, -1, display, frozen=True))

        # Initialize lives
        lives = []
        for i in range(1, 3):
            lives.append(Life(i, display))

        # Initialize power-ups
        powerups = []

        paddle.h_position(paddle.x)
        gameover = False
        try:
            while not gameover:
                timer = ticks_us()
                # Set paddle position to ADC spinner (scale 6 - 98)
                # paddle.h_position(adc.read() // 44 + 5)
                if not keyR.value():
                    paddle.h_position(paddle.x + 2)
                elif not keyL.value():
                    paddle.h_position(paddle.x - 2)
                # Handle balls
                score_points = 0
                for ball in balls:
                    # Position
                    ball.set_position(paddle.x, paddle.y, paddle.x2,
                                      paddle.center)

                    # Check for collision with bricks if not frozen
                    if not ball.frozen:
                        prior_collision = False
                        ball_x = ball.x
                        ball_y = ball.y
                        ball_x2 = ball.x2
                        ball_y2 = ball.y2
                        ball_center_x = ball.x + ((ball.x2 + 1 - ball.x) // 2)
                        ball_center_y = ball.y + ((ball.y2 + 1 - ball.y) // 2)
                        # Check for hits
                        for brick in bricks:
                            if (ball_x2 >= brick.x and ball_x <= brick.x2
                                    and ball_y2 >= brick.y
                                    and ball_y <= brick.y2):
                                # Hit
                                if not prior_collision:
                                    ball.x_speed, ball.y_speed = brick.bounce(
                                        ball.x, ball.y, ball.x2, ball.y2,
                                        ball.x_speed, ball.y_speed,
                                        ball_center_x, ball_center_y)
                                    prior_collision = True
                                score_points += 1
                                brick.clear()
                                bricks.remove(brick)

                        # Generate random power-ups
                        if score_points > 0 and randint(1, 20) == 7:
                            powerups.append(Powerup(ball.x, 64, display))

                    # Check for missed
                    if ball.y2 > display.height - 3:
                        ball.clear_previous()
                        balls.remove(ball)
                        if not balls:
                            # Clear powerups
                            powerups.clear()
                            # Lose life if last ball on screen
                            if len(lives) == 0:
                                score.game_over()
                                gameover = True
                            else:
                                # Subtract Life
                                lives.pop().clear()
                                # Add ball
                                balls.append(
                                    Ball(59, 112, 2, -3, display, frozen=True))
                    else:
                        # Draw ball
                        ball.draw()
                # Update score if changed
                if score_points:
                    score.increment(score_points)
                # Handle power-ups
                for powerup in powerups:
                    powerup.set_position(paddle.x, paddle.y, paddle.x2,
                                         paddle.center)
                    powerup.draw()
                    if powerup.collected:
                        # Power-up collected
                        powerup.clear()
                        # Add ball
                        balls.append(
                            Ball(powerup.x, 112, 2, -1, display, frozen=False))
                        powerups.remove(powerup)
                    elif powerup.y2 > display.height - 3:
                        # Power-up missed
                        powerup.clear()
                        powerups.remove(powerup)

                # Check for level completion
                if not bricks:
                    for ball in balls:
                        ball.clear()
                    balls.clear()
                    for powerup in powerups:
                        powerup.clear()
                    powerups.clear()
                    level += 1
                    if level > MAX_LEVEL:
                        level = 1
                    bricks = load_level(level, display)
                    balls.append(Ball(59, 111, -2, -1, display, frozen=True))
                # Attempt to set framerate to 60 FPS
                timer_dif = 20000 - ticks_diff(ticks_us(), timer)
                if timer_dif > 0:
                    sleep_us(timer_dif)
        except KeyboardInterrupt:
            display.cleanup()
        # game over, wait for start key to restart another game.
        while keyStart.value():
            sleep_us(2000)
Beispiel #43
0
    def get_localtime(self):
        return time.localtime()

    def get_time(self):
        now = time.localtime()
        return (now[3], now[4], now[5])

    def uptime(self):
        return time.time()

    def get_uptime_ms(self):
        return int(time.time() * 1000)


backlight = Backlight()
spi = SPI(0)
spi.init(polarity=1, phase=1, baudrate=8000000)
display = ST7789_SPI(240,
                     240,
                     spi,
                     cs=Pin("DISP_CS", Pin.OUT, quiet=True),
                     dc=Pin("DISP_DC", Pin.OUT, quiet=True),
                     res=Pin("DISP_RST", Pin.OUT, quiet=True))
drawable = draw565.Draw565(display)

battery = Battery()
button = Pin('BUTTON', Pin.IN, quiet=True)
rtc = RTC()
touch = CST816S(I2C(0))
vibrator = Vibrator(Pin('MOTOR', Pin.OUT, value=0), active_low=True)
Beispiel #44
0
class MFRC522:
  RESET = 'GP22'
  CLK = 'GP14'
  MISO = 'GP15'
  MOSI = 'GP16'
  CS = 'GP17'

  MAX_LEN = 16
  
  PCD_IDLE       = 0x00
  PCD_AUTHENT    = 0x0E
  PCD_TRANSCEIVE = 0x0C
  PCD_RESETPHASE = 0x0F
  PCD_CALCCRC    = 0x03

  PICC_REQIDL    = 0x26
  PICC_REQALL    = 0x52
  PICC_ANTICOLL  = 0x93
  PICC_SElECTTAG = 0x93
  PICC_AUTHENT1A = 0x60
  PICC_READ      = 0x30
  PICC_WRITE     = 0xA0
  
  MI_OK       = 0
  MI_NOTAGERR = 1
  MI_ERR      = 2
  MI_AUTH_ERROR_STATUS2REG = 3

  CommandReg     = 0x01
  CommIEnReg     = 0x02
  CommIrqReg     = 0x04
  DivIrqReg      = 0x05
  ErrorReg       = 0x06
  Status2Reg     = 0x08
  FIFODataReg    = 0x09
  FIFOLevelReg   = 0x0A
  WaterLevelReg  = 0x0B
  ControlReg     = 0x0C
  BitFramingReg  = 0x0D
  
  ModeReg        = 0x11
  TxControlReg   = 0x14
  TxAutoReg      = 0x15
  
  CRCResultRegM     = 0x21
  CRCResultRegL     = 0x22
  TModeReg          = 0x2A
  TPrescalerReg     = 0x2B
  TReloadRegH       = 0x2C
  TReloadRegL       = 0x2D
    
  serNum = []

  def __init__(self, spd=1000000):
    # first assign CLK, MISO, MOSI, CS to the correct pins
    self.pin_clk = Pin(self.CLK, mode=Pin.OUT)    # CLK
    self.pin_miso = Pin(self.MISO)    # MISO
    self.pin_mosi = Pin(self.MOSI, mode=Pin.OUT)    # MOSI
    self.pin_cs = Pin(self.CS, mode=Pin.OUT)    # NSS/CS
    self.pin_reset = Pin(self.RESET, mode=Pin.OUT)

    self.pin_reset.value(0)
    self.pin_cs.value(1)

    self.spi = SPI(0)
    self.spi.init(mode=SPI.MASTER, baudrate=spd, pins=(self.CLK, self.MOSI, self.MISO))
    
    self.pin_reset.value(1)

    self.MFRC522_Init()
  
  def MFRC522_Reset(self):
    self.Write_MFRC522(self.CommandReg, self.PCD_RESETPHASE)
  
  def Write_MFRC522(self, addr, val):
    self.pin_cs.value(0)
    # 0(MSB = Write) ADDR1 ADDR2 ADDR3 ADDR4 ADDR5 ADDR6 0(LSB = 0) DATA
    spiBytes = bytearray(2)
    spiBytes[0] = ((addr<<1)&0x7E) 
    spiBytes[1] = val
    self.spi.write(spiBytes)
    self.pin_cs.value(1)
  
  def Read_MFRC522(self, addr):
    self.pin_cs.value(0)
    # 1(MSB = Read) ADDR1 ADDR2 ADDR3 ADDR4 ADDR5 ADDR6 0(LSB = 0)
    self.spi.write((addr<<1)&0x7E|0x80)
    data = self.spi.read(1)
    self.pin_cs.value(1)
    return data[0]
  
  def SetBitMask(self, reg, mask):
    tmp = self.Read_MFRC522(reg)
    self.Write_MFRC522(reg, tmp | mask)
    
  def ClearBitMask(self, reg, mask):
    tmp = self.Read_MFRC522(reg);
    self.Write_MFRC522(reg, tmp & (~mask))
  
  def AntennaOn(self):
    temp = self.Read_MFRC522(self.TxControlReg)
    if(~(temp & 0x03)):
      self.SetBitMask(self.TxControlReg, 0x03)

  
  def AntennaOff(self):
    self.ClearBitMask(self.TxControlReg, 0x03)
  
  def MFRC522_ToCard(self,command,sendData):
    backData = []
    backLen = 0
    status = self.MI_ERR
    irqEn = 0x00
    waitIRq = 0x00
    lastBits = None
    n = 0
    i = 0
    
    if command == self.PCD_AUTHENT:
      irqEn = 0x12
      waitIRq = 0x10
    if command == self.PCD_TRANSCEIVE:
      irqEn = 0x77
      waitIRq = 0x30

    self.Write_MFRC522(self.CommIEnReg, irqEn|0x80)
    self.ClearBitMask(self.CommIrqReg, 0x80)
    self.SetBitMask(self.FIFOLevelReg, 0x80)
    self.Write_MFRC522(self.CommandReg, self.PCD_IDLE);  

    while(i<len(sendData)):
      self.Write_MFRC522(self.FIFODataReg, sendData[i])
      i = i+1
    self.Write_MFRC522(self.CommandReg, command)

    if command == self.PCD_TRANSCEIVE:
      self.SetBitMask(self.BitFramingReg, 0x80)
    
    i = 2000
    while True:
      n = self.Read_MFRC522(self.CommIrqReg)
      i = i - 1
      if ~((i!=0) and ~(n&0x01) and ~(n&waitIRq)):
        break
    
    self.ClearBitMask(self.BitFramingReg, 0x80)
  
    if i != 0:
      st = self.Read_MFRC522(self.ErrorReg)
      if (st & 0x1B)==0x00:
        status = self.MI_OK

        if n & irqEn & 0x01:
          status = self.MI_NOTAGERR
        elif command == self.PCD_TRANSCEIVE:
          n = self.Read_MFRC522(self.FIFOLevelReg)
          lastBits = self.Read_MFRC522(self.ControlReg) & 0x07
          if lastBits != 0:
            backLen = (n-1)*8 + lastBits
          else:
            backLen = n*8
          
          if n == 0:
            n = 1
          if n > self.MAX_LEN:
            n = self.MAX_LEN
    
          i = 0
          while i<n:
            backData.append(self.Read_MFRC522(self.FIFODataReg))
            i = i + 1;
      else:
        status = self.MI_ERR
    return (status,backData,backLen)
  
  
  def MFRC522_Request(self, reqMode):
    status = None
    backBits = None
    TagType = [reqMode]

    self.Write_MFRC522(self.BitFramingReg, 0x07)

    (status,backData,backBits) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, TagType)
    if ((status != self.MI_OK) | (backBits != 0x10)):
      status = self.MI_ERR
      
    return (status,backBits)
  
  
  def MFRC522_Anticoll(self):
    backData = []
    serNumCheck = 0
    
    serNum = [self.PICC_ANTICOLL, 0x20]
  
    self.Write_MFRC522(self.BitFramingReg, 0x00)
    
    (status,backData,backBits) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE,serNum)
    
    if(status == self.MI_OK):
      i = 0
      if len(backData)==5:
        while i<4:
          serNumCheck = serNumCheck ^ backData[i]
          i = i + 1
        if serNumCheck != backData[i]:
          status = self.MI_ERR
      else:
        status = self.MI_ERR
  
    return (status,backData)
  
  def CalulateCRC(self, pIndata):
    self.ClearBitMask(self.DivIrqReg, 0x04)
    self.SetBitMask(self.FIFOLevelReg, 0x80);
    i = 0
    while i<len(pIndata):
      self.Write_MFRC522(self.FIFODataReg, pIndata[i])
      i = i + 1
    self.Write_MFRC522(self.CommandReg, self.PCD_CALCCRC)
    i = 0xFF
    while True:
      n = self.Read_MFRC522(self.DivIrqReg)
      i = i - 1
      if not ((i != 0) and not (n&0x04)):
        break
    pOutData = []
    pOutData.append(self.Read_MFRC522(self.CRCResultRegL))
    pOutData.append(self.Read_MFRC522(self.CRCResultRegM))
    return pOutData
  
  def MFRC522_SelectTag(self, serNum):
    backData = []
    buf = [self.PICC_SElECTTAG, 0x70] + serNum[:5]

    buf += self.CalulateCRC(buf)
    (status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buf)
    
    if (status == self.MI_OK) and (backLen == 0x18):
      return self.MI_OK
    else:
      return self.MI_ERR
  
  def MFRC522_Auth(self, authMode, BlockAddr, Sectorkey, serNum):
    #First byte should be the authMode (A or B)
    #Second byte is the trailerBlock (usually 7)
    #Now we need to append the authKey which usually is 6 bytes of 0xFF
    #Next we append the first 4 bytes of the UID
    buff = [authMode, BlockAddr] + Sectorkey + serNum[:4]

    # Now we start the authentication itself
    (status, backData, backLen) = self.MFRC522_ToCard(self.PCD_AUTHENT,buff)

    # Check if an error occurred


    # Return the status
    return status
  
  def MFRC522_StopCrypto1(self):
    self.ClearBitMask(self.Status2Reg, 0x08)

  def MFRC522_Read(self, blockAddr):
    recvData = [self.PICC_READ, blockAddr]
    recvData += self.CalulateCRC(recvData)

    (status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, recvData)
    return (status, backData)
  
  def MFRC522_Write(self, blockAddr, writeData):
    buff = [self.PICC_WRITE, blockAddr]
    buff += self.CalulateCRC(buff)
    (status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buff)
    if not(status == self.MI_OK) or not(backLen == 4) or not((backData[0] & 0x0F) == 0x0A):
        status = self.MI_ERR
    
    if status == self.MI_OK:
        i = 0
        buf = []
        while i < 16:
            buf.append(writeData[i])
            i = i + 1
        buf += self.CalulateCRC(buf)
        (status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE,buf)
        if not(status == self.MI_OK) or not(backLen == 4) or not((backData[0] & 0x0F) == 0x0A):
            status = self.MI_ERR

    return status

  def MFRC522_Init(self):
    self.MFRC522_Reset();
    
    self.Write_MFRC522(self.TModeReg, 0x8D)
    self.Write_MFRC522(self.TPrescalerReg, 0x3E)
    self.Write_MFRC522(self.TReloadRegL, 30)
    self.Write_MFRC522(self.TReloadRegH, 0)
    self.Write_MFRC522(self.TxAutoReg, 0x40)
    self.Write_MFRC522(self.ModeReg, 0x3D)
    self.AntennaOn()
oled.fill(0)
oled.text("Listening ...", 0, 0)
oled.show()
time.sleep(2)

# radio test
sck = Pin(25)
mosi = Pin(33)
miso = Pin(32)
cs = Pin(26, Pin.OUT)
#reset=Pin(13)
led = Pin(13, Pin.OUT)

resetNum = 27

spi = SPI(1, baudrate=5000000, sck=sck, mosi=mosi, miso=miso)

rfm9x = RFM9x(spi, cs, resetNum, 915.0)

# set up FARMOS params
url = 'http://64.227.0.108:8700/api/'

headers = {'Content-type': 'application/json', 'Accept': 'application/json'}

# wifi parameters
#WIFI_NET = 'Artisan\'s Asylum'
#WIFI_PASSWORD = '******'t download stuff that will get us in legal trouble.'

#WIFI_NET = 'InmanSquareOasis'
#WIFI_PASSWORD = '******'
Beispiel #46
0
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

from machine import Pin, SPI
from gd import *
import os
import urandom # on recent MicroPython Firmware v1.10+

# Initialize the SPI Bus (on ESP8266-EVB)
# Software SPI
#    spi = SPI(-1, baudrate=4000000, polarity=1, phase=0, sck=Pin(14), mosi=Pin(13), miso=Pin(12))
# Hardware SPI
spi = SPI(2) # MOSI=Y8, MISO=Y7, SCK=Y6, SS=Y5
spi.init( baudrate=20000000, phase=0, polarity=0 ) # raise @ 20 Mhz
# We must manage the SS signal ourself
ss = Pin( Pin.board.Y5, Pin.OUT )

# Gameduino Lib
gd = Gameduino( spi, ss )
gd.begin()

# === Toolbox ==================================================================
def draw_ball( x, y, pal ):
	global gd
	gd.xsprite(x, y, -40, -56, 0, pal, 0)
	gd.xsprite(x, y, -24, -56, 1, pal, 0)
	gd.xsprite(x, y, -8, -56, 2, pal, 0)
	gd.xsprite(x, y, 8, -56, 3, pal, 0)
Beispiel #47
0
scl = Pin(15, Pin.OUT, Pin.PULL_UP)
sda = Pin(4, Pin.OUT, Pin.PULL_UP)
i2c = I2C(scl=scl, sda=sda, freq=450000)
oled = ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3c)

oled.fill(0)
oled.text('Iniciando (t={})'.format(utime.ticks_ms()), 0, 0)
oled.show()
#objeto MPU
mpu = mpu6050.MPU()
#objeto UART/GPS
gps = UART(2, 115200)
gps.init(9600, bits=8, parity=None, stop=1, tx=17, rx=5)
#objeto SPI
Pin(18, Pin.OUT, value=1)  #para desactivar LoRa
spi = SPI(sck=Pin(23), miso=Pin(14), mosi=Pin(12))
#objeto SD
sd = sdcard.SDCard(spi, Pin(2, Pin.OUT))
###################################Control de tiempo de muestreo####################################
milis_antes = utime.ticks_ms()
intervalo = 100  # en milisegundos
oled.text('(t={})'.format(utime.ticks_ms()), 0, 8)
oled.show()
################################################loop################################################
while 1:
    milis_ahora = utime.ticks_ms()
    if (utime.ticks_diff(milis_ahora, milis_antes) >= intervalo):
        milis_antes = milis_ahora
        #se monta el sistema de archivos en la sd
        os.mount(sd, '/fc')
        # INFORMACION MODULO GPS
Beispiel #48
0
from machine import Pin, SPI
import time
import ubinascii

vref = 3.3
cs = Pin(15, Pin.OUT)
cs.high()
hspi = SPI(1, baudrate=1600000, polarity=0, phase=0)
value = bytearray(2)

while True:
    data = bytearray(2)
    wget = b'\xA0\x00'
    cs.low()
    hspi.write(b'\x01')
    hspi.write(b'\xA0')
    data = hspi.read(1)
    # data = hspi.write_readinto(wget, data)
    cs.high()
    print(str(int(ubinascii.hexlify(data & b'\x0fff'))*vref/4096))
    time.sleep(1)
    # data = data*vref/4096
    # time.sleep(1)
    # print(str(data & b'\x0fff'))
Beispiel #49
0
#hardware platform:FireBeetle-ESP8266
from machine import SPI, Pin
import sdcard
import os
spi = SPI(baudrate=100000,
          polarity=1,
          phase=0,
          sck=Pin(14),
          mosi=Pin(13),
          miso=Pin(12))  #Initialise the SPI bus with the given parameters
sd = sdcard.SDCard(spi, Pin(2))  #create sdcard object base spi and Pin2
os.mount(sd, "/sd")  #mount sdcard with specified dir
print(os.listdir('/sd'))  #print the filename in '/sd' dir
fd = open(
    '/sd/dfrobot.txt', 'rw'
)  #open file 'dfrobot.txt' in sdcard ,the mode is read and write,and create the file descriptor as fd
fd.write('hello dfrobot')  #write "hello dfrobot" to the file 'dfrobot.txt'
fd.seek(0)  #move the file pointer to the start
print(fd.read())  #read from the start of "dfrobot.txt"
fd.close()  #close file
os.umount("/sd")  #unmount sdcard
Beispiel #50
0
# QR Code
# You'll have to scan it to find out what it is.

import pcd8544
from machine import Pin, SPI

spi = SPI(1)
spi.init(baudrate=2000000, polarity=0, phase=0)
cs = Pin(2)
dc = Pin(15)
rst = Pin(0)
bl = Pin(12, Pin.OUT, value=1)
lcd = pcd8544.PCD8544(spi, cs, dc, rst)

import framebuf
buffer = bytearray((pcd8544.HEIGHT // 8) * pcd8544.WIDTH)
fbuf = framebuf.FrameBuffer(buffer, pcd8544.WIDTH, pcd8544.HEIGHT,
                            framebuf.MONO_VLSB)

fbuf.fill(0)

# QR Code - col major msb
# See qr-code.gif
qr = bytearray(
    b'\x7F\x41\x5D\x5D\x5D\x41\x7F\x00\xF6\x1A\xF3\x80\x70\x38\xEB\xB7\x60\x00\x7F\x41\x5D\x5D\x5D\x41\x7F\x47\x8B\xA4\xF5\x96\xF6\x55\x89\x98\x8A\x18\xCB\x72\x9B\x73\x00\xD3\x1E\x7B\x79\xC5\x30\x61\x95\x76\xFD\x05\x74\x75\x75\x04\xFD\x01\xA6\xBD\x96\x91\xBA\xD6\x68\x4F\x9F\xD1\x15\x71\x7F\xBF\x69\x0C\x46\x01\x01\x01\x01\x01\x01\x01\x00\x01\x00\x00\x00\x00\x00\x00\x01\x01\x00\x01\x01\x00\x00\x00\x01\x01'
)
qr_fbuf = framebuf.FrameBuffer(qr, 25, 25, framebuf.MONO_VLSB)

fbuf.blit(qr_fbuf, int((pcd8544.WIDTH - 25) / 2), int(
    (pcd8544.HEIGHT - 25) / 2), 0)
Beispiel #51
0
#import LoRaDuplexCallback
#import LoRaPingPong
#import LoRaSender
from examples import LoRaSender
from examples import LoRaReceiver

from config import *
from machine import Pin, SPI
from sx127x import SX127x

device_spi = SPI(baudrate=10000000,
                 polarity=0,
                 phase=0,
                 bits=8,
                 firstbit=SPI.MSB,
                 sck=Pin(device_config['sck'], Pin.OUT, Pin.PULL_DOWN),
                 mosi=Pin(device_config['mosi'], Pin.OUT, Pin.PULL_UP),
                 miso=Pin(device_config['miso'], Pin.IN, Pin.PULL_UP))

lora = SX127x(device_spi, pins=device_config, parameters=lora_parameters)

#example = 'sender'
example = 'receiver'

if __name__ == '__main__':
    if example == 'sender':
        LoRaSender.send(lora)
    if example == 'receiver':
        LoRaReceiver.receive(lora)
class TOUCH:
#
# Init just sets the PIN's to In / out as required
# async: set True if asynchronous operation intended
# confidence: confidence level - number of consecutive touches with a margin smaller than the given level
#       which the function will sample until it accepts it as a valid touch
# margin: Distance from mean centre at which touches are considered at the same position
# delay: Delay between samples in ms. (n/a if asynchronous)
#
    DEFAULT_CAL = (-3917, -0.127, -3923, -0.1267, -3799, -0.07572, -3738,  -0.07814)

    def __init__(self, controller="XPT2046", asyn=False, *, confidence=5, margin=50, delay=10, calibration=None, spi = None):
        if spi is None:
            self.spi = SPI(-1, baudrate=1000000, sck=Pin("X12"), mosi=Pin("X11"), miso=Pin("Y2"))
        else:
            self.spi = spi
        self.recv = bytearray(3)
        self.xmit = bytearray(3)
# set default values
        self.ready = False
        self.touched = False
        self.x = 0
        self.y = 0
        self.buf_length = 0
        cal = TOUCH.DEFAULT_CAL if calibration is None else calibration
        self.asynchronous = False
        self.touch_parameter(confidence, margin, delay, cal)
        if asyn:
            self.asynchronous = True
            import uasyncio as asyncio
            loop = asyncio.get_event_loop()
            loop.create_task(self._main_thread())

# set parameters for get_touch()
# res: Resolution in bits of the returned values, default = 10
# confidence: confidence level - number of consecutive touches with a margin smaller than the given level
#       which the function will sample until it accepts it as a valid touch
# margin: Difference from mean centre at which touches are considered at the same position
# delay: Delay between samples in ms.
#
    def touch_parameter(self, confidence=5, margin=50, delay=10, calibration=None):
        if not self.asynchronous: # Ignore attempts to change on the fly.
            confidence = max(min(confidence, 25), 5)
            if confidence != self.buf_length:
                self.buff = [[0,0] for x in range(confidence)]
                self.buf_length = confidence
            self.delay = max(min(delay, 100), 5)
            margin = max(min(margin, 100), 1)
            self.margin = margin * margin # store the square value
            if calibration:
                self.calibration = calibration

# get_touch(): Synchronous use. get a touch value; Parameters:
#
# initital: Wait for a non-touch state before getting a sample.
#           True = Initial wait for a non-touch state
#           False = Do not wait for a release
# wait: Wait for a touch or not?
#       False: Do not wait for a touch and return immediately
#       True: Wait until a touch is pressed.
# raw: Setting whether raw touch coordinates (True) or normalized ones (False) are returned
#      setting the calibration vector to (0, 1, 0, 1, 0, 1, 0, 1) result in a identity mapping
# timeout: Longest time (ms, or None = 1 hr) to wait for a touch or release
#
# Return (x,y) or None
#
    def get_touch(self, initial=True, wait=True, raw=False, timeout=None):
        if self.asynchronous:
            return None # Should only be called in synhronous mode
        if timeout is None:
            timeout = 3600000 # set timeout to 1 hour
#
        if initial:  ## wait for a non-touch state
            sample = True
            while sample and timeout > 0:
                sample = self.raw_touch()
                pyb.delay(self.delay)
                timeout -= self.delay
            if timeout <= 0: # after timeout, return None
                return None
#
        buff = self.buff
        buf_length = self.buf_length
        buffptr = 0
        nsamples = 0
        while timeout > 0:
            if nsamples == buf_length:
                meanx = sum([c[0] for c in buff]) // buf_length
                meany = sum([c[1] for c in buff]) // buf_length
                dev = sum([(c[0] - meanx)**2 + (c[1] - meany)**2 for c in buff]) / buf_length
                if dev <= self.margin: # got one; compare against the square value
                    if raw:
                        return (meanx, meany)
                    else:
                        return self.do_normalize((meanx, meany))
# get a new value
            sample = self.raw_touch()  # get a touch
            if sample is None:
                if not wait:
                    return None
                nsamples = 0    # Invalidate buff
            else:
                buff[buffptr] = sample # put in buff
                buffptr = (buffptr + 1) % buf_length
                nsamples = min(nsamples + 1, buf_length)
            pyb.delay(self.delay)
            timeout -= self.delay
        return None

# Asynchronous use: this thread maintains self.x and self.y
    async def _main_thread(self):
        import uasyncio as asyncio
        buff = self.buff
        buf_length = self.buf_length
        buffptr = 0
        nsamples = 0
        await asyncio.sleep(0)
        while True:
            if nsamples == buf_length:
                meanx = sum([c[0] for c in buff]) // buf_length
                meany = sum([c[1] for c in buff]) // buf_length
                dev = sum([(c[0] - meanx)**2 + (c[1] - meany)**2 for c in buff]) / buf_length
                if dev <= self.margin: # got one; compare against the square value
                    self.ready = True
                    self.x, self.y = self.do_normalize((meanx, meany))
            sample = self.raw_touch()  # get a touch
            if sample is None:
                self.touched = False
                self.ready = False
                nsamples = 0    # Invalidate buff
            else:
                self.touched = True
                buff[buffptr] = sample # put in buff
                buffptr = (buffptr + 1) % buf_length
                nsamples = min(nsamples + 1, buf_length)
            await asyncio.sleep(0)

# Asynchronous get_touch
    def get_touch_async(self):
        if self.ready:
            self.ready = False
            return self.x, self.y
        return None
#
# do_normalize(touch)
# calculate the screen coordinates from the touch values, using the calibration values
# touch must be the tuple return by get_touch
#
    def do_normalize(self, touch):
        xmul = self.calibration[3] + (self.calibration[1] - self.calibration[3]) * (touch[1] / 4096)
        xadd = self.calibration[2] + (self.calibration[0] - self.calibration[2]) * (touch[1] / 4096)
        ymul = self.calibration[7] + (self.calibration[5] - self.calibration[7]) * (touch[0] / 4096)
        yadd = self.calibration[6] + (self.calibration[4] - self.calibration[6]) * (touch[0] / 4096)
        x = int((touch[0] + xadd) * xmul)
        y = int((touch[1] + yadd) * ymul)
        return (x, y)
#
# raw_touch(tuple)
# raw read touch. Returns (x,y) or None
#
    def raw_touch(self):
        global CONTROL_PORT
        x  = self.touch_talk(T_GETX, 12)
        y  = self.touch_talk(T_GETY, 12)
        if x > X_LOW and y < Y_HIGH:  # touch pressed?
            return (x, y)
        else:
            return None
#
# Send a command to the touch controller and wait for the response
# cmd:  command byte
# bits: expected data size. Reasonable values are 8 and 12
#
    def touch_talk(self, cmd, bits):
        self.xmit[0] = cmd
        self.spi.write_readinto(self.xmit, self.recv)
        return (self.recv[1] * 256 + self.recv[2]) >> (15 - bits)
Beispiel #53
0
import waveshare2in9b
import random
from fbdrawing import FrameBufferExtended
import time
import framebuf

# baudrate = int(20e6)
baudrate = int(20e6)
# Software SPI
# We use specific values below are they match the default hardware SPI pins
# Although hardware SPI works, I had however better perf and less troubles with software SPI.
# Comment the line below is you want to use hardware SPI
spi = SPI(-1,
          baudrate=baudrate,
          polarity=0,
          phase=0,
          sck=Pin(14),
          mosi=Pin(13),
          miso=Pin(12))

# Hardware SPI
# Comment out the 2 lines below if you want to use hardware SPI
# hspi = SPI(1, baudrate=baudrate, polarity=0, phase=0, sck=Pin(14), mosi=Pin(13), miso=Pin(12))
# spi = hspi

e = waveshare2in9b.EPD(spi, cs=32, dc=33, rst=25, busy=26, idle=0)

WIDTH = waveshare2in9b.EPD_WIDTH
HEIGHT = waveshare2in9b.EPD_HEIGHT

buf_b = bytearray(WIDTH * HEIGHT // 8)
Beispiel #54
0
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

from machine import Pin, SPI
from gd import *

# Initialize the SPI Bus (on Pyboard)
# Hardware SPI
spi = SPI(2) # MOSI=Y8, MISO=Y7, SCK=Y6, SS=Y5
spi.init( SPI.MASTER, baudrate=2000000, phase=0, polarity=0 )
# We must manage the SS signal ourself
ss = Pin( Pin.board.Y5, Pin.OUT )


# Gameduino Lib
gd = Gameduino( spi, ss )
gd.begin()
gd.ascii()

gd.putstr( 5 ,  0, "  *** DEMOs ***" )
gd.putstr( 5 ,  1, " 04_demo/ascii/scrsize.py " )
gd.putstr( 0,   5, ''.join(["%s         " % i for i in range(6)]) )
gd.putstr( 0,   6, '0123456789'*6 )
for line in range( 38 ):
Beispiel #55
0
class LCD_1inch14(framebuf.FrameBuffer):
    def __init__(self):
        self.width = 240
        self.height = 135

        self.cs = Pin(CS, Pin.OUT)
        self.rst = Pin(RST, Pin.OUT)

        self.cs(1)
        self.spi = SPI(1)
        self.spi = SPI(1, 1000_000)
        self.spi = SPI(1,
                       10000_000,
                       polarity=0,
                       phase=0,
                       sck=Pin(SCK),
                       mosi=Pin(MOSI),
                       miso=None)
        self.dc = Pin(DC, Pin.OUT)
        self.dc(1)
        self.buffer = bytearray(self.height * self.width * 2)
        super().__init__(self.buffer, self.width, self.height, framebuf.RGB565)
        self.init_display()

        self.red = 0x07E0  # 0 ok     (actually green)
        self.green = 0x001f  # 1 ok     (actually blue)
        self.blue = 0xf800  # 2 ok     (actually red)
        self.white = 0xffff  # ok
        self.black = 0x0000  # 3 ok
        self.orange = 0x07f6  # 5 ok
        self.ergoblue = 0x06DF  #
        self.yellow = 0x9fe0  # 6 ok    0x07ff
        self.pink = 0xF81D  #
        self.purple = 0xffe0  # 4 ok
        self.brown = 0x23cb  # 7 ok

    def write_cmd(self, cmd):
        self.cs(1)
        self.dc(0)
        self.cs(0)
        self.spi.write(bytearray([cmd]))
        self.cs(1)

    def write_data(self, buf):
        self.cs(1)
        self.dc(1)
        self.cs(0)
        self.spi.write(bytearray([buf]))
        self.cs(1)

    def init_display(self):
        """Initialize dispaly"""
        self.rst(1)
        self.rst(0)
        self.rst(1)

        self.write_cmd(0x36)
        self.write_data(0x70)

        self.write_cmd(0x3A)
        self.write_data(0x05)

        self.write_cmd(0xB2)
        self.write_data(0x0C)
        self.write_data(0x0C)
        self.write_data(0x00)
        self.write_data(0x33)
        self.write_data(0x33)

        self.write_cmd(0xB7)
        self.write_data(0x35)

        self.write_cmd(0xBB)
        self.write_data(0x19)

        self.write_cmd(0xC0)
        self.write_data(0x2C)

        self.write_cmd(0xC2)
        self.write_data(0x01)

        self.write_cmd(0xC3)
        self.write_data(0x12)

        self.write_cmd(0xC4)
        self.write_data(0x20)

        self.write_cmd(0xC6)
        self.write_data(0x0F)

        self.write_cmd(0xD0)
        self.write_data(0xA4)
        self.write_data(0xA1)

        self.write_cmd(0xE0)
        self.write_data(0xD0)
        self.write_data(0x04)
        self.write_data(0x0D)
        self.write_data(0x11)
        self.write_data(0x13)
        self.write_data(0x2B)
        self.write_data(0x3F)
        self.write_data(0x54)
        self.write_data(0x4C)
        self.write_data(0x18)
        self.write_data(0x0D)
        self.write_data(0x0B)
        self.write_data(0x1F)
        self.write_data(0x23)

        self.write_cmd(0xE1)
        self.write_data(0xD0)
        self.write_data(0x04)
        self.write_data(0x0C)
        self.write_data(0x11)
        self.write_data(0x13)
        self.write_data(0x2C)
        self.write_data(0x3F)
        self.write_data(0x44)
        self.write_data(0x51)
        self.write_data(0x2F)
        self.write_data(0x1F)
        self.write_data(0x1F)
        self.write_data(0x20)
        self.write_data(0x23)

        self.write_cmd(0x21)

        self.write_cmd(0x11)

        self.write_cmd(0x29)

    def show(self):
        self.write_cmd(0x2A)
        self.write_data(0x00)
        self.write_data(0x28)
        self.write_data(0x01)
        self.write_data(0x17)

        self.write_cmd(0x2B)
        self.write_data(0x00)
        self.write_data(0x35)
        self.write_data(0x00)
        self.write_data(0xBB)

        self.write_cmd(0x2C)

        self.cs(1)
        self.dc(1)
        self.cs(0)
        self.spi.write(self.buffer)
        self.cs(1)
Beispiel #56
0
class MFRC522:

	OK = 0
	NOTAGERR = 1
	ERR = 2

	REQIDL = 0x26
	REQALL = 0x52
	AUTHENT1A = 0x60
	AUTHENT1B = 0x61

	def __init__(self, sck, mosi, miso, rst, cs):

		self.sck = Pin(sck, Pin.OUT)
		self.mosi = Pin(mosi, Pin.OUT)
		self.miso = Pin(miso)
		self.rst = Pin(rst, Pin.OUT)
		self.cs = Pin(cs, Pin.OUT)

		self.rst.value(0)
		self.cs.value(1)

		if uname()[0] == 'WiPy':
			self.spi = SPI(0)
			self.spi.init(SPI.MASTER, baudrate=1000000, pins=(self.sck, self.mosi, self.miso))
		elif uname()[0] == 'esp8266':
			self.spi = SPI(baudrate=100000, polarity=0, phase=0, sck=self.sck, mosi=self.mosi, miso=self.miso)
			self.spi.init()
		else:
			raise RuntimeError("Unsupported platform")

		self.rst.value(1)
		self.init()

	def _wreg(self, reg, val):

		self.cs.value(0)
		self.spi.write(b'%c' % int(0xff & ((reg << 1) & 0x7e)))
		self.spi.write(b'%c' % int(0xff & val))
		self.cs.value(1)

	def _rreg(self, reg):

		self.cs.value(0)
		self.spi.write(b'%c' % int(0xff & (((reg << 1) & 0x7e) | 0x80)))
		val = self.spi.read(1)
		self.cs.value(1)

		return val[0]

	def _sflags(self, reg, mask):
		self._wreg(reg, self._rreg(reg) | mask)

	def _cflags(self, reg, mask):
		self._wreg(reg, self._rreg(reg) & (~mask))

	def _tocard(self, cmd, send):

		recv = []
		bits = irq_en = wait_irq = n = 0
		stat = self.ERR

		if cmd == 0x0E:
			irq_en = 0x12
			wait_irq = 0x10
		elif cmd == 0x0C:
			irq_en = 0x77
			wait_irq = 0x30

		self._wreg(0x02, irq_en | 0x80)
		self._cflags(0x04, 0x80)
		self._sflags(0x0A, 0x80)
		self._wreg(0x01, 0x00)

		for c in send:
			self._wreg(0x09, c)
		self._wreg(0x01, cmd)

		if cmd == 0x0C:
			self._sflags(0x0D, 0x80)

		i = 2000
		while True:
			n = self._rreg(0x04)
			i -= 1
			if ~((i != 0) and ~(n & 0x01) and ~(n & wait_irq)):
				break

		self._cflags(0x0D, 0x80)

		if i:
			if (self._rreg(0x06) & 0x1B) == 0x00:
				stat = self.OK

				if n & irq_en & 0x01:
					stat = self.NOTAGERR
				elif cmd == 0x0C:
					n = self._rreg(0x0A)
					lbits = self._rreg(0x0C) & 0x07
					if lbits != 0:
						bits = (n - 1) * 8 + lbits
					else:
						bits = n * 8

					if n == 0:
						n = 1
					elif n > 16:
						n = 16

					for _ in range(n):
						recv.append(self._rreg(0x09))
			else:
				stat = self.ERR

		return stat, recv, bits

	def _crc(self, data):

		self._cflags(0x05, 0x04)
		self._sflags(0x0A, 0x80)

		for c in data:
			self._wreg(0x09, c)

		self._wreg(0x01, 0x03)

		i = 0xFF
		while True:
			n = self._rreg(0x05)
			i -= 1
			if not ((i != 0) and not (n & 0x04)):
				break

		return [self._rreg(0x22), self._rreg(0x21)]

	def init(self):

		self.reset()
		self._wreg(0x2A, 0x8D)
		self._wreg(0x2B, 0x3E)
		self._wreg(0x2D, 30)
		self._wreg(0x2C, 0)
		self._wreg(0x15, 0x40)
		self._wreg(0x11, 0x3D)
		self.antenna_on()

	def reset(self):
		self._wreg(0x01, 0x0F)

	def antenna_on(self, on=True):

		if on and ~(self._rreg(0x14) & 0x03):
			self._sflags(0x14, 0x03)
		else:
			self._cflags(0x14, 0x03)

	def request(self, mode):

		self._wreg(0x0D, 0x07)
		(stat, recv, bits) = self._tocard(0x0C, [mode])

		if (stat != self.OK) | (bits != 0x10):
			stat = self.ERR

		return stat, bits

	def anticoll(self):

		ser_chk = 0
		ser = [0x93, 0x20]

		self._wreg(0x0D, 0x00)
		(stat, recv, bits) = self._tocard(0x0C, ser)

		if stat == self.OK:
			if len(recv) == 5:
				for i in range(4):
					ser_chk = ser_chk ^ recv[i]
				if ser_chk != recv[4]:
					stat = self.ERR
			else:
				stat = self.ERR

		return stat, recv

	def select_tag(self, ser):

		buf = [0x93, 0x70] + ser[:5]
		buf += self._crc(buf)
		(stat, recv, bits) = self._tocard(0x0C, buf)
		return self.OK if (stat == self.OK) and (bits == 0x18) else self.ERR

	def auth(self, mode, addr, sect, ser):
		return self._tocard(0x0E, [mode, addr] + sect + ser[:4])[0]

	def stop_crypto1(self):
		self._cflags(0x08, 0x08)

	def read(self, addr):

		data = [0x30, addr]
		data += self._crc(data)
		(stat, recv, _) = self._tocard(0x0C, data)
		return recv if stat == self.OK else None

	def write(self, addr, data):

		buf = [0xA0, addr]
		buf += self._crc(buf)
		(stat, recv, bits) = self._tocard(0x0C, buf)

		if not (stat == self.OK) or not (bits == 4) or not ((recv[0] & 0x0F) == 0x0A):
			stat = self.ERR
		else:
			buf = []
			for i in range(16):
				buf.append(data[i])
			buf += self._crc(buf)
			(stat, recv, bits) = self._tocard(0x0C, buf)
			if not (stat == self.OK) or not (bits == 4) or not ((recv[0] & 0x0F) == 0x0A):
				stat = self.ERR

		return stat
Beispiel #57
0
from machine import Pin,SPI
import Screen
import time

power=Pin(13,Pin.OUT)
power.value(1)
spi=SPI(1,sck=Pin(18,Pin.OUT),mosi=Pin(5,Pin.OUT),baudrate=24000000)

# width:128, height:64, dc-->pin16, res-->pin17
s = Screen.create(128, 64, spi, Pin(22,Pin.OUT), Pin(23,Pin.OUT))
s.print('Hello, world.\nadbd')