Skip to content

Instantly share code, notes, and snippets.

@amaork
Created July 27, 2017 03:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amaork/6a833e137540647e1904f90c1c45caee to your computer and use it in GitHub Desktop.
Save amaork/6a833e137540647e1904f90c1c45caee to your computer and use it in GitHub Desktop.
Raspberry pi using gpio simulate spi write
from __future__ import print_function
from raspi_io import GPIO
__all__ = ['GPIOSPI']
class GPIOSPI(object):
"""
SPI Frame | reg, reg | data 0 - 7|
"""
# Frame 10 bits
FRAME_MASK = 0x3ff
BIT_PER_FRAME = 10
BIT_SHIFT_MASK = 1 << BIT_PER_FRAME
def __init__(self, address, clk, dat, stb, debug=True):
"""GPIO simulate spi
:param address: raspi address
:param clk: spi sclk
:param dat: spi mosi
:param stb: spi cs
:param debug: debug option
"""
self.__clk = clk
self.__dat = dat
self.__stb = stb
self.__debug = debug
self.__gpio = GPIO(address)
self.__gpio.setmode(GPIO.BCM)
self.__gpio.setup([clk, dat, stb], GPIO.OUT, initial=False)
def write_frame(self, data):
"""Write basic frame
:param data: frame data
:return:
"""
data &= self.FRAME_MASK
self.__gpio.output([self.__clk, self.__dat, self.__stb], 0)
if self.__debug:
print("Frame: 0x{0:03X},".format(data), end=' ')
for i in range(self.BIT_PER_FRAME):
self.__gpio.output(self.__clk, 0)
if self.__debug:
print(1 if data & 0x200 else 0, end=' ')
self.__gpio.output(self.__dat, 1 if data & self.BIT_SHIFT_MASK else 0)
if i == self.BIT_PER_FRAME - 1:
self.__gpio.output(self.__stb, 1)
self.__gpio.output(self.__clk, 1)
data = (data << 1) & self.FRAME_MASK
if __name__ == "__main__":
spi = GPIOSPI(('192.168.1.166', 9876), 11, 10, 7)
spi.write_frame(0x3ff)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment