diff --git a/simpleio.py b/simpleio.py index 4d553fc..da0ab95 100644 --- a/simpleio.py +++ b/simpleio.py @@ -28,6 +28,72 @@ import digitalio import math +import time + +def shift_in(dataPin, clock, msb_first=True): + """ + Shifts in a byte of data one bit at a time. Starts from either the LSB or + MSB. + + :param ~digitalio.DigitalInOut dataPin: pin on which to input each bit + :param ~digitalio.DigitalInOut clock: toggles to signal dataPin reads + :param bool msb_first: True when the first bit is most significant + :return: returns the value read + :rtype: int + """ + + value = 0 + i = 0 + + for i in range(0, 8): + clock.value = True + if msb_first: + value |= ((dataPin.value) << (7-i)) + else: + value |= ((dataPin.value) << i) + clock.value = False + i+=1 + return value + +def shift_out(dataPin, clock, value, msb_first=True): + """ + Shifts out a byte of data one bit at a time. Data gets written to a data + pin. Then, the clock pulses hi then low + + :param ~digitalio.DigitalInOut dataPin: value bits get output on this pin + :param ~digitalio.DigitalInOut clock: toggled once the data pin is set + :param bool msb_first: True when the first bit is most significant + :param int value: byte to be shifted + + Example for Metro M0 Express: + + .. code-block:: python + + import digitalio + import simpleio + from board import * + clock = digitalio.DigitalInOut(D12) + dataPin = digitalio.DigitalInOut(D11) + clock.direction = digitalio.Direction.OUTPUT + dataPin.direction = digitalio.Direction.OUTPUT + + while True: + valueSend = 500 + # shifting out least significant bits + shift_out(dataPin, clock, (valueSend>>8), msb_first = False) + shift_out(dataPin, clock, valueSend, msb_first = False) + # shifting out most significant bits + shift_out(dataPin, clock, (valueSend>>8)) + shift_out(dataPin, clock, valueSend) + """ + value = value&0xFF + for i in range(0, 8): + if msb_first: + tmpval = bool(value & (1 << (7-i))) + dataPin.value = tmpval + else: + tmpval = bool((value & (1 << i))) + dataPin.value = tmpval class DigitalOut: """