Free Your Innovation: Freenove Is An Open-Source Electronics Platform
Free Your Innovation: Freenove Is An Open-Source Electronics Platform
Free Your Innovation: Freenove Is An Open-Source Electronics Platform
Freenove is an open-source electronics platform. Freenove is committed to helping customer quickly realize
the creative idea and product prototypes, making it easy to get started for enthusiasts of programing and
electronics and launching innovative open source products. Our services include:
Electronic components and modules
Learning kits for Arduino
Learning kits for Raspberry Pi
Learning kits for Technology
Robot kits
Auxiliary tools for creations
Our code and circuit are open source. You can obtain the details and the latest information through visiting
the following web sites:
http://www.freenove.com
https://github.com/freenove
Your comments and suggestions are warmly welcomed, please send them to the following email address:
[email protected]
Support
Freenove provides free and quick technical support, including but not limited to:
Quality problems of products
Problems in using products
Questions for learning and technology
Opinions and suggestions
Ideas and thoughts
Copyright
Freenove reserves all rights to this book. No copies or plagiarizations are allowed for the purpose of
commercial use.
The code and circuit involved in this product are released as Creative Commons Attribution ShareAlike 3.0.
This means you can use them on your own derived works, in part or completely, as long as you also adopt
the same license. Freenove brand and Freenove logo are copyright of Freenove Creative Technology Co., Ltd
and cannot be used without formal permission.
█ www.freenove.com Preface I
Contents
Contents .................................................................................... I
Preface ......................................................................................1
Install Processing Software ............................................................................................................................................................. 1
First Use .................................................................................................................................................................................................. 3
Chapter 4 RGBLED............................................................. 23
Project 4.1 ColorfulLED ..................................................................................................................................................................23
Preface
Processing software is used to write programs that can run on computers. Processing software is free and
open source, and runs on the Mac, Windows, and GNU/Linux platforms, which is the same with Arduino
software. In fact, the development of Arduino software is based on Processing software, and they still have
similar interface.
Programs written using Processing are also called sketches,and Java is the default language. Java language
and C++ language has many similarities, so the readers who have learned our basic tutorial are able to
understand and write simple Processing sketches quickly.
Processing continues to be an alternative to proprietary software tools with restrictive and expensive licenses,
making it accessible to schools and individual students. Its open source status encourages the community
participation and collaboration that is vital to Processing's growth. Contributors share programs, contribute
code, and build libraries, tools, and modes to extend the possibilities of the software. The Processing
community has written more than a hundred libraries to facilitate computer vision, data visualization, music
composition, networking, 3D file exporting, and programming electronics.
This tutorial is applicable for Freenove Ultimate Starter Kit for Raspberry Pi. If you have learned our C and
python tutorials, or you have learned basic electronic circuits and programming, you can start learning this
tutorial. Otherwise, we recommend that you had better learn our C and Python tutorials first. Sketchs of this
tutorial is written by java language in processing software. This tutorial has similar projects to C and python
tutorials. And graphical man-machine interface is added to achieve perfect integration of electronic circuits,
computer software, images and so on, which will let the readers fully experience the fun of programming and
DIY.
This tutorial will introduce how to install and use processing software on Raspberry Pi through some electronic
circuit projects. Chapters and sequence is similar to C and python tutorial. Equally, detailed description and
explanation is arranged for the skect in each project. Our elaborate electronic circuits and interactive project
with Processing are attached in the end, including virtual instruments, games (2D and 3D versions), etc.
Processing software / Processing Development Environment (PDE) makes it easy to write Processing programs.
First install Processing software: type following command in the terminal to start installation:
curl https://processing.org/download/install-arm.sh | sudo sh
Ensures that your RPi always has the Internet to access in the installation process.
2 Preface www.freenove.com █
You can also download and install the software by visiting the official website https://processing.org/.
After the installation is completed, you can enter the "processing" to open processing software in any directory
of the terminal, or open the software processing in the start menu of the system, as shown below:
Menu
ToolBar
Tabs
Message Area
Console
You're now running the Processing Development Environment (or PDE). There's not much to it; the large area
is the Text Editor, and there's a row of buttons across the top; this is the toolbar. Below the editor is the
Message Area, and below that is the Console. The Message Area is used for one line messages, and the
Console is used for more technical details.
█ www.freenove.com Preface 3
First Use
This line of code means "draw an ellipse, with the center 50 pixels over from the left and 50 pixels down from
the top, with a width and height of 80 pixels." Click the Run button (the triangle button in the Toolbar).
Display Window
Click on "Stop" (the rectangle button in the Toolbar) or "Close" on Display Window to stop running the
program.
If you didn't type it correctly, the Message Area will turn red and complain about an error. If this happens,
make sure that you've copied the example code exactly: the numbers should be contained within parentheses
and have commas between each of them, and the line should end with a semicolon.
You can export this sketch to an application to run it directly without opening the Processing.
To export the sketch to the application, you must first save it.
4 Preface www.freenove.com █
So far, we have completed the first use. I believe you have felt the joy of it.
█ www.freenove.com Chapter 1 LED 5
Chapter 1 LED
We will still start from Blink LED in this chapter, and also learn the usage of some commonly used functions
of Processing Software.
In this project, we will make a Blink LED and let Display window of Processing Blink at the same time.
6 Chapter 1 LED www.freenove.com █
Component List
BreadBoard x1
In the components list, 3B GPIO, Extension Shield Raspberry and Breadboard are necessary for each
experiment. They will be listed only in text form.
█ www.freenove.com Chapter 1 LED 7
Circuit
Disconnect RPi from GPIO Extension Shield first. Then build the circuit according to the circuit diagram and
the hardware connection diagram. After the circuit is built and confirmed, connect RPi to GPIO Extension
Shield. In addition, short circuit (especially 5V and GND, 3.3V and GND) should be avoid, because short circuit
may cause anormal circuit work, or even damage to PRi.
Schematic diagram
Hardware connection
Because Numbering of GPIO Extension Shield is the same as RPi GPIO, latter Hardware connection diagram
will only show the part of breadboard and GPIO Extension Shield.
8 Chapter 1 LED www.freenove.com █
Sketch
Processing code usually have two functions: setup() and draw(), where the function setup()is only executed
once, but the function draw() will be executed circularly. In the function setup(), size(100, 100) specifies the size
of the Display Window to 100x100pixl. FrameRate(1) specifies the refresh rate of Display Window to once per
second, namely, the draw() function will be executed once per second. GPIO.pinMode (ledPin, GPIO.OUTPUT)
is used to set ledPin to output mode.
void setup() {
size(100, 100);
frameRate(1); //set frame rate
GPIO.pinMode(ledPin, GPIO.OUTPUT); //set the ledPin to output mode
}
In draw() function, each execution will invert the variable "ledState". When “ledState” is true, LED is turned on,
and the background color of display window is set to red. And when the “ledState” is false, the LED will be
turned off and the background color of display window is set to gray. Since the function draw() is executed
once per second, the background color of Display Window and the state of LED will also change once per
second. Such cycle repeats itself to achieve the effect of blink.
void draw() {
ledState = !ledState;
if (ledState) {
GPIO.digitalWrite(ledPin, GPIO.HIGH); //led on
background(255, 0, 0); //set the fill color of led on
} else {
GPIO.digitalWrite(ledPin, GPIO.LOW); //led off
background(102); //set the fill color of led off
}
}
All functions used in this code can be found in the Reference of Processing Software, in which built-in
functions are described in details, and there are some sample programs. It is recommended for beginners to
view more usage and functions of the function. The localization of Reference can be opened by the following
steps: click the menu bar "Help""Reference".
In this project, we will use the mouse to control the state of LED.
The components and circuits of this project are the same as the last section.
Sketch
16 GPIO.digitalWrite(ledPin, GPIO.LOW);
17 background(102);
18 }
19 }
20
21 void mouseClicked() { //if the mouse Clicked
22 ledState = !ledState; //Change the led State
23 }
The function mouseClicked() is used in this code. The function is used to capture the mouse click events, which
is executed when the mouse is clicked on. We can change the state of the variable “ledState” in this function,
to realize controlling LED through clicking on the mouse.
void mouseClicked() { //if the mouse Clicked
ledState = !ledState; //Change the led State
}
█ www.freenove.com Chapter 2 LEDBar Graph 13
In this project, we will use the mouse to control the LEDBar Graph
Component List
Circuit
The network label is used in the circuit diagram below, and the pins with the same network label are connected
togather.
Schematic diagram
Hardware connection
In this circuit, the cathode of LED is connected to GPIO, which is the different from the front circuit. So, LED
will be turned on when GPIO output low level in the program.
█ www.freenove.com Chapter 2 LEDBar Graph 15
Sketch
In the function draw(), we draw 10 rectangles to represent 10 LEDs of LEDBar Graph. We make rectangles on
the left of mouse filled with red, corresponding LEDs turned on. And make We make rectangles on the right
of mouse filled with red, corresponding LEDs turned off. In this way, when slide the mouse to right, the more
LEDs on the left of mouse will be turned on. When to the left, the reverse is the case.
void draw() {
for (int i=0; i<10; i++) { //draw 10 rectanglar box
if (mouseX>(25+60*i)) { //if the mouse cursor on the right of rectanglar box
fill(255, 0, 0); //fill the rectanglar box in red color
GPIO.digitalWrite(leds[i], GPIO.LOW); //turn on the corresponding led
} else {
fill(255, 255, 255); //else fill the rectanglar box in white color
GPIO.digitalWrite(leds[i], GPIO.HIGH); //and turn off the led
}
rect(25+60*i, 90, 50, 180); //draw a rectanglar box
}
}
█ www.freenove.com Chapter 3 PWM 17
Chapter 3 PWM
In this chapter, we will learn how to use PWM.
In this project, we will make a breathing LED, and the Display Window will show a breathing LED pattern and
a progress bar, at the same time.
Component List
Jumper M/M x2
18 Chapter 3 PWM www.freenove.com █
Circuit
Schematic diagram
Hardware connection
█ www.freenove.com Chapter 3 PWM 19
Sketch
55 void barBgStyle() {
56 stroke(220);
57 noFill();
58 }
59
60 void barStyle() {
61 stroke(50);
62 noFill();
63 }
64
65 void barLabelStyle() {
66 noStroke();
67 fill(120);
68 }
First, use SOFTPWM class to create a PWM pin, which is used to control the brightness of LED. Then define a
variable “t” and variable “tStep” to control the PWM duty cycle and add-self rate.
float t = 0.0; //progress percent
float tStep = 0.004; // speed
SOFTPWM p = new SOFTPWM(ledPin, 10, 100);
In the function draw, if there is a click, the coordinate in X direction of mouse will be mapped into the duty
cycle “t”, otherwise, duty cycle “t” will be increased gradually. Then output PWM with the duty cycle.
if (mousePressed) {
int a = constrain(mouseX, borderSize, width - borderSize);
t = map(a, borderSize, width - borderSize, 0.0, 1.0);
} else {
t += tStep;
if (t > 1.0) t = 0.0;
}
p.softPwmWrite((int)(t*100)); //wirte the duty cycle according to t
The next code is designed to draw a circle filled colors with different depth according to the “t” value, which
is used to simulate the of LED with different brightness.
fill(255, 255-t*255, 255-t*255); //cycle
ellipse(width/2, height/2, 100, 100);
The last code is designed to draw the progress bar and the percentage of the progress.
barBgStyle(); //progressbar bg
line(0, 0, barLength, 0);
line(barLength, -5, barLength, 5);
barStyle(); //progressbar
line(0, -5, 0, 5);
22 Chapter 3 PWM www.freenove.com █
In processing software, you will see a tag page "SOFTPWM" in addition to above code.
Chapter 4 RGBLED
In this chapter, we will learn how to use RGBLED.
This project will make a ColorfulLED, namely, use Processing to control the color of RGBLED.
Component List
Jumper M/M x4
24 Chapter 4 RGBLED www.freenove.com █
Circuit
Schematic diagram
Hardware connection
█ www.freenove.com Chapter 4 RGBLED 25
Sketch
This project contains a lot of code files, and the core code is contained in the file
Sketch_04_1_1_ColorfulLED. The other files only contain some custom classes.
26 Chapter 4 RGBLED www.freenove.com █
In the code, first create three PWM pins and three progress bars to control RGBLED.
SOFTPWM pRed = new SOFTPWM(redPin, 100, 100);
SOFTPWM pGreen = new SOFTPWM(greenPin, 100, 100);
SOFTPWM pBlue = new SOFTPWM(bluePin, 100, 100);
//instantiate three ProgressBar Object
ProgressBar rBar, gBar, bBar;
And then in function setup(), define position and length of progress bar ccording to the size of Display
Window, and set the name of each progress bar.
void setup() {
size(640, 360); //display window size
28 Chapter 4 RGBLED www.freenove.com █
In function draw(), first set background, header and other basic information. Then draw a circle and set its
color according to the duty cycle of three channel of RGB. Finally draw three progress bars.
void draw() {
background(200); //A white background
titleAndSiteInfo(); //title and Site infomation
System function mousePressed(), mouseReleased() and mouseDragged() are used to determine whether the
mouse drag the progress bar and set the schedule. If the mouse button is pressed in a progress bar, then the
mousePressed () the progress of a flag *Mouse is set to true, mouseDragged (mouseX), in the mapping
progress value set at the same time, the progress of the corresponding schedule and PWM. When the mouse
is released, empty all the flags in the mouseReleased ().
void mousePressed() {
if ( (mouseY< rBar.y+5) && (mouseY>rBar.y-5) ) {
rMouse = true;
} else if ( (mouseY< gBar.y+5) && (mouseY>gBar.y-5) ) {
gMouse = true;
} else if ( (mouseY< bBar.y+5) && (mouseY>bBar.y-5) ) {
bMouse = true;
}
}
void mouseReleased() {
rMouse = false;
bMouse = false;
gMouse = false;
}
█ www.freenove.com Chapter 4 RGBLED 29
void mouseDragged() {
int a = constrain(mouseX, borderSize, width - borderSize);
float t = map(a, borderSize, width - borderSize, 0.0, 1.0);
if (rMouse) {
pRed.softPwmWrite((int)(100-t*100)); //wirte the duty cycle according to t
rBar.setProgress(t);
} else if (gMouse) {
pGreen.softPwmWrite((int)(100-t*100)); //wirte the duty cycle according to t
gBar.setProgress(t);
} else if (bMouse) {
pBlue.softPwmWrite((int)(100-t*100)); //wirte the duty cycle according to t
bBar.setProgress(t);
}
}
Chapter 5 Buzzer
In this chapter we will learn how to use buzzer.
Component List
Circuit
Schematic diagram
Hardware connection
Note: in this circuit, the power supply for buzzer is 5V, and pull-up resistor of the button connected to the
power 3.3V. The buzzer can work when connected to power 3.3V, but it will reduce the loudness.
32 Chapter 5 Buzzer www.freenove.com █
Sketch
void draw() {
background(255);
titleAndSiteInfo(); //title and site infomation
drawBuzzer(); //buzzer img
if (buzzerState) {
GPIO.digitalWrite(buzzerPin, GPIO.HIGH);
drawArc(); //Sounds waves img
} else {
GPIO.digitalWrite(buzzerPin, GPIO.LOW);
}
}
Code in this project is based on similar logic with the previous "MouseLED". And the difference is that this
project needs to draw the buzzer pattern and arc graphics after the buzzer sounding.
34 Chapter 6 PCF8591 www.freenove.com █
Chapter 6 PCF8591
In this chapter we will learn how to use AD/DA chip, PCF8591.
This project uses ADC function of PCF8591 to read potentiometer voltage value and display the value on
Display Window. And then use its DAC function to output the voltage value to turn on LED.
Component List
Circuit
Schematic diagram
Hardware connection
36 Chapter 6 PCF8591 www.freenove.com █
Sketch
This project contains a lot of code files, and the core code is contained in the file Sketch_06_1_1_PCF8591.
The other files only contain some custom classes.
█ www.freenove.com Chapter 6 PCF8591 37
The project code mainly use PCF8591 class member function analogRead() and analogWrite() to read ADC
and write DAC.
int adc = pcf.analogRead(0); //Read the ADC value of channel 0
float volt = adc*3.3/255.0; //calculate the voltage
pcf.analogWrite(adc); //Write the DAC
In this project, we will make a softlight, namely, using a potentiometer to control the brightness of LED.
Component List
Circuit
The circuit of this experiment is similar to the one in the last chapter. The only difference is that the pin used
to control LED is different.
Schematic diagram
Hardware connection
█ www.freenove.com Chapter 7 ADC & LED 41
Sketch
This project contains a lot of code files, and the core code is contained in the file Sketch_07_1_1_SoftLight.
The other files only contain some custom classes.
42 Chapter 7 ADC & LED www.freenove.com █
In this project code, get the ADC value of the potentiometer, then map it into the PWM duty cycle of LED to
control its brightness. In Display Window, the color filled in LED pattern changes to simulate the brightness
change of LED.
int adc = pcf.analogRead(0); //Read the ADC value of channel 0
float volt = adc*3.3/255.0; //calculate the voltage
float dt = adc/255.0;
p.softPwmWrite((int)(dt*100)); //output the pwm
█ www.freenove.com Chapter 7 ADC & LED 43
In this project, we will use Photoresistor, used to intense ambient light, to make a NightLamp. When the
ambient light get dark, LED brightness wil be enhanced automatically. Conversely, the LED brightness will be
weakened automatically.
Component List
Circuit
The circuit of this experiment is similar to the one in last chapter. The only difference is that the input signal
of the AIN0 pin of PCF8591 is changed from a potentiometer to combination of a photoresistor and a resistor.
Schematic diagram
Hardware connection
Sketch
The project code is the same as the last section "SoftLight" in addition to the title.
█ www.freenove.com Chapter 8 Thermistor 45
Chapter 8 Thermistor
In this chapter, we will learn how to use thermistor.
Component List
Component knowledge
First Review the knowledge of thermistor. The relationship between resistance value and temperature of
thermistor is:
Rt=R*EXP [B*(1/T2-1/T1)]
Where:
Rt is the thermistor resistance under T2 temperature;
R is in the nominal resistance of thermistor under T1 temperature;
EXP[n] is nth power of E;
B is for thermal index;
T1, T2 is Kelvin temperature (absolute temperature). Kelvin temperature=273.15+celsius temperature.
Parameters of the thermistor we use is: B=3950, R=10k, T1=25.
46 Chapter 8 Thermistor www.freenove.com █
Circuit
The circuit of this experiment is similar to the one in the last chapter. The only difference is that the
photoresistor is replaced by the thermistor.
Schematic diagram
Hardware connection
The formula for calculating temperature according to the circuit is shown below:
T2 = 1/(1/T1 + ln(Rt/R)/B)
█ www.freenove.com Chapter 8 Thermistor 47
Sketch
This project contains a lot of code files, and the core code is contained in the file
Sketch_08_1_1_Thermometer. The other files only contain some custom classes.
48 Chapter 8 Thermistor www.freenove.com █
In this project, we use L293D to drive the DC motor. We can click on the button in the Processing Display
Window to control motor direction, and drag the progress bar to control the motor speed.
Component List
Circuit
When connecting the circuit, pay attention to that beacause the motor is a high-power component, do not
use the power provided by the RPi, which may do damage to your RPi. the logic circuit can be powered by
RPi power or external power supply which should have the common ground with RPi.
Schematic diagram
█ www.freenove.com Chapter 9 Motor & Driver 51
Hardware connection
Sketch
This project contains a lot of code files, and the core code is contained in the file Sketch_09_1_1_Motor. The
other files only contain some custom classes.
█ www.freenove.com Chapter 9 Motor & Driver 53
43 }
44 //Draw a clover fan according to the stating angle
45 void drawFan(float angle) {
46 constrain(angle, 0, 2*PI);
47 fill(0);
48 for (int i=0; i<3; i++) {
49 arc(width/2, height/2, 200, 200, 2*i*PI/3+angle, (2*i+0.3)*PI/3+angle, PIE);
50 }
51 fill(0);
52 ellipse(width/2, height/2, 30, 30);
53 fill(128);
54 ellipse(width/2, height/2, 15, 15);
55 }
56
57 void mousePressed() {
58 if ( (mouseY< mBar.y+5) && (mouseY>mBar.y-5) ) {
59 mMouse = true; //the mouse click the progressBar
60 } else if ((mouseY< btn.y+btn.h) && (mouseY>btn.y)
61 && (mouseX< btn.x+btn.w) && (mouseX>btn.x)) { // the mouse click the button
62 if (motorDir == motor.CW) { //change the direction of rotation of motor
63 motorDir = motor.CCW;
64 btn.setBgColor(255, 0, 0);
65 btn.setText("CCW");
66 } else if (motorDir == motor.CCW) {
67 motorDir = motor.CW;
68 btn.setBgColor(0, 255, 0);
69 btn.setText("CW");
70 }
71 }
72 }
73 void mouseReleased() {
74 mMouse = false;
75 }
76 void mouseDragged() {
77 int a = constrain(mouseX, borderSize, width - borderSize);
78 float t = map(a, borderSize, width - borderSize, 0.0, 1.0);
79 if (mMouse) {
80 mBar.setProgress(t);
81 }
82 }
83 void titleAndSiteInfo() {
84 fill(0);
85 textAlign(CENTER); //set the text centered
86 textSize(40); //set text size
█ www.freenove.com Chapter 9 Motor & Driver 55
First define the GPIO pin connected to the Motor, motor class object, the L293D class object, the ProgressBar
class object, the Button class object, and some variables.
int motorPin1 = 17; //connect to the L293D
int motorPin2 = 27;
int enablePin = 22;
final int borderSize = 45; //border size
//MOTOR Object
MOTOR motor = new MOTOR(motorPin1, motorPin2, enablePin);
ProgressBar mBar; //ProgressBar Object
boolean mMouse = false; //determined whether a mouse click the ProgressBar
BUTTON btn; //BUTTON Object, For controlling the direction of motor
int motorDir = motor.CW; //motor direction
float rotaSpeed = 0, rotaPosition = 0; //motor speed
In function draw(), draw all the contents to be displayed. Then set the motor speed, as well as the speed of
virtual fan according to the progress of progress bar. And set the motor direction according to the button
flag.
void draw() {
background(255);
titleAndSiteInfo(); //title and site information
strokeWeight(4); //border weight
mBar.create(); //create the ProgressBar
motor.start(motorDir, (int)(mBar.progress*100)); //control the motor starts to rotate
btn.create(); //create the button
rotaSpeed = mBar.progress * 0.02 * PI; //virtual fan's rotating speed
if (motorDir == motor.CW) {
rotaPosition += rotaSpeed;
if (rotaPosition >= 2*PI) {
rotaPosition = 0;
}
} else {
rotaPosition -= rotaSpeed;
56 Chapter 9 Motor & Driver www.freenove.com █
In the mousePressed(), judge if the Button is clicked on. If the mouse clicked on the Button, then change the
motor direction and the text and color of Button. We have learned how to drag ProgressBarBar before, so
here is no representation.
else if ((mouseY< btn.y+btn.h) && (mouseY>btn.y)
&& (mouseX< btn.x+btn.w) && (mouseX>btn.x)) { // the mouse click the button
if (motorDir == motor.CW) { //change the direction of rotation of motor
motorDir = motor.CCW;
btn.setBgColor(255, 0, 0);
btn.setText("CCW");
} else if (motorDir == motor.CCW) {
motorDir = motor.CW;
btn.setBgColor(0, 255, 0);
btn.setText("CW");
}
Subfunction drawFan(float angle) is used to draw a three leaf fan, based on an initial angle angle. And the
angle between each two leaf is 120°. Changing the value of “angle” can make the fan rotate to different angle.
void drawFan(float angle) {
constrain(angle, 0, 2*PI);
fill(0);
for (int i=0; i<3; i++) {
arc(width/2, height/2, 200, 200, 2*i*PI/3+angle, (2*i+0.3)*PI/3+angle, PIE);
}
fill(0);
ellipse(width/2, height/2, 30, 30);
fill(128);
ellipse(width/2, height/2, 15, 15);
}
is used to decide the duty cycle of PWM. Its value is within range of 0-100.
In this chapter, we will use 74HC595 and LEDBar Graph to recreate a FollowLight.
Component List
Circuit
Schematic diagram
Hardware connection
60 Chapter 10 74HC595 & LEDBar Graph www.freenove.com █
Sketch
This project contains a lot of code files, and the core code is contained in the file Sketch_10_1_1_LightWater.
The other files only contain some custom classes.
█ www.freenove.com Chapter 10 74HC595 & LEDBar Graph 61
34 strokeWeight(1);
35 for (int i=0; i<10; i++) { //draw 10 rectanglar box
36 if (leds == (1<<i)) { //
37 fill(255, 0, 0); //fill the rectanglar box in red color
38 } else {
39 fill(255, 255, 255); //else fill the rectanglar box in white color
40 }
41 rect(25+60*i, 90, 50, 180); //draw a rectanglar box
42 }
43 }
44
45 void mousePressed() {
46 if ( (mouseY< mBar.y+5) && (mouseY>mBar.y-5) ) {
47 mMouse = true; //the mouse click the progressBar
48 }
49 }
50 void mouseReleased() {
51 mMouse = false;
52 }
53 void mouseDragged() {
54 int a = constrain(mouseX, borderSize, width - borderSize);
55 float t = map(a, borderSize, width - borderSize, 0.0, 1.0);
56 if (mMouse) {
57 mBar.setProgress(t);
58 }
59 }
60 void titleAndSiteInfo() {
61 fill(0);
62 textAlign(CENTER); //set the text centered
63 textSize(40); //set text size
64 text("LightWater", width / 2, 40); //title
65 textSize(16);
66 text("www.freenove.com", width / 2, height - 20); //site
67 }
First define the GPIO pin connected to 74HC595, the ProgressBar class object, IC74HC595 class object, and
some variables.
int dataPin = 17; //connect to the 74HC595
int latchPin = 27;
int clockPin = 22;
final int borderSize = 45; //border size
ProgressBar mBar; //ProgressBar Object
IC74HC595 ic; //IC74HC595 Object
boolean mMouse = false; //determined whether a mouse click the ProgressBar
█ www.freenove.com Chapter 10 74HC595 & LEDBar Graph 63
In the function setup(), instantiate ProgressBar class object and IC74HC595 class object.
mBar = new ProgressBar(borderSize, height-borderSize, width-borderSize*2);
mBar.setTitle("Speed"); //set the ProgressBar's title
ic = new IC74HC595(dataPin, latchPin, clockPin);
In the function draw(), set the background, text, and other information and draw the progress bar.
background(255);
titleAndSiteInfo(); //title and site information
strokeWeight(4); //border weight
mBar.create(); //create the ProgressBar
Then according to the speed of followlight, calculate the data “leds” for 74HC595, and make it written to
74HC595, then LEDBar Graph is turned on.
if (millis() - lastMoveTime > 50/(0.05+mBar.progress)) {
lastMoveTime = millis();
leds<<=1;
if (leds == 0x100)
leds = 0x01;
}
ic.write(ic.LSBFIRST, leds); //write 74HC595
Finally, according to the variable leds, draw the virtual LEDBar Graph in Display Window.
stroke(0);
strokeWeight(1);
for (int i=0; i<10; i++) { //draw 10 rectanglar box
if (leds == (1<<i)) { //
fill(255, 0, 0); //fill the rectanglar box in red color
} else {
fill(255, 255, 255); //else fill the rectanglar box in white color
}
rect(25+60*i, 90, 50, 180); //draw a rectanglar box
}
About class IC74HC595:
class IC74HC595
This is a custom class that is used to operate integrated circuit 74HC595.
public IC74HC595(int dPin, int lPin, int cPin)
Constructor, the parameter for the GPIO pin connected to 74HC595.
public void write(int order,int value)
Used to write data to 74HC595, and the 74HC595 output port will output these data immediately.
64 Chapter 11 74HC595 & Seven-segment display. www.freenove.com █
We will use 74HC595 to control Seven-segment display (SSD). And make it display decimal character "0-9".
Component List
Circuit
Schematic diagram
Hardware connection
66 Chapter 11 74HC595 & Seven-segment display. www.freenove.com █
Sketch
This project contains a lot of code files, and the core code is contained in the file Sketch_11_1_1_SSD. The
other files only contain some custom classes.
█ www.freenove.com Chapter 11 74HC595 & Seven-segment display. 67
44 textAlign(CENTER, CENTER);
45 text(num, width/2, height/2);
46 }
47 void mousePressed() {
48 if ( (mouseY< mBar.y+5) && (mouseY>mBar.y-5) ) {
49 mMouse = true; //the mouse click the progressBar
50 }
51 }
52 void mouseReleased() {
53 mMouse = false;
54 }
55 void mouseDragged() {
56 int a = constrain(mouseX, borderSize, width - borderSize);
57 float t = map(a, borderSize, width - borderSize, 0.0, 1.0);
58 if (mMouse) {
59 mBar.setProgress(t);
60 }
61 }
62 void titleAndSiteInfo() {
63 fill(0);
64 textAlign(CENTER); //set the text centered
65 textFont(createFont("", 100)); //default font
66 textSize(40); //set text size
67 text("Seven-segment Display", width / 2, 40); //title
68 textSize(16);
69 text("www.freenove.com", width / 2, height - 20); //site
}
The project code is similar to the last chapter. The difference is that in this project the data output by 74HC595
is the fixed coding information of SSD. First, the character "0-9" is defined as code of common anode SSD.
final int[] numCode = {0xc0, 0xf9, 0xa4, 0xb0, 0x99, 0x92, 0x82, 0xf8, 0x80, 0x90};
In the function draw(), the data is output at a certain speed. At the same time the Display Window outputs
the same character.
if (millis() - lastMoveTime > 50/(0.05+mBar.progress)) {
lastMoveTime = millis();
index++;
if (index > 9) {
index = 0;
}
}
ic.write(ic.MSBFIRST, numCode[index]); //write 74HC595
showNum(index); //show the number in dispaly window
█ www.freenove.com Chapter 11 74HC595 & Seven-segment display. 69
By creating the font "mFont", we change the font of the characters in Display Window. The font ".vlw" file is
created by clicking the "Create Font" of the menu bar, which is saved in the data folder of current Sketch.
PFont mFont;
……
mFont = loadFont("DigifaceWide-100.vlw"); //create DigifaceWide font
About more details about loadFont(), please refer to "HelpReferenceloadFont()" or the official website:
https://processing.org/reference/loadFont_.html
By creating an empty font, you can reset the font to default font.
textFont(createFont("", 100)); //default font
70 Chapter 11 74HC595 & Seven-segment display. www.freenove.com █
Component List
Circuit
Schematic diagram
72 Chapter 11 74HC595 & Seven-segment display. www.freenove.com █
Hardware connection
█ www.freenove.com Chapter 11 74HC595 & Seven-segment display. 73
Sketch
In this project, open an independent thread to control the FDSSD. The uncertainty of the system time slice
allocation may lead to FDSS flashing in the display, which is is a normal phenomenon. For details about display
principle of FDSSD, please refer to our C and Python manual.
Sketch 11.2.1 FDSSD
First observe the running result of the sketch, and then analyze the code.
1. Use Processing to open the file Sketch_11_2_1_FDSSD.
processing
Freenove_Ultimate_Starter_Kit_for_Raspberry_Pi/Processing/Sketchs/Sketch_11_2_1_FDSSD/Sketch_11_2_1_F
DSSD.pde
2. Click on "RUN" to run the code.
After the program is executed, Display Window and FDSSD in the circuit will show same figures, and they
have the same add-self rate. They will constantly show the number of "0-9999" circularly. And dragging the
progress bar can change the rate.
This project code is similar to the last section "SSD". The difference is that this project needs to control four
SSD. The four coanodes of four SSD is controlled by four GPIO through 4 transistors. First, the four GPIO is
defined.
int[] digitPin = {17, 27, 22, 10};
In a separate thread, make the FDSSD display numbers in scan mode. Subfunction display() is used to make
FDSSD display a four-digit number.
thread("displaySSD");
……
void displaySSD() {
while (true) {
display(index);
}
}
Other contents of the program are the same as the last section "SSD".
█ www.freenove.com Chapter 11 74HC595 & Seven-segment display. 77
78 Chapter 12 74HC595 & LED Matrix www.freenove.com █
In this project, we will use two 74HC595 to control a monochrome LEDMatrix (8*8) to make it display some
graphics and characters.
Component List
Circuit
In this experimental circuit, the power pin of 74HC595 is connected to 3.3V. It can also be connected to 5V to
make LEDMatrix brighter.
Schematic diagram
80 Chapter 12 74HC595 & LED Matrix www.freenove.com █
Hardware connection
Second stage
74HC595:B
First stage
74HC595:A
█ www.freenove.com Chapter 12 74HC595 & LED Matrix 81
Sketch
This project contains a lot of code files, and the core code is contained in the file Sketch_12_1_1_LEDMatrix.
The other files only contain some custom classes.
82 Chapter 12 74HC595 & LED Matrix www.freenove.com █
43 void draw() {
44 background(255);
45 titleAndSiteInfo(); //title and site information
46 strokeWeight(4); //border weight
47 mBar.create(); //create the ProgressBar
48 displayNum(hex(index, 1)); //show the number in dispaly window
49 }
50 class myThread extends Thread {
51 public void run() {
52 while (true) {
53 showMatrix(); //show smile picture
54 showNum(); //show the character "0-F"
55 }
56 }
57 }
58 void showMatrix() {
59 for (int j=0; j<100; j++) { //picture show time
60 int x=0x80;
61 for (int i=0; i<8; i++) { //display a frame picture
62 GPIO.digitalWrite(latchPin, GPIO.LOW);
63 ic.shiftOut(ic.MSBFIRST, pic[i]);
64 ic.shiftOut(ic.MSBFIRST, ~x);
65 GPIO.digitalWrite(latchPin, GPIO.HIGH);
66 x>>=1;
67 }
68 }
69 }
70 void showNum() {
71 for (int j=0; j<numCode.length-8; j++) { //where to start showing
72 index = j/8;
73 for (int k =0; k<10*(1.2-mBar.progress); k++) { //speed
74 int x=0x80;
75 for (int i=0; i<8; i++) { //display a frame picture
76 GPIO.digitalWrite(latchPin, GPIO.LOW);
77 ic.shiftOut(ic.MSBFIRST, numCode[j+i]);
78 ic.shiftOut(ic.MSBFIRST, ~x);
79 GPIO.digitalWrite(latchPin, GPIO.HIGH);
80 x>>=1;
81 }
82 }
83 }
84 }
85 void displayNum(String num) {
86 fill(0);
84 Chapter 12 74HC595 & LED Matrix www.freenove.com █
87 textSize(100);
88 textAlign(CENTER, CENTER);
89 text(num, width/2, height/2);
90 }
91 void mousePressed() {
92 if ( (mouseY< mBar.y+5) && (mouseY>mBar.y-5) ) {
93 mMouse = true; //the mouse click the progressBar
94 }
95 }
96 void mouseReleased() {
97 mMouse = false;
98 }
99 void mouseDragged() {
100 int a = constrain(mouseX, borderSize, width - borderSize);
101 float t = map(a, borderSize, width - borderSize, 0.0, 1.0);
102 if (mMouse) {
103 mBar.setProgress(t);
104 }
105 }
106 void titleAndSiteInfo() {
107 fill(0);
108 textAlign(CENTER); //set the text centered
109 textFont(createFont("", 100)); //default font
110 textSize(40); //set text size
111 text("LEDMatrix Display", width / 2, 40); //title
112 textSize(16);
113 text("www.freenove.com", width / 2, height - 20); //site
114 }
In the code, first define the data of smiling face and characters "0-F".
//encoding for smile face
final int[] pic = {0x1c, 0x22, 0x51, 0x45, 0x45, 0x51, 0x22, 0x1c};
//encoding for character 0-9 of ledmatrix
final int[] numCode={
……
};
Then create a new thread t. LEDMatrix scan display code will be executed in run() of this thread.
myThread t = new myThread(); //create a new thread for ledmatrix
……
class myThread extends Thread {
public void run() {
while (true) {
showMatrix(); //show smile picture
█ www.freenove.com Chapter 12 74HC595 & LED Matrix 85
The function setup(), define size of Display Window, ProgressBar class objects and IC75HC595 class object,
and start the thread t.
void setup() {
size(640, 360);
mBar = new ProgressBar(borderSize, height-borderSize, width-borderSize*2);
mBar.setTitle("Speed"); //set the ProgressBar's title
ic = new IC74HC595(dataPin, latchPin, clockPin);
t.start(); //thread start
}
In draw(), draw the relevant information and the current number to display.
void draw() {
background(255);
titleAndSiteInfo(); //title and site information
strokeWeight(4); //border weight
mBar.create(); //create the ProgressBar
displayNum(hex(index, 1)); //show the number in dispaly window
}
Subfunction showMatrix () makes LEDMatrix display a smiling face patterns, and last for a period of time.
void showMatrix() {
for (int j=0; j<100; j++) { //picture show time
int x=0x80;
for (int i=0; i<8; i++) { //display a frame picture
GPIO.digitalWrite(latchPin, GPIO.LOW);
ic.shiftOut(ic.MSBFIRST, pic[i]);
ic.shiftOut(ic.MSBFIRST, ~x);
GPIO.digitalWrite(latchPin, GPIO.HIGH);
x>>=1;
}
}
}
86 Chapter 12 74HC595 & LED Matrix www.freenove.com █
Subfunction showNum() makes LEDMatrix scroll display of character "0-F", in which the variable k is used to
adjust the scrolling speed.
void showNum() {
for (int j=0; j<numCode.length-8; j++) { //where to start showing
index = j/8;
for (int k =0; k<10*(1.2-mBar.progress); k++) { //speed
int x=0x80;
for (int i=0; i<8; i++) { //display a frame picture
GPIO.digitalWrite(latchPin, GPIO.LOW);
ic.shiftOut(ic.MSBFIRST, numCode[j+i]);
ic.shiftOut(ic.MSBFIRST, ~x);
GPIO.digitalWrite(latchPin, GPIO.HIGH);
x>>=1;
}
}
}
}
█ www.freenove.com Chapter 13 I2C-LCD1602 87
Chapter 13 I2C-LCD1602
In this chapter, we will learn a display screen, LCD1602.
In the project, the current time and date will be displayed on the LCD1602 and Display Window.
Component List
Circuit
Note that the power supply for I2CLCD1602 in this circuit is 5V.
Schematic diagram
Hardware connection
█ www.freenove.com Chapter 13 I2C-LCD1602 89
Sketch
This project contains a lot of code files, and the core code is contained in the file Sketch_13_1_1_LCD. The
other files only contain some custom classes.
90 Chapter 13 I2C-LCD1602 www.freenove.com █
First create a PCF8574 class object “pcf”, and take “pcf” as a parameter to create a LCD1602 class object. And
then define the variable time to store date and time. Display window need not refresh frequently. Therefore,
the frame rate can be set to 1Hz or 2Hz.
PCF8574 pcf = new PCF8574(0x27);
Freenove_LCD1602 lcd; //Create a lcd object
String time = "";
String date = "";
void setup() {
size(640, 360);
lcd = new Freenove_LCD1602(pcf);
frameRate(2); //set display window frame rate for 2 HZ
}
In the function draw(), get the current time and date, and display them on the LCD1602 and Display Window.
void draw() {
background(255);
titleAndSiteInfo();
//get current time
time = nf(hour(), 2, 0) + ":" + nf(minute(), 2, 0) + ":" + nf(second(), 2, 0);
//get current date
date = nf(day(), 2, 0)+"/"+nf(month(), 2, 0)+"/"+nf(year(), 2, 0);
lcd.position(4, 0); //show time on the lcd display
lcd.puts(time);
lcd.position(3, 1); //show date on the lcd display
lcd.puts(date);
showTime(time, date); //show time/date on the display window
}
Chapter 14 Joystick
In the previous chapter, we have learned how to use rotary potentiometer. Now, let's learn a new electronic
module Joystick which working on the same principle as rotary potentiometer.
Project 14 Joystick
In this project, we will read the data of joystick, and draw its coordinates position and Z axis state in the Display
window.
Component List
Circuit
Schematic diagram
Hardware connection
█ www.freenove.com Chapter 14 Joystick 95
Sketch
When the button of Z axis is pressed, the circle will change the filled color.
96 Chapter 14 Joystick www.freenove.com █
Component List
Circuit
Pay attention to the power supply voltage needed for the components in circuit, in which the relay needs
power supply voltage 5V, and the motor needs 3.3V. Additionally, a LED is used as an indicator for the relay
(turned on or turned off).
Schematic diagram
100 Chapter 15 Relay & Motor www.freenove.com █
Hardware connection
█ www.freenove.com Chapter 15 Relay & Motor 101
Sketch
Click on the button in Display Window or press the button in the circuit, then the relay is opened and the
motor drived. Press the Button again, then the reverse is the case.
10 void setup() {
11 size(640, 360);
12 GPIO.pinMode(relayPin, GPIO.OUTPUT);
13 btn = new BUTTON(90, height - 90, 50, 30); //define the button
14 btn.setBgColor(0, 255, 0); //set button color
15 btn.setText("OFF"); //set button text
16 }
17
18 void draw() {
19 background(255);
20 titleAndSiteInfo(); //title and site information
21
22 skey.keyScan(); //key scan
23 if (skey.isPressed) { //key is pressed?
24 relayAction();
25 }
26 textAlign(RIGHT, CENTER);
27 text("RelayState: ", btn.x, btn.y+btn.h/2);
28 btn.create(); //create the button
29 if (relayState) {
30 rotaPosition += rotaSpeed;
31 }
32 if (rotaPosition >= 2*PI) {
33 rotaPosition = 0;
34 }
35 drawFan(rotaPosition); //show the virtual fan in Display window
36 }
37 //Draw a clover fan according to the stating angle
38 void drawFan(float angle) {
39 constrain(angle, 0, 2*PI);
40 fill(0);
41 for (int i=0; i<3; i++) {
42 arc(width/2, height/2, 200, 200, 2*i*PI/3+angle, (2*i+0.3)*PI/3+angle, PIE);
43 }
44 fill(0);
45 ellipse(width/2, height/2, 30, 30);
46 fill(128);
47 ellipse(width/2, height/2, 15, 15);
48 }
49 void relayAction() {
50 if (relayState) {
51 GPIO.digitalWrite(relayPin, GPIO.LOW);
52 relayState = false;
53 btn.setBgColor(255, 0, 0);
104 Chapter 15 Relay & Motor www.freenove.com █
54 btn.setText("OFF");
55 } else {
56 GPIO.digitalWrite(relayPin, GPIO.HIGH);
57 relayState = true;
58 btn.setBgColor(0, 255, 0);
59 btn.setText("ON");
60 }
61 }
62 void mousePressed() {
63 if ((mouseY< btn.y+btn.h) && (mouseY>btn.y)
64 && (mouseX< btn.x+btn.w) && (mouseX>btn.x)) { // the mouse click the button
65 relayAction();
66 }
67 }
68 void titleAndSiteInfo() {
69 fill(0);
70 textAlign(CENTER); //set the text centered
71 textSize(40); //set text size
72 text("Relay & Motor", width / 2, 40); //title
73 textSize(16);
74 text("www.freenove.com", width / 2, height - 20); //site
75 }
In the function setup(), Window Display and virtual button are initialized.
void setup() {
size(640, 360);
GPIO.pinMode(relayPin, GPIO.OUTPUT);
btn = new BUTTON(90, height - 90, 50, 30); //define the button
btn.setBgColor(0, 255, 0); //set button color
btn.setText("OFF"); //set button text
}
In the function draw(), scan entity buttons. If the button is pressed, then executed the subfunction relayAction(),
in which the state of Relay and virtual buttons will be changed. And then draw the virtual buttons and fan
blades.
void draw() {
background(255);
█ www.freenove.com Chapter 15 Relay & Motor 105
In this project, we will learn to control the speed, turning and step number of Stepping Motor.
Component List
Circuit
When building the circuit, the rated voltage of the stepper motor is 5V, and use the breadboard power supply
independently, and do not use the RPi power supply. Additionally, breadboard power supply needs to share
Ground with RPi.
Schematic diagram
108 Chapter 16 Stepping Motor www.freenove.com █
Hardware connection
█ www.freenove.com Chapter 16 Stepping Motor 109
Sketch
In this project, a separate thread is opened to control the stepper motor. The uncertainty of the system time
slice allocation may lead to the running of the stepper motor not smooth, which is a normal phenomenon.
Sketch 16.1.1 SteppingMotor
First observe the running result of the sketch, and then analyze the code.
1. Use Processing to open the file Sketch_16_1_1_SteppingMotor.
processing
Freenove_Ultimate_Starter_Kit_for_Raspberry_Pi/Processing/Sketchs/Sketch_16_1_1_SteppingMotor/Sketch_
16_1_1_SteppingMotor.pde
2. Click on "RUN" to run the code.
After the program is executed, Display Window shows a pattern used to simulate the motor, and a button
used to control RUN/STOP state of stepper motor. The stepper motor in the circuit and the virtual motor in
the Display Window will start to rotate at the same time.
110 Chapter 16 Stepping Motor www.freenove.com █
The stepping motor rotates at a fixed speed for a circle and then rotates counterclockwise for a circle,
circularly. Clicking on the Button can change the state (start or stop) of the stepping motor.
10 size(640, 360);
11 btn = new BUTTON(45, height - 90, 50, 30); //define the button
12 btn.setBgColor(0, 255, 0); //set button color
13 btn.setText("RUN"); //set button text
14 m.motorStart(); //start motor thread
15 rotaSpeed = 0.002 * PI; //virtual fan's rotating speed
16 }
17
18 void draw() {
19 background(255);
20 titleAndSiteInfo(); //title and site information
21 btn.create(); //create the button
22 if (isMotorRun) { //motor is runnig
23 fill(0);
24 textAlign(LEFT,BOTTOM);
25 textSize(20);
26 if (m.dir == m.CW) {
27 text("CW",btn.x,btn.y); //text "CW "
28 rotaPosition+=rotaSpeed;
29 if (rotaPosition>=TWO_PI) {
30 rotaPosition = 0;
31 }
32 } else if (m.dir == m.CCW) {
33 text("CCW",btn.x,btn.y); //text "CCW"
34 rotaPosition-=rotaSpeed;
35 if (rotaPosition<=0) {
36 rotaPosition = TWO_PI;
37 }
38 }
39 }
40 if (m.steps<=0) { //if motor has stopped,
41 if (m.dir == m.CCW) { //change the direction ,restart.
42 m.moveSteps(m.CW, 1, 512);
43 } else if (m.dir == m.CW) {
44 m.moveSteps(m.CCW, 1, 512);
45 }
46 }
47 drawFan(rotaPosition); //show the virtual fan in Display window
48 }
49 //Draw a clover fan according to the stating angle
50 void drawFan(float angle) {
51 constrain(angle, 0, 2*PI);
52 fill(0);
53 for (int i=0; i<3; i++) {
112 Chapter 16 Stepping Motor www.freenove.com █
Code, first define 4 GPIO connected to the motor, the BUTTON class object and SteppingMotor class object.
int[] pins = {18, 23, 24, 25}; //connect to motor phase A,B,C,D pins
BUTTON btn; //BUTTON Object, For controlling the direction of motor
SteppingMotor m = new SteppingMotor(pins);
█ www.freenove.com Chapter 16 Stepping Motor 113
In the function setup(), initialize the Button, start thread of stepping motor, and set the rotating speed of the
virtual motor.
void setup() {
size(640, 360);
btn = new BUTTON(45, height - 90, 50, 30); //define the button
btn.setBgColor(0, 255, 0); //set button color
btn.setText("RUN"); //set button text
m.motorStart(); //start motor thread
rotaSpeed = 0.002 * PI; //virtual fan's rotating speed
}
In the function draw(), first draw button, and calculate the position of the virtual motor and show the current
rotating direction.
background(255);
titleAndSiteInfo(); //title and site information
btn.create(); //create the button
if (isMotorRun) { //motor is runnig
fill(0);
textAlign(LEFT,BOTTOM);
textSize(20);
if (m.dir == m.CW) {
text("CW",btn.x,btn.y); //text "CW "
rotaPosition+=rotaSpeed;
if (rotaPosition>=TWO_PI) {
rotaPosition = 0;
}
} else if (m.dir == m.CCW) {
text("CCW",btn.x,btn.y); //text "CCW"
rotaPosition-=rotaSpeed;
if (rotaPosition<=0) {
rotaPosition = TWO_PI;
}
}
}
And then determine whether the stepping motor is in stoping state according to the value of “m.steps”. If it
is true, change the rotation direction of motor, and drive the motor to rotate a circle.
if (m.steps<=0) { //if motor has stopped,
if (m.dir == m.CCW) { //change the direction ,restart.
m.moveSteps(m.CW, 1, 512);
} else if (m.dir == m.CW) {
m.moveSteps(m.CCW, 1, 512);
}
114 Chapter 16 Stepping Motor www.freenove.com █
Component List
Jumper M/M x8
116 Chapter 17 Matrix Keypad www.freenove.com █
Component knowledge
Circuit
Schematic diagram
118 Chapter 17 Matrix Keypad www.freenove.com █
Hardware connection
█ www.freenove.com Chapter 17 Matrix Keypad 119
Sketch
Calculator achieve the basic operation of add, subtract, multiply and divide. Button "C" means Clear, namely,
clear the current content. When a button is pressed, the color of corresponding button on the virtual
keyboard will be changed into green, which indicates that the button is pressed.
In the code, first define key code of the Keypad, and the GPIO connected to the Keypad. Then create a Keypad
class object based on the information, and finally create a Calculator class object according to the Keypad
class object.
final static char[] keys = { //key code
'1', '2', '3', '+',
'4', '5', '6', '-',
'7', '8', '9', '*',
'C', '0', '=', '/' };
final int[] rowsPins = {18, 23, 24, 25}; //Connect to the row pinouts of the keypad
final int[] colsPins = {10, 22, 27, 17}; //Connect to the column pinouts of the keypad
Keypad kp = new Keypad(keys, rowsPins, colsPins); //class Object
Calculator cc = new Calculator(kp); //class Object
In draw(), use cc.process() to obtain the key code of Keypad and for processing. And then draw the display
area and virtual Keypad.
void draw() {
background(102);
titleAndSiteInfo(); //Tile and site information
cc.process(); //Get key and processing
drawDisplay(cc.contentStr); //Draw display area and content
drawKeypad(width-kpSize, 70); //draw virtual Keypad
}
122 Chapter 17 Matrix Keypad www.freenove.com █
Component List
Circuit
Schematic diagram
Hardware connection
█ www.freenove.com Chapter 18 Infrared Motion Sensor 125
Sketch
11 void draw() {
12 background(102);
13 titleAndSiteInfo();
14 //if read sensor for high level
15 if (GPIO.digitalRead(sensorPin) == GPIO.HIGH) {
16 GPIO.digitalWrite(ledPin, GPIO.HIGH); //led on
17 fill(64,255,64); //fill in green
18 } else {
19 GPIO.digitalWrite(ledPin, GPIO.LOW); //led off
20 fill(255); //fill in white
21 }
22 ellipse(width/2,height/2,height/2,height/2);
23 }
24
25 void titleAndSiteInfo() {
26 fill(0);
27 textAlign(CENTER); //set the text centered
28 textSize(40); //set text size
29 text("SENSE LED", width / 2, 40); //title
30 textSize(16);
31 text("www.freenove.com", width / 2, height - 20); //site
32 }
In this project, the code is relatively simple. In the function draw(), read level of sensor pin. When it is a high
level, LED is turned on. At the same time the filled color will be changed to green. When Low, LED off, and
filled color white. Finally draw a circle.
void draw() {
background(102);
titleAndSiteInfo();
//if read sensor for high level
if (GPIO.digitalRead(sensorPin) == GPIO.HIGH) {
GPIO.digitalWrite(ledPin, GPIO.HIGH); //led on
fill(64,255,64); //fill in green
} else {
GPIO.digitalWrite(ledPin, GPIO.LOW); //led off
fill(255); //fill in white
}
ellipse(width/2,height/2,height/2,height/2);
}
█ www.freenove.com App 1 Oscilloscope 127
App 1 Oscilloscope
We have used the PCF8591 to read the voltage of potentiometer to realize function of the voltmeter, before.
In this chapter, we will make a more complex virtual instrument, oscilloscope. Oscilloscope is a widely used
electronic measuring instrument. It can get the electrical signals not directly observed into visible image to
facilitate the analysis and study of various electrical signals change process.
Component List
Circuit
Note that the power supply voltage of PCF8591 in this circuit is 5V.
Schematic diagram
Hardware connection
█ www.freenove.com App 1 Oscilloscope 129
Sketch
The left side of the software interface is a voltage scale, which is used to indicate the voltage of the waveform.
The "1000ms" on top left corner is the time of a square, and you can press “↑” and “↓” key on keyboard to
adjust it.
The "0.00V" on top right corner is the voltage value of current signal.
You can press the space bar on keyboard to pause the display waveform, which is easy to view and analysis.
We believe that with the help of this oscilloscope, you can obtain more intuitive understanding of the actual
work of some electronic circuits. It will help you complete the project and eliminate the trouble. You can
export this sketch to an application used as a tool.
130 App 2 Control Graphics www.freenove.com █
This project uses two potentiometers to control the size and shape of an ellipse respectively.
Component List
Circuit
Schematic diagram
Hardware connection
132 App 2 Control Graphics www.freenove.com █
Sketch
Component List
Circuit
Schematic diagram
Hardware connection
█ www.freenove.com App 3 Pong Game 135
Sketch
Pressing the space bar keyboard can start the game. Then you can try to turn the potentiometer to control
the movement of paddle:
Use potentiometer to control the movement of paddle to turn back the ball. The rules are the same as the
classic Pong game:
█ www.freenove.com App 3 Pong Game 137
The game will be over when one side gets three points. Pressing the space can restart the game:
You can restart the game by pressing the space bar at any time during the game.
138 App 4 Snake Game www.freenove.com █
Component List
Circuit
Schematic diagram
Hardware connection
140 App 4 Snake Game www.freenove.com █
Sketch
You can control the movement direction of the snake through the four buttons in circuit or four arrow keys
on the keyboard. The rules are the same as the classic Snake game:
142 App 4 Snake Game www.freenove.com █
When game is over, pressing the space can restart the game:
You can restart the game by pressing the space bar at any time during the game.
█ www.freenove.com App 5 Tetris Game 143
Component List
Circuit
Schematic diagram
Hardware connection
█ www.freenove.com App 5 Tetris Game 145
Sketch
The left and right button in the circuit can control the moving of the falling block to left or right. And the
button below can accelerate falling of the block. The button above is used for rotating of the block. Four
direction keys on keboard can also be used to play the game.
146 App 5 Tetris Game www.freenove.com █
In the process of game, pressing the space bar on the keyboard can pause the game. The right side of the
Display Window shows the next upcoming block, the current game speed and the current score. The more
lines you eliminate once, the higher the scores. If you eliminate one line once, you will get 10 points. If you
eliminate 4 lines once, you will get 70 points.
█ www.freenove.com App 5 Tetris Game 147
When the blocks are beyond the screen, the game is over. After the game is over, press the space bar to start
a new game.
148 What's next? www.freenove.com █
What's next?
Thanks for your reading.
This tutorial is all over here. If you find any mistakes, missions or you have other ideas and questions about
contents of this tutorial or the kit and ect, please feel free to contact us, and we will check and correct it as
soon as possible.
If you want to learn more about Arduino, Raspberry Pi, smart cars, robots and orther interesting products in
science and technology, please continue to focus on our website. We will continue to launch cost-effective,
innovative and exciting products.