Python spidev.SpiDev() Examples

The following are 30 code examples of spidev.SpiDev(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module spidev , or try the search function .
Example #1
Source File: sensor.py    From raspberrypi-examples with MIT License 10 votes vote down vote up
def readadc(adcnum):
    spi = spidev.SpiDev()
    spi.open(0,0)
    # read SPI data from MCP3004 chip, 4 possible adc’s (0 thru 3)
    if ((adcnum > 3) or (adcnum < 0)):
        return-1
    r = spi.xfer2([1,8+adcnum <<4,0])
    #print(r)
    adcout = ((r[1] &3) <<8)+r[2]
    return adcout 
Example #2
Source File: lorem.py    From Waveshare-E-Ink with MIT License 7 votes vote down vote up
def main():
  bus, device = 0, 0
  spi = SPI.SpiDev(bus, device)
  display = Epd(spi, DISPLAY_TYPE)

  print('--> Init and clear full screen %s' % display.size)
  display.clearDisplayPart()

  height, width = display.size

  # canvas to draw to
  image = Image.new('1', display.size, WHITE)

  # add some text to it
  text = Text(width, height, "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.", chars=24)
  image.paste(text.image, (0, 0, height, width), mask=BLACK)

  # send image to display
  display.showImageFull(display.imageToPixelArray(image))

# main 
Example #3
Source File: apa102.py    From GassistPi with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, num_led, global_brightness=MAX_BRIGHTNESS,
                 order='rgb', bus=0, device=1, max_speed_hz=8000000):
        self.num_led = num_led  # The number of LEDs in the Strip
        order = order.lower()
        self.rgb = RGB_MAP.get(order, RGB_MAP['rgb'])
        # Limit the brightness to the maximum if it's set higher
        if global_brightness > self.MAX_BRIGHTNESS:
            self.global_brightness = self.MAX_BRIGHTNESS
        else:
            self.global_brightness = global_brightness

        self.leds = [self.LED_START,0,0,0] * self.num_led # Pixel buffer
        self.spi = spidev.SpiDev()  # Init the SPI device
        self.spi.open(bus, device)  # Open SPI port 0, slave device (CS) 1
        # Up the speed a bit, so that the LEDs are painted faster
        if max_speed_hz:
            self.spi.max_speed_hz = max_speed_hz 
Example #4
Source File: spi.py    From rpieasy with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, cs=None):
        self.spi = spidev.SpiDev(0, 0)
        GPIO.setmode(GPIO.BCM)
        self._cs = cs
        if cs:
            GPIO.setup(self._cs, GPIO.OUT)
            GPIO.output(self._cs, GPIO.HIGH)
        self.spi.max_speed_hz = 1000000
        self.spi.mode = 0b10    # CPOL=1 & CPHA=0 
Example #5
Source File: apa102.py    From kim-voice-assistant with MIT License 6 votes vote down vote up
def __init__(self, num_led, global_brightness=MAX_BRIGHTNESS,
                 order='rgb', bus=0, device=1, max_speed_hz=8000000):
        self.num_led = num_led  # The number of LEDs in the Strip
        order = order.lower()
        self.rgb = RGB_MAP.get(order, RGB_MAP['rgb'])
        # Limit the brightness to the maximum if it's set higher
        if global_brightness > self.MAX_BRIGHTNESS:
            self.global_brightness = self.MAX_BRIGHTNESS
        else:
            self.global_brightness = global_brightness

        self.leds = [self.LED_START,0,0,0] * self.num_led # Pixel buffer
        self.spi = spidev.SpiDev()  # Init the SPI device
        self.spi.open(bus, device)  # Open SPI port 0, slave device (CS) 1
        # Up the speed a bit, so that the LEDs are painted faster
        if max_speed_hz:
            self.spi.max_speed_hz = max_speed_hz 
