-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPiLabs.tex
More file actions
1964 lines (1355 loc) · 89.9 KB
/
PiLabs.tex
File metadata and controls
1964 lines (1355 loc) · 89.9 KB
1
2
3
4
5
6
7
8
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
% LaTeX source for ``Introduction to Computer Science (Java/Pi Edition)''
% Copyright (c) 2015- David S. Read, All Rights Reserved
\chapter{Raspberry Pi Labs}
\section{A Platform for Experimentation and Learning}
\index{Raspberry Pi}
In the early days of home computing the machines were very basic and packaged software was limited to
some simple games and very basic office tools. Many computers were targeted at hobbyists who would
write their own programs. There was no Internet full of information and media to consume,
so the computer was a device for active experimentation rather than passive entertainment.
Over the years computers have become more sophisticated, expensive and central to many household operations
(such as paying bills) while the Internet grew up and provided a nearly inexhaustible amount
of content and functionality to use and explore. Computers transitioned from experimental
workshops for hobbyists to a common appliance, leveraged by all family members for a variety
of purposes.
The Raspberry Pi\footnote{Another small computing device good for experimentation is the Arduino} was created
by several individuals who work in the computer science field and felt that having an affordable
computer for basic experimentation would be of interest to the general public. It appears they were correct
given the increasing popularity of the Pi, including its use in production environments.
This chapter will introduce you to the Raspberry Pi 3 while providing a series of lab exercises for you
to complete. The labs are intended to meet two goals:
\begin{itemize}
\item Have some fun building simple circuits and interacting with them using programs you write.
\item Reinforce the principles of object oriented programming by associating physical objects (LEDs and buttons)
with virtual objects (instances of classes) and seeing how the attributes and behaviors in the
virtual environments manifest in the physical world.
\end{itemize}
\section{Introducing the Raspberry Pi 3}
\begin{figure}[H]
\centering
% \begin{mdframed}
\includegraphics[height=3.50in]{pi_images/Raspi-3-Layout.jpg}
% \end{mdframed}
\caption{The Raspberry Pi 3 with key components labeled}
\label{fig:raspberrypi3}
\end{figure}
Hereafter I'll generally refer to the Raspberry Pi as the Pi.
The Pi is a great environment for learning about computing devices and programming. It has several key
advantages over programming on a general computer system:
\begin{itemize}
\item it is a relatively inexpensive full-featured computing device
\item it is capable of running a variety of commodity software development tools
\item it provides access to input and output signals via its General Purpose Input/Output (GPIO) connector
\end{itemize}
The first two advantages are straightforward. The GPIO interface deserves a little more definition.
\section{GPIO - General Purpose Input/Output}
\index{GPIO}
We often interact with computers using screens, keyboards and mice. Sometimes we use other input devices
such as scanners and drawing tablets. We can output information to printers or other computers across a network.
Often that is the limit of our direct computer interactions. However, inside the computer there are
a variety of electrical signals being used to communicate between the computer's components. These core components, which
we discussed in chapter 0, include the CPU, main memory, disk drives and network cards.
Typically we don't have any easy way to interface directly with these types of signals. For example, many computers
have a light which indicates when the disk drive is being accessed. Generally we don't have access to that
electrical signal, we just see the light flickering.
The Pi's J8 GPIO interface allows us to attach devices to the Pi and use them for input and output. For example
we can connect an LED to a GPIO pin and then write a program that turns the LED on and off. Similarly we
can connect a button to another GPIO pin and use the button as a signal for a program to take a certain
action when the button is pressed.
Figure~\ref{fig:j8header} is a close-up of the GPIO J8 40-pin interface that depicts several pin numbers (these are \textbf{\textit{not}} the GPIO numbers, which we'll see shortly). The pins are simply numbered sequentially:
\begin{figure}[H]
\centering
% \begin{mdframed}
\includegraphics[height=1.30in]{pi_images/j8header-photo-transparentbg.png}
% \end{mdframed}
\caption{Raspberry Pi 3's J8 Header with several pins labeled}
\label{fig:j8header}
\end{figure}
To allow our programs to interface with the pins we need a way to identify which physical pins we want to
control from within our program. The Pi uses a numbering scheme where the controllable pins are assigned
a GPIO number. Unfortunately different versions of the Pi have used different GPIO numbering schemes.
To
deal with this numbering confusion, the Java library we will be using, known as Pi4J\footnote{Short for \textbf{Pi \textit{for} Java}. You can read more about this library at \url{http://pi4j.com/}}, assigns consistent GPIO numbers to the
pins regardless of which Pi device we are using.
\pagebreak
Figure~\ref{fig:pi4jgpio} depicts the GPIO numbers assigned by the Pi4J library. We will use these numbers throughout the chapter. You'll want to keep
track of this figure for quick reference when you are building the lab circuits.
\begin{figure}[H]
\centering
% \begin{mdframed}
\includegraphics[height=6.0in]{pi_images/j8header-2b-dsr-flat.png}
% \end{mdframed}
\caption{The Pi's J8 pin and row numbers with the Pi4J GPIO numbering}
\label{fig:pi4jgpio}
\end{figure}
The bold numbers at the extreme right and left of the diagram are the GPIO numbers. The numbers in green give the row number of the pin (useful when we are describing the wiring for a lab project since they line up with the row numbers printed on the breadboard). The small vertically-oriented (sideways) numbers are the physical pin numbers which we generally won't be concerned with.
\pagebreak
\section{Breadboards - Easy Wiring}
\index{breadboard}
In order to create our lab project circuits, we will use
a breadboard which allows us to easily connect different
electrical devices to the Pi without worrying about soldering. A breadboard has a set of electrically-connected
holes into which we insert jumper wires, LEDs,
buttons, etc.
Figure~\ref{fig:breadboard} is a picture of the breadboard we will be using for the labs:
\begin{figure}[H]
\centering
% \begin{mdframed}
\includegraphics[height=2in]{pi_images/half-size-breadboard-600x600_grande.jpg}
% \end{mdframed}
\caption{Standard half-size breadboard}
\label{fig:breadboard}
\end{figure}
Note that there are 14 columns of holes. The first and last two columns are special (marked with + and -). The center set of 10 columns are labeled a-j in two groups, a-e and f-j. There are 30 rows of holes available for columns a-j.
Let's consider how the breadboard is wired internally. The connection points for the first and last two columns (labeled + and -) are electrically connected by column. The connection points in the columns labeled a-e and the ones in columns f-j are connected horizontally in groups of 5. For example a connection to point a1 is connected to holes b1, c1, d1 and e1. Similarly f1 is connected to g1, h1, i1 and j1.
These images below attempt to clarify how the holes are tied together:
%\beforefig
%\centerline{\includegraphics[height=2.00in]{pi_images/Breadboard_Remarked_grande.png}}
%\afterfig
\iffalse % comment out images displayed one above the other
\beforefig
\centerline{\includegraphics[height=2.0in]{pi_images/verticalpower.png}}
\afterfig
\beforefig
\centerline{\includegraphics[height=2.0in]{pi_images/horizontal-rows.png}}
\afterfig
\fi % end of skipping images
\begin{tabular}{p{0.4\textwidth} p{0.3\textwidth}}
\vspace{0pt} \includegraphics[height=1.4in]{pi_images/verticalpower.png} &
\vspace{0pt} \includegraphics[height=1.4in]{pi_images/horizontal-rows.png}
\end{tabular}
This layout will make more sense once you complete the first lab
and put together your initial set of components.
\section{Connecting the Pi and a Breadboard}
It may have occurred to you that there is no way to directly attach the breadboard to the Pi. For that we need two more pieces of equipment: a breakout board and ribbon cable.
A breakout board\footnote{Also called a cobbler breakout} provides a way to connect the 40 pins from the J8 GPIO interface to separate sets of holes on the breadboard. A ribbon cable then allows us to connect the breakout board to the Pi.
Figure~\ref{fig:piwithbreadboard} shows the entire setup, connecting the Pi to the ribbon cable, which attaches to the breakout board which is installed on the breadboard. This is the basic workbench we will be using for our Pi labs.
\begin{figure}[H]
\centering
% \begin{mdframed}
\includegraphics[height=2.5in]{pi_images/breadboard-cobbler-pi.jpg}
% \end{mdframed}
\caption{Raspberry Pi, ribbon cable, breakout board and breadboard}
\label{fig:piwithbreadboard}
\end{figure}
\section{Electronics - keeping it basic}
This book is not intended to make you an electrical engineer. Each lab will clearly spell out all of the
connections you need to make in order to setup the
breadboard for the specific assignment. Your job will be
to write programs. In this case the programs will control
(or be controlled by) devices attached to the Pi via the breadboard.
\pagebreak
The basic components you will be working with are:
\begin{enumerate}
\item \textbf{Jumper cables}
\index{jumper cable}
\index{breadboard!jumper cable}
\beforefig
\centerline{\includegraphics[height=1.50in]{pi_images/breadboard-jumper-cables.jpg}}
\afterfig
Jumper cables have a pin at each end that are easily inserted into the breadboard holes. The cables are used to connect one set of holes to another set of holes. For example, when we need to connect an LED to a GPIO pin we will insert one end of a jumper cable into the same row as the GPIO pin and insert the other end of the jumper into a hole in the same row with the LED's wire.
\item \textbf{Resistors}
\beforefig
\centerline{\includegraphics[height=0.50in]{pi_images/resistor3-500x500.jpg}}
\afterfig
A resistor, as its name implies, resists the flow of electricity through a circuit. In our case we want to be sure that we do not damage the Pi or our LEDs with too high a current flow.
The resistors have two connecting wires whose orientation doesn't matter. When we list two holes on the breadboard for the resistor's wires to be inserted into, you can insert either end of the resistor into either hole.
\item \textbf{Buttons}
\index{button}
\index{breadboard!button}
\beforefig
\centerline{\includegraphics[height=0.70in]{pi_images/button_large.jpg}}
\afterfig
The buttons we will use are known as momentary contact buttons. This means that they only make contact (complete a circuit) while being held down. Our programs can then respond to the button being pressed when the Pi detects that a circuit has been completed by the button. Here is a diagram of how the switch is wired.
\beforefig
\centerline{\includegraphics[height=0.70in]{pi_images/button_schematic.png}}
\afterfig
Like resistors, each button has two connection points and their orientation does not matter. When we list two holes on the breadboard for the button's terminals to be inserted into, you can insert either end of the button into either hole.
\iffalse % Ignoring this information for the 4 connection buttons
\beforefig
\centerline{\includegraphics[height=1.00in]{pi_images/Push-Switch-fs8-1024x269.png}}
\afterfig
The buttons we will use are known as momentary contact buttons. This means that they only make contact (complete a circuit) while being held down. Our programs can then respond to the button being pressed when the Pi detects that a circuit has been completed by the button. Above is a picture of a button with a diagram of how the switch is wired.
Don't worry about the A-B-C-D labeling yet. We'll formally work through connecting the switch in the first lab to use one. It turns out the orientation of the button will matter when we place it on the breadboard.
\textbf{\underline{Take note that the orientation of buttons matters}}. Looking at the bottom of the buttons you'll note that they have four contacts. In one direction the contacts are closer together than in the other. Looking at the diagram above, the A-D and B-C contacts are more widely spaced than the A-B and C-D contacts.
For our labs, \textbf{when inserting the buttons into the breadboard you will need to place them so that the more widely spaced contacts are arranged on opposite sides of the breadboard's center line}. That is, A-B goes on one side of the center line and C-D go on the other. \textit{If you're unsure about their placement, check with your instructor.}
\fi % End of ignored section discussing the 4 contact buttons
\item \textbf{LEDs}
\index{LED}
\index{breadboard!LED}
\beforefig
\centerline{\includegraphics[height=1.50in]{pi_images/led_2.jpg}}
\afterfig
The acronym LED stands for Light Emitting Diode. A key term is diode. A diode is sensitive to the direction of electrical current flow. There is a right way and wrong way to connect one.
The anode end must tie to the positive side of the circuit while the cathode end must tie to the negative side. You can identify the anode on the LED since it has a longer connector wire.
If the wire lengths are too close to differentiate you can also look for a flat spot on one side of the LED. The wire nearest the flat spot will be the cathode.
\end{enumerate}
Those are the only components we will work with for this set of labs. They extend our keyboard and screen with new ways to interact with the computer, pressing a button to provide input and lighting an LED to provide output.
\section{PiLib - classes for components}
\index{PiLib}
\index{library!PiLib}
We've toured through the hardware we'll be using. Now we need to describe the software that will allow us to turn on LEDs and detect button presses.
\textbf{\underline{Widget Control}} \newline
The library, called PiLib, is comprised of several classes that are used to represent the physical components. Developers often call such components widgets. The base class in PiLib for interacting with
physical components is Widget. This class is abstract so you won't be creating any instances of it.
Each Widget subclass will represent a physical component such as an LED or button. Since any physical component must be connected to a GPIO pin in order to be accessible from the Pi, the Widget class has an attribute representing the GPIO number (as depicted in the earlier Pi4J numbering diagram).
Below is an overview of the specific Widget subclasses that you will be using. The first time each one is used in a lab we will go into more detail.
Also, note that there is complete JavaDoc for PiLib. It can be found with the library itself as well as at: \url{https://monead.com/iot/PiLibClient/}.
\index{PiLib!JavaDoc location}
The four classes of interest are:
\begin{enumerate}
\item \textbf{Widget} \newline
This represents any widget. Each of the classes listed below are subclasses of Widget. The Widget class has a few special static methods including \textbf{\texttt{gpioReset()}} which removes old GPIO pin mappings.
\index{Widget class}
\index{PiLib!Widget class}
\index{gpioReset() method}
\index{Widget.gpioReset() method}
\index{PiLib!gpioReset() method}
You'll normally want to call that at the beginning of your program to be sure there aren't any old GPIO pin mappings configured. You call the method by simply including the statement \textbf{\texttt{Widget.gpioReset();}} in your program before creating your mappings. You may also call it at the end of your program to remove mappings and leave the environment in a clean state.
The Widget class also defines the static methods \textbf{\texttt{turnOffAllLeds()}}, \textbf{\texttt{turnOnAllLedsSolid()}} and \textbf{\texttt{turnOnAllLedsBlink()}} which are convenience methods to quickly set all the LEDs to a specific mode.
\index{turnOffAllLeds() method}
\index{Widget.turnOffAllLeds() method}
\index{PiLib!turnOffAllLeds() method}
\index{turnOnAllLedsSolid() method}
\index{Widget.turnOnAllLedsSolid() method}
\index{PiLib!turnOnAllLedsSolid() method}
\index{turnOnAllLedsBlink() method}
\index{Widget.turnOnAllLedsBlink() method}
\index{PiLib!turnOnAllLedsBlink() method}
For controlling \texttt{BinaryLed} instances (see below) the \textbf{\texttt{Widget.setBinaryValue()}} method takes an \texttt{int} parameter which is the value you want displayed by the \texttt{BinaryLed} instances.
\index{BinaryLed class}
\index{PiLib!BinaryLed class}
If you review the JavaDoc for the Widget class you will see that it also contains a method called \texttt{shutdown()}. You will rarely use this method since it shuts down the PiLibServer. \textit{You cannot make further use of the library methods (for instance you can't call methods on the Led instances) once the \texttt{shutdown()} method is called until you restart the PiLibServer program.}
\item \textbf{Button} \newline
This represents the operations and attributes that are allowed for a button. The operations are detecting that the button has been pressed, getting a count of times it has been pressed and resetting the button's counter.
The three methods of interest provided by the Button class are \textbf{\texttt{getPressCount()}}, \textbf{\texttt{clearPressCount()}} and \textbf{\texttt{waitForPress()}}. See the JavaDoc for details.
\index{Button class}
\index{PiLib!Button class}
\index{getPressCount() method}
\index{Button.getPressCount() method}
\index{PiLib!Button.getPressCount() method}
\index{clearPressCount() method}
\index{Button.clearPressCount() method}
\index{PiLib!Button.clearPressCount() method}
\index{waitForPress() method}
\index{Button.waitForPress() method}
\index{PiLib!Button.waitForPress() method}
\item \textbf{Led} \newline
This represents the operations that are allowed for an LED. The operations include turning the LED off, turning it on and making it blink. There are no additional attributes associated with an LED.
The three methods of interest provided by the Led class are \textbf{\texttt{turnOff()}}, \textbf{\texttt{turnOnSolid()}} and \textbf{\texttt{turnOnBlink()}}. See the JavaDoc for details.
\index{Led class}
\index{PiLib!Led class}
\index{turnOff() method}
\index{Led.turnOff() method}
\index{PiLib!Led.turnOff() method}
\index{turnOnSolid() method}
\index{Led.turnOnSolid() method}
\index{PiLib!Led.turnOnSolid() method}
\index{turnOnBlink() method}
\index{Led.turnOnBlink() method}
\index{PiLib!Led.turnOnBlink() method}
\item \textbf{BinaryLed} \newline
This represents an LED that is being used in a group
with other LEDs as a way to represent binary numbers. Don't worry about binary if you aren't familiar with it. We'll cover it in a later lab. The \texttt{Widget.setBinaryValue()} method (described above) is used to make displaying of binary numbers easy.
\texttt{BinaryLed} is a subclass of \texttt{Led} meaning it inherits the \texttt{Led} class's methods \textbf{\texttt{turnOff()}}, \textbf{\texttt{turnOnSolid()}} and \textbf{\texttt{turnOnBlink()}}. See the PiLib JavaDoc for details.
\index{BinaryLed class}
\index{PiLib!BinaryLed class}
\index{turnOff() method}
\index{BinaryLed.turnOff() method}
\index{PiLib!BinaryLed.turnOff() method}
\index{turnOnSolid() method}
\index{BinaryLed.turnOnSolid() method}
\index{PiLib!BinaryLed.turnOnSolid() method}
\index{turnOnBlink() method}
\index{BinaryLed.turnOnBlink() method}
\index{PiLib!BinaryLed.turnOnBlink() method}
\end{enumerate}
The classes that you will use in your programs send commands to a server program. That program must be running on your Pi. The server, \textbf{PiLibServer}, needs special permissions in order to access the GPIO pins. See the section, \textbf{\textit{Starting the PiLib Server}} for information in using the PiLib server program.
\textbf{\underline{Utilities}} \newline
In addition to classes for controlling the widgets, PiLib has several utility methods to make working with the Pi and interacting with users a little simpler. Each of these methods is in the \textbf{\texttt{Utility}} class.
\begin{enumerate}
\item \textbf{Collecting user input} \newline
Many labs require our program to ask the user for information that must be supplied using the keyboard. Java makes it fairly easy to read input from the keyboard, however there is a redundant set of code that has to be written each time we want to get another piece of information.
To simplify keyboard input, the \texttt{Utility} class contains the method \textbf{\texttt{readKeyboardLine()}}. The method waits for the user to type some characters and press the \textbf{Enter} key. Once the user presses \textbf{Enter} the method returns a \textbf{String} containing any characters the user typed prior to pressing \textbf{Enter}.
Here is a simple program that asks the user to enter their name, gets the information from the keyboard and then prints his or her response on the screen.
\beforeverb
\begin{verbatim}
import us.daveread.raspberrypi.gpio.lib.Utility;
public class DemokeyboardInput {
public static void main(String[] args) {
String name;
System.out.print("What is your name? ");
name = Utility.readKeyboardLine();
System.out.println("You replied with the name " + name);
}
}\end{verbatim}
\afterverb
Here is an example of what this would look like when it is run:
\beforeverb
\begin{verbatim}
What is your name? Dave
You replied with the name Dave
\end{verbatim}
\afterverb
\item \textbf{Pausing Program Execution} \newline
When you are working with the LEDs you will often need to have your program pause so that the LED stays on or off for a defined period of time. For instance, if you wrote a program to turn on an LED, the LED would turn off as soon as the program ended. If you want to have the LED stay on for a couple of seconds before the program ends (turning off the LED) you need a way to pause the program.
The \texttt{Utility} class contains the method \textbf{\texttt{pause()}} which will cause the program to stop executing statements for a defined period of time. You tell the \texttt{pause()} method how long to pause by passing the number of milliseconds to pause as a parameter.
Here is an example of using the \texttt{pause()} method to print out the message, \textit{Hello World! Glad to meet you.} one word at a time. The amount of time the program pauses is different between different words.
The program pauses for 1 second (1000 milliseconds) after printing \textit{Hello}. It pauses one half-second after printing \textit{World!} Looking at the code you can see the other pause lengths being used. Give the program a try to experience how the output will be presented.
\beforeverb
\begin{verbatim}
import us.daveread.raspberrypi.gpio.lib.Utility;
public class DemoPause {
public static void main(String[] args) {
System.out.println("Hello");
Utility.pause(1000);
System.out.println("World!");
Utility.pause(500);
System.out.println("Glad");
Utility.pause(1500);
System.out.println("to");
Utility.pause(250);
System.out.println("meet");
Utility.pause(750);
System.out.println("you.");
Utility.pause(1250);
}
}\end{verbatim}
\afterverb
\end{enumerate}
\section{Starting the PiLibServer}
If you have not installed the PiLib server please see the section \textbf{\textit{Setup the PiLib Server}} on page \pageref{setupPiLibServer} in the \textit{Raspberry Pi Setup} appendix.
\index{PiLib}
\index{library!PiLib}
\index{PiLib!Server program}
Whenever you want to use the PiLib server program you will use a terminal (accessing your home directory) and type the following command:
\textbf{\texttt{\$ PiLibServerDist/runServerSudo.sh}}
\textit{Note that the} \texttt{\$} \textit{(dollar sign) is the terminal prompt.} You do not type the \texttt{\$}. Also, your terminal prompt may look different than a plain dollar sign.
This command starts the server. Your screen should contain a message similar to:
\texttt{2016-06-16 10:37:55,869 [us.daveread.raspberrypi.gpio.lib.server.PiLibServer] [main] (PiLibServer.java:45) WARN us.daveread.raspberrypi.gpio.lib.server.PiLibServer - PiLib service ready}
You must leave the terminal open (running) while working on your Pi Lab program. You may close the PiLib Server by selecting the terminal and typing \textbf{\texttt{[Ctrl]C}}. That is, hold the [Ctrl] key and press the letter \textbf{C}.
\section{PiLib Server Web Control}
The PiLib Server supports a web-based interface for three purposes:
\begin{enumerate}
\item Client library control
\item Viewing the current GPIO configuration
\item Interacting with the GPIO configuration
\end{enumerate}
\textbf{\underline{View Current GPIO Configuration}}
If you want to view the current configuration, use the following address in your browser (note that the PiLib server must be running when you do this):
\textbf{\texttt{\url{http://localhost:5162/PiLib}}}
If you are not running a program that has setup GPIO mappings then you will see an empty page containing the message, \textit{No widgets have been created} (figure~\ref{fig:servernowidget}). Otherwise you will see a graphical representation for each mapped LED and button (figure~\ref{fig:serverwithwidget}).
\begin{figure}[H]
\centering
% \begin{mdframed}
\includegraphics[height=1.50in]{pi_images/PiLibServerNoWidgets.png}
% \end{mdframed}
\caption{PiLib Server web page with no widgets}
\label{fig:servernowidget}
\end{figure}
\begin{figure}[H]
\centering
% \begin{mdframed}
\includegraphics[height=1.8in]{pi_images/PiLibServerWithWidgets.png}
% \end{mdframed}
\caption{PiLib Server web page with widgets configured}
\label{fig:serverwithwidget}
\end{figure}
You may find this view helpful when building your Pi labs since you can see what GPIOs are configured for which components as well as seeing the state of the LEDs and interacting with the buttons. If you have your project setup and LEDs aren't lighting when expected or button presses aren't being detected, you can use this web page to see if the issue is with components on the breadboard or with the program.
\textbf{\underline{PiLib Server Test Web Page}}
If you want to test out a GPIO configuration without writing Java code you can setup several simple arrangements of components. The web URL for this is:
\textbf{\texttt{\url{http://localhost:5162/PiLib/test}}}
You may use this web page (figure~\ref{fig:servertestpage}) to modify the GPIO Configuration, mapping LEDs and buttons to GPIO numbers as well as clearing old mappings or even shutting-down the PiLib server. This page is intended for basic testing of the GPIO server. You will probably not find it particularly useful as you work through the Pi lab exercises.
\begin{figure}[H]
\centering
% \begin{mdframed}
\includegraphics[height=1.8in]{pi_images/PiLibServerTestPage.png}
% \end{mdframed}
\caption{PiLib Server test page (top of page)}
\label{fig:servertestpage}
\end{figure}
\section{Wiring Tests}
\label{wiringTestDescription}
\index{PiLab Wiring Test}
\index{Wiring Test!PiLab}
\beforefig
\begin{wrapfigure}{r}{40mm}
\centerline{\includegraphics[height=1in]{images/approved-151676_960_720.png}}
\end{wrapfigure}
\afterfig
Every Pi Lab project includes a test program to check that all of the components are properly connected and working. The class file will always be called \textbf{\texttt{WiringTest.java}}.
For each lab, after wiring your breadboard and connecting it to your Pi, you should open the \textbf{\texttt{WiringTest}} program and run it. Depending on the components being used for your lab the program will exercise each one.
Generally it will turn on all the LEDs and then, if the lab uses buttons, it will have you press each button in sequence and report that the press was detected.
\beforefig
\begin{wrapfigure}{l}{40mm}
\centerline{\includegraphics[height=1in]{images/exclamation-mark-red-md.png}}
\end{wrapfigure}
\afterfig
If one or more of the components aren't working when the \texttt{WiringTest} is run you will need to fix it. Here are the three most common issues I've seen which cause the test to fail:
\begin{itemize}
\item The PiLib Server has not been started
\item The ribbon cable connector which plugs into the Pi is loose or not aligned correctly
\item The components are not wired correctly on the breadboard. A common wiring mistake is connecting resistors to the wrong power rail (such as connecting to 3V3+ when the connection should be to 3V3--).
\end{itemize}
Make sure that the \texttt{WiringTest} works before proceeding. Your own program won't work correctly if the test isn't working.
Now that we have discussed the PiLib client and server components as well as how to test our breadboard wiring, let's give it all a try with our first lab.
\clearpage
\section{Lab 1 - Part 1}
\textbf{Learning Goals}
\begin{enumerate}
\item Create a working circuit with 1 LED controlled by a Java program running on the Pi
\item Explore the Led class methods that allow us to control a physical LED
\item Understand the relationship between virtual objects (instances of a class) and their physical counterparts
\end{enumerate}
\textbf{Overview}
You will use your breadboard to connect an LED to a GPIO pin. With this setup you will write a Java program which controls the LED. In a second part of the lab you will add a second LED and control both of them with a program.
\textbf{Breadboard Configuration}
\hfill
{\centering
\fbox{\begin{minipage}{300pt}
\textbf{\underline{WARNING:} NEVER connect or disconnect the breadboard's ribbon cable from your Raspberry Pi when the Pi is powered-up. NEVER change the wiring on your
breadboard when it is connected to your powered-up Raspberry Pi. \textit{You
can do \underline{permanent damage} (including rendering your Pi unusable)
if you are changing connections while your Pi is running.} Your best bet is to do the wiring when your Pi is disconnected from a power source.}
\end{minipage}
}\par
}
\hfill
For each lab we'll provide two images of the configured breadboard. One image will depict the components using drawings that clearly show the connection points. The other image will be a photo of a completed breadboard to help you validate the overall arrangement of the components.
In addition to the images there will be a step by step set of connection instructions. If you are unsure of a connection, verify it with the instructor, TA or a classmate.
\pagebreak
\underline{Wiring Depiction}
\beforefig
\centerline{\includegraphics[height=2in]{pi_images/lab01images/PiLab01-1Light.png}}
\afterfig
\underline{Wiring Steps}
\textbf{Remember, your Pi must be disconnected from a power source while wiring the circuit.}
\begin{enumerate}
\item Insert an LED anode (longer wire) into hole \textbf{d22}
\item Insert the same LED's cathode into hole \textbf{d23}
\item Insert a jumper from hole \textbf{a6} to hole \textbf{a22}
\item Insert a resistor between hole \textbf{a23} and a \textbf{3V3--} (negative) hole adjacent to row 23.
\item If your ribbon cable is not connected to the Pi and the breakout board, connect it now (making sure your Pi is disconnected from any power source)
\end{enumerate}
\underline{Completed Breadboard Picture}
\beforefig
\centerline{\includegraphics[height=2in]{pi_images/lab01images/PiLab01-1Light-photo.jpg}}
\afterfig
\underline{GPIO Assignments}
\begin{center}
\begin{tabular}{c | c | c}
\hline
\textbf{Type} & \textbf{GPIO} & \textbf{Description} \\ \hline
Led & 0 & Only LED for part 1 \\
\hline
\end{tabular}
\end{center}
\vspace{10pt}
Start up your Pi and bring up the Eclipse environment. Remember to start the \textbf{PiLib Server}. Download and setup the PiLab01 project from the class website.
\underline{Run the Wiring Test}
Open the \textbf{\texttt{WiringTest}} program and run it. For information about wiring tests and common problems when testing your breadboard project please see the description on page \pageref{wiringTestDescription}.
\textbf{Program Implementation}
The project contains two additional source code files containing classes named \texttt{ControlOneLight} and \texttt{ControlTwoLights}. We will start by working on the \texttt{ControlOneLight} class, since we only have one light on our breadboard.
Open the source file for \texttt{ControlOneLight} and review the code. The class has a \texttt{main()} method containing all the code that controlls the light.
Our goal at this point is to walk through the code and understand what it is doing. First run the program and make sure the LED lights up.
When the program runs it attempts to turn on the light for 2 seconds, turn it off for 2 seconds, make it blink for 4 seconds and finally turn it off as the program ends. If the LED isn't lighting up when you run the program, check your breadboard connections very carefully. If you can't find a problem, try a different LED, perhaps the one you are using is broken.
\textbf{Exploring the \texttt{ControlOneLight} Class}
This simple program uses most of the building blocks that we'll need for more advanced labs. Lets take the time to understand what the code is doing.
Here is the complete program:
\beforeverb
\begin{verbatim}
package edu.skidmore.cs106.pi.lab01;
import us.daveread.raspberrypi.gpio.lib.client.Led;
import us.daveread.raspberrypi.gpio.lib.client.Utility;
import us.daveread.raspberrypi.gpio.lib.client.Widget;
/**
* Controls a single LED, turning it on, blinking and off.
* @author readda
*/
public class ControlOneLight {
/**
* Creates an Led instance and uses different methods to control the LED.
* @param args
* Command line arguments - not used
*/
public static void main(String[] args) {
// Reset old mappings
Widget.gpioReset();
// Declare an Led variable
Led myLight;
// Create an instance of the Led class
myLight = new Led(0);
// Turn the light on for 2 seconds
myLight.turnOnSolid();
Utility.pause(2000);
// leave the light off for 2 seconds
myLight.turnOff();
Utility.pause(2000);
// Make the light blink for 3 seconds
myLight.turnOnBlink();
Utility.pause(4000);
// Turn off the light
myLight.turnOff();
System.out.println("Program ends");
}
}
\end{verbatim}
\afterverb
The \texttt{package} and \texttt{import} statements are covered in other parts of the course. For our purposes note that the library classes that we are using are located in a separate package and need to be imported. You will generally just import these into each lab. One other class, Button, will also need to be imported when we starting using buttons.
As we've covered elsewhere, the program starts running by executing the code in the \texttt{main()} method.
The first statement we see is \texttt{Widget.gpioReset()}. Remember this assures that there aren't any old GPIO pin mappings left from some other program. It is a good practice to include this statement before setting up your widgets.
%The keywords \texttt{try} and \texttt{finally} are also covered separately in the class. When using the PiLib library for these labs simply follow this template approach to your main method:
%\begin{enumerate}
% \item Start a \texttt{try} block
% \item Write your code within the \texttt{try} block
% \item End the \texttt{try} block
% \item Start a \texttt{finally} block that contains one statement: %\texttt{GpioWidgetPool.close()}
% \item End the {finally} block and the \texttt{main} method.
%\end{enumerate}
The next statement is a declaration of a variable named \texttt{myLight} of type \texttt{Led}.
\beforeverb
\begin{verbatim}
Led myLight;
\end{verbatim}
\afterverb
The \texttt{Led} class represents a physical LED, providing the behaviors (methods) for turning it on and off.
Next we create an instance of the \texttt{Led} class and associate it with GPIO 0. We place that new instance in the variable, \texttt{myLight}, which we had declared above. Here is the statement that creates and assigns the instance:
\beforeverb
\begin{verbatim}
myLight = new Led(0);
\end{verbatim}
\afterverb
Note that the way we associate an instance of an Led (and we'll see this is true for any widget) with a GPIO number is to include that number within the parentheses as we create the instance. Put another way, the GPIO number is a parameter we pass to the Led class' constructor.
Now that we have an instance of an Led that is associated with a GPIO pin, we can use the class' methods to control the LED. The next statement turns on the Led connected to GPIO 0:
\beforeverb
\begin{verbatim}
myLight.turnOnSolid();
\end{verbatim}
\afterverb
We've seen this syntax in previous chapters but let's highlight what is happening. We are telling Java to use the Led instance stored in the variable \texttt{myLight} and to run the code in the method \texttt{turnOn()} on that instance. The \texttt{turnOn()} method is written to supply power to the instance's GPIO pin.
After this line of code executes the LED will be on. However, we need a way to make the program wait a couple of seconds so that the light stay on. Remember, by default the program just keeps executing its statements one after the other as fast as it can.
In order to pause the program so that the light stays on for a couple of seconds we can use Java's ability to make a program "sleep" for a period of time. The \texttt{Utility} class contains a \texttt{pause()} method that we can use for this purpose. The method takes one parameter, the number of milliseconds to pause.
In the next statement we have our program pause for 2 seconds (2000 milliseconds).
\beforeverb
\begin{verbatim}
Utility.pause(2000);
\end{verbatim}
\afterverb
Our program will pause its execution for two seconds before moving onto the next statement. This means the light will stay on for those two seconds.
We next turn off the LED and have it remain off for two seconds. Here are the statements that do that:
\beforeverb
\begin{verbatim}
myLight.turnOff();
Utility.pause(2000);
\end{verbatim}
\afterverb
After those two seconds pass we turn on the light in blinking mode. We want it to blink for 4 seconds. Here are the statements for that operation:
\beforeverb
\begin{verbatim}
myLight.turnOnBlink();
Utility.pause(4000);
\end{verbatim}
\afterverb
Finally we turn the light off before exiting the program.
\beforeverb
\begin{verbatim}
myLight.turnOff();
\end{verbatim}
\afterverb
We end the program with a message on the console verifying that the program has ended.
\beforeverb
\begin{verbatim}
System.out.println("Program ends");
\end{verbatim}
\afterverb
\textbf{Note that if you don't remember to turn off the LEDs, they will remain on as long as the server program (PiLibServer) is running and the \texttt{Widget.gpioReset()} method hasn't been called.} If you want to assure that all LEDs are off when your program ends, simply include a call to \texttt{Widget.gpioReset()} at the end of your program.
\section{Lab 1 - Part 2}
\textbf{Learning Goals}
\begin{enumerate}
\item Create a working circuit with 2 LEDs controlled by a Java program running on the Pi
\item Creatively use the Led class methods that allow us to control our physical LEDs
\item Reinforce the relationship between virtual objects (instances of a class) and their physical counterparts
\end{enumerate}
\textbf{Overview}
You will use your breadboard to connect two LEDs to two GPIO pins. With this setup you will write a Java program which controls the LEDs.
\textbf{Breadboard Configuration}
\underline{Wiring Depiction}
\beforefig
\centerline{\includegraphics[height=2in]{pi_images/lab01images/PiLab01-2Light.png}}
\afterfig
\underline{Wiring Steps}
\textbf{Remember, your Pi must be disconnected from a power source while wiring the circuit.}
These steps assume your breadboard is setup as described in \textbf{Lab 1 - Part 1}. If it isn't , go through those wiring steps before returning to the ones below.
\begin{enumerate}
\item Insert an LED anode (longer wire) into hole \textbf{g22}
\item Insert the same LED's cathode into hole \textbf{g23}
\item Insert a jumper from hole \textbf{j8} to hole \textbf{j22}
\item Insert a resistor between hole \textbf{j23} and a \textbf{5V--} (negative) hole adjacent to row 23.
\item If your ribbon cable is not connected to the Pi and the breakout board, connect it now (making sure your Pi is disconnected from any power source)
\end{enumerate}
\underline{Completed Breadboard Picture}
\beforefig
\centerline{\includegraphics[height=2in]{pi_images/lab01images/PiLab01-2Light-photo.jpg}}
\afterfig
\underline{GPIO Assignments}
\begin{center}
\begin{tabular}{c | c | c}
\hline
\textbf{Type} & \textbf{GPIO} & \textbf{Description} \\ \hline
Led & 0 & First LED \\
\hline
Led & 4 & Second LED \\
\hline
\end{tabular}
\end{center}
\vspace{10pt}
Start up your Pi and remember to start the \textbf{PiLib Server}. Bring up the Eclipse environment. Return to the PiLab01 project (which you setup in part 1 of this lab).
\underline{Run the Wiring Test}
Open the \textbf{\texttt{WiringTest}} program and run it. For information about wiring tests and common problems when testing your breadboard project please see the description on page \pageref{wiringTestDescription}.
\textbf{Program Implementation}
Open the source file for \texttt{ControlTwoLights} and review the code. The class has a \texttt{main()} method with a \texttt{try} and \texttt{finally} blocks.
The implementation code has not been supplied. Your job is to use the concepts you learned in part one of this lab and create a program that does the following:
\begin{enumerate}
\item Declare two variables of type Led. Consider naming them \texttt{myFirstLight} and \texttt{mySecondLight} though you are free to name them something different if you prefer.
\item Create an instance of an Led associated with GPIO 0 and assign it to your first Led variable. We will call this \textbf{LED 1}
\item Create an instance of an Led associated with GPIO 4 and assign it to your second Led variable. We will call this \textbf{LED 2}
\item Turn on LED 1 in blinking mode while turning on LED 2 so that it stays steadily lit.
\item Pause your program for 3 seconds, allowing the LEDs to blink and illuminate
\item Switch the LEDs so that your LED 1 stays on steadily and LED 2 blinks
\item Pause your program for another 3 seconds
\item Turn off LED 1 and set LED 2 to stay steadily lit
\item Pause your program for half a second (500 milliseconds)
\item Turn on LED 1 (steady) and turn off LED 2
\item Pause your program for half a second (500 milliseconds)
\item Repeat the prior 4 steps 2 more times. Our goal is to have the LEDs flashing back and forth when the program gets to this part of the code.
\end{enumerate}
Test your program and adjust your code until the steps are working. Go ahead and experiment by creating other outputs.
For example can you figure out how to send the message "SOS" in Morse Code? S is three short signals and O is three long signals. We would write it out as:
\beforeverb
\begin{verbatim}
dot-dot-dot dash-dash-dash dot-dot-dot (... --- ...)
\end{verbatim}
\afterverb
Using the LEDs we could define "long" as 1 second and short as a quarter second (250 milliseconds). We could define the time between signals as a quarter second and the time between letters as 1 second. With those timings, the code you write to depict "SOS" will turn an LED on and off for the correct durations.
Your solution will end up being sets of \texttt{turnOn()} and \texttt{pause()} statements followed by \texttt{turnOff()} and \texttt{pause()} statements. A video of what this lab might end up looking like when run is located at: \url{https://youtu.be/2a2cu42BZHE}
\textbf{End of Lab}
This concludes lab 1. You've covered a lot of ground in terms of wiring up your breadboard and controlling devices from your Java program. We'll build more complex circuits and programs as we build on this foundation.
\textbf{Remember to submit your completed lab using the process defined by your instructor.}
{\centering
\beforefig
\centerline{\includegraphics[height=1in]{pi_images/stop_sign_clip_art_16252.jpg}}
\afterfig
}
\newpage
\section{Lab 2 - Part 1}
\textbf{Learning Goals}
\begin{enumerate}
\item Reinforce relationship between instances and physical LEDs
\item Use user input to make decisions
\end{enumerate}
\textbf{Overview}
Create a circuit that has 4 LEDs. One of the 4 lights will be turned on based on keyboard input.
\textbf{Breadboard Configuration}
\underline{Wiring Depiction}
\beforefig
\centerline{\includegraphics[height=2in]{pi_images/lab02images/PiLab02-4Light.png}}
\afterfig
\underline{Wiring Steps}
\textbf{Remember, your Pi must be disconnected from a power source while wiring the circuit.}
\begin{enumerate}
\item Insert an LED anode into hole \textbf{e22}
\item Insert the same LED's cathode into hole \textbf{e23}
\item Insert an LED anode into hole \textbf{e24}
\item Insert the same LED's cathode into hole \textbf{e25}
\item Insert an LED anode into hole \textbf{e26}
\item Insert the same LED's cathode into hole \textbf{e27}
\item Insert an LED anode into hole \textbf{e28}
\item Insert the same LED's cathode into hole \textbf{e29}
\item Insert a jumper from hole \textbf{a6} to hole \textbf{a22}
\item Insert a jumper from hole \textbf{a7} to hole \textbf{a24}
\item Insert a jumper from hole \textbf{a8} to hole \textbf{a26}
\item Insert a jumper from hole \textbf{a10} to hole \textbf{a28}
\item Insert a resistor between hole \textbf{a23} and a \textbf{3V3--} hole adjacent to row 23
\item Insert a resistor between hole \textbf{a25} and a \textbf{3V3--} hole adjacent to row 25
\item Insert a resistor between hole \textbf{a27} and a \textbf{3V3--} hole adjacent to row 27
\item Insert a resistor between hole \textbf{a29} and a \textbf{3V3--} hole adjacent to row 29
\item If your ribbon cable is not connected do so now.
\end{enumerate}
\underline{Completed Breadboard Picture}
\beforefig
\centerline{\includegraphics[height=2in]{pi_images/lab02images/PiLab02-4Light-photo.jpg}}
\afterfig
\underline{GPIO Assignments}
\begin{center}
\begin{tabular}{c | c | c}
\hline
\textbf{Type} & \textbf{GPIO} & \textbf{Description} \\ \hline
Led & 0 & First LED \\
\hline
Led & 2 & Second LED \\
\hline
Led & 3 & Third LED \\
\hline
Led & 12 & Fourth LED \\
\hline
\end{tabular}
\end{center}