Damit Du nicht den ganzen Code abschreiben musst, findest Du unten die Code-Stücke die auch im iBook sind.
Öffne dazu auf dem Raspberry Pi das Programm Chromium und gehe dort auf diese Seite. Jetzt kannst Du den Code einfach mittels Copy & Paste in den Thonny hinüberkopieren.


S020 led_taster_dim.py
	
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(25, GPIO.OUT, initial=False)
GPIO.setup(4, GPIO.IN)

ledOn = 50  # Anteil von 100, wo die LED leuchtet
dimUp = 1   # 1 = Taster macht heller, -1 0 Taster macht dunkler

print ("Strg+C beendet das Programm")
try:
    while True:
        # Wenn Taster gedrückt:
        if GPIO.input(4)==True:
            # Helligkeit verändern (Leuchtanteil +1 oder -1)
            ledOn = ledOn + dimUp
            # Wenn ganz hell:
            if ledOn >= 100:
                # Dimm-Richtung umkehren
                dimUp = -1
            # Wenn ganz dunkel:
            if ledOn <= 0:
                # Dimm-Richtung umkehren
                dimUp = 1
        # LED einschalten
        GPIO.output(25,True)
        # Ein Blinkzyklus dauert 100*0.0001 s, also 1/100 s)
        # Leucht-Zeitanteil warten
        time.sleep(ledOn*0.0001)
        # LED ausschalten
        GPIO.output(25,False)
        # Rest des Blinkzyklus warten
        time.sleep((100-ledOn)*0.0001)
except KeyboardInterrupt:
    print("Programm abgebrochen.")
    GPIO.cleanup()
    
S035 7seg_segc_dig4_blink.py
	
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)

# Alle Segment-Pins auf Output stellen:
GPIO.setup(4, GPIO.OUT, initial=False)  # Segment A
GPIO.setup(5, GPIO.OUT, initial=False)  # Segment B
GPIO.setup(6, GPIO.OUT, initial=False)  # Segment C
GPIO.setup(12, GPIO.OUT, initial=False)  # Segment D
GPIO.setup(13, GPIO.OUT, initial=False)  # Segment E
GPIO.setup(16, GPIO.OUT, initial=False)  # Segment F
GPIO.setup(17, GPIO.OUT, initial=False)  # Segment G

# Alle Stellen-Pins auf Output stellen:
GPIO.setup(22, GPIO.OUT, initial=True)  # DIG.1
GPIO.setup(23, GPIO.OUT, initial=True)  # DIG.2
GPIO.setup(24, GPIO.OUT, initial=True)  # DIG.3
GPIO.setup(25, GPIO.OUT, initial=True)  # DIG.4

print("Strg+C beendet das Programm")
try:
    while True:
        # Segment C von Dig:4 einschalten:
        GPIO.output(6, True)
        GPIO.output(25, False)
        time.sleep(1)
        # ... und ausschalten
        # (eine der beiden Anweisungen wuerde auch reichen):
        GPIO.output(6, False)
        GPIO.output(25, True)
        time.sleep(1)
except KeyboardInterrupt:
    print("Programm abgebrochen.")
    GPIO.cleanup()
	
S040 7seg_zeigezahl.py
	
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)

# Segment PGIO-Pins:
segA = 4
segB = 5
segC = 6
segD = 12
segE = 13
segF = 16
segG = 17

# Stellen GPIO-Pins:
dig1 = 22
dig2 = 23
dig3 = 24
dig4 = 25

# Alle Segment-Pins und Digit-Pins auf Output stellen:
for seg in [segA, segB, segC, segD, segE, segF, segG]:
    GPIO.setup(seg, GPIO.OUT, initial = False)
for dig in [dig1, dig2, dig3, dig4]:
    GPIO.setup(dig, GPIO.OUT, initial = True)