Example #6
Source File: inky.py    From inky with MIT License 6 votes vote down vote up
def setup(self):
        """Set up Inky GPIO and reset display."""
        if not self._gpio_setup:
            if self._gpio is None:
                try:
                    import RPi.GPIO as GPIO
                    self._gpio = GPIO
                except ImportError:
                    raise ImportError('This library requires the RPi.GPIO module\nInstall with: sudo apt install python-rpi.gpio')
            self._gpio.setmode(self._gpio.BCM)
            self._gpio.setwarnings(False)
            self._gpio.setup(self.dc_pin, self._gpio.OUT, initial=self._gpio.LOW, pull_up_down=self._gpio.PUD_OFF)
            self._gpio.setup(self.reset_pin, self._gpio.OUT, initial=self._gpio.HIGH, pull_up_down=self._gpio.PUD_OFF)
            self._gpio.setup(self.busy_pin, self._gpio.IN, pull_up_down=self._gpio.PUD_OFF)

            if self._spi_bus is None:
                import spidev
                self._spi_bus = spidev.SpiDev()

            self._spi_bus.open(0, self.cs_channel)
            self._spi_bus.max_speed_hz = 488000

            self._gpio_setup = True

        self._gpio.output(self.reset_pin, self._gpio.LOW)
        time.sleep(0.1)
        self._gpio.output(self.reset_pin, self._gpio.HIGH)
        time.sleep(0.1)

        self._send_command(0x12)  # Soft Reset
        self._busy_wait() 
Example #7
Source File: apa102.py    From HermesLedControl with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, num_led, global_brightness=MAX_BRIGHTNESS,
                 order='rgb', bus=0, device=1, max_speed_hz=8000000, endFrame=255):
        self.num_led = num_led  # The number of LEDs in the Strip
        self._endFrame = endFrame
        order = order.lower()
        self.rgb = RGB_MAP.get(order, RGB_MAP['rgb'])
        # Limit the brightness to the maximum if it's set higher
        if global_brightness > self.MAX_BRIGHTNESS:
            self.global_brightness = self.MAX_BRIGHTNESS
        else:
            self.global_brightness = global_brightness

        self.leds = [self.LED_START,0,0,0] * self.num_led # Pixel buffer
        self.spi = spidev.SpiDev()  # Init the SPI device
        self.spi.open(bus, device)  # Open SPI port 0, slave device (CS) 1
        # Up the speed a bit, so that the LEDs are painted faster
        if max_speed_hz:
            self.spi.max_speed_hz = max_speed_hz 
Example #8
Source File: apa102.py    From ollie with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, num_led, global_brightness=MAX_BRIGHTNESS,
                 order='rgb', bus=0, device=1, max_speed_hz=8000000):
        self.num_led = num_led  # The number of LEDs in the Strip
        order = order.lower()
        self.rgb = RGB_MAP.get(order, RGB_MAP['rgb'])
        # Limit the brightness to the maximum if it's set higher
        if global_brightness > self.MAX_BRIGHTNESS:
            self.global_brightness = self.MAX_BRIGHTNESS
        else:
            self.global_brightness = global_brightness

        self.leds = [self.LED_START,0,0,0] * self.num_led # Pixel buffer
        self.spi = spidev.SpiDev()  # Init the SPI device
        self.spi.open(bus, device)  # Open SPI port 0, slave device (CS) 1
        # Up the speed a bit, so that the LEDs are painted faster
        if max_speed_hz:
            self.spi.max_speed_hz = max_speed_hz 
Example #9
Source File: system.py    From Waveshare-E-Ink with MIT License 6 votes vote down vote up
def sysInfo(eth0info, wlan0info):
  bus, device = 0, 0
  spi = SPI.SpiDev(bus, device)

  display = Epd(spi, DISPLAY_TYPE)
  display.clearDisplayPart()
  height, width = display.size

  # canvas to draw to
  image = Image.new('1', display.size, WHITE)

  # add some text to it
  info = eth0info + wlan0info
  text = Text(width, height, info, chars=24)
  image.paste(text.image, (0, 0, height, width), mask=BLACK)

  # send image to display
  display.showImageFull(display.imageToPixelArray(image)) 
Example #10
Source File: ExpanderPi.py    From ABElectronics_Python_Libraries with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, gainFactor=1):
        """
        Class Constructor - Define SPI bus and init

        :param gainFactor: Set the DAC's gain factor. The value should
           be 1 or 2.  Gain factor is used to determine output voltage
           from the formula: Vout = G * Vref * D/4096
           Where G is gain factor, Vref (for this chip) is 2.048 and
           D is the 12-bit digital value, defaults to 1
        :type gainFactor: int, optional
        :raises ValueError: DAC __init__: Invalid gain factor. Must be 1 or 2
        """

        # Define SPI bus and init
        self.__spiDAC = spidev.SpiDev()
        self.__spiDAC.open(0, 1)
        self.__spiDAC.max_speed_hz = (20000000)

        if (gainFactor != 1) and (gainFactor != 2):
            raise ValueError('DAC __init__: Invalid gain factor. \
                            Must be 1 or 2')
        else:
            self.gain = gainFactor

            self.maxdacvoltage = self.__dacMaxOutput__[self.gain] 
