Skip to content

Commit 6e488af

Browse files
brentrutannewt
authored andcommitted
shift_in/shift_out (#11)
Add `shift_in` and `shift_out` modeled after Arduino's `shiftIn` and `shiftOut`.
1 parent 1f54b1f commit 6e488af

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

simpleio.py

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,72 @@
2828

2929
import digitalio
3030
import math
31+
import time
32+
33+
def shift_in(dataPin, clock, msb_first=True):
34+
"""
35+
Shifts in a byte of data one bit at a time. Starts from either the LSB or
36+
MSB.
37+
38+
:param ~digitalio.DigitalInOut dataPin: pin on which to input each bit
39+
:param ~digitalio.DigitalInOut clock: toggles to signal dataPin reads
40+
:param bool msb_first: True when the first bit is most significant
41+
:return: returns the value read
42+
:rtype: int
43+
"""
44+
45+
value = 0
46+
i = 0
47+
48+
for i in range(0, 8):
49+
clock.value = True
50+
if msb_first:
51+
value |= ((dataPin.value) << (7-i))
52+
else:
53+
value |= ((dataPin.value) << i)
54+
clock.value = False
55+
i+=1
56+
return value
57+
58+
def shift_out(dataPin, clock, value, msb_first=True):
59+
"""
60+
Shifts out a byte of data one bit at a time. Data gets written to a data
61+
pin. Then, the clock pulses hi then low
62+
63+
:param ~digitalio.DigitalInOut dataPin: value bits get output on this pin
64+
:param ~digitalio.DigitalInOut clock: toggled once the data pin is set
65+
:param bool msb_first: True when the first bit is most significant
66+
:param int value: byte to be shifted
67+
68+
Example for Metro M0 Express:
69+
70+
.. code-block:: python
71+
72+
import digitalio
73+
import simpleio
74+
from board import *
75+
clock = digitalio.DigitalInOut(D12)
76+
dataPin = digitalio.DigitalInOut(D11)
77+
clock.direction = digitalio.Direction.OUTPUT
78+
dataPin.direction = digitalio.Direction.OUTPUT
79+
80+
while True:
81+
valueSend = 500
82+
# shifting out least significant bits
83+
shift_out(dataPin, clock, (valueSend>>8), msb_first = False)
84+
shift_out(dataPin, clock, valueSend, msb_first = False)
85+
# shifting out most significant bits
86+
shift_out(dataPin, clock, (valueSend>>8))
87+
shift_out(dataPin, clock, valueSend)
88+
"""
89+
value = value&0xFF
90+
for i in range(0, 8):
91+
if msb_first:
92+
tmpval = bool(value & (1 << (7-i)))
93+
dataPin.value = tmpval
94+
else:
95+
tmpval = bool((value & (1 << i)))
96+
dataPin.value = tmpval
3197

3298
class DigitalOut:
3399
"""

0 commit comments

Comments
 (0)