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")
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()
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)
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 199
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 212
from gpiozero import SPIDevice
Dev=SPIDevice()
Dev.clock_mode=0
Dev.select_high=False
Dev._spi._interface.max_speed_hz=7000
words=Dev._spi.transfer([0xAA])
if words[0]==0xAA:
print("data received correctly")
Page 215
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 220
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 224
import lgpio
GPIOChip = lgpio.gpiochip_open(0)
lgpio.gpio_claim_output(GPIOChip, 4)
while True:
lgpio.gpio_write(GPIOChip, 4, 0)
lgpio.gpio_write(GPIOChip, 4, 1)
lgpio.gpiochip_close(GPIOChip)
Page 226
import lgpio
GPIOChip = lgpio.gpiochip_open(4)
lgpio.gpio_claim_output(GPIOChip, 4)
lgpio.gpio_claim_output(GPIOChip, 17)
while True:
lgpio.gpio_write(GPIOChip, 4, 1)
lgpio.gpio_write(GPIOChip, 17, 0)
lgpio.gpio_write(GPIOChip, 4, 0)
lgpio.gpio_write(GPIOChip, 17, 1)
lgpio.gpiochip_close(GPIOChip)
import lgpio
import time
GPIOChip = lgpio.gpiochip_open(4)
lgpio.tx_pwm(GPIOChip, 4, 1000, 25)
time.sleep(1)
lgpio.tx_pwm(GPIOChip, 4, 1000, 50)
while True:
pass
Page 231
import lgpio
from collections import namedtuple
Pulse = namedtuple('Pulse', ['group_bits', 'group_mask', 'pulse_delay'])
GPIOChip = lgpio.gpiochip_open(4)
lgpio.group_claim_output(GPIOChip, [4,17])
lgpio.tx_wave(GPIOChip, 4,[Pulse(1,3,1000),Pulse(2,3,1000), Pulse(1,3,1000),Pulse(2,3,1000)] )
while True:
pass
Page 232
import lgpio
from collections import namedtuple
Pulse = namedtuple('Pulse', ['group_bits', 'group_mask','pulse_delay'])
GPIOChip = lgpio.gpiochip_open(4)
lgpio.group_claim_output(GPIOChip, [4,17])
while True:
if lgpio.tx_room(GPIOChip,4,lgpio.TX_WAVE)>2:
lgpio.tx_wave(GPIOChip, 4, [Pulse(1,3,1000),Pulse(2,3,1000)])
Page 227 Appendix
settings.json
{
"sshUser": "pi",
"sshEndpoint": "192.168.11.170",
"remoteDirectory": "/home/pi/Documents/",
}
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,
},
},
]
}
launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Remote Attach",
"type": "python",
"connect": {
"host": "localhost",
"port": 5678
},
"pathMappings": [
{
"localRoot": "${workspaceFolder}/
${relativeFileDirname}/",
"remoteRoot": "${config:remoteDirectory}/
${relativeFileDirname}"
}
],
"request": "attach",
"preLaunchTask": "copyAndDebug",
"postDebugTask": "StopREmotePython"
}
]
}