ProgramsGPIO Zero Second Edition

GPIOZero2E360

We have decided not to make the programs available as a download because this is not the point of the book - the programs are not finished production code but something you should type in and study.

The best solution is to provide the source code of the programs in a form that can be copied and pasted into a VS Code project. 

 

Note: The VS Code task listings are at the very end of this page.

The only downside is that you have to create a project to paste the code into.

To do this follow the instructionin the book- in particular remember to add the bcm2835 library and also any library references that may be needed. 

All of the programs below were copy and pasted from working programs in the IDE. They have been formatted using the built in formatter and hence are not identical in layout to the programs in the book. This is to make copy and pasting them easier. The programs in the book are formatted to be easy to read on the page.

If anything you consider important is missing or if you have any requests or comments  contact:

This email address is being protected from spambots. You need JavaScript enabled to view it. 

 


Page 27

 
from gpiozero import Device
Device()
print(Device.pin_factory.board_info.model)

 


Page 32

from gpiozero import LED
from time import sleep

led = LED(4)

while True:
    led.on()
    sleep(1)
    led.off()
    sleep(1)

 

Page 52

from gpiozero import LED
from signal import pause

led = LED(4)
led.blink(on_time=1,off_time=1,n=100)
print("Program Complete")
pause()
 

Page 52

from gpiozero import LED
led = LED(4)
led.blink(on_time=1,off_time=1,n=100,background=False)
print("Program Complete")
 

Page 58

from gpiozero import LED
from time import sleep

led = LED(4)

while True:
    led.toggle()
    sleep(1)
    led.toggle()
    sleep(1)
 

Page 59

from gpiozero import Buzzer
from signal import pause

buzz = Buzzer(4)
buzz.beep(on_time=1,off_time=1,n=100)
print("Program Complete")
pause()
 

Page 61

from gpiozero import DigitalOutputDevice
class Lock(DigitalOutputDevice):
  def __init__(self,*args,**kwargs):
      if 'active_high' in kwargs:
          raise TypeError("active_high not supported")
      super().__init__(*args,**kwargs)            
  def lock(self):
      super().on()
  def unlock(self):
      super().off()
  def on(self):
      raise AttributeError("'Lock' object has no attribute 'on'")
  def off(self):
      raise AttributeError("'Lock' object has no attribute 'off'")
  def blink(self):
      raise AttributeError("'Lock' object has no attribute 'blink'")
 

Page 62

from gpiozero import LED
led1 = LED(4)
led2 = LED(17)
while True:
    led1.on()
    led2.on()
    led1.off()
    led2.off()
 

Page 65

from gpiozero import Device
from time import sleep
Device()
pin=Device.pin_factory.pin(4)
pin._set_function('output')
while True:
    pin.state=1
    sleep(1)
    pin.state=0
    sleep(1) 

Page 70

from gpiozero import Device
Device()
pin = Device.pin_factory.pin(4)
pin._set_function("output")
while True:
    pin.state=1
    pin.state=0
 

 

Page 98

from gpiozero import Button
from signal import pause
button = Button(4, bounce_time=0.25)

def pressed():
    print(“Button pressed”)

def released():
    print(“Button released”)

button.when_pressed = pressed
button.when_released = released
pause()

Page 102

from gpiozero import Button
from gpiozero import LED
from time import sleep

button = Button(4)
led1 = LED(17, initial_value=True)
led2 = LED(27)
led3 = LED(22)

state = 0
buttonState = button.value
while True:
    buttonNow = button.value
    buttonDelta = buttonNow-buttonState
    buttonState = buttonNow
    if state == 0:
        if buttonDelta == 1:
            state = 1
            led1.off()
            led2.on()
            led3.off()

        continue
    if state == 1:
        if buttonDelta == 1:
            state = 2
            led1.off()
            led2.on()
            led3.off()
        continue
    if state == 2:
        if buttonDelta == 1:
            state = 0
            led1.on()
            led2.off()
            led3.off()
        continue
    sleep(0.1)

 

Page 103 

from gpiozero import Button
from time import perf_counter_ns

button = Button(4)
while True:
    button.wait_for_press()
button.wait_for_release()
t1 = perf_counter_ns()
button.wait_for_press()
t2 = perf_counter_ns()
print((t2-t1)/1000000)
 

Page 104 

from gpiozero import Button
from time import perf_counter_ns
button = Button(4)
while True:
    while not button.value:
        pass
    while button.value:
        pass
    t1 = perf_counter_ns()
    while not button.value:
        pass
    t2 = perf_counter_ns()
    print((t2-t1)/1000000)
 

Page 104

from gpiozero import DigitalInputDevice
from time import perf_counter_ns
pulse = DigitalInputDevice(4)
while True:
    while not pulse.value:
        pass
    while pulse.value:
        pass
    t1 = perf_counter_ns()
    while not pulse.value:
        pass
    t2 = perf_counter_ns()
    print((t2-t1)/1000000)
 

Page 105

 
from gpiozero import Device
from time import perf_counter_ns

Device()
pulse = Device.pin_factory.pin(4)
pulse.input_with_pull("up")
while True:
    while not pulse.state:
        pass
    while pulse.state:
        pass
    t1 = perf_counter_ns()
    while not pulse.state:
        pass
    t2 = perf_counter_ns()
    print((t2-t1)/1000000)
 

Page 105

from gpiozero import DigitalInputDevice


class Door(DigitalInputDevice):
    def __init__(self, pin=None, pull_up=True, active_state=None,
                 bounce_time=None, pin_factory=None):
        super(Door, self).__init__(
            pin, pull_up=pull_up, active_state=active_state,
            bounce_time=bounce_time, pin_factory=pin_factory)

    @property
    def value(self):
        return super(Door, self).value


Door.is_closed = Door.is_active
Door.when_open = Door.when_deactivated
Door.when_closed = Door.when_activated
Door.wait_for_open = Door.wait_for_inactive
Door.wait_for_close = Door.wait_for_active
 
 

 

 

Page 116

 
from gpiozero import LightSensor


class Moisture(LightSensor):
    def __init__(self, pin=None, queue_len=5, charge_time_limit=0.01, threshold=0.1, partial=False, pin_factory=None):
        super(Moisture, self).__init__(pin, threshold=threshold, queue_len=queue_len,
                                       charge_time_limit=charge_time_limit, pin_factory=pin_factory)


