Page 155
from gpiozero import Servo
class ServoInvert(Servo):
@Servo.value.setter
def value(self, value):
if value is None:
self.pwm_device.pin.frequency = None
elif -1 <= value <= 1:
self.pwm_device.pin.frequency = int(1 / self.frame_width)
self.pwm_device.value = (self._min_dc + self._dc_range *((value - self._min_value) / self._value_range))
else:
raise OutputDeviceBadValue(
"Servo value must be between -1 and 1, or None")
Page 164
from gpiozero import DigitalOutputDevice
from time import sleep
class StepperBi4():
def __init__(self, A=None, Am=None, B=None, Bm=None):
self.phase = 0
self.gpios = tuple(DigitalOutputDevice(pin) for pin in (A, B, Am, Bm))
self.halfstepSeq = [
[1, 0, 0, 0],
[1, 1, 0, 0],
[0, 1, 0, 0],
[0, 1, 1, 0],
[0, 0, 1, 0],
[0, 0, 1, 1],
[0, 0, 0, 1],
[1, 0, 0, 1]
]
def setPhase(self, phase):
self.phase = phase
for gpio, state in zip(self.gpios, self.halfstepSeq[phase]):
gpio.value = state
def stepForward(self):
self.phase = (self.phase+1) % 8
self.setPhase(self.phase)
def stepReverse(self):
self.phase = (self.phase-1) % 8
self.setPhase(self.phase)
step = StepperBi4(4, 17, 27, 22)
step.setPhase(0)
while True:
sleep(0.001)
step.stepForward()
Page 170
from gpiozero import LED
from time import sleep
class TriLED():
def __init__(self, pin1=None, pin2=None, pin3=None):
self.LEDs = (LED(pin1), LED(pin2), LED(pin3))
def AllOn(self):
self.LEDs[0].on()
self.LEDs[1].on()
self.LEDs[2].on()
def AllOff(self):
self.LEDs[0].off()
self.LEDs[1].off()
self.LEDs[2].off()
Page 171
class TriLED(CompositeDevice):
def __init__(self, pin1=None, pin2=None, pin3=None):
super(TriLED, self).__init__(LED(pin1), LED(pin2), LED(pin3))
def AllOn(self):
self[0].on()
self[1].on()
self[2].on()
def AllOff(self):
self[0].off()
self[1].off()
self[2].off()
Page 183
from gpiozero import DigitalOutputDevice, CompositeDevice
class StepperBi4(CompositeDevice):
def __init__(self, A=None, Am=None, B=None, Bm=None):
if not all(p is not None for p in [A, Am, B, Bm]):
raise GPIOPinMissing(
'Four GPIO pins must be provided'
)
super(StepperUni4, self).__init__(DigitalOutputDevice(A), DigitalOutputDevice(
B), DigitalOutputDevice(Am), DigitalOutputDevice(Bm))
self.phase = 0
self.halfstepSeq = [
[1, 0, 0, 0],
[1, 1, 0, 0],
[0, 1, 0, 0],
[0, 1, 1, 0],
[0, 0, 1, 0],
[0, 0, 1, 1],
[0, 0, 0, 1],
[1, 0, 0, 1]
]
def setPhase(self, phase):
self.phase = phase
for gpio, state in zip(self, self.halfstepSeq[phase]):
gpio.pin._set_state(state)
def stepForward(self):
self.phase = (self.phase+1) % 8
self.setPhase(self.phase)
def stepReverse(self):
self.phase = (self.phase-1) % 8
self.setPhase(self.phase)
Page 186
from gpiozero import DigitalOutputDevice, CompositeDevice
from time import sleep
from gpiozero.threads import GPIOThread
class StepperBi4(CompositeDevice):
def __init__(self, A=None, Am=None, B=None, Bm=None):
if not all(p is not None for p in [A, Am, B, Bm]):
raise GPIOPinMissing('Four GPIO pins must be provided')
super(StepperUni4, self).__init__(DigitalOutputDevice(A), DigitalOutputDevice(
B), DigitalOutputDevice(Am), DigitalOutputDevice(Bm))
self.phase = 0
self._rotate_thread = None
self.halfstepSeq = [
[1, 0, 0, 0],
[1, 1, 0, 0],
[0, 1, 0, 0],
[0, 1, 1, 0],
[0, 0, 1, 0],
[0, 0, 1, 1],
[0, 0, 0, 1],
[1, 0, 0, 1]
]
def setPhase(self, phase):
self.phase = phase
for gpio, state in zip(self, self.halfstepSeq[phase]):
gpio.pin._set_state(state)
def stepForward(self):
self.phase = (self.phase+1) % 8
self.setPhase(self.phase)
def stepReverse(self):
self.phase = (self.phase-1) % 8
self.setPhase(self.phase)
def forward(self, speed=0):
self._stop_rotate()
if speed == 0:
return
self._rotate_thread = GPIOThread(
target=self._rotate, args=(+1, speed))
self._rotate_thread.start()
def reverse(self, speed=1):
self._stop_rotate()
if speed == 0:
return
self._rotate_thread = GPIOThread(
target=self._rotate, args=(-1, speed))
self._rotate_thread.start()
def _rotate(self, dir, speed):
delay = 60/(speed*400)-0.001
while True:
if dir == 1:
self.stepForward()
if dir == -1:
self.stepReverse()
if self._rotate_thread.stopping.wait(delay):
break
def _stop_rotate(self):
if getattr(self, '_rotate_thread', None):
self._rotate_thread.stop()
self._rotate_thread = None
Page 186
import subprocess
temp = subprocess.Popen(["sudo", "dtparam", "-l"], stdout=subprocess.PIPE)
output = str(temp.communicate())
print(output)
lastSPI = output.rfind("spi")
if lastSPI != -1:
lastSPI = output.find("spi=on", lastSPI)
if lastSPI == -1:
temp = subprocess.Popen(
["sudo", "dtparam", "spi=on"], stdout=subprocess.PIPE)
output = str(temp.communicate())
print("adding", output)
else:
temp = subprocess.Popen(
["sudo", "dtparam", "spi=on"], stdout=subprocess.PIPE)
output = str(temp.communicate())
print("adding", output)
Page 190
import subprocess
temp = subprocess.Popen(["sudo", "dtparam", "-l"], stdout=subprocess.PIPE)
output = str(temp.communicate())
print(output)
lastSPI = output.rfind("spi")
if lastSPI != -1:
lastSPI = output.find("spi=on", lastSPI)
if lastSPI == -1:
temp = subprocess.Popen(
["sudo", "dtparam", "spi=on"], stdout=subprocess.PIPE)
output = str(temp.communicate())
print("adding", output)
else:
temp = subprocess.Popen(
["sudo", "dtparam", "spi=on"], stdout=subprocess.PIPE)
output = str(temp.communicate())
print("adding", output)
Page 207
from gpiozero import SPIDevice
Dev = SPIDevice()
Dev.clock_mode = 0
Dev.select_high = False
Dev._spi._interface.max_speed_hz = 60000
words = Dev._spi.transfer([0x01, 0x80, 0x00])
data = (words[1] & 0x03) << 8 | words[2]
volts = data * 3.3 / 1023.0
print(volts)
Dev.close()
Page 212
class DS3234rtc(SPIDevice):
def __init__(self):
super(DS3234rtc, self).__init__()
self.clock_mode = 1
self.select_high = False
self._spi._interface.max_speed_hz = 5000000
def setDateTime(self, dateTime):
datetimetuple = dateTime.timetuple()
datetimetuple = (datetimetuple[0]-2000,)+datetimetuple[1:3] + \
(dateTime.isoweekday(),)+datetimetuple[3:6]
datetimetuple = datetimetuple[::-1]
for i in range(0, 7):
data = datetimetuple[i]
data = (data//10) << 4 | (data % 10)
words = self._spi.transfer([0x80+i, data])
def getDateTime(self):
datetimelist = []
for i in range(7):
words = self._spi.transfer([i, 0x00])
if i == 3:
continue
byte = words[1]
data = (byte & 0x0F)+(byte >> 4)*10
datetimelist.insert(0, data)
datetimelist[0] += 2000
return datetime(*datetimelist)
Page 227 Appendix
settings.json
{
"sshUser": "pi",
"sshEndpoint": "192.168.11.170",
"remoteDirectory": "/home/pi/Documents/${workspaceFolderBasename}",
}
tasks.json
{
"version": "2.0.0",
"tasks": [
{
"label": "copyToRemote",
"type": "shell",
"command": "scp -r ${fileDirname} ${config:sshUser}@${config:sshEndpoint}:${config:remoteDirectory}/",
"problemMatcher": [],
"presentation": {
"showReuseMessage": false,
"clear": true
}
},
{
"label": "makeRemoteWorkSpace",
"type": "shell",
"command": "ssh ${config:sshUser}@${config:sshEndpoint} ;'mkdir ${config:remoteDirectory}'",
"problemMatcher": [],
"presentation": {
"showReuseMessage": false,
}
},
{
"label": "RunR",
"type": "shell",
"command": "ssh ${config:sshUser}@${config:sshEndpoint} ;'python3 ${config:remoteDirectory}/${relativeFileDirname}/${fileBasename}'",
"problemMatcher": [],
"presentation": {
"showReuseMessage": false,
}
},
{
"label": "RunRemote",
"dependsOrder": "sequence",
"dependsOn": [
"copyToRemote",
"RunR"
],
"problemMatcher": [],
"group": {
"kind": "build",
"isDefault": true
},
},
{
"label": "StopRemotePython",
"type": "shell",
"command": "ssh ${config:sshUser}@${config:sshEndpoint} ;'pkill python3'",
"problemMatcher": [],
"presentation": {
"showReuseMessage": true,
}
},
{
"label": "wait",
"type": "shell",
"command": "timeout 10"
},
{
"label": "tunnel",
"type": "shell",
"command": "ssh -2 -L 5678:localhost:5678 ${config:sshUser}@${config:sshEndpoint}",
"problemMatcher": [],
"presentation": {
"showReuseMessage": false,
}
},
{
"label": "startDebug",
"type": "shell",
"command": "ssh -2 ${config:sshUser}@${config:sshEndpoint} ; 'nohup python3 -m debugpy --listen 0.0.0.0:5678 --wait-for-client ${config:remoteDirectory}/${relativeFileDirname}/${fileBasename} > /dev/null 2>&1 &'",
"problemMatcher": [],
"presentation": {
"showReuseMessage": false,
}
},
{
"label": "copyAndDebug",
"dependsOrder": "sequence",
"dependsOn": [
"copyToRemote",
"startDebug",
"wait"
],
"presentation": {
"showReuseMessage": false,
},
},
]
}