Example #11
Source File: ExpanderPi.py    From aws-builders-fair-projects with Apache License 2.0 6 votes vote down vote up
def __init__(self, gainFactor=1):
        """Class Constructor

        gainFactor -- Set the DAC's gain factor. The value should
           be 1 or 2.  Gain factor is used to determine output voltage
           from the formula: Vout = G * Vref * D/4096
           Where G is gain factor, Vref (for this chip) is 2.048 and
           D is the 12-bit digital value
        """

        # Define SPI bus and init
        self.__spiDAC = spidev.SpiDev()
        self.__spiDAC.open(0, 1)
        self.__spiDAC.max_speed_hz = (20000000)

        if (gainFactor != 1) and (gainFactor != 2):
            raise ValueError('DAC __init__: Invalid gain factor. \
                            Must be 1 or 2')
        else:
            self.gain = gainFactor

            self.maxdacvoltage = self.__dacMaxOutput__[self.gain] 
Example #12
Source File: apa102.py    From mic_hat with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, num_led, global_brightness=MAX_BRIGHTNESS,
                 order='rgb', bus=0, device=1, max_speed_hz=8000000):
        self.num_led = num_led  # The number of LEDs in the Strip
        order = order.lower()
        self.rgb = RGB_MAP.get(order, RGB_MAP['rgb'])
        # Limit the brightness to the maximum if it's set higher
        if global_brightness > self.MAX_BRIGHTNESS:
            self.global_brightness = self.MAX_BRIGHTNESS
        else:
            self.global_brightness = global_brightness

        self.leds = [self.LED_START,0,0,0] * self.num_led # Pixel buffer
        self.spi = spidev.SpiDev()  # Init the SPI device
        self.spi.open(bus, device)  # Open SPI port 0, slave device (CS) 1
        # Up the speed a bit, so that the LEDs are painted faster
        if max_speed_hz:
            self.spi.max_speed_hz = max_speed_hz 
Example #13
Source File: rpi_spi_test.py    From SX127x_driver_for_MicroPython_on_ESP8266 with GNU General Public License v3.0 6 votes vote down vote up
def main(speed = 500000):
    spi = None
    try: 
        spi = spidev.SpiDev()
    except Exception as e:
        print(e)
        
    spi = prepare_spi(spi, speed)
    orig = [i for i in range(128)] * 30
    result = spi.transfer(orig)
    # print(orig)
    # print(result)
    count_all, count_err, error_ratio = cal_error_rate(orig, result)
    print('count_all: {}, count_err: {}, error_ratio: {}'.format(count_all, count_err, error_ratio))
    
    if spi: spi.close() 
Example #14
Source File: controller_rpi.py    From SX127x_driver_for_MicroPython_on_ESP8266 with GNU General Public License v3.0 6 votes vote down vote up
def get_spi(self):
        spi = None

        try:
            spi = spidev.SpiDev()
            bus = 0
            device = 0
            spi.open(bus, device)
            spi.max_speed_hz = 10000000
            spi.mode = 0b00
            spi.lsbfirst = False

        except Exception as e:
            print(e)
            GPIO.cleanup()
            if spi:
                spi.close()
                spi = None

        return spi


    # https://www.raspberrypi.org/documentation/hardware/raspberrypi/spi/README.md
    # https://www.raspberrypi.org/forums/viewtopic.php?f=44&t=19489 
Example #15
Source File: controller_rpi.py    From SX127x_driver_for_MicroPython_on_ESP8266 with GNU General Public License v3.0 6 votes vote down vote up
def get_spi(self):             
        spi = None
        
        try: 
            spi = spidev.SpiDev()
            bus = 0
            device = 0
            spi.open(bus, device)            
            spi.max_speed_hz = 10000000
            spi.mode = 0b00
            spi.lsbfirst = False
                
        except Exception as e:
            print(e)
            GPIO.cleanup()
            if spi:
                spi.close()
                spi = None
        
        return spi
        
            
    # https://www.raspberrypi.org/documentation/hardware/raspberrypi/spi/README.md
    # https://www.raspberrypi.org/forums/viewtopic.php?f=44&t=19489 