Moisture.wait_for_dry = Moisture.wait_for_light
Moisture.wait_for_wet = Moisture.wait_for_dark
Moisture.when_dry = Moisture.when_light
Moisture.when_wet = Moisture.when_dark

Page 119

from gpiozero import PWMLED, DistanceSensor
from signal import pause

led=PWMLED(4)
dist=DistanceSensor(5,6)
led.source=dist
pause

Page 121

from gpiozero import PWMLED, DistanceSensor
from gpiozero.tools import inverted
from signal import pause
led = PWMLED(4)
dist = DistanceSensor(5, 6)
led.source = inverted(dist)
pause

Page 121

 
from gpiozero import PWMLED, DistanceSensor
from gpiozero.tools import inverted, averaged
from signal import pause

led = PWMLED(4)
front = DistanceSensor(5, 6)
back = DistanceSensor(7, 8)
led.source = averaged(front, back)
pause

Page 122

from signal import pause
from gpiozero import PWMLED, DistanceSensor
from gpiozero.tools import _normalize


def mined(*values):
    values = [_normalize(v) for v in values]
    for v in zip(*values):
        yield min(v)


led = PWMLED(4)
front = DistanceSensor(5, 6)
back = DistanceSensor(7, 8)
led.source = mined(front, back)
pause

Page 123

def PWM_values(period=360, duty=0.5):
    _ontime = int(period*duty)
    _offtime = period-_ontime
    data = [1]*_ontime+[0]*_offtime
    while True:
        for i in range(_ontime):
            print(1)
            yield 1
        for i in range(_offtime):
            print(0)
            yield 0

Page 126

from gpiozero import LED, CPUTemperature
from signal import pause
from gpiozero.tools import booleanized

cpu = CPUTemperature(min_temp=58, max_temp=90)
print(cpu.temperature)
led=LED(4)
led.source = booleanized(cpu,0,1)
pause()

Page 126

import io
from gpiozero import InternalDevice

class MemoryFree(InternalDevice):
    def __init__(self, threshold=0.9, memfile='/proc/meminfo',
                                               pin_factory=None):
        super(MemoryFree, self).__init__(pin_factory=pin_factory)
        self._fire_events(self.pin_factory.ticks(), None)
        self.memfile = memfile
        self.threshold = threshold
        self._totalmem = 0
        self._availablemem = 0

   
    @property
    def free_mem(self):
        with io.open(self.memfile, 'r') as f:
            self._totalmem = int(f.readline().strip().split()[1])
            freemem = int(f.readline().strip().split()[1])
            self._availablemem = int(f.readline().strip().split()[1])
            return freemem

    @property
    def value(self):
        return self.free_mem/self._availablemem

    @property
    def is_active(self):
        return self.value < 1-self.threshold

Page 127 You need to add the previous class to make this work

from gpiozero import PWMLED
from signal import pause

led = PWMLED(4)

mem = MemoryFree(0.1)
print(mem.value, flush=True)
print(mem.is_active, flush=True)

led.source=mem
pause()

 

Page 134

from gpiozero import PWMOutputDevice
from signal import pause
pwm = PWMOutputDevice(4)
pwm.frequency = 10000
pwm.value = 0.5
pause()

Page 136

from gpiozero import PWMOutputDevice
pwm = PWMOutputDevice(4)
pwm.frequency = 1000
while True:
    pwm.value = 0.1
    pwm.value = 0.9

Page 132

from gpiozero import PWMOutputDevice
from time import sleep
pwm = PWMOutputDevice(4)
pwm.frequency = 1000
pwm.value = 0.1
while True:
    sleep(0.5)
    pwm.toggle()

Page 139

from gpiozero import PWMOutputDevice
from time import sleep

pwm = PWMOutputDevice(4)
pwm.frequency = 1000
steps = 8
delay = 0.01
while True:
    for d in range(steps):
        pwm.value = d/steps
    sleep(delay)

for d in range(steps):
    pwm.value = (steps-d)/steps
    sleep(delay)

Page 145

from gpiozero import PWMOutputDevice
from time import sleep

pwm = PWMOutputDevice(4)
pwm.frequency = 1000
steps = 8
delay = 0.001
while True:
    for d in range(steps):
        pwm.value = d/steps
        sleep(delay)

    for d in range(steps):
        pwm.value = (steps-d)/steps
        sleep(delay)

Page 153

class uniMotor(PWMOutputDevice):
    def __init__(self, pin=None, active_high=True, initial_value=0, pin_factory=None):
        super(uniMotor, self).__init__(pin, active_high, initial_value, pin_factory=pin_factory)

    def speed(self, value):
        self._write(value)

motor = uniMotor(4)
motor.speed(0.5)
sleep(10)

Page 161

from gpiozero import Servo
from time import sleep

servo = Servo(4)

while True:
    servo.min()
    sleep(0.5)
    servo.mid()
    sleep(0.5)
    servo.max()
    sleep(0.5)

Page 162

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 171

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 176

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 177

 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 192

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 194

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)
 
Page 229
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"
        }
    ]
}
 

Clicking on any link opens an HTML page with the program. 

Right click on page and use view source to see code.

Use inspect to see any additional JavaScript loaded. 

Part I

Chapter 2

Page 20 Page 21

Chapter 3

Page 26    Page 28    Page 30 Page 33 Page 34  Page 38  Page 47  Page 49 

Chapter 4

Page 55 Page 57 Page 59 Page 61 Page 63  Page 67  Page 69  Page 70  Page 71  Page 72  Page 73  Page 74  Page 74b  Page 76 

Chapter 5

Page 81  Page 85  Page 86  Page 87  Page 89

Chapter 6

Page 96 Page 97 Page 104

Chapter 7

Page 110 Page 118 Page 126

Part II

Chapter 8

Page 130 Page 132 Page 134 Page 139 Page 140 Page 140b Page 141 Page 145 Page 148 Page 149

Chapter 9

Page 162  Page 165  Page 168  

Chapter 12

Page 201   Page 205   Page 205b   Page 206   Page 208   Page 214  

The file upload examples are listed as text files to avoid priviacy and security issues. 
(IO Press cannot host files users upload without conforming to the GDPR)

Page 216 (text)   Page 217 (text)  Page 218 (text)  Page 219 (text)  Page 221 (text)  Page 222 (text)  Page 224  

Chapter 13

Page 229   Page 230   Page 231  Page 235  Page 239  Page 246