# Funktion zur Anzeige einer Dezimalziffer an einer bestimmten Stelle:
def zeigeZifferAnStelle(ziffer, stelle):
    # alle Segmente und Stellen ausschalten:
    for seg in [segA, segB, segC, segD, segE, segF, segG]:
        GPIO.output(seg,False)
    for dig in [dig1, dig2, dig3, dig4]:
        GPIO.output(dig,True)
    # gewuenschte Stelle einschalten:
    GPIO.output(stelle,False)
    # Segmente einschalten je nach zu anzuzeigender Dezimalziffer:
    if (ziffer == 0):
        for s in [segA, segB, segC, segD, segE, segF]:
            GPIO.output(s,True)
    if (ziffer == 1):
        for s in [segB, segC]:
            GPIO.output(s,True)
    if (ziffer == 2):
        for s in [segA, segB, segD, segE, segG]:
            GPIO.output(s,True)
    if (ziffer == 3):
        for s in [segA, segB, segC, segD, segG]:
            GPIO.output(s,True)
    if (ziffer == 4):
        for s in [segB, segC, segF, segG]:
            GPIO.output(s,True)
    if (ziffer == 5):
        for s in [segA, segC, segD, segF, segG]:
            GPIO.output(s,True)
    if (ziffer == 6):
        for s in [segA, segC, segD, segE, segF, segG]:
            GPIO.output(s,True)
    if (ziffer == 7):
        for s in [segA, segB, segC]:
            GPIO.output(s,True)
    if (ziffer == 8):
        for s in [segA, segB, segC, segD, segE, segF, segG]:
            GPIO.output(s,True)
    if (ziffer == 9):
        for s in [segA, segB, segC, segD, segF, segG]:
            GPIO.output(s,True)
# end zeigeZifferAnStelle()

print ("Strg+C beendet das Programm")
try:
    while True:
        # Text von Tastatur einlesen:
        s = raw_input("Bitte vierstellige Zahl eingeben:")
        z0 = int(s[3]) # Einer
        z1 = int(s[2]) # Zehner
        z2 = int(s[1]) # Hunderter
        z3 = int(s[0]) # Tausender
        # Zahl 500 mal anzeigen mit Multiplexing:
        # Ein Durchgang dauert 4 x 0.001s = 0.004s.
        # Die Zahl bleibt also 500 x 0.004s = 2s stehen.
        for i in range (1,500):
            # Alle Ziffern nacheinander kurz (0.001 s) aufblinken lassen:
            zeigeZifferAnStelle(z0,dig4)
            time.sleep(0.001)
            zeigeZifferAnStelle(z1,dig3)
            time.sleep(0.001)
            zeigeZifferAnStelle(z2,dig2)
            time.sleep(0.001)
            zeigeZifferAnStelle(z3,dig1)
            time.sleep(0.001)
     # Bemerkung: die Tausender-Ziffer bleibt stehen. Klar wieso?
except KeyboardInterrupt:
    print("Programm abgebrochen.")
    GPIO.cleanup()
	
S048 buzzer_tonleiter_pwm.py
	
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)

GPIO.setup(18, GPIO.OUT)

f = 440.0
p = GPIO.PWM(18,f)
p.start(50)

for i in range (0,24):
    p.ChangeFrequency(f)
    f = f * 1.059463094 # 2^(1/12)
    time.sleep(0.2)
for i in range (0,24):
    p.ChangeFrequency(f)
    f = f / 1.059463094 # 2^(1/12)
    time.sleep(0.2)
p.stop()
GPIO.cleanup()
	
S058 tkinter_led_einaus.py
	
import RPi.GPIO as GPIO
# tkinter Bibliothek importieren:
from tkinter import *

LED = 25
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED,GPIO.OUT)

# Methode zum Einschalten der LED (Event-Handler):
def LedEin():
  GPIO.output(LED,True)

# Methode zum Ausschalten der LED (Event-Handler):
def LedAus():
  GPIO.output(LED,False)
  
# Fenster erzeugen:
win = Tk()
# Titel setzen:
win.title("LED")
# Ein Label hinzufuegen:
l = Label(win, text="Bitte Button klicken, um die LED ein- und auszuschalten")
l.pack()
# Zwei Buttons mit Event-Handler erzeugen:
b1 = Button(win, text="Ein", command=LedEin)
b2 = Button(win, text="Aus", command=LedAus)
# und dem Fenster hinzufuegen (linksbuendig):
b1.pack(side=LEFT)
b2.pack(side=LEFT)
# Hauptschleife starten:
win.mainloop()
# Nach dem Schliessen GPIO aufraeumen:
GPIO.cleanup()
	
S059 tkinter_slider.py
	
from tkinter import *

def show_value(val):
    # Slider-Wert in Label ausgeben:
    l.config(text="Wert = "+str(val))