Example #16
Source File: epd.py    From rpi_epd2in7 with MIT License 6 votes vote down vote up
def __init__(self, partial_refresh_limit=32, fast_refresh=True):
        """ Initialize the EPD class.
        `partial_refresh_limit` - number of partial refreshes before a full refrersh is forced
        `fast_frefresh` - enable or disable the fast refresh mode,
                          see smart_update() method documentation for details"""
        self.width = EPD_WIDTH
        """ Display width, in pixels """
        self.height = EPD_HEIGHT
        """ Display height, in pixels """
        self.fast_refresh = fast_refresh
        """ enable or disable the fast refresh mode """
        self.partial_refresh_limit = partial_refresh_limit
        """ number of partial refreshes before a full refrersh is forced """

        self._last_frame = None
        self._partial_refresh_count = 0
        self._init_performed = False
        self.spi = spidev.SpiDev(0, 0) 
Example #17
Source File: ExpanderPi.py    From aws-builders-fair-projects with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        # Define SPI bus and init
        self.__spiADC = spidev.SpiDev()
        self.__spiADC.open(0, 0)
        self.__spiADC.max_speed_hz = (1900000)

    # public methods 
Example #18
Source File: ExpanderPi.py    From ABElectronics_Python_Libraries with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self):
        """
        Define SPI bus and init
        """
        self.__spiADC = spidev.SpiDev()
        self.__spiADC.open(0, 0)
        self.__spiADC.max_speed_hz = (200000)

    # public methods 
Example #19
Source File: board_config.py    From pySX127x with GNU Affero General Public License v3.0 5 votes vote down vote up
def SpiDev(spi_bus=0, spi_cs=0):
        """ Init and return the SpiDev object
        :return: SpiDev object
        :param spi_bus: The RPi SPI bus to use: 0 or 1
        :param spi_cs: The RPi SPI chip select to use: 0 or 1
        :rtype: SpiDev
        """
        BOARD.spi = spidev.SpiDev()
        BOARD.spi.open(spi_bus, spi_cs)
        BOARD.spi.max_speed_hz = 5000000    # SX127x can go up to 10MHz, pick half that to be safe
        return BOARD.spi 
Example #20
Source File: board_config.py    From pySX127x with GNU Affero General Public License v3.0 5 votes vote down vote up
def teardown():
        """ Cleanup GPIO and SpiDev """
        GPIO.cleanup()
        BOARD.spi.close() 
Example #21
Source File: MFRC522.py    From MFRC522-python with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, bus=0, device=0, spd=1000000, pin_mode=10, pin_rst=-1, debugLevel='WARNING'):
        self.spi = spidev.SpiDev()
        self.spi.open(bus, device)
        self.spi.max_speed_hz = spd

        self.logger = logging.getLogger('mfrc522Logger')
        self.logger.addHandler(logging.StreamHandler())
        level = logging.getLevelName(debugLevel)
        self.logger.setLevel(level)

        gpioMode = GPIO.getmode()
        
        if gpioMode is None:
            GPIO.setmode(pin_mode)
        else:
            pin_mode = gpioMode
            
        if pin_rst == -1:
            if pin_mode == 11:
                pin_rst = 15
            else:
                pin_rst = 22
            
        GPIO.setup(pin_rst, GPIO.OUT)
        GPIO.output(pin_rst, 1)
        self.MFRC522_Init() 
Example #22
Source File: epdconfig.py    From Inky-Calendar with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        import spidev
        import RPi.GPIO

        self.GPIO = RPi.GPIO

        # SPI device, bus = 0, device = 0
        self.SPI = spidev.SpiDev(0, 0) 
Example #23
Source File: spi.py    From hifiberry-dsp with MIT License 5 votes vote down vote up
def init_spi():
    import spidev
    spi = spidev.SpiDev()
    spi.open(0, 0)
    spi.bits_per_word = 8
    spi.max_speed_hz = 1000000
    spi.mode = 0
    logging.debug("spi initialized %s", spi)
    return spi 
Example #24
Source File: temperature.py    From raspberrypi-examples with MIT License 5 votes vote down vote up
def __init__(self, thread_id, notification_queue, sleeptime, pin = 0):
        super().__init__(thread_id, notification_queue, sleeptime) # python 3 syntax only
        self.pin = pin
        self.spi = spidev.SpiDev()
        self.spi.open(0,0) 