You can use pond.pcx to test the PCX program, page 246. Download it to a suitable directory and then use at as a local file to be processed.

Chapter 14

Page 257 This is the program that starts being built up on page 257 and finishes at page 265 Page 270

Chapter 15

Page 275  Page 285  Page 290  Page 293  Page 298  

IOT Raspberry Pi Programs

We have decided not to make the programs available as a download because this is not the point of the book - the programs are not finished production code but something you should type in and study.

There is also the problem of what happens when NetBeans changes and the downloads no longer work. 

The best solution is to provide the source code of the programs in a form that can be copied and pasted into a NetBeans project. This means that you have some interaction with the code rather than just running it and it means that it is immune to changes in NetBeans.

The only downside is that you have to create a project to paste the code into.

To do this follow the instruction starting on page 31 - in particular remember to add the bcm2835 library as described on page 33.

If anything you consider important is missing or if you have any requests or comments  contact me

This email address is being protected from spambots. You need JavaScript enabled to view it.

 

Page 34

#include <bcm2835.h>
#include <stdio.h> int main(int argc, char **argv) {
 if (!bcm2835_init())
       return 1;
 bcm2835_gpio_fsel(RPI_GPIO_P1_07,BCM2835_GPIO_FSEL_OUTP);
 while (1) { 
  bcm2835_gpio_write(RPI_GPIO_P1_07, HIGH);
  bcm2835_delay(500);
  bcm2835_gpio_write(RPI_GPIO_P1_07, LOW);
  bcm2835_delay(500);
 }
 bcm2835_close();
 return 0;
}

 Page 47

#define _GNU_SOURCE   //added not in first edition
#include <stdlib.h> #include <stdio.h> #include <bcm2835.h> #include <time.h> #define BILLION 1000000000L int main(int argc, char** argv) { struct timespec btime, etime; volatile int i; clock_gettime(CLOCK_REALTIME, &btime); for (i = 0; i < 10000000; i++) { }; clock_gettime(CLOCK_REALTIME, &etime); double nseconds = (double) ((etime.tv_sec - btime.tv_sec)* BILLION)+ (double) (etime.tv_nsec - btime.tv_nsec); int n = (int) 10 / nseconds * BILLION + 0.5; printf("time = %f (s) \n \r", nseconds / BILLION); printf("n= %d \n\r", n); return (EXIT_SUCCESS); }
include <time.h>
int busyWaitCalibrate() {
    struct timespec btime, etime;
    volatile int i;
    clock_gettime(CLOCK_REALTIME, &btime);
    for (i = 0; i < 10000000; i++) {};
    clock_gettime(CLOCK_REALTIME, &etime);
    double nseconds = (double) ((etime.tv_sec – btime.tv_sec)  * 1000000000L)+(double) (etime.tv_nsec - btime.tv_nsec);
    int n = (int) 10 / nseconds * 1000000000L + 0.5;
    return n;
}

Page 49 - See Errata This program doesn't work

#include "bcm2835.h"
#include <stdio.h>
#include <unistd.h>
int main()
{
 bcm2835_init();
 bcm2835_gpio_context pin15 = bcm2835_gpio_init(15);
 bcm2835_gpio_dir(pin15, bcm2835_GPIO_OUT_HIGH);
 bcm2835_gpio_context pin31 = bcm2835_gpio_init(31);
 bcm2835_gpio_dir(pin31, bcm2835_GPIO_OUT_LOW);
 for (;;) {
  bcm2835_gpio_write(pin15, 0);
  bcm2835_gpio_write(pin31, 1);
  bcm2835_gpio_write(pin15, 1);
  bcm2835_gpio_write(pin31, 0);
 }
 return bcm2835_SUCCESS;
 }
}

 

 Page 55

#include <stdio.h>
#include <string.h> int main(int argc, char** argv) { int gpio = 4; FILE* fd = fopen("/sys/class/gpio/export", "w"); fprintf(fd, "%d", gpio); fclose(fd); return 0; }

Page 56 

#include <stdio.h>
#include <string.h>

int main(int argc, char** argv) {
    int gpio = 4;
    char buf[100];

    FILE* fd = fopen("/sys/class/gpio/export", "w");
    fprintf(fd, "%d", gpio);
    fclose(fd);

    sprintf(buf, "/sys/class/gpio/gpio%d/direction", gpio);
    fd = fopen(buf, "w");
    fprintf(fd, "out");
    fclose(fd);

    sprintf(buf, "/sys/class/gpio/gpio%d/value", gpio);
    fd = fopen(buf, "w");

    for (;;) {
        fd = fopen(buf, "w");
        fprintf(fd, "1");
        fclose(fd);
        fd = fopen(buf, "w");
        fprintf(fd, "0");
        fclose(fd);
    }
    return 0;
}

Page 64

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>
#include <sched.h>
#include <sys/mman.h>

int main(int argc, char** argv) {
    const struct sched_param priority = {1};
    sched_setscheduler(0, SCHED_FIFO, &priority);
    mlockall(MCL_CURRENT | MCL_FUTURE);
if (!bcm2835_init()) return 1;
  
bcm2835_gpio_fsel(RPI_GPIO_P1_07,BCM2835_GPIO_FSEL_INPT);

volatile int i;
while (1) {
  while (1 == bcm2835_gpio_lev(RPI_GPIO_P1_07));
        while (0 == bcm2835_gpio_lev(RPI_GPIO_P1_07));
        for (i = 0; i < 5000; i++) {
            if (0 == bcm2835_gpio_lev(RPI_GPIO_P1_07)) break;
        }
        printf("%d\n\r", i); fflush(stdout);
    }

    return (EXIT_SUCCESS);
}

Page 73

 

#include <stdio.h>
#include <string.h>
#include <bcm2835.h>
#include <fcntl.h>
#include <unistd.h>
#include <poll.h>

#define BUFFER_MAX 50
int fd[32] = {0};

int openGPIO(int pin, int direction);
int writeGPIO(int gpio, int value);
int readGPIO(int gpio);
int setEdgeGPIO(int gpio, char *edge);