# Fenster erzeugen:
win = Tk()
win.title("Slider")
# Slider erzeugen mit Bereich und Event-Handler
slider = Scale(win, from_=0, to=100, length = 300, command=show_value, orient=HORIZONTAL)
slider.pack()
#Startwert setzen:
slider.set(23)
# Label erzeugen:
l = Label(win, text="##")
l.pack()
# Hauptschleife starten:
win.mainloop()
	
S062 pygame_key_event.py
	
import pygame
import sys

# Pygame initialisieren:
pygame.init()
# Fenstergroesse festlegen:
pygame.display.set_mode((200,200))

print ("Press Esc to quit")
while True:
    keys=pygame.key.get_pressed()
    if keys[pygame.K_LEFT] :
        print("Left")
    elif keys[pygame.K_RIGHT]:
        print("Right")
    elif keys[pygame.K_a]:
        print("A")
    elif keys[pygame.K_s]:
        print("S")
    elif keys[pygame.K_ESCAPE]:
        pygame.quit()                
        sys.exit()
    # Event-Queue abarbeiten:
    pygame.event.pump()  
	
S062 pygame_key_event2.py
	
import pygame
import sys

# Pygame initialisieren:
pygame.init()
# Fenstergroesse festlegen:
pygame.display.set_mode((200,200))

print ("Press Esc to quit")
while True:
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if (event.key == pygame.K_LEFT or event.key == pygame.K_a):
                print("Left or a")
            elif (event.key == pygame.K_RIGHT or event.key == pygame.K_d):
                print("Right or d")
            elif (event.key == pygame.K_UP or event.key == pygame.K_w):
                print("Up or w")
            elif (event.key == pygame.K_DOWN or event.key == pygame.K_s):
                print("Down or s")
            elif event.key == pygame.K_ESCAPE:
                pygame.quit()                
                sys.exit()
	
S064 pygame_uhr.py
	
import pygame, time
from pygame.locals import *
from math import sin, cos, radians

# Init:
pygame.init()
rot = (255, 0, 0) weiss = (255, 255, 255) schwarz = (0, 0, 0)
canvas = pygame.display.set_mode((400, 400))
canvas.fill(weiss)

# Mittelpunkt der Uhr:
MX = 200
MY = 200
MP = ((MX, MY))

# erzeugt einen Punkt mit Abstand r vom Mittelpunkt
# für t Minuten nach der vollen Stunde
# bzw t Sekunden nach der vollen Minute
def punkt(r, t):
    alpha = radians(t * 6 - 90)
    x1 = int(MX + r * cos(alpha))
    y1 = int(MY + r * sin(alpha))
    return((x1, y1))
# end punkt()

# Minutenmarken:
for i in range(60):
    pygame.draw.circle(canvas, schwarz, punkt(190, i), 2)
# Stundenmarken (bzw 5-Minutenmarken):
for i in range(12):
    pygame.draw.circle(canvas, schwarz, punkt(190, i * 5), 4)

s1 = 0
mainloop = True
while mainloop:
    zeit = time.localtime()
    s = zeit.tm_sec
    m = zeit.tm_min
    h = zeit.tm_hour
    if h > 12:
        h = h - 12
    hm = (h + m / 60.0) * 5
    if s1 != s:
        pygame.draw.circle(canvas, weiss, MP, 182)                # Löschen
        pygame.draw.line(canvas, schwarz, MP, punkt(120, hm), 6)  # Std-Zeiger
        pygame.draw.line(canvas, schwarz, MP, punkt(170, m), 4)   # Min-Zeiger
        pygame.draw.line(canvas, rot, MP, punkt(180, s), 2)       # Sek-Zeiger
        s1 = s
        pygame.display.set_caption("Aktuelle Zeit: " + time.asctime())
        pygame.display.update()
        
        # Event zum Beenden des Programms behandeln:
        for event in pygame.event.get():
            if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
                mainloop = False
        time.sleep(0.1)
pygame.quit()
	
S069 keypad_simple.py
	
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)

col1 = 4
col2 = 5
col3 = 6
cols = [col1, col2, col3]

row1 = 12
row2 = 13
row3 = 16
row4 = 17
rows = [row1, row2, row3, row4]

keys = [
    ['1', '2', '3'],
    ['4', '5', '6'],
    ['7', '8', '9'],
    ['*', '0', '#']]