Example #25
Source File: max7219.py    From letsrobot with Apache License 2.0 5 votes vote down vote up
def setup(robot_config):
    global LEDEmoteSmile
    global LEDEmoteSad
    global LEDEmoteTongue
    global LEDEmoteSuprise
    global module
    global spi
    
    #LED controlling
    spi = spidev.SpiDev()
    spi.open(0,0)
    #VCC -> RPi Pin 2
    #GND -> RPi Pin 6
    #DIN -> RPi Pin 19
    #CLK -> RPi Pin 23
    #CS -> RPi Pin 24
    
    # decoding:BCD
    spi.writebytes([0x09])
    spi.writebytes([0x00])
    # Start with low brightness
    spi.writebytes([0x0a])
    spi.writebytes([0x03])
    # scanlimit; 8 LEDs
    spi.writebytes([0x0b])
    spi.writebytes([0x07])
    # Enter normal power-mode
    spi.writebytes([0x0c])
    spi.writebytes([0x01])
    # Activate display
    spi.writebytes([0x0f])
    spi.writebytes([0x00])
    rotate = robot_config.getint('max7219', 'ledrotate')
    if rotate == 180:
        LEDEmoteSmile = LEDEmoteSmile[::-1]
        LEDEmoteSad = LEDEmoteSad[::-1]
        LEDEmoteTongue = LEDEmoteTongue[::-1]
        LEDEmoteSurprise = LEDEmoteSurprise[::-1]
    SetLED_Off() 
Example #26
Source File: opc_test.py    From py-opc with MIT License 5 votes vote down vote up
def setUp(self):
        self.spi = spidev.SpiDev()

        self.assertIsInstance(self.spi, spidev.SpiDev) 
Example #27
Source File: nrf.py    From blueborne with GNU General Public License v3.0 5 votes vote down vote up
def main(spi_id, spi_cs, chan=None):
    spi = spidev.SpiDev()
    spi.open(int(spi_id), int(spi_cs))
    spi.max_speed_hz = 2000000

    nrf = NRF24BREDR(spi)
    nrf.setup(int(chan) if chan else 0)

    cur_chan = 0
    last_time = time.time()

    while True:
        pack = nrf.poll()

        if chan is None and time.time() - last_time > 0.5:
            nrf.set_channel(2 + cur_chan)
            print('Hopped to chan: %d' % (cur_chan,))
            cur_chan = (cur_chan + 1) % 79
            last_time = time.time()

        if not pack:
            continue
        parsed = nrf.parse_bredr(pack)
        if not parsed:
            continue

        lap, uap_candidates = parsed
        print('LAP: %06x, UAPs: %s' % (lap, ','.join(['%02x' % (x,) for x in uap_candidates]))) 
Example #28
Source File: apa102.py    From RibbaPi with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, width=16, height=16, color_type=ColorType.bgr,
                 wire_mode=WireMode.zig_zag, origin=Origin.bottom_left,
                 orientation=Orientation.horizontally):
        super().__init__(width, height)

        # setup initial brightness level
        self.brightness = DEFAULT_BRIGHTNESS / MAX_BRIGHTNESS

        # init SPI interface
        self.spi = spidev.SpiDev()
        self.spi.open(0, 1)
        self.spi.max_speed_hz = SPI_MAX_SPEED_HZ

        # setup hardware and wiring related parameters
        self.color_type = color_type
        self.wire_mode = wire_mode
        self.origin = origin
        self.orientation = orientation

        # setup apa102 protocol stuff
        self.__start_frame = [0] * 4
        # end frame is >= (n/2) bits of 1, where n is the number of LEDs
        self.__end_frame = [0xff] * ((self.num_pixels + 15) // (2 * 8))
        self.__led_frame_start = 0b11100000

        # setup datastructures for fast lookup of led
        # led index for given coordinate
        (self.__pixel_coord_to_led_index,
         self.__virtual_to_physical_byte_indices) = \
            self.__create_pixel_to_led_index_datastructures()

        # create gamma correction values
        self.gamma = DEFAULT_GAMMA
        self.__gamma8 = self.get_gamma8_array(self.gamma)

        self.show() 
Example #29
Source File: DAC_LTC2666_communication.py    From qkit with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, cs = 0, word32 = False):
        '''
        Inputs:
        - cs: chip select connection
        - word32: switch to the 32bit version by passing 'True', default: 24bit
        '''
        self.word32 = word32
    
        self.SPIBUS = cs   #chip select
        self.spi = spidev.SpiDev()
        self.spi.open(0,self.SPIBUS)
        
        self.init() 
Example #30
Source File: SPI.py    From Adafruit_Python_GPIO with MIT License 5 votes vote down vote up
def __init__(self, port, device, max_speed_hz=500000):
        """Initialize an SPI device using the SPIdev interface.  Port and device
        identify the device, for example the device /dev/spidev1.0 would be port
        1 and device 0.
        """
        import spidev
        self._device = spidev.SpiDev()
        self._device.open(port, device)
        self._device.max_speed_hz=max_speed_hz
        # Default to mode 0, and make sure CS is active low.
        self._device.mode = 0
        self._device.cshigh = False