int main(int argc, char** argv) {
    if (!bcm2835_init())
        return 1;

    openGPIO(4, 0);
    setEdgeGPIO(4, "rising");
    struct pollfd fdset[1];
    for (;;) {

        fdset[0].fd = fd[4];
        fdset[0].events = POLLPRI;
        fdset[0].revents = 0;

        int rc = poll(fdset, 1, 5000);
        if (rc < 0) {
            printf("\npoll() failed!\n");
            return -1;
        }
        if (rc == 0) {
            printf(".");
        }
        if (fdset[0].revents & POLLPRI) {
              lseek(fd[4], 0, SEEK_SET);
              int val=readGPIO(4);
            printf("\npoll() GPIO 4 interrupt occurred %d\n\r",val);

        }
        fflush(stdout);
    }
    return 0;
}

int openGPIO(int gpio, int direction) {
    if (gpio < 0 || gpio > 31) return -1;
    if (direction < 0 || direction > 1)return -2;
    int len;
    char buf[BUFFER_MAX];
    if (fd[gpio] != 0) {
        close(fd[gpio]);
        fd[gpio] = open("/sys/class/gpio/unexport", O_WRONLY);
        len = snprintf(buf, BUFFER_MAX, "%d", gpio);
        write(fd[gpio], buf, len);
        close(fd[gpio]);
        fd[gpio] = 0;
    }

    fd[gpio] = open("/sys/class/gpio/export", O_WRONLY);
    len = snprintf(buf, BUFFER_MAX, "%d", gpio);
    write(fd[gpio], buf, len);
    close(fd[gpio]);
    len = snprintf(buf, BUFFER_MAX,"/sys/class/gpio/gpio%d/direction", gpio);
    fd[gpio] = open(buf, O_WRONLY);
    if (direction == 1) {
        write(fd[gpio], "out", 4);
        close(fd[gpio]);
        len = snprintf(buf, BUFFER_MAX,"/sys/class/gpio/gpio%d/value", gpio);
        fd[gpio] = open(buf, O_WRONLY);

    } else {
        write(fd[gpio], "in", 3);
        close(fd[gpio]);
        len = snprintf(buf, BUFFER_MAX,"/sys/class/gpio/gpio%d/value", gpio);
        fd[gpio] = open(buf, O_RDONLY);
    }
    return 0;
}

int writeGPIO(int gpio, int b) {
    if (b == 0) {
        write(fd[gpio], "0", 1);
    } else {
        write(fd[gpio], "1", 1);
    }

    lseek(fd[gpio], 0, SEEK_SET);
    return 0;
}

int readGPIO(int gpio) {
    char value_str[3];
    int c = read(fd[gpio], value_str, 3);
    lseek(fd[gpio], 0, SEEK_SET);

    if (value_str[0] == '0') {
        return 0;
    } else {
        return 1;
    }

}

int setEdgeGPIO(int gpio, char *edge) {
    char buf[BUFFER_MAX];
    int len = snprintf(buf, BUFFER_MAX,"/sys/class/gpio/gpio%d/edge", gpio);
    int fd = open(buf, O_WRONLY);
    write(fd, edge, strlen(edge) + 1);
    close(fd);
    return 0;
}

Page 92

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <errno.h>

int main(int argc, char** argv) {
int memfd = open("/dev/mem", O_RDWR | O_SYNC);
uint32_t * map = (uint32_t *)mmap(
                    NULL,
                    4*1024,
                    (PROT_READ | PROT_WRITE),
                    MAP_SHARED, 
                    memfd, 
                    0x3f200000);
 if (map == MAP_FAILED)
    printf("bcm2835_init: %s mmap failed: %s\n", strerror(errno));    
close(memfd);

volatile uint32_t* paddr = map;
*paddr=0x1000;
volatile uint32_t* paddr1 = map + 0x1C/4;
volatile uint32_t* paddr2 = map + 0x28/4;
for(;;){
 *paddr1=0x10;
 *paddr2=0x10;
};
    return (EXIT_SUCCESS); 
}

 Page 98

#define CLK_GP0_CTL 28
#define CLK_GP0_DIV 29
void bcm2835_GPIO4_set_clock_source(
           uint32_t source,
           uint32_t divisorI,
           uint32_t divisorF) {
 if (bcm2835_clk == MAP_FAILED)
       return;
 divisorI &= 0xfff;
 divisorF &= 0xfff;
 source &= 0xf;
   
 uint8_t mask=bcm2835_peri_read(bcm2835_clk + CLK_GP0_CTL) & 0xffffffef;
   
 bcm2835_peri_write(bcm2835_clk + CLK_GP0_CTL, BCM2835_PWM_PASSWRD | mask);
    
 while ((bcm2835_peri_read(bcm2835_clk + CLK_GP0_CTL) & 0x80) != 0){};

 bcm2835_peri_write(bcm2835_clk + CLK_GP0_DIV, BCM2835_PWM_PASSWRD | (divisorI << 12) | divisorF);
 bcm2835_peri_write(bcm2835_clk + CLK_GP0_CTL, BCM2835_PWM_PASSWRD |  source|0x200);
 bcm2835_peri_write(bcm2835_clk + CLK_GP0_CTL, BCM2835_PWM_PASSWRD | 0x0210 | source);
}

 

Page 105

#include <bcm2835.h>
#include <stdio.h>
#include <sched.h> 
int main(int argc, char **argv) { if (!bcm2835_init()) return 1; bcm2835_gpio_fsel(RPI_GPIO_P1_07 , BCM2835_GPIO_FSEL_OUTP); while (1) { bcm2835_gpio_write(RPI_GPIO_P1_07 , HIGH); bcm2835_gpio_write(RPI_GPIO_P1_07 , LOW); } bcm2835_close(); return 0; }

 

 Page 107

#include <bcm2835.h>
#include <stdio.h>
#include <sched.h> 
 int main(int argc, char **argv) {
  const struct sched_param priority = {1};
  sched_setscheduler(0, SCHED_FIFO, &priority);
  if (!bcm2835_init()) 
   return 1;
 bcm2835_gpio_fsel(RPI_GPIO_P1_07 ,BCM2835_GPIO_FSEL_OUTP);
 while (1) {
  bcm2835_gpio_write(RPI_GPIO_P1_07 , HIGH);
  bcm2835_gpio_write(RPI_GPIO_P1_07 , LOW);
 }
 bcm2835_close();
 return 0;
}

Page 116 

#include <bcm2835.h>
int main(int argc, char** argv) {
  if (!bcm2835_init())
       return 1;
 bcm2835_gpio_fsel(18,BCM2835_GPIO_FSEL_ALT5 );    
 bcm2835_pwm_set_clock(2);
 bcm2835_pwm_set_mode(0, 1, 1);
 bcm2835_pwm_set_range(0,2);
 bcm2835_pwm_set_data(0,1);
 return (EXIT_SUCCESS);
}

 