GPIO.setup(cols, GPIO.OUT, initial = False)
GPIO.setup(rows, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

print ("Strg+C beendet das Programm")
try:
    while True:
        for i in range (0,3) :
            GPIO.output(cols[i],True)
            for k in range (0,4):
                if GPIO.input(rows[k]) == True:
                    print keys [k][i]
                time.sleep(0.01)
            GPIO.output(cols[i],False)
except KeyboardInterrupt:
    print("Programm abgebrochen.")
    GPIO.cleanup()
	
S075 ds18b20_simple.py
	
# Source:
# https://learn.adafruit.com/adafruits-raspberry-pi-lesson-11-ds18b20-temperature-sensing?view=all

import os
import glob
import time
 
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
 
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'
 
def read_temp_raw():
    f = open(device_file, 'r')
    lines = f.readlines()
    f.close()
    return lines
 
def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp = float(temp_string) / 1000.0
        return temp

print ("Strg+C beendet das Programm")
try:
    while True:
        print(read_temp())  
        time.sleep(1)
except KeyboardInterrupt:
    print("Programm beendet.")
	
S081 photocell_simple.py
	
import RPi.GPIO as GPIO
import time
     
GPIO.setmode(GPIO.BCM)

print ("Strg+C beendet das Programm")
try:
  while True:
    # Pin 18 auf Output stellen und auf Wert 0 setzen.
    # Dadurch wird der Kondensator entladen.
    GPIO.setup(18, GPIO.OUT)
    GPIO.output(18, 0)
    time.sleep(0.1)
    # Pin 18 auf Input stellen.
    # Dadurch wird der Ladevorgang des Kondensators gestartet.
    GPIO.setup(18, GPIO.IN)
    # In einer Schleife warten, bis der Kondensator aufgeladen ist.
    # Anzahl Durchgänge zählen.
    n = 0
    while (GPIO.input(18) == 0):
      n += 1
    # Ergebnis ausgeben.
    print(n)
except KeyboardInterrupt:
  GPIO.cleanup()
	
S087 mcp3008_simple.py
	
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)

def readData(channel):
  # read SPI data from MCP3008 chip, 8 possible adc channels (0 thru 7)
  # this function was written by Limor "Ladyada" Fried
  # for Adafruit Industries, (c) 2015
  if ((channel > 7) or (channel < 0)):
    return -1
  GPIO.output(cs, True)
  GPIO.output(clk, False) # start clock low
  GPIO.output(cs, False)  # bring CS low

  command = channel
  command |= 0x18       # start bit + single-ended bit
  command <<= 3         # we only need to send 5 bits here

  for i in range(5):
    if (command & 0x80):
      GPIO.output(din, True)
    else:
      GPIO.output(din, False)
    command <<= 1
    GPIO.output(clk, True)
    GPIO.output(clk, False)

  adcout = 0
  # read in one empty bit, one null bit and 10 ADC bits
  for i in range(12):
    GPIO.output(clk, True)
    GPIO.output(clk, False)
    adcout <<= 1
    if (GPIO.input(dout)):
      adcout |= 0x1

  GPIO.output(cs, True)
        
  adcout >>= 1       # first bit is 'null' so drop it
  return adcout
# end readData()

# Pin-Belegung:
clk = 18
dout = 23
din = 24
cs = 25

GPIO.setup(clk, GPIO.OUT)
GPIO.setup(cs, GPIO.OUT)
GPIO.setup(din, GPIO.OUT)
GPIO.setup(dout, GPIO.IN)

print ("Strg+C beendet das Programm")
try:
  while True:
    potValue = readData(0)
    print(potValue)
    time.sleep(0.1)
except KeyboardInterrupt:
  GPIO.cleanup()
	
S093 example2.php
	
<?php // content="text/plain; charset=utf-8"
require_once ('jpgraph/jpgraph.php');
require_once ('jpgraph/jpgraph_line.php');

// Some (random) data
$ydata = array(11,3,8,12,5,1,9,13,5,7);

// Size of the overall graph
$width=350;
$height=250;

// Create the graph and set a scale.
// These two calls are always required
$graph = new Graph($width,$height);
$graph->SetScale('intlin');

// Setup margin and titles
$graph->SetMargin(40,20,20,40);
$graph->title->Set('Calls per operator');
$graph->subtitle->Set('(March 12, 2008)');
$graph->xaxis->title->Set('Operator');
$graph->yaxis->title->Set('# of calls');

