├── .gitignore
├── 03_01_dice.py
├── 03_02_double_dice.py
├── 03_03_double_dice_solution.py
├── 03_04_double_dice_while.py
├── 03_05_double_dice_while_break.py
├── 04_01_list_and_for.py
├── 04_02_polite_function.py
├── 04_03_hello_n.py
├── 04_04_hangman_words.py
├── 04_05_hangman_play.py
├── 04_06_hangman_get_guess.py
├── 04_07_hangman_print_word.py
├── 04_08_hangman_full.py
├── 04_09_hangman_full_solution.py
├── 04_10_stats.py
├── 04_11_except.py
├── 05_01_converter.py
├── 05_02_converter_offset_bad.py
├── 05_03_converters_final.py
├── 06_01_hangman_file.py
├── 06_02_hangman_file_try.py
├── 06_03_file_readline.py
├── 06_04_json_file.py
├── 06_05_weather.py
├── 06_06_weather_summary.py
├── 07_01_hello.py
├── 07_02_temp_gui.py
├── 07_03_temp_final.py
├── 07_04_kitchen_sink.py
├── 07_05_drawing.py
├── 07_06_resizing.py
├── 07_06_yes_no.py
├── 07_07_file_viewer.py
├── 07_07_scrolling.py
├── 07_08_dialogs.py
├── 07_08_file_viewer_menu.py
├── 07_09_color_chooser.py
├── 07_10_menus.py
├── 08_01_hello_pygame.py
├── 08_02_rasp_game_mouse.py
├── 08_03_rasp_game_one.py
├── 08_04_rasp_game_scoring.py
├── 08_05_rasp_game_refactored.py
├── 08_06_rasp_game_final.py
├── 09_01_blink.py
├── 09_02_blink_easy.py
├── 09_03_pwm.py
├── 09_04_switch.py
├── 09_05_resistance.py
├── 10_01_RGB_LED.py
├── 11_01_clock.py
├── 11_02_fancy_clock.py
├── LICENSE
├── README.md
├── ch12
├── 12_01_rover_web.py
├── 12_02_rover_avoiding.py
├── PCA9685.py
├── home.tpl
├── mb_head
└── motor_driver_i2c.py
├── converters.py
├── hangman_words.txt
├── raspberry.jpg
├── spoon.jpg
└── test.png
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | pip-wheel-metadata/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .nox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | *.py,cover
51 | .hypothesis/
52 | .pytest_cache/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | target/
76 |
77 | # Jupyter Notebook
78 | .ipynb_checkpoints
79 |
80 | # IPython
81 | profile_default/
82 | ipython_config.py
83 |
84 | # pyenv
85 | .python-version
86 |
87 | # pipenv
88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
91 | # install all needed dependencies.
92 | #Pipfile.lock
93 |
94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95 | __pypackages__/
96 |
97 | # Celery stuff
98 | celerybeat-schedule
99 | celerybeat.pid
100 |
101 | # SageMath parsed files
102 | *.sage.py
103 |
104 | # Environments
105 | .env
106 | .venv
107 | env/
108 | venv/
109 | ENV/
110 | env.bak/
111 | venv.bak/
112 |
113 | # Spyder project settings
114 | .spyderproject
115 | .spyproject
116 |
117 | # Rope project settings
118 | .ropeproject
119 |
120 | # mkdocs documentation
121 | /site
122 |
123 | # mypy
124 | .mypy_cache/
125 | .dmypy.json
126 | dmypy.json
127 |
128 | # Pyre type checker
129 | .pyre/
130 |
--------------------------------------------------------------------------------
/03_01_dice.py:
--------------------------------------------------------------------------------
1 | #03_01_dice
2 | import random
3 | for x in range(1, 11):
4 | random_number = random.randint(1, 6)
5 | print(random_number)
--------------------------------------------------------------------------------
/03_02_double_dice.py:
--------------------------------------------------------------------------------
1 | #03_02_double_dice
2 | import random
3 | for x in range(1, 11):
4 | throw_1 = random.randint(1, 6)
5 | throw_2 = random.randint(1, 6)
6 | total = throw_1 + throw_2
7 | print(total)
8 | if total == 7:
9 | print('Seven Thrown!')
10 | if total == 11:
11 | print('Eleven Thrown!')
12 | if throw_1 == throw_2:
13 | print('Double Thrown!')
--------------------------------------------------------------------------------
/03_03_double_dice_solution.py:
--------------------------------------------------------------------------------
1 | #03_03_double_dice_solution
2 | import random
3 | for x in range(1, 11):
4 | throw_1 = random.randint(1, 6)
5 | throw_2 = random.randint(1, 6)
6 | total = throw_1 + throw_2
7 | print(total)
8 | if total == 7:
9 | print('Seven Thrown!')
10 | if total == 11:
11 | print('Eleven Thrown!')
12 | if throw_1 == throw_2:
13 | print('Double Thrown!')
14 | if total >= 5 and total <= 9:
15 | print('Not Bad!')
16 | if total > 10:
17 | print('Good Throw!')
18 | if total < 4:
19 | print('Unlucky!')
20 |
--------------------------------------------------------------------------------
/03_04_double_dice_while.py:
--------------------------------------------------------------------------------
1 | #03_04_double_dice_while
2 | import random
3 | throw_1 = random.randint(1, 6)
4 | throw_2 = random.randint(1, 6)
5 | while not (throw_1 == 6 and throw_2 == 6):
6 | total = throw_1 + throw_2
7 | print(total)
8 | throw_1 = random.randint(1, 6)
9 | throw_2 = random.randint(1, 6)
10 | print('Double Six thrown!')
--------------------------------------------------------------------------------
/03_05_double_dice_while_break.py:
--------------------------------------------------------------------------------
1 | #03_05_double_dice_while_break
2 | import random
3 | while True:
4 | throw_1 = random.randint(1, 6)
5 | throw_2 = random.randint(1, 6)
6 | total = throw_1 + throw_2
7 | print(total)
8 | if throw_1 == 6 and throw_2 == 6:
9 | break
10 | print('Double Six thrown!')
--------------------------------------------------------------------------------
/04_01_list_and_for.py:
--------------------------------------------------------------------------------
1 | #04_01_list_and_for
2 | list = [1, 'one', 2, True]
3 | for item in list:
4 | print(item)
5 |
--------------------------------------------------------------------------------
/04_02_polite_function.py:
--------------------------------------------------------------------------------
1 | #04_02_polite_function
2 | def make_polite(sentence):
3 | polite_sentence = sentence + ' please'
4 | return polite_sentence
5 |
6 | print(make_polite('Pass the salt'))
7 |
--------------------------------------------------------------------------------
/04_03_hello_n.py:
--------------------------------------------------------------------------------
1 | #04_03_hello_n
2 | def say_hello(n):
3 | for x in range(0, n):
4 | print('Hello')
5 |
6 | say_hello(5)
--------------------------------------------------------------------------------
/04_04_hangman_words.py:
--------------------------------------------------------------------------------
1 | #04_04_hangman_words
2 | import random
3 |
4 | words = ['chicken', 'dog', 'cat', 'mouse', 'frog']
5 |
6 | def pick_a_word():
7 | return random.choice(words)
8 |
9 | print(pick_a_word())
--------------------------------------------------------------------------------
/04_05_hangman_play.py:
--------------------------------------------------------------------------------
1 | #04_05_hangman_play
2 |
3 | import random
4 |
5 | words = ['chicken', 'dog', 'cat', 'mouse', 'frog']
6 | lives_remaining = 14
7 |
8 | def play():
9 | word = pick_a_word()
10 | while True:
11 | guess = get_guess(word)
12 | if process_guess(guess, word):
13 | print('You win! Well Done!')
14 | break
15 | if lives_remaining == 0:
16 | print('You are Hung!')
17 | print('The word was: ' + word)
18 | break
19 |
20 | def pick_a_word():
21 | return random.choice(words)
22 |
23 | def get_guess(word):
24 | return 'a'
25 |
26 | def process_guess(guess, word):
27 | global lives_remaining
28 | lives_remaining = lives_remaining -1
29 | return False
30 |
31 | play()
--------------------------------------------------------------------------------
/04_06_hangman_get_guess.py:
--------------------------------------------------------------------------------
1 | #04_06_hangman_get_guess
2 |
3 | import random
4 |
5 | words = ['chicken', 'dog', 'cat', 'mouse', 'frog']
6 | lives_remaining = 14
7 |
8 | def play():
9 | word = pick_a_word()
10 | while True:
11 | guess = get_guess(word)
12 | if process_guess(guess, word):
13 | print('You win! Well Done!')
14 | break
15 | if lives_remaining == 0:
16 | print('You are Hung!')
17 | print('The word was: ' + word)
18 | break
19 |
20 | def pick_a_word():
21 | return random.choice(words)
22 |
23 | def get_guess(word):
24 | print_word_with_blanks(word)
25 | print('Lives Remaining: ' + str(lives_remaining))
26 | guess = input(' Guess a letter or whole word?')
27 | return guess
28 |
29 | def process_guess(guess, word):
30 | global lives_remaining
31 | lives_remaining = lives_remaining -1
32 | return False
33 |
34 | def print_word_with_blanks(word):
35 | print('print_word_with_blanks: not done yet')
36 |
37 | play()
--------------------------------------------------------------------------------
/04_07_hangman_print_word.py:
--------------------------------------------------------------------------------
1 | #04_07_hangman_print_word
2 |
3 | import random
4 |
5 | words = ['chicken', 'dog', 'cat', 'mouse', 'frog']
6 | lives_remaining = 14
7 | guessed_letters = ''
8 |
9 | def play():
10 | word = pick_a_word()
11 | while True:
12 | guess = get_guess(word)
13 | if process_guess(guess, word):
14 | print('You win! Well Done!')
15 | break
16 | if lives_remaining == 0:
17 | print('You are Hung!')
18 | print('The word was: ' + word)
19 | break
20 |
21 | def pick_a_word():
22 | return random.choice(words)
23 |
24 | def get_guess(word):
25 | print_word_with_blanks(word)
26 | print('Lives Remaining: ' + str(lives_remaining))
27 | guess = input(' Guess a letter or whole word?')
28 | return guess
29 |
30 | def process_guess(guess, word):
31 | global lives_remaining
32 | global guessed_letters
33 | lives_remaining = lives_remaining - 1
34 | guessed_letters = guessed_letters + guess
35 | return False
36 |
37 | def print_word_with_blanks(word):
38 | display_word = ''
39 | for letter in word:
40 | if guessed_letters.find(letter) > -1:
41 | # letter found
42 | display_word = display_word + letter
43 | else:
44 | # letter not found
45 | display_word = display_word + '-'
46 | print(display_word)
47 |
48 | play()
--------------------------------------------------------------------------------
/04_08_hangman_full.py:
--------------------------------------------------------------------------------
1 | #04_08_hangman_full
2 | import random
3 |
4 | words = ['chicken', 'dog', 'cat', 'mouse', 'frog']
5 | lives_remaining = 14
6 | guessed_letters = ''
7 |
8 |
9 |
10 | def play():
11 | word = pick_a_word()
12 | while True:
13 | guess = get_guess(word)
14 | if process_guess(guess, word):
15 | print('You win! Well Done!')
16 | break
17 | if lives_remaining == 0:
18 | print('You are Hung!')
19 | print('The word was: ' + word)
20 | break
21 |
22 | def pick_a_word():
23 | return random.choice(words)
24 |
25 | def get_guess(word):
26 | print_word_with_blanks(word)
27 | print('Lives Remaining: ' + str(lives_remaining))
28 | guess = input(' Guess a letter or whole word?')
29 | return guess
30 |
31 | def print_word_with_blanks(word):
32 | display_word = ''
33 | for letter in word:
34 | if guessed_letters.find(letter) > -1:
35 | # letter found
36 | display_word = display_word + letter
37 | else:
38 | # letter not found
39 | display_word = display_word + '-'
40 | print(display_word)
41 |
42 | def process_guess(guess, word):
43 | if len(guess) > 1:
44 | return whole_word_guess(guess, word)
45 | else:
46 | return single_letter_guess(guess, word)
47 |
48 |
49 | def whole_word_guess(guess, word):
50 | global lives_remaining
51 | if guess == word:
52 | return True
53 | else:
54 | lives_remaining = lives_remaining - 1
55 | return False
56 |
57 | def single_letter_guess(guess, word):
58 | global guessed_letters
59 | global lives_remaining
60 | if word.find(guess) == -1:
61 | # letter guess was incorrect
62 | lives_remaining = lives_remaining - 1
63 | guessed_letters = guessed_letters + guess
64 | if all_letters_guessed(word):
65 | return True
66 | return False
67 |
68 | def all_letters_guessed(word):
69 | for letter in word:
70 | if guessed_letters.find(letter) == -1:
71 | return False
72 | return True
73 |
74 | play()
--------------------------------------------------------------------------------
/04_09_hangman_full_solution.py:
--------------------------------------------------------------------------------
1 | #04_09_hangman_full_solution
2 | import random
3 |
4 | words = ['chicken', 'dog', 'cat', 'mouse', 'frog']
5 | lives_remaining = 14
6 | guessed_letters = ''
7 |
8 |
9 |
10 | def play():
11 | word = pick_a_word()
12 | while True:
13 | guess = get_guess(word)
14 | if process_guess(guess, word):
15 | print('You win! Well Done!')
16 | break
17 | if lives_remaining == 0:
18 | print('You are Hung!')
19 | print('The word was: ' + word)
20 | break
21 |
22 | def pick_a_word():
23 | return random.choice(words)
24 |
25 | def get_guess(word):
26 | print_word_with_blanks(word)
27 | print('Lives Remaining: ' + str(lives_remaining))
28 | guess = input(' Guess a letter or whole word?')
29 | return guess
30 |
31 | def print_word_with_blanks(word):
32 | display_word = ''
33 | for letter in word:
34 | if guessed_letters.find(letter) > -1:
35 | # letter found
36 | display_word = display_word + letter
37 | else:
38 | # letter not found
39 | display_word = display_word + '-'
40 | print(display_word)
41 |
42 | def process_guess(guess, word):
43 | if len(guess) > 1 and len(guess) == len(word):
44 | return whole_word_guess(guess, word)
45 | else:
46 | return single_letter_guess(guess, word)
47 |
48 |
49 | def whole_word_guess(guess, word):
50 | global lives_remaining
51 | if guess.lower() == word.lower():
52 | return True
53 | else:
54 | lives_remaining = lives_remaining - 1
55 | return False
56 |
57 | def single_letter_guess(guess, word):
58 | global guessed_letters
59 | global lives_remaining
60 | if word.find(guess) == -1:
61 | # letter guess was incorrect
62 | lives_remaining = lives_remaining - 1
63 | guessed_letters = guessed_letters + guess.lower()
64 | if all_letters_guessed(word):
65 | return True
66 | return False
67 |
68 | def all_letters_guessed(word):
69 | for letter in word:
70 | if guessed_letters.find(letter.lower()) == -1:
71 | return False
72 | return True
73 |
74 | play()
--------------------------------------------------------------------------------
/04_10_stats.py:
--------------------------------------------------------------------------------
1 | #04_09_stats
2 | def stats(numbers):
3 | numbers.sort()
4 | return (numbers[0], numbers[-1])
5 |
6 | list = [5, 45, 12, 1, 78]
7 | min, max = stats(list)
8 | print(min)
9 | print(max)
--------------------------------------------------------------------------------
/04_11_except.py:
--------------------------------------------------------------------------------
1 | #04_11_except
2 | try:
3 | list = [1, 2, 3, 4]
4 | list[4]
5 | except IndexError, detail:
6 | print('Oops')
7 |
--------------------------------------------------------------------------------
/05_01_converter.py:
--------------------------------------------------------------------------------
1 | #05_01_converter
2 | class ScaleConverter:
3 |
4 | def __init__(self, units_from, units_to, factor):
5 | self.units_from = units_from
6 | self.units_to = units_to
7 | self.factor = factor
8 |
9 | def description(self):
10 | return 'Convert ' + self.units_from + ' to ' + self.units_to
11 |
12 | def convert(self, value):
13 | return value * self.factor
14 |
15 |
16 |
17 | c1 = ScaleConverter('inches', 'mm', 25)
18 | print(c1.description())
19 | print('converting 2 inches')
20 | print(str(c1.convert(2)) + c1.units_to)
21 |
--------------------------------------------------------------------------------
/05_02_converter_offset_bad.py:
--------------------------------------------------------------------------------
1 | #05_02_converter_offset_bad
2 | class ScaleAndOffsetConverter:
3 |
4 | def __init__(self, units_from, units_to, factor, offset):
5 | self.units_from = units_from
6 | self.units_to = units_to
7 | self.factor = factor
8 | self.offset = offset
9 |
10 | def description(self):
11 | return 'Convert ' + self.units_from + ' to ' + self.units_to
12 |
13 | def convert(self, value):
14 | return value * self.factor + self.offset
15 |
16 | c2 = ScaleAndOffsetConverter('C', 'F', 1.8, 32)
17 | print(c2.description())
18 | print('converting 20C')
19 | print(str(c2.convert(20)) + c2.units_to)
20 |
--------------------------------------------------------------------------------
/05_03_converters_final.py:
--------------------------------------------------------------------------------
1 | #05_03_converters_final
2 | class ScaleConverter:
3 |
4 | def __init__(self, units_from, units_to, factor):
5 | self.units_from = units_from
6 | self.units_to = units_to
7 | self.factor = factor
8 |
9 | def description(self):
10 | return 'Convert ' + self.units_from + ' to ' + self.units_to
11 |
12 | def convert(self, value):
13 | return value * self.factor
14 |
15 | class ScaleAndOffsetConverter(ScaleConverter):
16 |
17 | def __init__(self, units_from, units_to, factor, offset):
18 | ScaleConverter.__init__(self, units_from, units_to, factor)
19 | self.offset = offset
20 |
21 | def convert(self, value):
22 | return value * self.factor + self.offset
23 |
24 | c1 = ScaleConverter('inches', 'mm', 25)
25 | print(c1.description())
26 | print('converting 2 inches')
27 | print(str(c1.convert(2)) + c1.units_to)
28 |
29 | c2 = ScaleAndOffsetConverter('C', 'F', 1.8, 32)
30 | print(c2.description())
31 | print('converting 20C')
32 | print(str(c2.convert(20)) + c2.units_to)
--------------------------------------------------------------------------------
/06_01_hangman_file.py:
--------------------------------------------------------------------------------
1 | #06_01_hangman_file
2 | import random
3 |
4 | f = open('prog_pi_ed3/hangman_words.txt')
5 | words = f.read().splitlines()
6 | f.close()
7 |
8 | lives_remaining = 14
9 | guessed_letters = ''
10 |
11 |
12 |
13 | def play():
14 | word = pick_a_word()
15 | while True:
16 | guess = get_guess(word)
17 | if process_guess(guess, word):
18 | print('You win! Well Done!')
19 | break
20 | if lives_remaining == 0:
21 | print('You are Hung!')
22 | print('The word was: ' + word)
23 | break
24 |
25 | def pick_a_word():
26 | word_position = random.randint(0, len(words) - 1)
27 | return words[word_position]
28 |
29 | def get_guess(word):
30 | print_word(word)
31 | print('Lives Remaining: ' + str(lives_remaining))
32 | guess = input(' Guess a letter or whole word?')
33 | return guess
34 |
35 | def print_word(word):
36 | display_word = ''
37 | for letter in word:
38 | if guessed_letters.find(letter) > -1:
39 | display_word = display_word + letter
40 | else:
41 | display_word = display_word + '-'
42 | print(display_word)
43 |
44 | def process_guess(guess, word):
45 | if len(guess) > 1:
46 | return whole_word_guess(guess, word)
47 | else:
48 | return single_letter_guess(guess, word)
49 |
50 |
51 | def whole_word_guess(guess, word):
52 | global lives_remaining
53 | if guess == word:
54 | return True
55 | else:
56 | lives_remaining = lives_remaining - 1
57 |
58 | def single_letter_guess(guess, word):
59 | global guessed_letters
60 | global lives_remaining
61 | if word.find(guess) == -1:
62 | lives_remaining = lives_remaining - 1
63 | guessed_letters = guessed_letters + guess
64 | if all_letters_guessed(word):
65 | return True
66 |
67 | def all_letters_guessed(word):
68 | for letter in word:
69 | if guessed_letters.find(letter) == -1:
70 | return False
71 | return True
72 |
73 | play()
--------------------------------------------------------------------------------
/06_02_hangman_file_try.py:
--------------------------------------------------------------------------------
1 | #06_02_hangman_file_try
2 | import random
3 |
4 | words_file = 'prog_pi_ed3/hangman_words.txt'
5 | try:
6 | f = open(words_file)
7 | words = f.read().splitlines()
8 | f.close()
9 | except IOError:
10 | print("Cannot find file: " + words_file)
11 | exit()
12 |
13 |
14 | lives_remaining = 14
15 | guessed_letters = ''
16 |
17 |
18 |
19 | def play():
20 | word = pick_a_word()
21 | while True:
22 | guess = get_guess(word)
23 | if process_guess(guess, word):
24 | print('You win! Well Done!')
25 | break
26 | if lives_remaining == 0:
27 | print('You are Hung!')
28 | print('The word was: ' + word)
29 | break
30 |
31 | def pick_a_word():
32 | word_position = random.randint(0, len(words) - 1)
33 | return words[word_position]
34 |
35 | def get_guess(word):
36 | print_word(word)
37 | print('Lives Remaining: ' + str(lives_remaining))
38 | guess = input(' Guess a letter or whole word?')
39 | return guess
40 |
41 | def print_word(word):
42 | display_word = ''
43 | for letter in word:
44 | if guessed_letters.find(letter) > -1:
45 | display_word = display_word + letter
46 | else:
47 | display_word = display_word + '-'
48 | print(display_word)
49 |
50 | def process_guess(guess, word):
51 | if len(guess) > 1:
52 | return whole_word_guess(guess, word)
53 | else:
54 | return single_letter_guess(guess, word)
55 |
56 |
57 | def whole_word_guess(guess, word):
58 | global lives_remaining
59 | if guess == word:
60 | return True
61 | else:
62 | lives_remaining = lives_remaining - 1
63 |
64 | def single_letter_guess(guess, word):
65 | global guessed_letters
66 | global lives_remaining
67 | if word.find(guess) == -1:
68 | lives_remaining = lives_remaining - 1
69 | guessed_letters = guessed_letters + guess
70 | if all_letters_guessed(word):
71 | return True
72 |
73 | def all_letters_guessed(word):
74 | for letter in word:
75 | if guessed_letters.find(letter) == -1:
76 | return False
77 | return True
78 |
79 | play()
--------------------------------------------------------------------------------
/06_03_file_readline.py:
--------------------------------------------------------------------------------
1 | #06_03_file_readline
2 | words_file = 'hangman_words.txt'
3 | try:
4 | f = open(words_file)
5 | line = f.readline()
6 | while line != '':
7 | if line == 'elephant\n':
8 | print('There is an elephant in the file')
9 | break
10 | line = f.readline()
11 | f.close()
12 | except IOError:
13 | print("Cannot find file: " + words_file)
14 |
--------------------------------------------------------------------------------
/06_04_json_file.py:
--------------------------------------------------------------------------------
1 | #06_04_json_file
2 | import json
3 |
4 | f = open('books.json')
5 | j = json.load(f)
6 | f.close()
7 |
8 | print(j['books'][1]['title'])
--------------------------------------------------------------------------------
/06_05_weather.py:
--------------------------------------------------------------------------------
1 | #06_05_weather
2 | import json
3 | import urllib.parse, urllib.request
4 |
5 | url = 'http://api.weatherstack.com/current'
6 | city = urllib.parse.quote('San Francisco')
7 | key = '03121fa790d2f1d5c6a9a32fa968ffeb' # paste_your_key_here'
8 |
9 | response = urllib.request.urlopen(url + '?access_key=' + key + '&query=' + city)
10 | j = json.load(response)
11 |
12 | print(j)
--------------------------------------------------------------------------------
/06_06_weather_summary.py:
--------------------------------------------------------------------------------
1 | #06_06_weather_summary
2 | import json
3 | import urllib.parse, urllib.request
4 |
5 | url = 'http://api.weatherstack.com/current'
6 | city = urllib.parse.quote('San Francisco')
7 | key = '03121fa790d2f1d5c6a9a32fa968ffeb' # paste_your_key_here'
8 |
9 | response = urllib.request.urlopen(url + '?access_key=' + key + '&query=' + city)
10 | j = json.load(response)
11 |
12 | print(j['current']['weather_descriptions'][0])
--------------------------------------------------------------------------------
/07_01_hello.py:
--------------------------------------------------------------------------------
1 | #07_01_hello.py
2 |
3 | from guizero import App, Text
4 |
5 | app = App()
6 | Text(app, text="Hello World")
7 | app.display()
--------------------------------------------------------------------------------
/07_02_temp_gui.py:
--------------------------------------------------------------------------------
1 | #07_02_temp_gui.py
2 |
3 | from guizero import *
4 |
5 | app = App(title="Temp Converter", layout="grid", width=300, height=100)
6 | Text(app, text="degrees C", grid=[0,0])
7 | degCfield = TextBox(app, grid=[1,0], width="fill")
8 |
9 | Text(app, text="degrees F", grid=[0,1])
10 | degFfield = Text(app, grid=[1,1])
11 |
12 | button = PushButton(app, text="Convert", grid=[0,2])
13 |
14 | app.display()
--------------------------------------------------------------------------------
/07_03_temp_final.py:
--------------------------------------------------------------------------------
1 | #07_03_temp_final.py
2 |
3 | from guizero import *
4 | from converters import ScaleAndOffsetConverter
5 |
6 | c_to_f_conv = ScaleAndOffsetConverter('C', 'F', 1.8, 32)
7 |
8 | def convert():
9 | c = float(degCfield.value)
10 | degFfield.value = str(c_to_f_conv.convert(c))
11 |
12 | app = App(title="Temp Converter", layout="grid", width=300, height=100)
13 | Text(app, text="degrees C", grid=[0,0])
14 | degCfield = TextBox(app, grid=[1,0], width="fill")
15 |
16 | Text(app, text="degrees F", grid=[0,1])
17 | degFfield = Text(app, grid=[1,1])
18 |
19 | button = PushButton(app, text="Convert", grid=[0,2], command=convert)
20 |
21 | app.display()
--------------------------------------------------------------------------------
/07_04_kitchen_sink.py:
--------------------------------------------------------------------------------
1 | #07_04_kitchen_sink.py
2 |
3 | from guizero import *
4 |
5 | app = App(title="Kitchen Sink", layout="grid", width=400, height=400)
6 |
7 | # Row 0
8 | Text(app, text="Label", grid=[0,0])
9 | TextBox(app, grid=[1,0])
10 | PushButton(app, text="Button", grid=[2,0])
11 |
12 | # Row 1
13 | CheckBox(app, text="Checkbox", grid=[0,1])
14 | ListBox(app, items=["red", "green", "blue"], grid=[1,1])
15 | Combo(app, options=["red", "green", "blue"], grid=[2,1])
16 |
17 | # Row 2
18 | ButtonGroup(app, options=["portrait", "landscape"], selected="portrait", grid=[0,2])
19 | Slider(app, start=0, end=10, grid=[1,2])
20 | Picture(app, image="prog_pi_ed3/test.png", width=100, height=100, grid=[2,2])
21 |
22 | app.display()
--------------------------------------------------------------------------------
/07_05_drawing.py:
--------------------------------------------------------------------------------
1 | #07_05_drawing.py
2 |
3 | from guizero import *
4 |
5 | app = App(width=400, height=200)
6 | drawing = Drawing(app, width="fill", height="fill")
7 | drawing.rectangle(20, 20, 300, 100, color="blue")
8 | drawing.oval(30, 50, 290, 190, color='#ff2277')
9 | drawing.line(0, 0, 400, 200, color='black', width=5)
10 | drawing.text(20, 100, "Hello World", color="green", font="Times", size=48)
11 | app.display()
12 |
--------------------------------------------------------------------------------
/07_06_resizing.py:
--------------------------------------------------------------------------------
1 | #07_06_resizing.py
2 |
3 | from tkinter import *
4 |
5 | class App:
6 |
7 | def __init__(self, master):
8 | frame = Frame(master)
9 | frame.pack(fill=BOTH, expand=1)
10 | #Listbox
11 | listbox = Listbox(frame)
12 | for item in ['red', 'green', 'blue', 'yellow', 'pink']:
13 | listbox.insert(END, item)
14 | listbox.grid(row=0, column=0, sticky=W+E+N+S)
15 |
16 | #Message
17 | text = Text(frame, relief=SUNKEN)
18 | text.grid(row=0, column=1, sticky=W+E+N+S)
19 | text.insert(END, 'word ' * 100)
20 | frame.columnconfigure(1, weight=1)
21 | frame.rowconfigure(0, weight=1)
22 | root = Tk()
23 | app = App(root)
24 | root.geometry("400x300+0+0")
25 | root.mainloop()
26 |
--------------------------------------------------------------------------------
/07_06_yes_no.py:
--------------------------------------------------------------------------------
1 | #07_06_yes_no.py
2 |
3 | from guizero import *
4 |
5 | def ask():
6 | if yesno("Question", "Yes or No?"):
7 | info("Result", "You clicked Yes")
8 | else:
9 | warn("Result", "You clicked No")
10 |
11 | app = App()
12 | button = PushButton(app, text="Click Me", command=ask)
13 | app.display()
--------------------------------------------------------------------------------
/07_07_file_viewer.py:
--------------------------------------------------------------------------------
1 | #07_07_file_viewer
2 |
3 | from guizero import *
4 |
5 | def ask():
6 | filename = select_file(title="Choose a text file", filetypes=[["*.md", "*.txt"]])
7 | if not filename:
8 | print("No file selected")
9 | else:
10 | read_file(filename)
11 |
12 | def read_file(filename):
13 | f = open(filename)
14 | text = f.read()
15 | f.close()
16 | text_area.value = text
17 |
18 | app = App(width=600, height=200)
19 | text_area = TextBox(app, width="fill", height=10, multiline=True, scrollbar=True)
20 | button = PushButton(app, text="Open", command=ask)
21 | app.display()
--------------------------------------------------------------------------------
/07_07_scrolling.py:
--------------------------------------------------------------------------------
1 | #07_07_scrolling.py
2 |
3 | from tkinter import *
4 |
5 | class App:
6 |
7 | def __init__(self, master):
8 | scrollbar = Scrollbar(master)
9 | scrollbar.pack(side=RIGHT, fill=Y)
10 | text = Text(master, yscrollcommand=scrollbar.set)
11 | text.pack(side=LEFT, fill=BOTH)
12 | text.insert(END, 'word ' * 1000)
13 | scrollbar.config(command=text.yview)
14 |
15 | root = Tk()
16 | root.wm_title('Scrolling')
17 | app = App(root)
18 | root.mainloop()
19 |
--------------------------------------------------------------------------------
/07_08_dialogs.py:
--------------------------------------------------------------------------------
1 | #07_08_gen_dialogs.py
2 |
3 | from tkinter import *
4 | import tkinter.messagebox as mb
5 |
6 | class App:
7 |
8 | def __init__(self, master):
9 | b=Button(master, text='Press Me', command=self.info).pack()
10 |
11 | def info(self):
12 | mb.showinfo('Information', "Please don't press that button again!")
13 |
14 | root = Tk()
15 | app = App(root)
16 | root.mainloop()
17 |
--------------------------------------------------------------------------------
/07_08_file_viewer_menu.py:
--------------------------------------------------------------------------------
1 | #07_08_file_viewer_menu.py
2 |
3 | from guizero import *
4 |
5 | def ask_file():
6 | filename = select_file(title="Choose a text file", filetypes=[["*.md", "*.txt"]])
7 | if not filename:
8 | print("No file selected")
9 | else:
10 | read_file(filename)
11 |
12 | def save_file():
13 | print("not implemented")
14 |
15 | def find():
16 | print("not implemented")
17 |
18 | def read_file(filename):
19 | f = open(filename)
20 | text = f.read()
21 | f.close()
22 | text_area.value = text
23 |
24 | app = App(width=600, height=200)
25 | menubar = MenuBar(app,
26 | toplevel=["File", "Edit"],
27 | options=[
28 | [ ["Open", ask_file], ["Save", save_file], ["Quit", app.destroy]],
29 | [ ["Find", find]]
30 | ])
31 | text_area = TextBox(app, width="fill", height=10, multiline=True, scrollbar=True)
32 | app.display()
--------------------------------------------------------------------------------
/07_09_color_chooser.py:
--------------------------------------------------------------------------------
1 | #07_09_color_chooser.py
2 |
3 | from tkinter import *
4 | import tkinter.colorchooser as cc
5 |
6 | class App:
7 |
8 | def __init__(self, master):
9 | b=Button(master, text='Color..', command=self.ask_color).pack()
10 |
11 | def ask_color(self):
12 | (rgb, hx) = cc.askcolor()
13 | print("rgb=" + str(rgb) + " hx=" + hx)
14 |
15 | root = Tk()
16 | app = App(root)
17 | root.mainloop()
18 |
--------------------------------------------------------------------------------
/07_10_menus.py:
--------------------------------------------------------------------------------
1 | #07_10_menus.py
2 |
3 | from tkinter import *
4 |
5 | class App:
6 |
7 | def __init__(self, master):
8 | self.entry_text = StringVar()
9 | Entry(master, textvariable=self.entry_text).pack()
10 |
11 | menubar = Menu(root)
12 |
13 | filemenu = Menu(menubar, tearoff=0)
14 | filemenu.add_command(label='Quit', command=exit)
15 | menubar.add_cascade(label='File', menu=filemenu)
16 |
17 | editmenu = Menu(menubar, tearoff=0)
18 | editmenu.add_command(label='Fill', command=self.fill)
19 | menubar.add_cascade(label='Edit', menu=editmenu)
20 |
21 | master.config(menu=menubar)
22 |
23 | def fill(self):
24 | self.entry_text.set('abc')
25 |
26 | root = Tk()
27 | app = App(root)
28 |
29 | root.mainloop()
30 |
31 |
--------------------------------------------------------------------------------
/08_01_hello_pygame.py:
--------------------------------------------------------------------------------
1 | #08_01_hello_pygame.py
2 |
3 | import pygame
4 |
5 | pygame.init()
6 |
7 | screen = pygame.display.set_mode((200, 200))
8 | screen.fill((255, 255, 255))
9 | pygame.display.set_caption('Hello Pygame')
10 |
11 | raspberry = pygame.image.load('prog_pi_ed3/raspberry.jpg').convert()
12 | screen.blit(raspberry, (100, 100))
13 |
14 | pygame.display.update()
15 |
--------------------------------------------------------------------------------
/08_02_rasp_game_mouse.py:
--------------------------------------------------------------------------------
1 | #08_02_rasp_game_mouse
2 |
3 | import pygame
4 | from pygame.locals import *
5 |
6 | spoon_x = 300
7 | spoon_y = 300
8 |
9 | pygame.init()
10 |
11 | screen = pygame.display.set_mode((600, 400))
12 | pygame.display.set_caption('Raspberry Catching')
13 |
14 | spoon = pygame.image.load('prog_pi_ed3/spoon.jpg').convert()
15 |
16 | while True:
17 |
18 | for event in pygame.event.get():
19 | if event.type == QUIT:
20 | pygame.quit()
21 |
22 | screen.fill((255, 255, 255))
23 | spoon_x, ignore = pygame.mouse.get_pos()
24 | screen.blit(spoon, (spoon_x, spoon_y))
25 |
26 | pygame.display.update()
27 |
--------------------------------------------------------------------------------
/08_03_rasp_game_one.py:
--------------------------------------------------------------------------------
1 | #08_03_rasp_game_one
2 |
3 | import pygame
4 | from pygame.locals import *
5 | import random
6 |
7 | screen_width = 600
8 | screen_height = 400
9 |
10 | spoon_x = 300
11 | spoon_y = screen_height - 100
12 |
13 | raspberry_x = random.randint(10, screen_width)
14 | raspberry_y = 0
15 |
16 | pygame.init()
17 |
18 | screen = pygame.display.set_mode((screen_width, screen_height))
19 | pygame.display.set_caption('Raspberry Catching')
20 |
21 | spoon = pygame.image.load('prog_pi_ed3/spoon.jpg').convert()
22 | raspberry = pygame.image.load('prog_pi_ed3/raspberry.jpg').convert()
23 |
24 | def update_spoon():
25 | global spoon_x
26 | global spoon_y
27 | spoon_x, ignore = pygame.mouse.get_pos()
28 | screen.blit(spoon, (spoon_x, spoon_y))
29 |
30 | def update_raspberry():
31 | global raspberry_x
32 | global raspberry_y
33 | raspberry_y += 5
34 | if raspberry_y > spoon_y:
35 | raspberry_y = 0
36 | raspberry_x = random.randint(10, screen_width)
37 | raspberry_x += random.randint(-5, 5)
38 | if raspberry_x < 10:
39 | raspberry_x = 10
40 | if raspberry_x > screen_width - 20:
41 | raspberry_x = screen_width - 20
42 | screen.blit(raspberry, (raspberry_x, raspberry_y))
43 |
44 | while True:
45 | for event in pygame.event.get():
46 | if event.type == QUIT:
47 | pygame.quit()
48 |
49 | screen.fill((255, 255, 255))
50 | update_raspberry()
51 | update_spoon()
52 | pygame.display.update()
--------------------------------------------------------------------------------
/08_04_rasp_game_scoring.py:
--------------------------------------------------------------------------------
1 | #08_04_rasp_game_scoring
2 |
3 | import pygame
4 | from pygame.locals import *
5 | import random
6 |
7 | score = 0
8 |
9 | screen_width = 600
10 | screen_height = 400
11 |
12 | spoon_x = 300
13 | spoon_y = screen_height - 100
14 |
15 | raspberry_x = random.randint(10, screen_width)
16 | raspberry_y = 0
17 |
18 | pygame.init()
19 |
20 | screen = pygame.display.set_mode((screen_width, screen_height))
21 | pygame.display.set_caption('Raspberry Catching')
22 |
23 | spoon = pygame.image.load('prog_pi_ed3/spoon.jpg').convert()
24 | raspberry = pygame.image.load('prog_pi_ed3/raspberry.jpg').convert()
25 |
26 | def update_spoon():
27 | global spoon_x
28 | global spoon_y
29 | spoon_x, ignore = pygame.mouse.get_pos()
30 | screen.blit(spoon, (spoon_x, spoon_y))
31 |
32 | def update_raspberry():
33 | global raspberry_x
34 | global raspberry_y
35 | raspberry_y += 5
36 | if raspberry_y > spoon_y:
37 | raspberry_y = 0
38 | raspberry_x = random.randint(10, screen_width)
39 | raspberry_x += random.randint(-5, 5)
40 | if raspberry_x < 10:
41 | raspberry_x = 10
42 | if raspberry_x > screen_width - 20:
43 | raspberry_x = screen_width - 20
44 | screen.blit(raspberry, (raspberry_x, raspberry_y))
45 |
46 | def check_for_catch():
47 | global score
48 | if raspberry_y >= spoon_y and raspberry_x >= spoon_x and \
49 | raspberry_x < spoon_x + 50:
50 | score += 1
51 | display("Score: " + str(score))
52 |
53 | def display(message):
54 | font = pygame.font.Font(None, 36)
55 | text = font.render(message, 1, (10, 10, 10))
56 | screen.blit(text, (0, 0))
57 |
58 | while True:
59 |
60 | for event in pygame.event.get():
61 | if event.type == QUIT:
62 | pygame.quit()
63 |
64 | screen.fill((255, 255, 255))
65 | update_raspberry()
66 | update_spoon()
67 | check_for_catch()
68 | pygame.display.update()
69 |
70 |
--------------------------------------------------------------------------------
/08_05_rasp_game_refactored.py:
--------------------------------------------------------------------------------
1 | #08_05_rasp_game_refactored
2 |
3 | import pygame
4 | from pygame.locals import *
5 |
6 | import random
7 |
8 | score = 0
9 |
10 | screen_width = 600
11 | screen_height = 400
12 |
13 | spoon_x = 300
14 | spoon_y = screen_height - 100
15 |
16 | class Raspberry:
17 | x = 0
18 | y = 0
19 |
20 | def __init__(self):
21 | self.x = random.randint(10, screen_width)
22 | self.y = 0
23 |
24 | def update(self):
25 | self.y += 5
26 | if self.y > spoon_y:
27 | self.y = 0
28 | self.x = random.randint(10, screen_width)
29 | self.x += random.randint(-5, 5)
30 | if self.x < 10:
31 | self.x = 10
32 | if self.x > screen_width - 20:
33 | self.x = screen_width - 20
34 | screen.blit(raspberry_image, (self.x, self.y))
35 |
36 | def is_caught(self):
37 | return self.y >= spoon_y and self.x >= spoon_x and self.x < spoon_x + 50
38 |
39 | clock = pygame.time.Clock()
40 | r = Raspberry()
41 |
42 | pygame.init()
43 |
44 | screen = pygame.display.set_mode((screen_width, screen_height))
45 | pygame.display.set_caption('Raspberry Catching')
46 |
47 | spoon = pygame.image.load('prog_pi_ed3/spoon.jpg').convert()
48 | raspberry_image = pygame.image.load('prog_pi_ed3/raspberry.jpg').convert()
49 |
50 | def update_spoon():
51 | global spoon_x
52 | global spoon_y
53 | spoon_x, ignore = pygame.mouse.get_pos()
54 | screen.blit(spoon, (spoon_x, spoon_y))
55 |
56 | def check_for_catch():
57 | global score
58 | if r.is_caught():
59 | score += 1
60 |
61 | def display(message):
62 | font = pygame.font.Font(None, 36)
63 | text = font.render(message, 1, (10, 10, 10))
64 | screen.blit(text, (0, 0))
65 |
66 | while True:
67 |
68 | for event in pygame.event.get():
69 | if event.type == QUIT:
70 | pygame.quit()
71 |
72 | screen.fill((255, 255, 255))
73 | r.update()
74 | update_spoon()
75 | check_for_catch()
76 | display("Score: " + str(score))
77 | pygame.display.update()
78 | clock.tick(30)
79 |
80 |
--------------------------------------------------------------------------------
/08_06_rasp_game_final.py:
--------------------------------------------------------------------------------
1 | #08_06_rasp_game_final
2 |
3 | import pygame
4 | from pygame.locals import *
5 | import random
6 |
7 | score = 0
8 |
9 | screen_width = 600
10 | screen_height = 400
11 |
12 | spoon_x = 300
13 | spoon_y = screen_height - 100
14 |
15 | class Raspberry:
16 | x = 0
17 | y = 0
18 | dy = 0
19 |
20 | def __init__(self):
21 | self.x = random.randint(10, screen_width)
22 | self.y = 0
23 | self.dy = random.randint(3, 10)
24 |
25 | def update(self):
26 | self.y += self.dy
27 | if self.y > spoon_y:
28 | self.y = 0
29 | self.x = random.randint(10, screen_width)
30 | self.x += random.randint(-5, 5)
31 | if self.x < 10:
32 | self.x = 10
33 | if self.x > screen_width - 20:
34 | self.x = screen_width - 20
35 | screen.blit(raspberry_image, (self.x, self.y))
36 |
37 | def is_caught(self):
38 | return self.y >= spoon_y and self.x >= spoon_x and self.x < spoon_x + 50
39 |
40 | clock = pygame.time.Clock()
41 | rasps = [Raspberry(), Raspberry(), Raspberry()]
42 |
43 | pygame.init()
44 |
45 | screen = pygame.display.set_mode((screen_width, screen_height))
46 | pygame.display.set_caption('Raspberry Catching')
47 |
48 | spoon = pygame.image.load('prog_pi_ed3/spoon.jpg').convert()
49 | raspberry_image = pygame.image.load('prog_pi_ed3/raspberry.jpg').convert()
50 |
51 | def update_spoon():
52 | global spoon_x
53 | global spoon_y
54 | spoon_x, ignore = pygame.mouse.get_pos()
55 | screen.blit(spoon, (spoon_x, spoon_y))
56 |
57 | def check_for_catch():
58 | global score
59 | for r in rasps:
60 | if r.is_caught():
61 | score += 1
62 |
63 | def display(message):
64 | font = pygame.font.Font(None, 36)
65 | text = font.render(message, 1, (10, 10, 10))
66 | screen.blit(text, (0, 0))
67 |
68 | while True:
69 | for event in pygame.event.get():
70 | if event.type == QUIT:
71 | pygame.quit()
72 |
73 | screen.fill((255, 255, 255))
74 | for r in rasps:
75 | r.update()
76 | update_spoon()
77 | check_for_catch()
78 | display("Score: " + str(score))
79 | pygame.display.update()
80 | clock.tick(30)
81 |
--------------------------------------------------------------------------------
/09_01_blink.py:
--------------------------------------------------------------------------------
1 | #09_01_blink.py
2 |
3 | import gpiozero, time
4 |
5 | led = gpiozero.LED(18)
6 |
7 | while True:
8 | led.on()
9 | time.sleep(0.5) # delay 0.5 seconds
10 | led.off()
11 | time.sleep(0.5)
--------------------------------------------------------------------------------
/09_02_blink_easy.py:
--------------------------------------------------------------------------------
1 | #09_02_blink_easy.py
2 |
3 | import gpiozero, time
4 |
5 | led = gpiozero.LED(18)
6 |
7 | led.blink(on_time=0.5, off_time=0.5)
--------------------------------------------------------------------------------
/09_03_pwm.py:
--------------------------------------------------------------------------------
1 | #09_03_pwm.py
2 |
3 | import gpiozero
4 |
5 | led = gpiozero.PWMLED(18)
6 |
7 | while True:
8 | duty_s = input("Enter Brightness (0 to 100):")
9 | duty = float(duty_s) / 100.0
10 | led.value = duty
--------------------------------------------------------------------------------
/09_04_switch.py:
--------------------------------------------------------------------------------
1 | #09_04_switch.py
2 |
3 | import gpiozero, time
4 |
5 | switch = gpiozero.Button(23, pull_up=True)
6 |
7 | while True:
8 | if switch.is_pressed:
9 | print("Button Pressed")
10 | time.sleep(0.2)
--------------------------------------------------------------------------------
/09_05_resistance.py:
--------------------------------------------------------------------------------
1 | #09_05_resistance.py
2 |
3 | from PiAnalog import *
4 | import time
5 |
6 | p = PiAnalog()
7 |
8 | while True:
9 | print(p.read_resistance())
10 | time.sleep(1)
--------------------------------------------------------------------------------
/10_01_RGB_LED.py:
--------------------------------------------------------------------------------
1 | # 10_01_RGB_LED.py
2 |
3 | from gpiozero import RGBLED
4 | from guizero import App, Slider, Text
5 | from colorzero import Color
6 |
7 | rgb_led = RGBLED(18, 23, 24)
8 |
9 | red = 0
10 | green = 0
11 | blue = 0
12 |
13 | def red_changed(value):
14 | global red
15 | red = int(value)
16 | rgb_led.color = Color(red, green, blue)
17 |
18 | def green_changed(value):
19 | global green
20 | green = int(value)
21 | rgb_led.color = Color(red, green, blue)
22 |
23 | def blue_changed(value):
24 | global blue
25 | blue = int(value)
26 | rgb_led.color = Color(red, green, blue)
27 |
28 | app = App(title='RGB LED', width=500, height=400, layout='grid')
29 |
30 | Text(app, text='Red', grid=[0,0]).text_size = 30
31 | Slider(app, command=red_changed, end=255, width=350, height=50, grid=[1,0]).text_size = 30
32 | Text(app, text='Green', grid=[0,1]).text_size = 30
33 | Slider(app, command=green_changed, end=255, width=350, height=50, grid=[1,1]).text_size = 30
34 | Text(app, text='Blue', grid=[0,2]).text_size = 30
35 | Slider(app, command=blue_changed, end=255, width=350, height=50, grid=[1,2]).text_size = 30
36 |
37 | app.display()
--------------------------------------------------------------------------------
/11_01_clock.py:
--------------------------------------------------------------------------------
1 | # 11_01_clock.py
2 |
3 | import board, time
4 | from adafruit_ht16k33.segments import Seg7x4
5 | from datetime import datetime
6 |
7 | i2c = board.I2C()
8 | display = Seg7x4(i2c)
9 | display.brightness = 0.3
10 | show_colon = True
11 |
12 | while True:
13 | now = datetime.now()
14 | current_time = now.strftime("%H:%M")
15 | display.print(current_time)
16 | if show_colon:
17 | display.colon = True
18 | show_colon = False
19 | else:
20 | display.colon = False
21 | show_colon = True
22 | time.sleep(0.5)
--------------------------------------------------------------------------------
/11_02_fancy_clock.py:
--------------------------------------------------------------------------------
1 | # 11_02_fancy_clock.py
2 |
3 | import board, time, gpiozero
4 | from adafruit_ht16k33.segments import Seg7x4
5 | from datetime import datetime
6 |
7 | switch = gpiozero.Button(23, pull_up=True)
8 | i2c = board.I2C()
9 | display = Seg7x4(i2c)
10 | display.brightness = 0.3
11 | show_colon = True
12 | time_mode, seconds_mode, date_mode = range(3)
13 | disp_mode = time_mode
14 |
15 | def display_time():
16 | global show_colon
17 | now = datetime.now()
18 | current_time = now.strftime("%H:%M")
19 | display.print(current_time)
20 | if show_colon:
21 | display.colon = True
22 | show_colon = False
23 | else:
24 | display.colon = False
25 | show_colon = True
26 | time.sleep(0.5)
27 |
28 | def display_seconds():
29 | now = datetime.now()
30 | current_seconds = now.strftime(" %S")
31 | display.print(current_seconds)
32 | time.sleep(0.5)
33 |
34 | def display_date():
35 | now = datetime.now()
36 | current_date = now.strftime("%m%d")
37 | display.print(current_date)
38 | time.sleep(0.5)
39 |
40 | while True:
41 | if switch.is_pressed:
42 | disp_mode = disp_mode + 1
43 | if disp_mode > date_mode:
44 | disp_mode = time_mode
45 | if disp_mode == time_mode:
46 | display_time()
47 | elif disp_mode == seconds_mode:
48 | display_seconds()
49 | elif disp_mode == date_mode:
50 | display_date()
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 Simon Monk
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # The Code Examples for Programming Raspberry Pi: Getting Started with Sketched - third edition.
2 |
3 | The third edition of the book switched from IDLE to Mu, so you should clone or extract this code into /home/pi/mu_code
4 |
5 |
--------------------------------------------------------------------------------
/ch12/12_01_rover_web.py:
--------------------------------------------------------------------------------
1 | # 12_01_rover_web.py
2 |
3 | from bottle import route, run, template, request
4 | from motor_driver_i2c import MotorDriver
5 |
6 | motors = MotorDriver()
7 |
8 | # Handler for the home page
9 | @route('/')
10 | def index():
11 | cmd = request.GET.get('command', '')
12 | if cmd == 'f':
13 | motors.forward()
14 | elif cmd == 'l':
15 | motors.left(0, 0.5) # turn at half speed
16 | elif cmd == 's':
17 | motors.stop()
18 | elif cmd == 'r':
19 | motors.right(0, 0.5)
20 | elif cmd == 'b':
21 | motors.reverse(0, 0.3) # reverse slowly
22 | return template('home.tpl')
23 |
24 | run(host="0.0.0.0", port=80)
25 |
--------------------------------------------------------------------------------
/ch12/12_02_rover_avoiding.py:
--------------------------------------------------------------------------------
1 | # 12_02_rover_avoiding.py
2 | from gpiozero import DistanceSensor
3 | from motor_driver_i2c import MotorDriver
4 | import time, random
5 |
6 | motors = MotorDriver()
7 | rangefinder = DistanceSensor(echo=18, trigger=17)
8 |
9 | def turn_randomly():
10 | turn_time = random.randint(1, 3)
11 | if random.randint(1, 2) == 1:
12 | motors.left(turn_time)
13 | else:
14 | motors.right(turn_time)
15 | motors.stop()
16 |
17 | while True:
18 | distance = rangefinder.distance * 100 # convert to cm
19 | print(distance)
20 | if distance < 20:
21 | motors.stop()
22 | elif distance < 50:
23 | turn_randomly()
24 | else:
25 | motors.forward()
26 | time.sleep(0.2)
27 |
--------------------------------------------------------------------------------
/ch12/PCA9685.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 |
3 | import time
4 | import math
5 | import smbus
6 |
7 | # ============================================================================
8 | # Raspi PCA9685 16-Channel PWM Servo Driver
9 | # ============================================================================
10 |
11 | class PCA9685:
12 |
13 | # Registers/etc.
14 | __SUBADR1 = 0x02
15 | __SUBADR2 = 0x03
16 | __SUBADR3 = 0x04
17 | __MODE1 = 0x00
18 | __PRESCALE = 0xFE
19 | __LED0_ON_L = 0x06
20 | __LED0_ON_H = 0x07
21 | __LED0_OFF_L = 0x08
22 | __LED0_OFF_H = 0x09
23 | __ALLLED_ON_L = 0xFA
24 | __ALLLED_ON_H = 0xFB
25 | __ALLLED_OFF_L = 0xFC
26 | __ALLLED_OFF_H = 0xFD
27 |
28 | def __init__(self, address, debug=False):
29 | self.bus = smbus.SMBus(1)
30 | self.address = address
31 | self.debug = debug
32 | if (self.debug):
33 | print("Reseting PCA9685")
34 | self.write(self.__MODE1, 0x00)
35 |
36 | def write(self, reg, value):
37 | "Writes an 8-bit value to the specified register/address"
38 | self.bus.write_byte_data(self.address, reg, value)
39 | if (self.debug):
40 | print("I2C: Write 0x%02X to register 0x%02X" % (value, reg))
41 |
42 | def read(self, reg):
43 | "Read an unsigned byte from the I2C device"
44 | result = self.bus.read_byte_data(self.address, reg)
45 | if (self.debug):
46 | print("I2C: Device 0x%02X returned 0x%02X from reg 0x%02X" % (self.address, result & 0xFF, reg))
47 | return result
48 |
49 | def setPWMFreq(self, freq):
50 | "Sets the PWM frequency"
51 | prescaleval = 25000000.0 # 25MHz
52 | prescaleval = prescaleval / 4096.0 # 12-bit
53 | prescaleval = prescaleval / float(freq)
54 | prescaleval = prescaleval - 1.0
55 | if (self.debug):
56 | print("Setting PWM frequency to %d Hz" % freq)
57 | print("Estimated pre-scale: %d" % prescaleval)
58 | prescale = math.floor(prescaleval + 0.5)
59 | if (self.debug):
60 | print("Final pre-scale: %d" % prescale)
61 |
62 | oldmode = self.read(self.__MODE1);
63 | newmode = (oldmode & 0x7F) | 0x10 # sleep
64 | self.write(self.__MODE1, newmode) # go to sleep
65 | self.write(self.__PRESCALE, int(math.floor(prescale)))
66 | self.write(self.__MODE1, oldmode)
67 | time.sleep(0.005)
68 | self.write(self.__MODE1, oldmode | 0x80)
69 |
70 | def setPWM(self, channel, on, off):
71 | "Sets a single PWM channel"
72 | self.write(self.__LED0_ON_L + 4*channel, on & 0xFF)
73 | self.write(self.__LED0_ON_H + 4*channel, 0xff & (on >> 8))
74 | self.write(self.__LED0_OFF_L + 4*channel, off & 0xFF)
75 | self.write(self.__LED0_OFF_H + 4*channel, 0xff & (off >> 8))
76 | if (self.debug):
77 | print("channel: %d LED_ON: %d LED_OFF: %d" % (channel,on,off))
78 |
79 | def setDutycycle(self, channel, pulse):
80 | self.setPWM(channel, 0, int(pulse * int(4096 / 100)))
81 |
82 | def setLevel(self, channel, value):
83 | if (value == 1):
84 | self.setPWM(channel, 0, 4095)
85 | else:
86 | self.setPWM(channel, 0, 0)
87 |
88 | # pwm = PCA9685(0x5f, debug=False)
89 | # pwm.setPWMFreq(50)
90 | # pwm.setDutycycle(0,100)
91 | # pwm.setLevel(1,0)
92 | # pwm.setLevel(2,1)
93 |
--------------------------------------------------------------------------------
/ch12/home.tpl:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
16 |
17 |
45 |
46 |
47 |
48 | Web Rover
49 |
50 |
51 | W
52 | A
53 | S
54 | D
55 |
56 | Z
57 |
58 |
59 |
60 |
61 |
62 |
--------------------------------------------------------------------------------
/ch12/mb_head:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | Animatronic Head Kit for micro:bit - Monk Makes
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
41 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
71 |
72 |
73 |
76 |
77 |
82 |
83 |
84 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
121 |
122 |
125 |
138 |
139 |
140 |
141 |
150 |
151 |
152 |
153 |
154 |
Skip to content
155 |
178 |
179 |
180 |
181 |
185 |
186 |
187 |
308 |
309 |
310 |
323 |
324 |
325 | This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish.Accept Read More Privacy & Cookies Policy
326 |
327 |
332 |
335 |
336 |
337 |
338 |
339 |
344 |
345 |
346 |
347 |
348 |
349 |
350 |
351 |
356 |
357 |
358 |
359 |
364 |
365 |
366 |
367 |
--------------------------------------------------------------------------------
/ch12/motor_driver_i2c.py:
--------------------------------------------------------------------------------
1 | # Class for motor control of Waveshare Motor pHAT
2 |
3 | from PCA9685 import PCA9685
4 | import time
5 |
6 | pwm = PCA9685(0x40, debug=False)
7 | pwm.setPWMFreq(50)
8 |
9 | class MotorDriver():
10 | def __init__(self):
11 | self.PWMA = 0
12 | self.AIN1 = 1
13 | self.AIN2 = 2
14 | self.PWMB = 5
15 | self.BIN1 = 3
16 | self.BIN2 = 4
17 |
18 | def set_motors(self, left_pwm, left_dir, right_pwm, right_dir):
19 | pwm.setDutycycle(self.PWMA, left_pwm * 100)
20 | if left_dir == 1:
21 | pwm.setLevel(self.AIN1, 0)
22 | pwm.setLevel(self.AIN2, 1)
23 | else:
24 | pwm.setLevel(self.AIN1, 1)
25 | pwm.setLevel(self.AIN2, 0)
26 | pwm.setDutycycle(self.PWMB, right_pwm * 100)
27 | if right_dir == 1:
28 | pwm.setLevel(self.BIN1, 0)
29 | pwm.setLevel(self.BIN2, 1)
30 | else:
31 | pwm.setLevel(self.BIN1, 1)
32 | pwm.setLevel(self.BIN2, 0)
33 |
34 | def forward(self, seconds=0, speed=1.0):
35 | self.set_motors(speed, 0, speed, 0)
36 | if seconds > 0:
37 | time.sleep(seconds)
38 | self.stop()
39 |
40 | def stop(self):
41 | self.set_motors(0, 0, 0, 0)
42 |
43 | def reverse(self, seconds=0, speed=1.0):
44 | self.set_motors(speed, 1, speed, 1)
45 | if seconds > 0:
46 | time.sleep(seconds)
47 | self.stop()
48 |
49 | def left(self, seconds=0, speed=0.5):
50 | self.set_motors(speed, 0, speed, 1)
51 | if seconds > 0:
52 | time.sleep(seconds)
53 | self.stop()
54 |
55 | def right(self, seconds=0, speed=0.5):
56 | self.set_motors(speed, 1, speed, 0)
57 | if seconds > 0:
58 | time.sleep(seconds)
59 | self.stop()
60 |
61 | # m = MotorDriver()
62 | # m.set_motors(1, 1, 0.25, 0)
63 | # input("stop")
64 | # m.stop()
65 | # input("forward")
66 | # m.forward(3, 0.5)
67 | # input("stop")
68 | # m.stop()
69 | # input("left")
70 | # m.left(5)
71 | # input("stop")
72 | # m.stop()
73 |
--------------------------------------------------------------------------------
/converters.py:
--------------------------------------------------------------------------------
1 | #05_03_converters_final
2 | class ScaleConverter:
3 |
4 | def __init__(self, units_from, units_to, factor):
5 | self.units_from = units_from
6 | self.units_to = units_to
7 | self.factor = factor
8 |
9 | def description(self):
10 | return 'Convert ' + self.units_from + ' to ' + self.units_to
11 |
12 | def convert(self, value):
13 | return value * self.factor
14 |
15 | class ScaleAndOffsetConverter(ScaleConverter):
16 |
17 | def __init__(self, units_from, units_to, factor, offset):
18 | ScaleConverter.__init__(self, units_from, units_to, factor)
19 | self.offset = offset
20 |
21 | def convert(self, value):
22 | return value * self.factor + self.offset
23 |
--------------------------------------------------------------------------------
/hangman_words.txt:
--------------------------------------------------------------------------------
1 | elephant
2 | cat
3 | tiger
4 | dog
5 | lion
6 | horse
7 | giraffe
8 | bird
9 | deers
--------------------------------------------------------------------------------
/raspberry.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/simonmonk/prog_pi_ed3/d1d0f645dcba77f2bb9f6859fd0e15b9647b147d/raspberry.jpg
--------------------------------------------------------------------------------
/spoon.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/simonmonk/prog_pi_ed3/d1d0f645dcba77f2bb9f6859fd0e15b9647b147d/spoon.jpg
--------------------------------------------------------------------------------
/test.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/simonmonk/prog_pi_ed3/d1d0f645dcba77f2bb9f6859fd0e15b9647b147d/test.png
--------------------------------------------------------------------------------