Page 117

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>
int main(int argc, char** argv) {
  if (!bcm2835_init())
        return 1;
 bcm2835_gpio_fsel(18,BCM2835_GPIO_FSEL_ALT5 );    
 bcm2835_gpio_fsel(13,BCM2835_GPIO_FSEL_ALT0 );    
 
 bcm2835_pwm_set_clock(2);
 
 bcm2835_pwm_set_mode(0, 1, 1);
 bcm2835_pwm_set_range(0,2);
 bcm2835_pwm_set_data(0,1);
   
 bcm2835_pwm_set_mode(1, 1, 1);
 bcm2835_pwm_set_range(1,8);
 bcm2835_pwm_set_data(1,2);
 return (EXIT_SUCCESS);
}

 

Page 146 

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>
int main(int argc, char** argv) {
if (!bcm2835_init())
        return 1;
 char buf[] = {0xE7};
 bcm2835_i2c_begin ();
 bcm2835_i2c_setSlaveAddress (0x40);
 bcm2835_i2c_write (buf,1);
 bcm2835_i2c_read (buf,1);
 printf("User Register = %X \r\n",buf[0]);
 bcm2835_i2c_end ();
 return (EXIT_SUCCESS);
}

 

 Page 154

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

uint8_t crcCheck(uint8_t msb, uint8_t lsb, uint8_t check);

int main(int argc, char** argv) {
    if (!bcm2835_init())
        return 1;
    bcm2835_i2c_begin();
    bcm2835_i2c_setClockDivider(BCM2835_I2C_CLOCK_DIVIDER_626);
    setTimeout(40000);
    bcm2835_i2c_setSlaveAddress(0x40);
    char buf[4] = {0xE3};
    uint8_t status = bcm2835_i2c_read_register_rs(buf, buf, 3);
    printf("status=%d\n\r",status);
    uint8_t msb = buf[0];
    uint8_t lsb = buf[1];
    uint8_t check = buf[2];
    printf("msb %d\n\rlsb %d\n\rchecksum %d\n\r",msb, lsb,check);
    printf("crc = %d\n\r", crcCheck(msb, lsb, check));
    unsigned int data16 = ((unsigned int) msb << 8) | (unsigned int) (lsb & 0xFC);
    float temp = (float) (-46.85 + (175.72 * data16 / (float) 65536));
    printf("Temperature %f C \n\r", temp);

    buf[0] = 0xF5;
    bcm2835_i2c_write(buf, 1);
    while (bcm2835_i2c_read(buf, 3)==BCM2835_I2C_REASON_ERROR_NACK){
      bcm2835_delayMicroseconds(500);
    };
    msb = buf[0];
    lsb = buf[1];
    check = buf[2];
    printf("msb %d\n\rlsb%d\n\rchecksum %d\n\r",msb,lsb,check);
    printf("crc = %d\n\r", crcCheck(msb, lsb, check));

    data16 = ((unsigned int) msb << 8) | (unsigned int)(lsb & 0xFC);
    float hum = -6 + (125.0 * (float) data16) / 65536;
    printf("Humidity %f %% \n\r", hum);
    bcm2835_i2c_end();
    return (EXIT_SUCCESS);
}

uint8_t crcCheck(uint8_t msb, uint8_t lsb, uint8_t check) {
    uint32_t data32 = ((uint32_t) msb << 16) |
            ((uint32_t) lsb << 8) |
            (uint32_t) check;
    uint32_t divisor = 0x988000;
    int i;
    for (i = 0; i < 16; i++) {
        if (data32 & (uint32_t) 1 << (23 - i))
            data32 ^= divisor;
        divisor >>= 1;
    };
    return (uint8_t) data32;
}

void setTimeout(uint16_t timeout) {
   volatile uint32_t* stimeout = bcm2835_bsc1+BCM2835_BSC_CLKT/4;
   bcm2835_peri_write(stimeout, timeout);
}

 

Page 165

#include <bcm2835.h>
#include <stdio.h>
#include <sched.h>
#include <sys/mman.h>

uint8_t getByte(int b, int buf[]);
void GetDHT22data(uint8_t pin);

int main(int argc, char** argv) {
    const struct sched_param priority = {1};
    sched_setscheduler(0, SCHED_FIFO, &priority);
    mlockall(MCL_CURRENT | MCL_FUTURE);
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_GPIO_P1_07, BCM2835_GPIO_FSEL_INPT);
    bcm2835_delayMicroseconds(1000);
    GetDHT22data(RPI_GPIO_P1_07);
    return 0;
}

void GetDHT22data(uint8_t pin) {
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_write(pin, LOW);
    bcm2835_delayMicroseconds(1000);
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_INPT);
    int i;
    for (i = 1; i < 2000; i++) {
        if (bcm2835_gpio_lev(pin) == 0)break;
    };
    uint64_t t;
    int buf[41];
    int j;
    bcm2835_delayMicroseconds(1);
    for (j = 0; j < 41; j++) {
        for (i = 1; i < 2000; i++) {
            if (bcm2835_gpio_lev(pin) == 1)break;
        };
        t = bcm2835_st_read();
        for (i = 1; i < 2000; i++) {
            if (bcm2835_gpio_lev(pin) == 0) break;
        }
        buf[j] = (bcm2835_st_read() - t) > 50;
    }
    int byte1 = getByte(1, buf);
    int byte2 = getByte(2, buf);
    int byte3 = getByte(3, buf);
    int byte4 = getByte(4, buf);
    int byte5 = getByte(5, buf);
     printf("Checksum %d %d \n\r", byte5, (byte1 + byte2 + byte3 + byte4) & 0xFF);
    float humidity = (float) (byte1 << 8 | byte2) / 10.0;
    printf("Humidity= %f \n\r", humidity);
    float temperature;
    int neg = byte3 & 0x80;
    byte3 = byte3 & 0x7F;
    temperature = (float) (byte3 << 8 | byte4) / 10.0;
    if (neg > 0)temperature = -temperature;
    printf("Temperature= %f \n\r", temperature);
    return;
}
uint8_t getByte(int b, int buf[]) {
    int i;
    uint8_t result = 0;
    b = (b - 1)*8 + 1;
    for (i = b; i <= b + 7; i++) {
        result = result << 1;
        result = result | buf[i];
    }
    return result;
  }

 Page 182