// Create the linear plot
$lineplot=new LinePlot($ydata);

// Add the plot to the graph
$graph->Add($lineplot);

// Display the graph
$graph->Stroke();
?>
	
S096 mcp3008_write_file.py
	
import RPi.GPIO as GPIO
import time
import os
import datetime

GPIO.setmode(GPIO.BCM)


def readData(channel):
    # read SPI data from MCP3008 chip, 8 possible adc channels (0 thru 7)
    # this function was written by Limor "Ladyada" Fried
    # for Adafruit Industries, (c) 2015
    if ((channel > 7) or (channel < 0)):
        return -1
    GPIO.output(cs, True)
    GPIO.output(clk, False)     # start clock low
    GPIO.output(cs, False)      # bring CS low
    command = channel
    command |= 0x18             # start bit + single-ended bit
    command <<= 3               # we only need to send 5 bits here
    for i in range(5):
        if (command & 0x80):
            GPIO.output(din, True)
        else:
            GPIO.output(din, False)
        command <<= 1
        GPIO.output(clk, True)
        GPIO.output(clk, False)
    adcout = 0
    # read in one empty bit, one null bit and 10 ADC bits
    for i in range(12):
        GPIO.output(clk, True)
        GPIO.output(clk, False)
        adcout <<= 1
        if (GPIO.input(dout)):
            adcout |= 0x1
    GPIO.output(cs, True)
    adcout >>= 1                # first bit is 'null' so drop it
    return adcout


# end readData()

# Pin-Belegung:
clk = 18
dout = 23
din = 24
cs = 25

GPIO.setup(clk, GPIO.OUT)
GPIO.setup(cs, GPIO.OUT)
GPIO.setup(din, GPIO.OUT)
GPIO.setup(dout, GPIO.IN)

print("Strg+C beendet das Programm")
try:
    while True:
        # Datei zum Anhaengen oeffnen (Append):
        outfile = open("/tmp/data.txt", 'a')
        potValue = readData(0)
        # t = datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%d %H:%M:%S")
        outfile.write(str(potValue) + "\n")
        outfile.close()
        time.sleep(1)
except KeyboardInterrupt:
    GPIO.cleanup()
	
S097 showdata.php
	
<?php // content="text/plain; charset=utf-8"
require_once ('jpgraph/jpgraph.php');
require_once ('jpgraph/jpgraph_line.php');

// Datenfile in Array lesen:
$ydata = file("/tmp/data.txt");
// Werte in int-Zahlen umwandeln (waren Strings):
$ydata = array_map('intval',$ydata);

// Size of the overall graph
$width=350;
$height=250;

// Create the graph and set a scale.
// These two calls are always required
$graph = new Graph($width,$height);
$graph->SetScale('intlin');

// Setup margin and titles
$graph->SetMargin(40,20,20,40);
$graph->title->Set('Raspi Messdaten');
$graph->xaxis->title->Set('Zeit [s]');
$graph->yaxis->title->Set('Messwert');

// Create the linear plot
$lineplot=new LinePlot($ydata);

// Add the plot to the graph
$graph->Add($lineplot);

// Display the graph
$graph->Stroke();
?>
	
S101 led_einaus_file.py
	
import RPi.GPIO as GPIO
import time
import os

GPIO.setmode(GPIO.BCM)
GPIO.setup(25, GPIO.OUT)
print ("Strg+C beendet das Programm")
try:
    while True:
        if (os.path.exists("/tmp/checkboxon.txt")):
            GPIO.output(25, 1)
        else:
            GPIO.output(25, 0)
        time.sleep(0.1)
except KeyboardInterrupt:
    GPIO.cleanup()
	
S102 checkboxfile.php
			
<?php
error_reporting(E_ALL);
$value = 'off';
if (isset($_GET["myCheckbox"])) { $value = $_GET["myCheckbox"];}
if ($value=='on') {
  // erzeuge (leeres) File:
  touch("/tmp/checkboxon.txt");
} else {
  // loesche File:
  unlink("/tmp/checkboxon.txt");
}
?>
	
	
<body>
  <h1>Turn LED on/off and have fun :-)</h1>
  <form id="myForm" method="get" action="checkboxfile.php">
    <input type="checkbox" name="myCheckbox"
       onclick="document.getElementById('myForm').submit()" 
       <?php if ($value=="on") { echo ' checked'; } ?>
    />
  </form>
</body>