#include <bcm2835.h>
#include <stdio.h>
#include <sched.h>
#include <sys/mman.h>

int presence(uint8_t pin);
void writeByte(uint8_t pin, int byte);
uint8_t crc8(uint8_t *data, uint8_t len);
int readByte(uint8_t pin);
int readiButton(uint8_t pin, uint8_t *data);

int main(int argc, char **argv) {
    const struct sched_param priority = {1};
    sched_setscheduler(0, SCHED_FIFO, &priority);
    mlockall(MCL_CURRENT | MCL_FUTURE);

    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_GPIO_P1_07, BCM2835_GPIO_FSEL_INPT);

    int i;
    uint8_t code[8];
    for (;;) {
        int p = readiButton(RPI_GPIO_P1_07, code);
        if (p == 1) {
            for (i = 0; i < 8; i++) {
                printf("%hhX ", code[i]);
            }
            printf("\n\r");
            fflush(stdout);
        }
        bcm2835_delayMicroseconds(100000);
    };
    bcm2835_close();
    return 0;
}

int presence(uint8_t pin) {
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_write(pin, LOW);
    bcm2835_delayMicroseconds(480);
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_INPT);
    bcm2835_delayMicroseconds(70);
    uint8_t b = bcm2835_gpio_lev(pin);
    bcm2835_delayMicroseconds(410);
    return b;
}

void writeBit(uint8_t pin, int b) {

    int delay1, delay2;
    if (b == 1) {
        delay1 = 6;
        delay2 = 64;
    } else {
        delay1 = 80;
        delay2 = 10;
    }
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_write(pin, LOW);
    bcm2835_delayMicroseconds(delay1);
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_INPT);
    bcm2835_delayMicroseconds(delay2);
}

uint8_t readBit(uint8_t pin) {
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_write(pin, LOW);
    bcm2835_delayMicroseconds(6);
    bcm2835_gpio_fsel(pin, BCM2835_GPIO_FSEL_INPT);
    bcm2835_delayMicroseconds(9);
    uint8_t b = bcm2835_gpio_lev(pin);
    bcm2835_delayMicroseconds(55);
    return b;
}

void writeByte(uint8_t pin, int byte) {
    int i;
    for (i = 0; i < 8; i++) {
        if (byte & 1) {
            writeBit(pin, 1);
        } else {
            writeBit(pin, 0);
        }
        byte = byte >> 1;
    }
}

int readByte(uint8_t pin) {
    int byte = 0;
    int i;
    for (i = 0; i < 8; i++) {
        byte = byte | readBit(pin) << i;
    };
    return byte;
}


uint8_t crc8(uint8_t *data, uint8_t len) {

    uint8_t i;
    uint8_t j;
    uint8_t temp;
    uint8_t databyte;
    uint8_t crc = 0;
    for (i = 0; i < len; i++) {
        databyte = data[i];
        for (j = 0; j < 8; j++) {
            temp = (crc ^ databyte) & 0x01;
            crc >>= 1;
            if (temp)
                crc ^= 0x8C;

            databyte >>= 1;
        }
    }

    return crc;
}

int readiButton(uint8_t pin, uint8_t *data) {
    int b = presence(pin);
    if (b != 0) return 0;
    writeByte(pin, 0x33);
    int i;
    for (i = 0; i < 8; i++) {
        data[i] = readByte(pin);
    }
    uint8_t crc = crc8(data, 8);
    if (crc == 0) return 1;
    return 0; 
}

Page 202

int oneWireScan(uint8_t pin, uint64_t serial[]) {
    static int bitcount = 0;
    static int deviceCount = 0;

    if (bitcount > 63) {
        bitcount = 0;
        deviceCount++;
        return deviceCount;

    }

    if (bitcount == 0) {
        if (presence(pin) == 1) {
            bitcount = 0;
            return deviceCount;
        }
        deviceCount = 0;
        serial[deviceCount] = 0;
        writeByte(pin, 0xF0);
    };

    int b1 = readBit(pin);
    int b2 = readBit(pin);
   
    if (b1 == 0 && b2 == 1) {
        serial[deviceCount] >>= 1;
        writeBit(pin, 0);
        bitcount++;
        oneWireScan(pin, serial);
    };

    if (b1 == 1 && b2 == 0) {
        serial[deviceCount] >>= 1;
        serial[deviceCount] |= 0x8000000000000000LL;
        writeBit(pin, 1);
        bitcount++;
        oneWireScan(pin, serial);

    };

   
 if (b1 == 1 && b2 == 1) {
        bitcount = 0;
        return deviceCount;
    };
    if (b1 == 0 && b2 == 0) {
        serial[deviceCount] >>= 1;
        writeBit(pin, 0);
        int bitposition = bitcount;
        bitcount++;
        oneWireScan(pin, serial);

        bitcount = bitposition;
        if (presence(pin) == 1){
            bitposition=0;
            return 0;
        }
        
        writeByte(pin, 0xF0);
        uint64_t temp = serial[deviceCount - 1] | (0x1LL << (bitcount));
        int i;
        uint64_t bit;
        for (i = 0; i < bitcount+1; i++) {
            bit = temp & 0x01LL;
            temp >>= 1;
            b1 = readBit(pin);
            b2 = readBit(pin);
            writeBit(pin, bit);
            serial[deviceCount] >>= 1;
            serial[deviceCount] |= (bit << 63);
        }
        bitcount++;
        oneWireScan(pin, serial);
    };

    return deviceCount;
}

 

Page 208

int main(int argc, char **argv) {
    const struct sched_param priority = {5};
    sched_setscheduler(0, SCHED_FIFO, &priority);
    mlockall(MCL_CURRENT | MCL_FUTURE);
    if (!bcm2835_init())
        return 1;
    bcm2835_gpio_fsel(RPI_GPIO_P1_07, BCM2835_GPIO_FSEL_INPT);
    uint64_t serial[15];
    int i, j;
    uint8_t *code;
    int crc,d;   
    for (;;) {
        for (j = 0; j < 1000; j++) {
            d = oneWireScan(RPI_GPIO_P1_07, serial);
            if (d != 4)continue;
            crc = 0;
            for (i = 0; i < d; i++) {
                code = (uint8_t*) & serial[i ];
                crc += crc8(code, 8);
            }
            printf("%hho %d %d\n\r", crc, d, j);
            fflush(stdout);
            if (crc == 0)break;
            bcm2835_delayMicroseconds(30000);
        }
        for (i = 0; i < d; i++) {
            printf("%llX \n", serial[i]);
            float temp = getDeviceTemperature(RPI_GPIO_P1_07,serial[i]);
            printf("temperature = %f C \n", temp);
        }
    }

Page 219

#include <stdio.h>
#include <stdlib.h>
#include <bcm2835.h>

int main(int argc, char** argv) {

 if (!bcm2835_init()) {
  return 1;
 }
 if (!bcm2835_spi_begin()) {
  return 1;
 }

 bcm2835_spi_setBitOrder(BCM2835_SPI_BIT_ORDER_MSBFIRST);
 bcm2835_spi_setDataMode(BCM2835_SPI_MODE0);
 bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_65536);
 bcm2835_spi_chipSelect(BCM2835_SPI_CS0);
 bcm2835_spi_setChipSelectPolarity(BCM2835_SPI_CS0, LOW);

 uint8_t read_data = bcm2835_spi_transfer(0xAA);
 if( read_data== 0xAA) printf("data received correctly");
 bcm2835_spi_end();
 bcm2835_close();
 return (EXIT_SUCCESS);
}

Page 247

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h> 
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#include <sys/ioctl.h>

int main(int argc, char** argv) {
 system("sudo systemctl stop This email address is being protected from spambots. You need JavaScript enabled to view it.");
 int sfd = open("/dev/serial0", O_RDWR | O_NOCTTY);
 if (sfd == -1) {
  printf("Error no is : %d\n", errno);
  printf("Error description is : %s\n", strerror(errno));
  return (-1);
 };

 struct termios options;
 tcgetattr(sfd, &options);
 cfsetspeed(&options, B9600);
 cfmakeraw(&options);
 options.c_cflag &= ~CSTOPB;
 options.c_cflag |= CLOCAL;
 options.c_cflag |= CREAD;
 options.c_cc[VTIME]=1; 
 options.c_cc[VMIN]=100;
 tcsetattr(sfd, TCSANOW, &options);
 char buf[] = "hello world";
 char buf2[100];
 int count = write(sfd, buf,strlen(buf));
 usleep(100000);
 int bytes;
 ioctl(sfd, FIONREAD, &bytes);
 if(bytes!=0){
   count = read(sfd, buf2, 100);
}  printf("%s\n\r", buf2);  close(sfd);  return (EXIT_SUCCESS); }

Page 248

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>

int main(int argc, char** argv) {
 system("sudo systemctl stop This email address is being protected from spambots. You need JavaScript enabled to view it.");
 int sfd = open("/dev/serial0", O_RDWR | O_NOCTTY); 
 if (sfd == -1) {
  printf("Error no is : %d\n", errno);
  printf("Error description is : %s\n", strerror(errno));
  return (-1);
 };

 struct termios options;
 tcgetattr(sfd, &options);
 cfsetspeed(&options, B9600);
 cfmakeraw(&options);
 options.c_cflag &= ~CSTOPB;
 options.c_cflag |= CLOCAL;
 options.c_cflag |= CREAD;
 options.c_cc[VTIME]=0;
 options.c_cc[VMIN]=0;

(sfd, TCSANOW, &options);
 char buf[] = "hello world";
 char buf2[100];
 char c;
 int count = write(sfd, buf,strlen(buf)+1);
 int i=0;
 while(1){
  count = read(sfd, &c, 1);
  if(count!=0){
    buf2[i]=c;
    i++;
    if(c==0)break;
  };
 };
 printf("%s\n\r", buf2);close(sfd);
 return (EXIT_SUCCESS);
}

Page 257

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>

#include <unistd.h> int main(int argc, char** argv) {  int sockfd = socket(AF_INET, SOCK_STREAM, 0);  struct sockaddr_in addr;addr.sin_family = AF_INET;  addr.sin_port = htons(80);  addr.sin_addr.s_addr = 0x22d8b85d;  if (connect(sockfd, (struct sockaddr *) &addr, sizeof (addr)) < 0)return -1;  char header[] = "GET /index.html HTTP/1.1\r\nHost:example.org\r\n\r\n";  int n = write(sockfd, header, strlen(header));  char buffer[2048];  n = read(sockfd, buffer, 2048);  printf("%s", buffer);  return (EXIT_SUCCESS); }

Page 263

#define _POSIX_C_SOURCE 200112L
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <string.h> #include <sys/types.h> #include <netinet/in.h> #include <netdb.h>
#include <unistd.h>
int main(int argc, char** argv) {  struct addrinfo hints, *server;  memset(&hints, 0, sizeof hints);  hints.ai_family =  AF_INET;  hints.ai_socktype = SOCK_STREAM;  hints.ai_flags = AI_PASSIVE;  getaddrinfo(NULL, "80", &hints, &server); int sockfd = socket(server->ai_family, server->ai_socktype| SOCK_NONBLOCK, server->ai_protocol);  bind(sockfd, server->ai_addr, server->ai_addrlen);  listen(sockfd, 10);   struct sockaddr_storage client_addr;  socklen_t addr_size = sizeof client_addr;  char headers[] = "HTTP/1.0 200 OK\r\nServer:CPi\r\nContent-type:text/html\r\n\r\n";  char buffer[2048];  char html[] = "<html><head><title>Temperature</title></head><body>{\"humidity\":81%,\"airtemperature\":23.5C}</p></body></html>\r\n";  char data[2048] = {0};  snprintf(data, sizeof data,"%s %s", headers, html);  for (;;) {   int client_fd = accept(sockfd,(struct sockaddr *) &client_addr, &addr_size);   if (client_fd > 0) {    int n = read(client_fd, buffer, 2048);    printf("%s", buffer);    fflush(stdout);    n = write(client_fd, data, strlen(data));    close(client_fd);    }  }  return (EXIT_SUCCESS); }

Page 271

#define _GNU_SOURCE
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h>  #include <termios.h> #include <errno.h>  #include <sys/ioctl.h> #include <time.h> #define blocksize 255 #define DEBUG 1 int sfd; char buf[blocksize]; int initWiFi(); int ATWiFi(); int getBlock(); int main(int argc, char** argv) {  initWiFi(); ATWiFi();  return (EXIT_SUCCESS); }   int initWiFi() { system("sudo systemctl stop This email address is being protected from spambots. You need JavaScript enabled to view it.");  sfd = open("/dev/serial0", O_RDWR | O_NOCTTY);  if (sfd == -1) {   printf("Error no is : %d\n", errno);   printf("Error description is : %s\n", strerror(errno));   return -1;  }  struct termios options;  tcgetattr(sfd, &options);cfsetspeed(&options, B115200);  cfmakeraw(&options);  options.c_cflag &= ~CSTOPB;  options.c_cflag |= CLOCAL;  options.c_cflag |= CREAD;  options.c_cc[VTIME] = 1;  options.c_cc[VMIN] = blocksize; (sfd, TCSANOW, &options); };   int getBlock() {  int bytes;  struct timespec pause;  pause.tv_sec = 0;  pause.tv_nsec = 100000000;  nanosleep(&pause, NULL);  memset(buf, '\0', sizeof (buf));  ioctl(sfd, FIONREAD, &bytes);  if (bytes == 0)return 0;  int count = read(sfd, buf, blocksize - 1);  buf[count] = 0;  if (DEBUG) {   printf("%s", buf);   fflush(stdout);  }  return count; } int ATWiFi() { dprintf(sfd, "AT\r\n");  return getBlock(); }

Page 282

#define _GNU_SOURCE
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h>  #include <fcntl.h>  #include <termios.h> #include <errno.h>  #include <sys/ioctl.h> #include <time.h> #define blocksize 255 #define DEBUG 1int sfd; char buf[blocksize];int initWiFi(); int ATWiFi(); int getBlock(); int getBlocks(int num, char target[]); int getVersionWiFi(); int resetWiFi(); int setUARTWiFi(); int modeWiFi(int mode); int scanWiFi(); int connectWiFi(char ssid[], char pass[]); int getIPWiFi(); int startServerWiFi(); int getWebPageWiFi(char URL[], char page[]);/* int main(int argc, char** argv) {  initWiFi();ATWiFi();  connectWiFi("ssid", "password");  getIPWiFi();  startServerWiFi();  return (EXIT_SUCCESS);  } int initWiFi() {  system("sudo systemctl stop This email address is being protected from spambots. You need JavaScript enabled to view it.";);  sfd = open("/dev/serial0", O_RDWR | O_NOCTTY);  if (sfd == -1) { printf("Error no is : %d\n", errno);   printf("Error description is : %s\n", strerror(errno));   return -1;  }  struct termios options;  tcgetattr(sfd, &options);  cfsetspeed(&options, B115200);  cfmakeraw(&options);  options.c_cflag &= ~CSTOPB;  options.c_cflag |= CLOCAL;  options.c_cflag |= CREAD;  options.c_cc[VTIME] = 1;  options.c_cc[VMIN] = blocksize; (sfd, TCSANOW, &options); }; int ATWiFi() {dprintf(sfd, "AT\r\n");  return getBlock(); } int getVersionWiFi() {  dprintf(sfd, "AT+GMR\r\n"); return getBlock(); } int resetWiFi() {  dprintf(sfd, "AT+RST\r\n");  return getBlock(); } int setUARTWiFi() {  dprintf(sfd, "AT+UART_CUR=115200,8,1,0,0\r\n");  return getBlock(); } int modeWiFi(int mode) {  dprintf(sfd, "AT+CWMODE_CUR=%d\r\n", mode);  return getBlock(); } int scanWiFi() {  dprintf(sfd, "AT+CWLAP\r\n");  return getBlocks(20, "OK"); } int connectWiFi(char ssid[], char pass[]) {  dprintf(sfd, "AT+CWJAP_CUR=\"%s\",\"%s\"\r\n", ssid, pass);  return getBlocks(20, "OK"); } int getIPWiFi() {  dprintf(sfd, "AT+CIFSR\r\n");  return getBlocks(10, "OK"); } int getWebPageWiFi(char URL[], char page[]) {  dprintf(sfd, "AT+CIPSTART=\"TCP\",\"%s\",80\r\n", URL);  if (getBlocks(10, "OK") < 0) return -1;  char http[150];  sprintf(http, "GET %s HTTP/1.1\r\nHost:%s\r\n\r\n", page, URL);  dprintf(sfd, "AT+CIPSEND=%d\r\n", strlen(http));  if (getBlocks(10, ">") < 0) return -1;  dprintf(sfd, "%s", http);  return getBlocks(10, "</html>"); } int startServerWiFi() {  char temp[blocksize];  char id[10];  dprintf(sfd, "AT+CIPMUX=1\r\n");  if (getBlocks(10, "OK") < 0) return -1;  dprintf(sfd, "AT+CIPSERVER=1,80\r\n");  if (getBlocks(10, "OK") < 0) return -1;  char data[] = "HTTP/1.0 200 OK\r\nServer:Pi\r\nContent-type: text/html\r\n\r\n<html><head><title>Temperature</title></head><body><p>{\"humidity\":81%,\"airtemperature\":23.5C}</p></body></html>\r\n";  for (;;) {   if (getBlocks(1, "+IPD") < 0)continue;   char *b = strstr(buf, "+IPD");   b += 5;   strncpy(temp, b, sizeof (temp));   char *e = strstr(temp, ",");   int d = e - temp;   memset(id, '\0', sizeof (id));   strncpy(id, temp, d);   dprintf(sfd, "AT+CIPSEND=%s,%d\r\n",id, strlen(data));   if (getBlocks(10, ">") < 0) return -1;   dprintf(sfd, "%s", data);   if (getBlocks(10, "OK") < 0) return -1;   dprintf(sfd, "AT+CIPCLOSE=%s\r\n", id);   if (getBlocks(10, "OK") < 0) return -1;  } } int getBlock() {  int bytes;  struct timespec pause;  pause.tv_sec = 0;  pause.tv_nsec = 100000000;  nanosleep(&pause, NULL);  memset(buf, '\0', sizeof (buf));  ioctl(sfd, FIONREAD, &bytes);  if (bytes == 0)return 0;  int count = read(sfd, buf, blocksize - 1);  buf[count] = 0;  if (DEBUG) {   printf("%s", buf);   fflush(stdout);  }  return count; } int getBlocks(int num, char target[]) {  int i;  struct timespec pause;  pause.tv_sec = 1;  pause.tv_nsec = 0;  for (i = 0; i < num; i++) {   nanosleep(&pause, NULL);   getBlock();   if (strstr(buf, target))return i;  }  return -1; }