Page 4
5 Add Libraries What is Library? ..........Add libraries .
Page 5
8 Play with Scratch Install and Introduce PictoBlox ........346 Projects .
Page 7
SunFounder uno-and-mega-kit With this kit, we will walk you through the know-how of using the SunFounder board in a hands-on way. Starting with the basics of electronics, you’ll learn through building several creative projects. Including a selection of the most common and useful electronic components, this kit will help you “control”...
Below is the introduction to each component, which contains the operating principle of the component and the corre- sponding projects. Basic 2.1 SunFounder R3 Board Note: The SunFounder R3 board is a mainboard with almost the same functions as the Arduino Uno, and the two...
Page 16
SunFounder R3 board is a microcontroller board based on the ATmega328P (datasheet). It has 14 digital input/output pins (of which 6 can be used as PWM outputs), 6 analog inputs, a 16 MHz ceramic resonator (CSTCE16M0V53-R0), a USB connection, a power jack, an ICSP header and a reset button.
• WIDTH: 53.4 mm • WEIGHT: 25 g • I2C Port: A4(SDA), A5(SCL) What’s More • Arduino IDE • Arduino Programming Language Reference • Install and Introduce Arduino IDE • ATmega328P Datasheet 2.2 SunFounder Mega Board 2.2. SunFounder Mega Board...
Page 18
USB cable or power it with a AC-to-DC adapter or battery to get started. The SunFounder Mega Board board is compatible with most shields designed for the Uno and the former boards Duemilanove or Diecimila.
SunFounder uno-and-mega-kit If you want to know more about breadboard, refer to: How to Use a Breadboard - Science Buddies 2.4 Jumper Wires Wires that connect two terminals are called jumper wires. There are various kinds of jumper wires. Here we focus on those used in breadboard.
SunFounder uno-and-mega-kit 2.5 Resistor Resistor is an electronic element that can limit the branch current. A fixed resistor is a kind of resistor whose resistance cannot be changed, while that of a potentiometer or a variable resistor can be adjusted.
Page 22
SunFounder uno-and-mega-kit As shown in the card, each color stands for a number. Black Brown Orange Yellow Green Blue Violet Grey White Gold Silver 0.01 The 4- and 5-band resistors are frequently used, on which there are 4 and 5 chromatic bands.
Page 23
Lesson 1 Blinking LED (Mega Board Project) • Lesson 3 Controlling LED by Button (Mega Board Project) • Lesson 1 Blinking LED (R3 Board Project) • Lesson 3 Controlling LED by Button (R3 Board Project) • 15. GAME - Eat Apple (Scratch Project) •...
SunFounder uno-and-mega-kit 2.6 Transistor Transistor is a semiconductor device that controls current by current. It functions by amplifying weak signal to larger amplitude signal and is also used for non-contact switch. A transistor is a three-layer structure composed of P-type and N-type semiconductors. They form the three regions internally.
Page 25
SunFounder uno-and-mega-kit When a High level signal goes through an NPN transistor, it is energized. But a PNP one needs a Low level signal to manage it. Both types of transistor are frequently used for contactless switches, just like in this experiment.
Page 28
There are 103 or 104 label on the ceramic capacitors, which represent the capacitance value, 103=10x10^3pF, 104=10x10^4pF Unit Conversion 1F=10^3mF=10^6uF=10^9nF=10^12pF Example • Lesson 4 Doorbell (Mega Board Project) • Lesson 4 Doorbell (R3 Board Project) • 7. Doorbell (Scratch Project) • (Scratch Project) 15. GAME - Eat Apple Chapter 2. Components Introduction...
SunFounder uno-and-mega-kit 2.8 Diode A diode is an electronic component with two electrodes. It allows current to flow in only one direction, which is often called the “Rectifying” function. Thus, a diode can be thought of as an electronic version of a check valve.
Example • Lesson 6 Relay (Mega Board Project) • (R3 Board Project) Lesson 6 Relay Chip 2.9 74HC595 The 74HC595 consists of an 8bit shift register and a storage register with threestate parallel outputs. It converts serial input into parallel output so you can save IO ports of an MCU. When MR (pin10) is high level and OE (pin13) is low level, data is input in the rising edge of SHcp and goes to the memory register through the rising edge of SHcp.
• (Mega Board Project) Lesson 23 Simple Creation - Digital Dice • Lesson 18 74HC595 (R3 Board Project) • Lesson 23 Simple Creation - Digital Dice (R3 Board Project) 2.10 L293D L293D is a 4-channel motor driver integrated by chip with high voltage and high current. It’s designed to connect to standard DTL, TTL logic level, and drive inductive loads (such as relay coils, DC, Stepper Motors) and power switching transistors etc.
• L293D Datasheet Example • Lesson 22 Simple Creation-Small Fan (Mega Board Project) • (R3 Board Project) Lesson 22 Simple Creation-Small Fan • 13. Rotating Fan (Scratch Project) Display 2.11 LED Semiconductor light-emitting diode is a type of component which can turn electric energy into light energy via PN junctions.
Page 33
Lesson 1 Blinking LED • Lesson 8 Controlling an LED by Potentiometer (Mega Board Project) • Lesson 1 Blinking LED (R3 Board Project) • Lesson 8 Controlling an LED by Potentiometer (R3 Board Project) • 2. Table Lamp (Scratch Project) •...
SunFounder uno-and-mega-kit 2.12 RGB LED RGB LEDs emit light in various colors. An RGB LED packages three LEDs of red, green, and blue into a transparent or semitransparent plastic shell. It can display various colors by changing the input voltage of the three pins and superimpose them, which, according to statistics, can create 16,777,216 different colors.
Page 35
find a cut. The pin closest to the cut is the first pin, marked as Red, then GND, Green and Blue in turn. Example • Lesson 7 RGB LED (Mega Board Project) • Lesson 7 RGB LED (R3 Board Project) • (Scratch Project) 4. Colorful Balls 2.12. RGB LED...
SunFounder uno-and-mega-kit 2.13 7-segment Display A 7-segment display is an 8-shaped component which packages 7 LEDs. Each LED is called a segment – when energized, one segment forms part of a numeral (both decimal and hexadecimal) to be displayed. An additional 8th LED is sometimes used within the same package thus allowing the indication of a decimal point (DP) when two or more 7-segment displays are connected together to display numbers greater than ten.
SunFounder uno-and-mega-kit 2.14 4-Digit 7-Segment Display 4-Digit 7-segment display consists of four 7- segment displays working together. The 4-digtal 7-segment display works independently. It uses the principle of human visual persistence to quickly display the characters of each 7-segment in a loop to form continuous strings.
• Lesson 20 Simple Creation-Stopwatch (Mega Board Project) • (R3 Board Project) Lesson 20 Simple Creation-Stopwatch 2.15 LCD1602 LCD1602, or 1602 character-type liquid crystal display, is a kind of dot matrix module to show letters, numbers, and characters and so on. It’s composed of 5x7 or 5x11 dot matrix positions; each position can display one character.
Example • Lesson 11 LCD1602 (Mega Board Project) • (Mega Board Project) Lesson 15 Humiture Sensor • Lesson 11 LCD1602 (R3 Board Project) • Lesson 15 Humiture Sensor (R3 Board Project) • 5. LCD1602 (Scratch Project) Sound 2.16 Buzzer As a type of electronic buzzer with an integrated structure, buzzers, which are supplied by DC power, are widely used in computers, printers, photocopiers, alarms, electronic toys, automotive electronic devices, telephones, timers and other electronic products or voice devices.
(Mega Board Project) • Lesson 21 Simple Creation-Answer Machine (Mega Board Project) • Lesson 4 Doorbell (R3 Board Project) • Lesson 21 Simple Creation-Answer Machine (R3 Board Project) Driver 2.17 DC Motor This is a 3V DC motor. When you give a high level and a low level to each of the 2 terminals, it will rotate.
Page 42
SunFounder uno-and-mega-kit • Size: 25*20*15MM • Operation Voltage: 1-6V • Free-run Current (3V): 70m • A Free-run Speed (3V): 13000RPM • Stall Current (3V): 800mA • Shaft Diameter: 2mm Direct current (DC) motor is a continuous actuator that converts electrical energy into mechanical energy. DC motors make rotary pumps, fans, compressors, impellers, and other devices work by producing continuous angular rotation.
• (Mega Board Project) Lesson 22 Simple Creation-Small Fan • Lesson 22 Simple Creation-Small Fan (R3 Board Project) • 13. Rotating Fan (Scratch Project) 2.18 Stepper Motor Stepper motors, due to their unique design, can be controlled to a high degree of accuracy without any feedback mechanisms.
Page 44
SunFounder uno-and-mega-kit similar situation goes on and on. Energize the A, B, C and D phases in turn, and the rotor will rotate in the order of A, B, C and D. The four-phase stepper motor has three operating modes: single four-step, double four-step, and eight-step. The step angle for the single four-step and double four-step are the same, but the driving torque for the single four-step is smaller.
Lesson 19 Stepper Motor (Mega Board Project) • Lesson 20 Stepper Motor (R3 Board Project) 2.19 Servo A servo is generally composed of the following parts: case, shaft, gear system, potentiometer, DC motor, and embed- ded board. It works like this: The microcontroller sends out PWM signals to the servo, and then the embedded board in the servo receives the signals through the signal pin and controls the motor inside to turn.
Generally the minimum pulse will be about 0.5 ms wide and the maximum pulse will be 2.5 ms wide. Example • Lesson 10 Servo (Mega Board Project) • (R3 Board Project) Lesson 10 Servo • 12. Pendulum (Scratch Project) 2.20 Relay...
Page 47
SunFounder uno-and-mega-kit As we may know, relay is a device which is used to provide connection between two or more points or devices in response to the input signal applied. In other words, relays provide isolation between the controller and the device as devices may work on AC as well as on DC.
SunFounder uno-and-mega-kit • Lesson 6 Relay (R3 Board Project) 2.21 Power Supply Module When we need a large current to drive a component, which will severely interfere with the normal work of main board. Therefore, we separately supply power for the component by this module to make it run safely and steadily.
SunFounder uno-and-mega-kit 2.22 Button Buttons are a common component used to control electronic devices, they are usually used as switches to connect or break circuits. The following is the internal structure of a button. The symbol on the right below is usually used to represent a button in circuits.
SunFounder uno-and-mega-kit 2.23 Potentiometer Potentiometer is also a resistance component with 3 terminals and its resistance value can be adjusted according to some regular variation. Potentiometers come in various shapes, sizes, and values, but they all have the following things in common: •...
If you want to know more about potentiometer, refer to: Potentiometer - Wikipedia Example • Lesson 9 Photo resistor (Mega Board Project) • Lesson 9 Photo resistor (R3 Board Project) • 6. Moving Mouse (Scratch Project) • (Scratch Project) 17. GAME - Breakout Clone 2.24 Joystick Module The basic idea of a joystick is to translate the movement of a stick into electronic information that a computer can process.
(M), while in the light, a photoresistor can have a resistance as low as a few hundred ohms. Here is the electronic symbol of photoresistor. • Photoresistor - Wikipedia Example • Lesson 9 Photo resistor (Mega Board Project) • (R3 Board Project) Lesson 9 Photo resistor • 10. Light Alarm Clock (Scratch Project) Chapter 2. Components Introduction...
SunFounder uno-and-mega-kit 2.26 Thermistor A thermistor is a type of resistor whose resistance is strongly dependent on temperature, more so than in standard resistors. The word is a combination of thermal and resistor. Thermistors are widely used as inrush current limiters, temperature sensors (negative temperature coefficient or NTC type typically), self-resetting overcurrent protectors,...
• (Mega Board Project) Lesson 12 Thermistor • Lesson 12 Thermistor (R3 Board Project) • 9. Low Temperature Alarm (Scratch Project) 2.27 Tilt Switch The tilt switch used here is a ball one with a metal ball inside. It is used to detect inclinations of a small angle.
SunFounder uno-and-mega-kit 2.29 Ultrasonic Module An ultrasonic sensor module is an instrument that measures the distance to an object using ultrasonic sound waves. It has two probes. One is to send ultrasonic waves and the other is to receive the waves and transform the time of sending and receiving into a distance, thus detecting the distance between the device and an obstacle.
• Lesson 13 Ultrasonic (Mega Board Project) • Lesson 13 Ultrasonic (R3 Board Project) • 16. GAME - Flappy Parrot (Scratch Project) 2.30 Humiture Sensor Module The digital temperature and humidity sensor DHT11 is a composite sensor that contains a calibrated digital signal output of temperature and humidity.
If you want to download all the codes to your local folder at once, please visit the link below: https://github.com/sunfounder/sunfounder-uno-and-mega-kit This is a github repository, which contains 3 folders, the Uno Kit and Mega Kit folders contain the Arduino code and libraries, datasheet and fritzing files, and the Scratch folder contains the code and pictures.
Page 64
SunFounder uno-and-mega-kit Chapter 3. Download the Code...
CHAPTER FOUR INSTALL AND INTRODUCE ARDUINO IDE 4.1 Description Arduino is an open source platform with simple software and hardware. You can pick it up in short time even if you are a beginner. It provides an integrated development environment (IDE) for code compiling, compatible with multiple control boards.
Page 66
SunFounder uno-and-mega-kit Find the one that suits your operation system and click to download. There are two versions of Arduino for Windows: Installer or ZIP file. You’re recommended to download the former. 4.2.1 For Installer File Step 1: Find the .exe file just downloaded.
Page 67
SunFounder uno-and-mega-kit Step 3: Click Next. Step 4: Select the path to install. By default, it’s set in the C disk. You can click Browse and choose other paths. Click OK. Then click Install. 4.2. Install Arduino IDE...
Page 68
SunFounder uno-and-mega-kit Step 5: Meanwhile, it will prompts install the needed drivers, please select the ‘Always trust software from “Arduino LLC” ’. After the installation is done, click Close. Note: The new IDE may prompt errors when you’re compiling code under Windows XP. So if your computer is running on XP, you’re suggested to install Arduino 1.0.5 or 1.0.6.
Page 69
SunFounder uno-and-mega-kit Step3: Right click on Arduino Mega 2560 and select Update Driver Software. 4.2. Install Arduino IDE...
Page 70
SunFounder uno-and-mega-kit Step4: Choose the second option, Browse my computer for Driver software. Chapter 4. Install and Introduce Arduino IDE...
Page 71
SunFounder uno-and-mega-kit Step5: A window pops up then. Click Browse. Then go to the folder where you just extracted the file. Go to the drivers folder and click OK -> Next. 4.2. Install Arduino IDE...
Page 72
SunFounder uno-and-mega-kit Step6: Select ‘Always trust software from “Arduino LLC” ‘ then click Install. Chapter 4. Install and Introduce Arduino IDE...
Page 73
SunFounder uno-and-mega-kit It may need a sec. Then the system prompts you the driver has been installed successfully. So the computer can recognize the board now. Click Close. 4.2. Install Arduino IDE...
Page 74
SunFounder uno-and-mega-kit 4.2.3 Open the Arduino Software (IDE) Double-click the Arduino icon (arduino.exe) created by the installation process Then the Arduino IDE will appear. Let’s check details of the software. Chapter 4. Install and Introduce Arduino IDE...
Page 75
SunFounder uno-and-mega-kit 1. Verify: Compile your code. Any syntax problem will be prompted with errors. 2. Upload: Upload the code to your board. When you click the button, the RX and TX LEDs on the board will flicker fast and won’t stop until the upload is done.
Page 76
SunFounder uno-and-mega-kit 5. Save: Save the sketch. 6. Serial Monitor: Click the button and a window will appear. It receives the data sent from your control board. It is very useful for debugging. 7. File: Click the menu and a drop-down list will appear, including file creating, opening, saving, closing, some parameter configuring, etc.
CHAPTER FIVE ADD LIBRARIES 5.1 What is Library? A library, gathering some function definitions and header files, usually contains two files: .h (header file, including function statement, Macro definition, constructor definition, etc.) and .cpp (execution file, with function implementa- tion, variable definition, and so on). When you need to use a function in some library, you just need to add a header file (e.g.
Page 78
SunFounder uno-and-mega-kit Step 2: Find SunFounder Mega KitLibrary, Click Open. Step 3: When you see “Library added to your libraries. Check “Include library” menu”, it means you have added the library successfully. Please use the same method to add other libraries then.
Page 79
SunFounder uno-and-mega-kit 5.2.2 Method 2 Directly copy the library to libraries/Arduino path. This method can copy all libraries and add them at a time, but the drawback is that it is difficult to find libraries/Arduino. Step 1: Click File -> Preferences and on the pop-up window you can see the path of the libraries folder in the text box as shown below.
Page 80
SunFounder uno-and-mega-kit Step 3: Go to the path above and you will see there is a libraries folder, click to open it. Step 4: Paste all the libraries copied before to the folder. Then you can see them in libraries folder.
Page 81
SunFounder uno-and-mega-kit 5.2.3 Method 3 Using the Library Manager to install a new library into the Arduino IDE. Step1: Click Sketch -> Include Library ->Manage Libraries Step2: Input a library name to search it, such as dht, you can choose the latest version to install.
6.1 Lesson 1 Blinking LED 6.1.1 Introduction You should’ve learnt how to install Arduino IDE and add libraries before. Now you can start with a simple experiment to learn the basic operation and code in the IDE. 6.1.2 Components • SunFounder Mega Board...
Page 84
SunFounder uno-and-mega-kit • Breadboard • Jumper Wires • • Resistor Principle Connect one end of the 220ohm resistor to pin 9 of the Mega 2560 and the other end to the anode (the long pin) of the LED, and the cathode (the short pin) of the LED to GND. When the pin 9 outputs high level, the current gets through the current limiting resistor to the anode of the LED.
Page 85
SunFounder uno-and-mega-kit Step Open Lesson_1_Blinking_LED.ino code file path SunFounder Mega Kit\Code\Lesson_1_Blinking_LED Step 3: Select the Board and Port Before uploading the code, you need to select the Board and Port. Click Tools ->Board and select Arduino/Genuino Mega or Mega 2560.
Page 86
SunFounder uno-and-mega-kit Then select Tools ->Port. Your port should be different from mine. Step 4: Upload the sketch to the SunFounder Mega2560 board Click the Upload icon to upload the code to the control board. Chapter 6. For Mega2560 User...
Page 87
SunFounder uno-and-mega-kit If “Done uploading” appears at the bottom of the window, it means the sketch has been successfully uploaded. You should now see the LED blinking. 6.1. Lesson 1 Blinking LED...
Page 88
SunFounder uno-and-mega-kit 6.1.4 Code Code Analysis Define variables ledPin //the number of the LED pin const int You should define every variable before using in case of making mistakes. This line defines a constant variable ledPin for the pin 9. In the following code, ledPin stands for pin 9. You can also directly use pin 9 instead.
SunFounder uno-and-mega-kit (continued from previous page) pinMode(ledPin,OUTPUT);//initialize the digital pin as an output The setup() function here sets the ledPin as OUTPUT. pinMode(Pin): Configures the specified pin to behave either as an input or an output. The void before the setup means that this function will not return a value. Even when no pins need to be initialized, you still need this function.
Page 90
SunFounder uno-and-mega-kit 6.2.2 Components • SunFounder Mega Board • Breadboard • Jumper Wires • • Resistor 6.2.3 Schematic Diagram The principle of this experiment is simply to turn on eight LEDs in turn. The eight LEDs are connected to pin 2-pin 9 respectively.
Page 91
SunFounder uno-and-mega-kit 6.2.4 Experimental Procedures Step 1: Build the circuit 6.2. Lesson 2 Flowing LED Lights...
Page 92
SunFounder uno-and-mega-kit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. Now, you should see eight LEDs brighten one by one from the LED connected to pin 2 to that to pin 9, and then dim in turn from the LED at pin 9 to the one at pin 2.
Page 93
SunFounder uno-and-mega-kit 6.2.5 Code Code Analysis for() statement for (int 2; i <= 9; i++) / * 8 LEDs are connect to pin2-pin9, When i=2, which accords with the condition i<=9, then run the code in the curly braces, set the pin2 to OUTPUT.
Page 94
SunFounder uno-and-mega-kit for (initialization; condition; increment) { //statement(s); }: The for statement is used to repeat a block of statements enclosed in curly braces.The initialization happens first and exactly once. Each time through the loop, the condition is tested; if it’s true, the statement block, and the increment is executed, then the condition is tested again. When the condition becomes false, the loop ends.
INPUT and OUTPUT port. Here the INPUT port of the Mega 2560 board is used to read the output of an external device. Since the board itself has an LED (connected to Pin 13), you can use this LED to do this experiment for convenience. 6.3.2 Components • SunFounder Mega Board • Breadboard • Jumper Wires •...
Page 96
SunFounder uno-and-mega-kit • Button 6.3.3 Schematic Diagram Connect one end of the buttons to pin 12 which connects with a pull-down resistor and a 0.1uF (104) capacitor (to eliminate jitter and output a stable level when the button is working). Connect the other end of the resistor to GND and one of the pins at the other end of the button to 5V.
Page 97
SunFounder uno-and-mega-kit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. Now, press the button, and the LED on the mega2560 board will light up. 6.3. Lesson 3 Controlling LED by Button...
Page 98
SunFounder uno-and-mega-kit 6.3.5 Code Code Analysis Define variables const int buttonPin //the button connect to pin 12 const int ledPin //the led connect to pin13 buttonState // variable for reading the pushbutton status Connect the button to pin 12. LED has been connected to pin 13. Define a variable buttonState to restore the state of the button.
SunFounder uno-and-mega-kit Set the input and output status of the pins pinMode(buttonPin, INPUT); //initialize thebuttonPin as input pinMode(ledPin, OUTPUT); //initialize the led pin as output We need to know the status of the button in this experiment, so here set the buttonPin as INPUT; to set HIGH/LOW of the LED, we set LedPin as OUTPUT.
Page 101
SunFounder uno-and-mega-kit 6.4.3 Schematic Diagram In this experiment, we use an active buzzer. The schematic diagram 6.4. Lesson 4 Doorbell...
Page 102
SunFounder uno-and-mega-kit 6.4.4 Experimental Procedures Step 1: Build the circuit (Long pins of buzzer is the Anode and the short pin is Cathode). Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board.
Page 103
SunFounder uno-and-mega-kit 6.4.5 Code Code Analysis Define variables const int buttonPin //the button connect to pin2 const int buzzerPin //the buzzer connect to pin8 / ********************************** / buttonState //variable for reading the pushbutton status Connect the button to pin 2 and buzzer to pin 8. Define a variable buttonState to restore the state of the button.
Page 104
SunFounder uno-and-mega-kit (continued from previous page) pinMode(buttonPin, INPUT); //initialize the buttonPin as input pinMode(buzzerPin, OUTPUT); //initialize the buzzerpin as output We need to know the status of the button in this experiment, so here set the buttonPin as INPUT; to set HIGH/LOW of the buzzer, we set buzzerPin as OUTPUT.
6.5 Lesson 5 Tilt Switch 6.5.1 Introduction The tilt switch used here is a ball one with a metal ball inside. It is used to detect inclinations of a small angle. 6.5.2 Components • SunFounder Mega Board • Breadboard • Jumper Wires •...
Page 106
SunFounder uno-and-mega-kit 6.5.3 Schematic Diagram The schematic diagram: 6.5.4 Experimental Procedures Step 1: Build the circuit Chapter 6. For Mega2560 User...
Page 107
SunFounder uno-and-mega-kit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. Now, tilt the switch, and the LED attached to pin 13 on Mega 2560 board will light up.
Page 108
SunFounder uno-and-mega-kit 6.5.5 Code Code Analysis Whole Code const int ledPin //the led attach to void setup() pinMode(ledPin,OUTPUT); //initialize the ledPin as an output pinMode(2,INPUT); //set pin2 as INPUT digitalWrite(2, HIGH); //set pin2 as HIGH / ****************************************** / void loop() digitalVal digitalRead(2);...
SunFounder uno-and-mega-kit 6.6 Lesson 6 Relay 6.6.1 Introduction As we may know, relay is a device which is used to provide connection between two or more points or devices in response to the input signal applied. In other words, relays provide isolation between the controller and the device as devices may work on AC as well as on DC.
Page 110
The schematic diagram: Connect a 1K resistor (for current limiting when the transistor is energized) to pin 8 of the SunFounder Mega2560 board, then to an NPN transistor whose collector is connected to the coil of a relay and emitter to GND; connect the normally open contact of the relay to an LED and then GND.
Page 111
SunFounder uno-and-mega-kit Function of the freewheeling diode When the voltage input changes from High (5V) to Low (0V), the transistor changes from saturation (three working conditions: amplification, saturation, and cut-off) to cut-off, the current in the coil suddenly has no way to flow through.
Page 112
SunFounder uno-and-mega-kit 6.6.4 Experimental Procedures Step 1: Build the circuit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. Now, send a High level signal, and the relay will close and the LED will light up; send a low one, and it will open and the LED will go out.
Page 113
SunFounder uno-and-mega-kit 6.6.5 Code 6.6.6 Code Analysis void loop() digitalWrite(relayPin, HIGH); //drive relay closure conduction delay(1000); //wait for a second digitalWrite(relayPin, LOW); //drive the relay is closed off delay(1000); //wait for a second The code in this experiment is simple. First, set relayPin as HIGH level and the LED connected to the relay will light up.
RGB LED to flash various kinds of color. When different PWM values are set to the R, G, and B pins of the LED, its brightness will be different. When the three different colors are mixed, we can see that the RGB LED flashes different colors. 6.7.2 Components • SunFounder Mega Board • Breadboard • Jumper Wires •...
Page 115
SunFounder uno-and-mega-kit 6.7.3 PWM Pulse width modulation, or PWM, is a technique for getting analog results with digital means. Digital control is used to create a square wave, a signal switched between on and off. This on-off pattern can simulate voltages in between full on (5 Volts) and off (0 Volts) by changing the portion of the time the signal spends on versus the time that the signal spends off.
Page 116
SunFounder uno-and-mega-kit connect any of these pins.Here we input a value between 0 and 255 to the three pins of the RGB LED to make it display different colors. After connecting the pins of R, G, and B to a current limiting resistor, connect them to the pin 9, pin 10, and pin 11 respectively.
Page 117
SunFounder uno-and-mega-kit 6.7.5 Experimental Procedures Step 1: Build the circuit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. Here you should see the RGB LED flash circularly red, green, and blue first, then red, orange, yellow, green, blue, indigo, and purple.
Page 118
SunFounder uno-and-mega-kit 6.7.6 Code Code Analysis Set the color Here use the color() function to set the color of the RGB LED. In the code, it is set to flash 7 different colors. You can use the paint tool on your computer to get the RGB value.
Page 119
SunFounder uno-and-mega-kit void loop() // run over and over again // Basic colors: color(255, 0, 0); // turn the RGB LED red delay(1000); // delay for 1 second color(0,255, 0); // turn the RGB LED green delay(1000); // delay for 1 second color(0, 0, 255);...
SunFounder uno-and-mega-kit void color (unsigned char red, unsigned char green, unsigned char blue) // the color generating function analogWrite(redPin, red); analogWrite(greenPin, green); analogWrite(bluePin, blue); Define three unsigned char variables, red, green and blue. Write their values to redPin, greenPin and bluePin. For example, color(128,0,128) is to write 128 to redPin, 0 to greenPin and 128 to bluePin.
Page 121
SunFounder uno-and-mega-kit 6.8.2 Components • SunFounder Mega Board • Breadboard • Jumper Wires • • Resistor • Potentiometer 6.8. Lesson 8 Controlling an LED by Potentiometer...
Page 122
SunFounder uno-and-mega-kit 6.8.3 Serial Monitor Serial Monitor is used for communication between the Mega 2560 board and a computer or other devices. It is a built-in software in the Arduino environment and you can click the button on the upper right corner to open it. You can send and receive data via the serial port on the control board and control the board by input from the keyboard.
Page 123
SunFounder uno-and-mega-kit In this experiment, the potentiometer is used as voltage divider, meaning connecting devices to all of its three pins. Connect the middle pin of the potentiometer to pin A0 and the other two pins to 5V and GND respectively. There- fore, the voltage of the potentiometer is 0-5V.
Page 124
SunFounder uno-and-mega-kit 6.8.4 Schematic Diagram 6.8.5 Experimental Procedures Step 1: Build the circuit Chapter 6. For Mega2560 User...
Page 125
SunFounder uno-and-mega-kit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. Step5: Open the Serial Monitor. Find the Serial.begin() code to see what baud rate is set, here is 9600. Then click the top right corner icon to open the Serial Monitor.
Page 126
SunFounder uno-and-mega-kit Step6: Set the baud rate to 9600. The default baud rate for serial monitors is 9600, and if the code is also set to 9600, there is no need to change the baud rate bar. Spin the shaft of the potentiometer and you should see the luminance of the LED change.
Page 127
SunFounder uno-and-mega-kit 6.8.6 Code Code Analysis Read the value from A0 inputValue analogRead(analogPin);//read the value from the potentiometer This line is to store the values A0 has read in the inputValue which has been defined before. analog Read() reads the value from the specified analog pin. This means that it will map input voltages between 0 and 5 volts into integer values between 0 and 1023.
Page 128
SunFounder uno-and-mega-kit • Serial.println(): Takes the same forms as Serial.print(), but it is followed by a carriage return character (ASCII 13, or ‘\r’) and a newline character (ASCII 10, or ‘\n’). Map the values outputValue map(inputValue, 0, 1023, 0, 255);...
In this lesson, you will learn to how to measure light intensity using a photo resistor. The resistance of a photo resistor changes with incident light intensity. If the light intensity gets higher, the resistance decreases; if it gets lower, the resistance increases. 6.9.2 Components • SunFounder Mega Board • Breadboard • Jumper Wires •...
Page 130
SunFounder uno-and-mega-kit 6.9.3 Schematic Diagram In this experiment, we will use 8 LEDs to show the light intensity. The higher the light intensity is, the more LEDs will light up. When the light intensity is high enough, all the LEDs will be on. When there is no light, all the LEDs will go out.
Page 131
SunFounder uno-and-mega-kit 6.9.4 Experimental Procedures Step 1: Build the circuit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. Now, shine some light on the photo resistor, and you will see several LEDs light up. Shine more light and you will see more LEDs light up.
Page 132
SunFounder uno-and-mega-kit 6.9.5 Code 6.9.6 Code Analysis Set the variables const int NbrLEDs // 8 leds const int ledPins[] {2, 3, 4, 5, 6, 7, 8, 9}; // 8 leds attach to pin 5-12 respectively const int photocellPin // photoresistor attach to A0...
Page 133
SunFounder uno-and-mega-kit (continued from previous page) pinMode(ledPins[led], OUTPUT); // make all the LED pins outputs Using the for() statement set the 8 pins to OUTPUT. The variable led is added from 0 to 8, and the pinMode() function sets pin5 to pin12 to OUTPUT in turn.
These pulses tell the servo what position it should move to. A servo has three wires: the brown wire is GND, the red one is VCC, and the orange one is signal line. 6.10.2 Components • SunFounder Mega Board • Breadboard •...
Page 136
SunFounder uno-and-mega-kit 6.10.4 Experimental Procedures Step 1: Build the circuit (Brown to GND, Red to VCC, Orange to pin 9 of the control board) Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board.
Page 137
SunFounder uno-and-mega-kit 6.10.5 Code 6.10.6 Code Analysis Include a library #include <Servo.h> Servo myservo; //create servo object to control a servo With the Servo.h file included, you can call the functions in this file later. Servo is a built-in library in the Arduino IDE.
SunFounder uno-and-mega-kit myservo.attach(): Attach the Servo variable to a pin. Initialize the servo attach to pin9. myservo.write(): Writes a value to the servo, controlling the shaft accordingly. On a standard servo, this will set the angle of the shaft (in degrees), moving the shaft to that orientation. Here let the servo stay in the 0 angle firstly.
Page 139
SunFounder uno-and-mega-kit 6.11.2 Components • SunFounder Mega Board • Breadboard • Jumper Wires • LCD1602 • Potentiometer 6.11.3 Schematic Diagram Connect K to GND and A to 3.3 V, and then the backlight of the LCD1602 will be turned on. Connect VSS to GND and the LCD1602 to the power source.
Page 140
SunFounder uno-and-mega-kit 6.11.4 Experimental Procedures Step 1: Build the circuit (make sure the pins are connected correctly. Otherwise, characters will not be displayed properly) Chapter 6. For Mega2560 User...
Page 141
Step 4: Upload the sketch to the board. Note: you may need to adjust the potentiometer on the LCD1602 until it can display clearly. You should now see the characters “SunFounder” and “hello, world” rolling on the LCD. 6.11. Lesson 11 LCD1602...
Page 142
SunFounder uno-and-mega-kit 6.11.5 Code 6.11.6 Code Analysis Include a library #include <LiquidCrystal.h>// include the library code With the LiquidCrystal.h file included, you can call the functions in this file later. Chapter 6. For Mega2560 User...
Page 143
SunFounder uno-and-mega-kit LiquidCrystal is a built-in library in the Arduino IDE. You can find the LiquidCrystal folder under the installation path C:\Program Files\Arduino\libraries. There is an example in the examples folder. The src folder contains the major part of the library: LiquidCrystal.cpp (execution file, with function implementation, variable definition, etc.) and LiquidCrystal.h (header file, including...
//wait for 250 microseconds Similarly, the code is to display the elements in array2[] on the LCD. Therefore, you will see “SunFounder” scroll in the top line of the LCD, move left until it disappears. And then in the bottom line, “hello, world ! ” appears, scrolls to the left until it disappears.
Page 146
SunFounder uno-and-mega-kit • LCD1602 6.12.3 Schematic Diagram Thermistor is a sensitive element, it has two types: Negative Temperature Coefficient (NTC) and Positive Temperature Coefficient (PTC), also NTC and PTC. Its resistance varies significantly with temperature. The resistance of PTC thermistor increases with higher temperature when that of NTC, decreases. In this experiment we use an NTC one.
Page 147
SunFounder uno-and-mega-kit quantities by the A/D adapter. The temperature in Celsius and Fahrenheit then is output via programming and then displayed on LCD1602. In this experiment a thermistor and a 10k pull-up resistor are used. Each thermistor has a normal resistance. Here it is 10k ohm, which is measured under 25 degree Celsius.
Page 148
SunFounder uno-and-mega-kit 6.12.4 Experimental Procedures Step 1: Build the circuit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. Now, you can see the current temperature displayed both in Celsius and Fahrenheit degrees on the LCD1602.
Page 149
SunFounder uno-and-mega-kit 6.12.5 Code 6.12.6 Code Analysis Set the variables #define analogPin A0 //the thermistor attach to #define beta 3950 //the beta of the thermistor #define resistance 10 //the value of the pull-up resistor Define the beta coefficient as 4090, which is described in the datasheet of thermistor.
SunFounder uno-and-mega-kit (continued from previous page) //read thermistor value long analogRead(analogPin); //the calculating formula of temperature tempC beta (log((1025.0 beta 298.0) 273.0; float float tempF tempC 32.0; The value of A0 (thermistor) is read, then the Celsius temperature is calculated by the formula, and then the Celsius temperature is converted to Fahrenheit temperature by the formula.
Page 152
SunFounder uno-and-mega-kit 6.13.3 Schematic Diagram The schematic diagram: 6.13.4 Experimental Procedures Step 1: Build the circuit Chapter 6. For Mega2560 User...
Page 153
SunFounder uno-and-mega-kit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. Note: If you receive the following error, it is because you didn’t add a library named NewPing, please refer to libraries.
Page 154
SunFounder uno-and-mega-kit Now, if you use a piece of paper to approach or keep it far away from the sensor. You will see the value displayed on the LCD changes, which indicates the distance between the paper and the ultrasonic sensor.
Page 155
SunFounder uno-and-mega-kit 6.13.5 Code 6.13.6 Code Analysis Initialize the ultrasonic sensor and LCD1602 #include <LiquidCrystal.h> // use #include to define the header file. #include <NewPing.h> // use #include to define the header file. LiquidCrystal lcd(4, 6, 10, 11, 12, 13);...
TTL level. It’s similar with a normal plastic-packaged transistor in size and it is suitable for all kinds of infrared remote control and infrared transmission. 6.14.2 Components • SunFounder Mega Board • Breadboard Chapter 6. For Mega2560 User...
Page 157
SunFounder uno-and-mega-kit • Jumper Wires • IR Receiver Module 6.14.3 Schematic Diagram Control a certain key (for example, Power key) via a remote controller by programming. When you press the key, infrared rays will be emitted from the remote controller and received by the infrared receiver, and the LED on the Mega 2560 board will light up.
Page 158
SunFounder uno-and-mega-kit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. Now, press Power on the remote control and the LED attached to pin 13 on the Mega 2560 board will light up. If you press other keys, the LED will go out.
Page 159
SunFounder uno-and-mega-kit 6.14.5 Code 6.14.6 Code Analysis Initialize the infrared-receiver #include <IRremote.h> const int irReceiverPin // the infrared-receiver attact to pin2 const int ledPin // built-in LED IRrecv irrecv(irReceiverPin); // Initialize the infrared-receiver decode_results results; // The decoding result is placed in the result of the decode results structure.
Page 160
SunFounder uno-and-mega-kit Enable infrared-receiver irrecv.enableIRIn(); // Restart the receiver Receive and print the data (irrecv.decode(&results)) { // If receive a data decode(&results): Decodes the received IR message, returns 0 if no data ready, 1 if data ready. Results of decoding are stored in results Serial.print("irCode:...
SunFounder uno-and-mega-kit (continued from previous page) else digitalWrite(ledPin,LOW); // else turn of the LED 6.15 Lesson 15 Humiture Sensor 6.15.1 Introduction The digital temperature and humidity sensor DHT11 is a composite sensor that contains a calibrated digital signal output of temperature and humidity. The technology of a dedicated digital modules collection and the temperature and humidity sensing technology are applied to ensure that the product has high reliability and excellent long-term stability.
Page 164
SunFounder uno-and-mega-kit 6.15.4 Experimental Procedures Step 1: Build the circuit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. Now, you can see the value of the current humidity and temperature displayed on the LCD.
Page 165
SunFounder uno-and-mega-kit 6.15.5 Code 6.15.6 Code Analysis Initialize the humiture and LCD1602 #include <dht.h> // Include the head file dht.h #include <LiquidCrystal.h> LiquidCrystal lcd(4, 6, 10, 11, 12, 13); // initialize the LCD1602 dht DHT; #define DHT11_PIN 3 // the humiture sensor attact to pin3...
Page 166
SunFounder uno-and-mega-kit Read the value of humiture DHT.read11(DHT11_PIN); switch (chk) case DHTLIB_OK: Serial.println("OK,\t"); break; case DHTLIB_ERROR_CHECKSUM: Serial.println("Checksum error,\t"); break; case DHTLIB_ERROR_TIMEOUT: Serial.println("Time out error,\t"); break; default: Serial.println("Unknown error,\t"); break; Use the read11() function to read the value of the temperature and humidity sensor. If OK is displayed on the Serial Monitor, the humiture sensor is working properly.
A joystick is an input device consisting of a stick that pivots on a base and reports its angle or direction to the device it is controlling. Joysticks are often used to control video games and robots. A Joystick PS2 is used here. 6.16.2 Components • SunFounder Mega Board • Breadboard •...
Page 168
SunFounder uno-and-mega-kit 6.16.3 Schematic Diagram This module has two analog outputs (corresponding to XY biaxial offsets) and one digital output representing whether it is pressed on Z axis. The module integrates power indicator and can display operation condition. In this experiment, we use the Mega 2560 board to detect the moving direction of the Joystick knob and pressing of the button.
Page 169
SunFounder uno-and-mega-kit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. Now, push the rocker and the coordinates of X and Y axes displayed on Serial Monitor will change accordingly; press the button, and the coordinate of Z=0 will also be displayed.
Page 170
SunFounder uno-and-mega-kit 6.16.5 Code 6.16.6 Code Analysis The code is use the Serial monitor to print the value of the VRX,VRY and SW pins of the joystick ps2. void loop() Serial.print("X: "); Serial.print(analogRead(xPin), DEC); // print the value of VRX in DEC Serial.print("|Y:...
Different letters/numbers can be shown by connecting pins on the display to the power source and enabling the related pins, thus turning on the corresponding LED segments. In this lesson let’s learn how to display specific characters on it. 6.17.2 Components • SunFounder Mega Board 6.17. Lesson 17 7-Segment Display...
Page 172
SunFounder uno-and-mega-kit • Breadboard • Jumper Wires • Resistor • 7-segment Display 6.17.3 Schematic Diagram In this experiment, connect each of pin a-g of the 7-Segment Display to one 220ohm current limiting resistor respec- tively and then to pin 4–11. GND connects to GND. By programming, we can set one or several of pin4-11 as High level to light up the corresponding LED(s).
Page 173
SunFounder uno-and-mega-kit 6.17.4 Experimental Procedures Step 1: Build the circuit (here a common cathode 7-segment display is used) The wiring between the 7-segment display and the Mega2560 board : 7-Segment Mega2560 Board “ - “ 6.17. Lesson 17 7-Segment Display...
Page 174
SunFounder uno-and-mega-kit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. You should now see the 7-segment display from 0 to 9 and then A to F, back and forth.
Page 175
SunFounder uno-and-mega-kit 6.17.5 Code 6.17.6 Code Analysis The code may be a little long for this experiment. But the syntax is simple. Let’s take a look. Call the function in loop() digital_1(); //diaplay 1 to the 7-segment delay(1000); //wait for a second digital_2();...
Page 176
SunFounder uno-and-mega-kit (continued from previous page) digitalWrite(b,HIGH); digitalWrite(a,HIGH); <= 11;j++) for(int digitalWrite(j,HIGH); digitalWrite(c,LOW); digitalWrite(f,LOW); First we need to know how it looks like when display the numeral 2 on the 7-Segment display. It’s actually the segments a, b, d, e and g are power on, which generates the display of 2. In programming, pins connected to these segments are set High level when c and f are Low level.
Mega 2560board and then the 7-segment display to the 74HC595. In this experiment, we will use the latter. By this way, we can save five ports – considering the Mega 2560 board’s limited ports, this is very important. Now let’s get started! 6.18.2 Components • SunFounder Mega Board • Breadboard • Jumper Wires •...
Page 178
SunFounder uno-and-mega-kit 6.18.3 Schematic Diagram In the experiment MR (pin10) is connected to 5V (HIGH Level) and OE (pin 1) to GND (LOW Level). Therefore, the data is input into the rising edge of SHcp and enters the memory register through the rising edge. We use the shiftout() function to output a 8-bit data to the shift register through DS.
Page 179
SunFounder uno-and-mega-kit 6.18.4 Experimental Procedures Step 1: Build the circuit (pay attention to the direction of the chip by the concave on it) 7-Segment Display 74HC595 Mega2560 Kit Q7’ • 6.18. Lesson 18 74HC595...
Page 180
SunFounder uno-and-mega-kit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. You should now see the 7-segment display from 0 to 9 and A to F. Chapter 6. For Mega2560 User...
Page 181
SunFounder uno-and-mega-kit 6.18.5 Code 6.18.6 Code Analysis Set the array elements This array stores the data of the 16 characters from 0 to F. 252 stands for 0, which you can calculate by yourself. To display 0, the segment g (the middle one) of the 7-segment display must be low level (dim).
SunFounder uno-and-mega-kit for(int 0; num < 16; num++) digitalWrite(STcp,LOW); //ground ST_CP and hold low for as long as you are transmitting shiftOut(DS,SHcp,MSBFIRST,datArray[num]); //return the latch pin high to signal chip that it //no longer needs to listen for information digitalWrite(STcp,HIGH);...
Page 184
SunFounder uno-and-mega-kit 6.19.3 Schematic Diagram The schematic diagram of the Stepper Motor Driver: 6.19.4 Experimental Procedures Step 1: Build the circuit The wiring between Stepper Motor Driver board and Mega 2560 board: Stepper Motor Driver Mega 2560 Chapter 6. For Mega2560 User...
Page 185
SunFounder uno-and-mega-kit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. Now, you should see the rocker arm of the stepper motor spin clockwise and counterclockwise alternately. 6.19. Lesson 19 Stepper Motor...
Page 186
SunFounder uno-and-mega-kit 6.19.5 Code 6.19.6 Code Analysis Initialize the stepper #include <Stepper.h> //include a head file //the steps of a circle #define STEPS 100 //set steps and the connection with MCU Stepper stepper(STEPS, 2, 3, 4, 5); //available to store previous value (continues on next page) Chapter 6.
Page 187
SunFounder uno-and-mega-kit (continued from previous page) previous Include a head file Stepper.h, set the steps to 100 and then initialize the stepper with a function stepper(). Stepper(steps, pin1, pin2, pin3, pin4): This function creates a new instance of the Stepper class that represents a particular stepper motor attached to your Arduino board.
SunFounder uno-and-mega-kit 6.20 Lesson 20 Simple Creation-Stopwatch 6.20.1 Introduction In this lesson, we will use a 4-digit 7-segment display to make a stopwatch. 6.20.2 Components • SunFounder Mega Board • Breadboard • Jumper Wires • Resistor • 4-Digit 7-Segment Display...
Page 189
SunFounder uno-and-mega-kit 6.20.3 Schematic Diagram When a 7-segment display is used, if it is a common anode display, connect the anode pin to power source; if it is a common cathode one, connect the cathode pin to GND. When a 4-digit 7-segment display is used, the common anode or common cathode pin is to control the digit displayed.
Page 190
SunFounder uno-and-mega-kit 6.20.4 Experimental Procedures Step 1: Build the circuit The wiring between the 4-digit 7-segment display and the Mega 2560 Board board is as shown below: 4-Digit 7-Segment Display Mega 2560 Board Chapter 6. For Mega2560 User...
Page 191
SunFounder uno-and-mega-kit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. Now, you can see the number increases by one per second on the 4-digit 7-segment display. 6.20. Lesson 20 Simple Creation-Stopwatch...
Page 192
SunFounder uno-and-mega-kit 6.20.5 Code 6.20.6 Code Analysis That’s all for the code. It is long enough, so let me sum it up. Setup: Set all the pins of the LED display as output. Set Timer1 as 0.1 second. Run the following functions. So add() will be called when it’s 0.1 second;...
Page 193
SunFounder uno-and-mega-kit Loop function void loop() clearLEDs(); //clear the 7-segment display screen pickDigit(0); //Light up 7-segment display d1 pickNumber((n/1000)); // get the value of thousand delay(del); //delay 5ms clearLEDs(); //clear the 7-segment display screen pickDigit(1); //Light up 7-segment display d2 pickNumber((n%1000)/100);...
Page 194
SunFounder uno-and-mega-kit (continued from previous page) digitalWrite(d2, HIGH); digitalWrite(d3, HIGH); digitalWrite(d4, HIGH); switch(x) case digitalWrite(d1, LOW); //Light d1 up break; case digitalWrite(d2, LOW); //Light d2 up break; case digitalWrite(d3, LOW); //Light d3 up break; default: digitalWrite(d4, LOW); //Light d4 up break;...
Page 195
SunFounder uno-and-mega-kit (continued from previous page) zero(); break; case one(); break; case two(); break; case three(); The function is to control the LED to display numbers. Call zero(), one() until the nine() function to display 0-9 numbers. Use zero() as an example: The function void zero is to control the high/low level of LED.
Page 196
SunFounder uno-and-mega-kit (continued from previous page) digitalWrite(a, LOW); digitalWrite(b, LOW); digitalWrite(c, LOW); digitalWrite(d, LOW); digitalWrite(e, LOW); digitalWrite(f, LOW); digitalWrite(g, LOW); Write all pins a-p to LOW level, let the 7-segment digital display go out. add() function void add() // Toggle LED count ++;...
SunFounder uno-and-mega-kit 6.21 Lesson 21 Simple Creation-Answer Machine 6.21.1 Introduction In quiz shows, especially entertainment activities (e.g. competitive answering activities), organizers often apply a buzzer system in order to accurately, fairly and visually determine the seat number of a responder.
Page 199
SunFounder uno-and-mega-kit • SunFounder Mega Board • Breadboard • Jumper Wires • Resistor • • Button • Buzzer 6.21.3 Schematic Diagram Button 1, 2 and 3 are answer buttons, and button 4 is the reset button. If button 1 is pressed first, the buzzer will beep, the corresponding LED will light up and all the other LEDs will go out.
Page 200
SunFounder uno-and-mega-kit 6.21.4 Experimental Procedures Step 1:Build the circuit Chapter 6. For Mega2560 User...
Page 201
SunFounder uno-and-mega-kit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. Now, first press button 4 to start. If you press button 1 first, you will see the corresponding LED light up and the buzzer will beep.
Page 202
SunFounder uno-and-mega-kit 6.21.5 Code 6.21.6 Code Analysis The code for this experiment may be a bit long. But the syntax is simple. Let’s see. Workflow: Read the state of button 4, if button 4 is pressed, the LED on pin 10 is illuminated while reading the state of the remaining buttons.
Page 203
SunFounder uno-and-mega-kit (continued from previous page) digitalWrite(LED4, HIGH); // turn the host LED on delay(200); if(1 flag) // read the state of the state of buttons b1State digitalRead(button1); b2State digitalRead(button2); b3State digitalRead(button3); // If the button1 press the first if(b1State flag digitalWrite(LED4, LOW);...
SunFounder uno-and-mega-kit (continued from previous page) digitalWrite(buzzerPin,LOW); // without sound delay(2); // when delay time changed,the frequency changed The alarm() function is to set the buzzer to beep. 6.22 Lesson 22 Simple Creation-Small Fan 6.22.1 Introduction In this experiment, we will learn how to control the direction and speed of a small-sized DC motor by a driver chip L293D.
Page 206
SunFounder uno-and-mega-kit 6.22.3 Schematic Diagram The maximum current of an Arduino I/O port is 20mA but the drive current of a motor is at least 70mA. Therefore, we cannot directly use the I/O port to drive the current; instead, we can use an L293D to drive the motor.
Page 207
SunFounder uno-and-mega-kit 6.22.4 Experimental Procedures Step 1: Build the circuit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. The blade of the DC motor will begin rotating left and right, in a speed that varies accordingly.
Page 208
SunFounder uno-and-mega-kit Code 6.22.5 Code Analysis This code nests five if statements to determine the button press status. • The first if statement is used to determine if the button is pressed. • The second if statement is used to determine if 50ms has elapsed.
SunFounder uno-and-mega-kit The switch statement, like the if statement, switch case allows the programmer to control the flow of the program with different code executed under various conditions. In particular, the switch statement compares the value of a variable with the value specified in the case statement. When a case statement is found whose value matches the value of a variable, the code in that case statement is run.
Page 211
SunFounder uno-and-mega-kit • 7-segment Display • 74HC595 • Button • Capacitor 6.23.3 Schematic Diagram The idea behind a digital dice is very simple: a 7-segment display circularly jumps from 1 to 7 rapidly. When the button is pressed, the jumping will slow down until it stops on a number. When the button is pressed again, the process will repeat.
Page 212
SunFounder uno-and-mega-kit 6.23.4 Experimental Procedures Step 1: Build the circuit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. You can now see the 7-segment display jump between numbers from 1 to 6. Press the button, and the jumping will slow down until it stops three seconds later.
Page 213
SunFounder uno-and-mega-kit 6.23.5 Code 6.23.6 Code Analysis The initial random number comes from A0 randomSeed(analogRead(0)); The initial random number is generated from A0 and the range for the random numbers is 0-1023. Digital Dice void loop() stat digitalRead(keyIn); //store value read from keyIn...
Page 214
SunFounder uno-and-mega-kit If num > 1, clear the value. This is to prevent repeated pressing. So just count it as once no matter how many times you press. Serial.println(num); // print the num on serial monitor if(num //when pushbutton is pressed randNumber random(1,7);...
CHAPTER SEVEN FOR UNO USER 7.1 Lesson 1 Blinking LED 7.1.1 Introduction You should’ve learnt how to install Arduino IDE and add libraries before. Now you can start with a simple experiment to learn the basic operation and code in the IDE.
Page 216
SunFounder uno-and-mega-kit 7.1.2 Components • SunFounder R3 Board • Breadboard • Jumper Wires • • Resistor 7.1.3 Schematic Diagram Connect one end of the 220ohm resistor to pin 9 of the Uno and the other end to the anode (the long pin) of the LED, and the cathode (the short pin) of the LED to GND.
Page 217
SunFounder uno-and-mega-kit 7.1.4 Experimental Procedures Step 1: Build the circuit (the pin with a curve is the anode of the LED). Then plug the board into the computer with a 5V USB cable. 7.1. Lesson 1 Blinking LED...
Page 218
SunFounder uno-and-mega-kit Chapter 7. For Uno User...
Page 219
SunFounder uno-and-mega-kit Step 2: Open the Lesson_3_Blinking_LED.ino code file in the path of SunFounder Uno KitCodeLes- son_3_Blinking_LED Step 3: Select the Board and Port Before uploading the code, you need to select the Board and Port. Click Tools ->Board and select Arduino/Genuino Uno.
Page 220
SunFounder uno-and-mega-kit Click the Upload icon to upload the code to the control board. If “Done uploading” appears at the bottom of the window, it means the sketch has been successfully uploaded. You should now see the LED blinking. Chapter 7. For Uno User...
Page 222
SunFounder uno-and-mega-kit 7.1.5 Code 7.1.6 Code Analysis Define variables const int ledPin //the number of the LED pin You should define every variable before using in case of making mistakes. This line defines a constant variable ledPin for the pin 9. In the following code, ledPin stands for pin 9. You can also directly use pin 9 instead.
In this lesson, we will conduct a simple yet interesting experiment – using LEDs to create flowing LED lights. As the name suggests, these eight LEDs in a row successively light up and dim one after another, just like flowing water. 7.2.2 Components • SunFounder R3 Board • Breadboard •...
Page 224
SunFounder uno-and-mega-kit • Resistor 7.2.3 Schematic Diagram The principle of this experiment is simply to turn on eight LEDs in turn. The eight LEDs are connected to pin 2-pin 9 respectively. Set them as High level and the corresponding LED at the pins will light up. Control the time of each LED brightening and you will see flowing LED lights.
Page 225
SunFounder uno-and-mega-kit Now, you should see eight LEDs brighten one by one from the LED connected to pin 2 to that to pin 9, and then dim in turn from the LED at pin 9 to the one at pin 2. After that, the LEDs will light up from the LED at pin 9 to that at pin 2 and dim from the LED at pin 2 to that at pin 9.
Page 226
SunFounder uno-and-mega-kit 7.2.5 Code 7.2.6 Code Analysis for() statement for (int 2; i <= 9; i++) / * 8 LEDs are connect to pin2-pin9, When i=2, which accords with the condition i<=9, then run the code in the curly braces, set the pin2 to OUTPUT.
Page 227
SunFounder uno-and-mega-kit (continued from previous page) Use the for() statement to set pin 2-pin 9 as output respectively. * / pinMode(i, OUTPUT); //initialize a as an output for (initialization; condition; increment) { //statement(s); }: The for statement is used to repeat a block of statements enclosed in curly braces.The initialization happens first and exactly once.
SunFounder uno-and-mega-kit (continued from previous page) delay(100); //wait for 100 ms Experiment Summary Through this experiment, you have learned how to use for() statement which is a very useful statement when you want to short the code. 7.3 Lesson 3 Controlling LED by Button 7.3.1 Introduction...
Page 230
SunFounder uno-and-mega-kit 7.3.3 Schematic Diagram Connect one end of the buttons to pin 12 which connects with a pull-down resistor and a 0.1uF (104) capacitor (to eliminate jitter and output a stable level when the button is working). Connect the other end of the resistor to GND and one of the pins at the other end of the button to 5V.
Page 231
SunFounder uno-and-mega-kit 7.3. Lesson 3 Controlling LED by Button...
Page 232
SunFounder uno-and-mega-kit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. Now, press the button, and the LED on the Uno board will light up. Chapter 7. For Uno User...
Page 233
SunFounder uno-and-mega-kit 7.3. Lesson 3 Controlling LED by Button...
Page 234
SunFounder uno-and-mega-kit 7.3.5 Code 7.3.6 Code Analysis Define variables const int buttonPin //the button connect to pin 12 const int ledPin //the led connect to pin13 buttonState // variable for reading the pushbutton status Connect the button to pin 12. LED has been connected to pin 13. Define a variable buttonState to restore the state of the button.
A buzzer is a great tool in your experiments whenever you want to make some sounds. In this lesson, we will learn how to drive an active buzzer to build a simple doorbell. 7.4.2 Components • SunFounder R3 Board 7.4. Lesson 4 Doorbell...
Page 236
SunFounder uno-and-mega-kit • Breadboard • Jumper Wires • Resistor • Capacitor • Button • Buzzer 7.4.3 Schematic Diagram 7.4.4 Experimental Procedures Step 1: Build the circuit (Long pins of buzzer is the Anode and the short pin is Cathode). Chapter 7. For Uno User...
Page 238
SunFounder uno-and-mega-kit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. Now, you should hear the buzzer beep. Chapter 7. For Uno User...
Page 239
SunFounder uno-and-mega-kit 7.4.5 Code 7.4.6 Code Analysis Define variables const int buttonPin //the button connect to pin2 const int buzzerPin //the led connect to pin8 / ********************************** / buttonState //variable for reading the pushbutton status Connect the button to pin 2 and buzzer to pin 8. Define a variable buttonState to restore the state of the button.
7.5 Lesson 5 Tilt Switch 7.5.1 Introduction The tilt switch used here is a ball one with a metal ball inside. It is used to detect inclinations of a small angle. 7.5.2 Components • SunFounder R3 Board • Breadboard • Jumper Wires •...
Page 241
SunFounder uno-and-mega-kit 7.5.3 Schematic Diagram 7.5.4 Experimental Procedures Step 1: Build the circuit. Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. Now, tilt the switch, and the LED attached to pin 13 on Uno board will light up.
Page 242
SunFounder uno-and-mega-kit 7.5.5 Code 7.5.6 Code Analysis Code Analysis 7-1 Whole Code const int ledPin //the led attach to setup() void pinMode(ledPin,OUTPUT); //initialize the ledPin as an output pinMode(2,INPUT); //set pin2 as INPUT digitalWrite(2, HIGH); //set pin2 as HIGH / ****************************************** /...
SunFounder uno-and-mega-kit (continued from previous page) digitalWrite(ledPin,LOW); //turn the led off else //if tilt switch breakover digitalWrite(ledPin,HIGH); //turn the led on The whole code are very simple, one pin of the tilt switch is connected to pin2, another pin is connected to GND, when tilt the switch, the two pins of the switch will be connected to GND, then let the LED on the pin13 lights up.
Page 245
7.6.3 Schematic Diagram Connect a 1K resistor (for current limiting when the transistor is energized) to pin 8 of the SunFounder Uno board, then to an NPN transistor whose collector is connected to the coil of a relay and emitter to GND; connect the normally open contact of the relay to an LED and then GND.
Page 246
SunFounder uno-and-mega-kit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. Chapter 7. For Uno User...
Page 247
SunFounder uno-and-mega-kit Now, send a High level signal, and the relay will close and the LED will light up; send a low one, and it will open and the LED will go out. In addition, you can hear a tick-tock caused by breaking the normally close contact and closing the normally open one.
SunFounder uno-and-mega-kit 7.6.5 Code 7.6.6 Code Analysis void loop() digitalWrite(relayPin, HIGH); //drive relay closure conduction delay(1000); //wait for a second digitalWrite(relayPin, LOW); //drive the relay is closed off delay(1000); //wait for a second The code in this experiment is simple. First, set relayPin as HIGH level and the LED connected to the relay will light up.
Page 250
SunFounder uno-and-mega-kit 7.7.3 PWM Pulse width modulation, or PWM, is a technique for getting analog results with digital means. Digital control is used to create a square wave, a signal switched between on and off. This on-off pattern can simulate voltages in between full on (5 Volts) and off (0 Volts) by changing the portion of the time the signal spends on versus the time that the signal spends off.
Page 251
SunFounder uno-and-mega-kit 7.7.4 Schematic Diagram On the UNO board, 356 and 9 to 1. Provide 8-bit PWM output with the analogWrite() function. You can connect any of these pins.Here we input a value between 0 and 255 to the three pins of the RGB LED to make it display different colors.
Page 252
SunFounder uno-and-mega-kit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. Here you should see the RGB LED flash circularly red, green, and blue first, then red, orange, yellow, green, blue,...
Page 254
SunFounder uno-and-mega-kit 7.7.6 Code 7.7.7 Code Analysis Set the color Here use the color() function to set the color of the RGB LED. In the code, it is set to flash 7 different colors. You can use the paint tool on your computer to get the RGB value.
Page 255
SunFounder uno-and-mega-kit (continued from previous page) color(0, 0, 255); // turn the RGB LED blue delay(1000); // delay for 1 second // Example blended colors: color(255,0,252); // turn the RGB LED red delay(1000); // delay for 1 second color(237,109,0); // turn the RGB LED orange delay(1000);...
In this lesson, let’s see how to change the luminance of an LED by a potentiometer, and receive the data of the potentiometer in Serial Monitor to see its value change. 7.8.2 Components • SunFounder R3 Board • Breadboard •...
Page 257
SunFounder uno-and-mega-kit • Potentiometer 7.8.3 Serial Monitor Serial Monitor is used for communication between the Uno board and a computer or other devices. It is a built-in software in the Arduino environment and you can click the button on the upper right corner to open it. You can send and receive data via the serial port on the control board and control the board by input from the keyboard.
Page 258
SunFounder uno-and-mega-kit 7.8.4 Schematic Diagram In this experiment, the potentiometer is used as voltage divider, meaning connecting devices to all of its three pins. Connect the middle pin of the potentiometer to pin A0 and the other two pins to 5V and GND respectively. There- fore, the voltage of the potentiometer is 0-5V.
Page 259
SunFounder uno-and-mega-kit 7.8.5 Experimental Procedures Step 1: Build the circuit. 7.8. Lesson 8 Controlling an LED by Potentiometer...
Page 260
SunFounder uno-and-mega-kit Chapter 7. For Uno User...
Page 261
SunFounder uno-and-mega-kit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. Step 5: Open the Serial Monitor. Find the Serial.begin() code to see what baud rate is set, here is 9600. Then click the top right corner icon to open the Serial Monitor.
Page 262
SunFounder uno-and-mega-kit Chapter 7. For Uno User...
Page 263
SunFounder uno-and-mega-kit 7.8.6 Code 7.8.7 Code Analysis Read the value from A0 inputValue analogRead(analogPin);//read the value from the potentiometer This line is to store the values A0 has read in the inputValue which has been defined before. analog Read() reads the value from the specified analog pin. This means that it will map input voltages between 0 and 5 volts into integer values between 0 and 1023.
SunFounder uno-and-mega-kit 7.8.8 Experiment Summary This experiment can also be changed to others as you like. For example, use the potentiometer to control the time interval for the LED blinking. It is to use the value read from the potentiometer for delaying, as shown below. Have a...
Page 266
SunFounder uno-and-mega-kit 7.9.3 Schematic Diagram 7.9.4 Experimental Procedures Step 1: Build the circuit. Chapter 7. For Uno User...
Page 267
SunFounder uno-and-mega-kit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. Now, shine some light on the photo resistor, and you will see several LEDs light up. Shine more light and you will see more LEDs light up.
Page 268
SunFounder uno-and-mega-kit 7.9.5 Code 7.9.6 Code Analysis Set the variables const int NbrLEDs // 8 leds const int ledPins[] {2, 3, 4, 5, 6, 7, 8, 9}; // 8 leds attach to pin 5-12 respectively const int photocellPin // photoresistor attach to A0 (continues on next page) Chapter 7.
Page 269
SunFounder uno-and-mega-kit (continued from previous page) sensorValue // value read from the sensor ledLevel // sensor value converted into LED 'bars' The 8 LEDs are connected to pin5-pin12, in this code, use a array to store the pins, ledPins[0] is equal to 5, ledPins[1] to 6 and so on.
SunFounder uno-and-mega-kit map(value, fromLow, fromHigh, toLow, toHigh) re-maps a number from one range to another. That is, a value of fromLow would get mapped to one of toLow, and a value of fromHigh to one of toHigh, values in-between to values in-between, etc.
Page 272
SunFounder uno-and-mega-kit 7.10.4 Experimental Procedures Step 1: Build the circuit (Brown to GND, Red to VCC, Orange to pin 9 of the control board) Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board.
Page 273
SunFounder uno-and-mega-kit 7.10.5 Code 7.10.6 Code Analysis Include a library #include <Servo.h> Servo myservo; //create servo object to control a servo With the Servo.h file included, you can call the functions in this file later. Servo is a built-in library in the Arduino IDE.
SunFounder uno-and-mega-kit (continued from previous page) myservo.attach(): Attach the Servo variable to a pin. Initialize the servo attach to pin9. myservo.write(): Writes a value to the servo, controlling the shaft accordingly. On a standard servo, this will set the angle of the shaft (in degrees), moving the shaft to that orientation. Here let the servo stay in the 0 angle firstly.
Page 275
SunFounder uno-and-mega-kit 7.11.2 Components • SunFounder R3 Board • Breadboard • Jumper Wires • LCD1602 • Potentiometer 7.11.3 Schematic Diagram Connect K to GND and A to 3.3 V, and then the backlight of the LCD1602 will be turned on. Connect VSS to GND and the LCD1602 to the power source.
Page 276
SunFounder uno-and-mega-kit 7.11.4 Experimental Procedures Step 1: Build the circuit. Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. Chapter 7. For Uno User...
Page 277
SunFounder uno-and-mega-kit Note: you may need to adjust the potentiometer on the LCD1602 until it can display clearly. You should now see the characters “SunFounder” and “hello, world” rolling on the LCD. 7.11. Lesson 11 LCD1602...
Page 278
SunFounder uno-and-mega-kit 7.11.5 Code 7.11.6 Code Analysis Include a library #include <LiquidCrystal.h>// include the library code With the LiquidCrystal.h file included, you can call the functions in this file later. LiquidCrystal is a built-in library in the Arduino IDE. You can find the LiquidCrystal folder under the installation path C:Program FilesArduinolibraries.
Page 279
SunFounder uno-and-mega-kit There is an example in the examples folder. The src folder contains the major part of the library: LiquidCrystal.cpp (execution file, with function implementation, variable definition, etc.) and LiquidCrystal.h (header file, including function statement, Macro definition, struct definition, etc.). If you want to explore how a function is implemented, you can look up in the file LiquidCrystal.cpp.
//wait for 250 microseconds Similarly, the code is to display the elements in array2[] on the LCD. Therefore, you will see “SunFounder” scroll in the top line of the LCD, move left until it disappears. And then in the bottom line, “hello, world ! ” appears, scrolls to the left until it disappears.
Page 282
SunFounder uno-and-mega-kit 7.12.3 Schematic Diagram The principle is that the resistance of the NTC thermistor changes with the temperature difference in the outer envi- ronment. It detects the real-time temperature of the environment. When the temperature gets higher, the resistance of the thermistor decreases and the voltage of pin A0 increases accordingly.
Page 283
SunFounder uno-and-mega-kit B, short for beta, is a constant. Here it is 4090. Ro is 10k ohms and To is 25 degrees Celsius. The data can be found in the datasheet of thermistor. Again, the above relation can be transformed into one to evaluate temperature: T= B/[ ln(R/ 10) + (B/ 298) ] –...
Page 284
SunFounder uno-and-mega-kit Now, you can see the current temperature displayed both in Celsius and Fahrenheit degrees on the LCD1602. Chapter 7. For Uno User...
Page 285
SunFounder uno-and-mega-kit Code 7.12.5 Code Analysis Set the variables #define analogPin A0 //the thermistor attach to #define beta 3950 //the beta of the thermistor #define resistance 10 //the value of the pull-up resistor Define the beta coefficient as 4090, which is described in the datasheet of thermistor.
SunFounder uno-and-mega-kit void loop() //read thermistor value long analogRead(analogPin); //the calculating formula of temperature float tempC beta (log((1025.0 beta 298.0) 273.0; float tempF tempC 32.0; The value of A0 (thermistor) is read, then the Celsius temperature is calculated by the formula, and then the Celsius temperature is converted to Fahrenheit temperature by the formula.
Page 288
SunFounder uno-and-mega-kit 7.13.3 Schematic Diagram 7.13.4 Experimental Procedures Step 1: Build the circuit. Chapter 7. For Uno User...
Page 289
SunFounder uno-and-mega-kit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. Note: If you receive the following error, it is because you didn’t add a library named NewPing, please refer to libraries.
Page 290
SunFounder uno-and-mega-kit Now, if you use a piece of paper to approach or keep it far away from the sensor. You will see the value displayed on the LCD changes, which indicates the distance between the paper and the ultrasonic sensor.
Page 291
SunFounder uno-and-mega-kit 7.13.5 Code 7.13.6 Code Analysis Initialize the ultrasonic sensor and LCD1602 #include <LiquidCrystal.h> // use #include to define the header file. #include <NewPing.h> // use #include to define the header file. LiquidCrystal lcd(4, 6, 10, 11, 12, 13);...
An infrared-receiver is a component that receives infrared signals and can independently receive infrared ray and output signals compatible with TTL level. It’s similar with a normal plastic-packaged transistor in size and it is suitable for all kinds of infrared remote control and infrared transmission. 7.14.2 Components • SunFounder R3 Board • Breadboard • Jumper Wires •...
Page 293
SunFounder uno-and-mega-kit 7.14.3 Schematic Diagram Control a certain key (for example, Power key) via a remote controller by programming. When you press the key, infrared rays will be emitted from the remote controller and received by the infrared receiver, and the LED on the Uno board will light up.
Page 294
SunFounder uno-and-mega-kit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. Now, press Power on the remote control and the LED attached to pin 13 on the Uno board will light up. If you press other keys, the LED will go out.
Page 295
SunFounder uno-and-mega-kit 7.14.5 Code 7.14.6 Code Analysis Initialize the infrared-receiver #include <IRremote.h> const int irReceiverPin //the infrared-receiver attact to pin2 const int ledPin //built-in LED IRrecv irrecv(irReceiverPin); //Initialize the infrared-receiver decode_results results; //The decoding result is placed in the result of the decode results structure.
Page 296
SunFounder uno-and-mega-kit decode(&results): Decodes the received IR message, returns 0 if no data ready, 1 if data ready. Results of decoding are stored in results Serial.print("irCode: "); //print "irCode: " on the serial monitor Serial.print(results.value, HEX); //print the signal on serial monitor in hexadecimal Serial.print(", bits:...
SunFounder uno-and-mega-kit (continued from previous page) 7.15 Lesson 15 Humiture Sensor 7.15.1 Introduction The digital temperature and humidity sensor DHT11 is a composite sensor that contains a calibrated digital signal output of temperature and humidity. The technology of a dedicated digital modules collection and the temperature and humidity sensing technology are applied to ensure that the product has high reliability and excellent long-term stability.
Page 300
SunFounder uno-and-mega-kit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. Now, you can see the value of the current humidity and temperature displayed on the LCD. Chapter 7. For Uno User...
Page 301
SunFounder uno-and-mega-kit 7.15.5 Code 7.15.6 Code Analysis Initialize the humiture and LCD1602 #include <dht.h> //Include the head file dht.h #include <LiquidCrystal.h> LiquidCrystal lcd(4, 6, 10, 11, 12, 13); // initialize the LCD1602 dht DHT; #define DHT11_PIN 3 //the humiture sensor attact to pin3 Read the value of humiture DHT.read11(DHT11_PIN);...
Page 302
SunFounder uno-and-mega-kit (continued from previous page) case DHTLIB_OK: Serial.println("OK,\t"); break; case DHTLIB_ERROR_CHECKSUM: Serial.println("Checksum error,\t"); break; case DHTLIB_ERROR_TIMEOUT: Serial.println("Time out error,\t"); break; default: Serial.println("Unknown error,\t"); break; Use the read11() function to read the value of the temperature and humidity sensor. If OK is displayed on the Serial Monitor, the humiture sensor is working properly.
A joystick is an input device consisting of a stick that pivots on a base and reports its angle or direction to the device it is controlling. Joysticks are often used to control video games and robots. A Joystick PS2 is used here. 7.16.2 Components • SunFounder R3 Board • Breadboard •...
Page 304
SunFounder uno-and-mega-kit 7.16.3 Schematic Diagram This module has two analog outputs (corresponding to XY biaxial offsets) and one digital output representing whether it is pressed on Z axis. The module integrates power indicator and can display operation condition. In this experiment, we use the Uno board to detect the moving direction of the Joystick knob and pressing of the button.
Page 305
SunFounder uno-and-mega-kit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. Now, push the rocker and the coordinates of X and Y axes displayed on Serial Monitor will change accordingly; press the button, and the coordinate of Z=0 will also be displayed.
Page 306
SunFounder uno-and-mega-kit 7.16.5 Code 7.16.6 Code Analysis The code is use the serial monitor to print the value of the VRX,VRY and SW pins of the joystick ps2. void loop() Serial.print("X: "); Serial.print(analogRead(xPin), DEC); // print the value of VRX in DEC Serial.print("|Y:...
Different letters/numbers can be shown by connecting pins on the display to the power source and enabling the related pins, thus turning on the corresponding LED segments. In this lesson let’s learn how to display specific characters on it. 7.17.2 Components • SunFounder R3 Board • Breadboard • Jumper Wires •...
Page 308
SunFounder uno-and-mega-kit • 7-segment Display 7.17.3 Schematic Diagram In this experiment, connect each of pin a-g of the 7-Segment Display to one 220ohm current limiting resistor respec- tively and then to pin 4–11. GND connects to GND. By programming, we can set one or several of pin4-11 as High level to light up the corresponding LED(s).
Page 309
SunFounder uno-and-mega-kit Step 2: Open the code file. Step 3: Select the Board and Port. 7.17. Lesson 17 7-Segment Display...
Page 310
SunFounder uno-and-mega-kit Step 4: Upload the sketch to the board. You should now see the 7-segment display from 0 to 9 and then A to F, back and forth. Chapter 7. For Uno User...
Page 311
SunFounder uno-and-mega-kit 7.17.5 Code 7.17.6 Code Analysis The code may be a little long for this experiment. But the syntax is simple. Let’s take a look. Call the function in loop() digital_1(); //diaplay 1 to the 7-segment delay(1000); //wait for a second digital_2();...
SunFounder uno-and-mega-kit First we need to know how it looks like when display the numeral 2 on the 7-Segment display. It’s actually the segments a, b, d, e and g are power on, which generates the display of 2. In programming, pins connected to these segments are set High level when c and f are Low level.
Page 314
SunFounder uno-and-mega-kit 7.18.3 Schematic Diagram In the experiment MR (pin10) is connected to 5V (HIGH Level) and OE (pin 1) to GND (LOW Level). Therefore, the data is input into the rising edge of SHcp and enters the memory register through the rising edge. We use the shiftout() function to output a 8-bit data to the shift register through DS.
Page 316
SunFounder uno-and-mega-kit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. You should now see the 7-segment display from 0 to 9 and A to F. Chapter 7. For Uno User...
Page 317
SunFounder uno-and-mega-kit 7.18.5 Code 7.18.6 Code Analysis Set the array elements datArray[16] {252, 96, 218, 242, 102, 182, 190, 224, 254, 246, 238, 62, 156, 122, 158, 142}; This array stores the data of the 16 characters from 0 to F. 252 stands for 0, which you can calculate by yourself. To display 0, the segment g (the middle one) of the 7-segment display must be low level (dim).
SunFounder uno-and-mega-kit Display 0-F in the 7-segment display for(int 0; num < 16; num++) digitalWrite(STcp,LOW); //ground ST_CP and hold low for as long as you are transmitting shiftOut(DS,SHcp,MSBFIRST,datArray[num]); //return the latch pin high to signal chip that it //no longer needs to listen for information digitalWrite(STcp,HIGH);...
Page 320
SunFounder uno-and-mega-kit 7.19.3 Schematic Diagram 7.19.4 Experimental Procedures Step 1: Build the circuit The wiring between Stepper Motor Driver board and Uno board: Stepper Motor Driver Chapter 7. For Uno User...
Page 321
SunFounder uno-and-mega-kit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. 7.19. Lesson 20 Stepper Motor...
Page 322
SunFounder uno-and-mega-kit Now, You can see the rotating shaft of the stepping motor rotating with the turning of the knob of the potentiometer. 7.19.5 Code 7.19.6 Code Analysis Initialize the stepper #include <Stepper.h> //include a head file //the steps of a circle...
SunFounder uno-and-mega-kit Code Analysis 21-2 setSpeed() function //speed of 180 per minute stepper.setSpeed(180); //set the motor speed in rotations per minute(RPMs) setSpeed(rpms): Sets the motor speed in rotations per minute (RPMs). This function doesn’t make the motor turn, just sets the speed at which it will when you call step().
Page 324
SunFounder uno-and-mega-kit 7.20.2 Components • SunFounder R3 Board • Breadboard • Jumper Wires • Resistor • 4-Digit 7-Segment Display 7.20.3 Schematic Diagram When a 7-segment display is used, if it is a common anode display, connect the anode pin to power source; if it is a common cathode one, connect the cathode pin to GND.
Page 328
SunFounder uno-and-mega-kit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. Now, you can see the number increases by one per second on the 4-digit 7-segment display. Chapter 7. For Uno User...
Page 329
SunFounder uno-and-mega-kit 7.20.5 Code 7.20.6 Code Analysis That’s all for the code. It is long enough, so let me sum it up. Setup: Set all the pins of the LED display as output. Set Timer1 as 0.1 second. Run the following functions. So add() will be called when it’s 0.1 second;...
Page 330
SunFounder uno-and-mega-kit (continued from previous page) pickNumber(n%10);//Get the value of single digit delay(del);//delay 5ms The loop function is used to let four segment display to display the single digit, ten, one hundred and thousand of a value. Such as n=1345, (1345/1000)=1, (1345%1000)/100)=3, ((1345%100)/10)=4, (n%10)=5.
Page 331
SunFounder uno-and-mega-kit (continued from previous page) The 4 digital 7 segment is a common cathode one, set all the d1,d2,d3,d4 to HIGH to let them go out. If x is equals to 0, then run case0 let d1 to LOW level to light first 7 segment up.
SunFounder uno-and-mega-kit (continued from previous page) count //which means count from 0 n ++; //then n++=1 if(n 10000) //When n=10000, //n restores to 0. 7.21 Lesson 21 Simple Creation-Answer Machine 7.21.1 Introduction In quiz shows, especially entertainment activities (e.g. competitive answering activities), organizers often apply a buzzer system in order to accurately, fairly and visually determine the seat number of a responder.
Page 335
SunFounder uno-and-mega-kit • Button • Buzzer 7.21.3 Schematic Diagram Button 1, 2 and 3 are answer buttons, and button 4 is the reset button. If button 1 is pressed first, the buzzer will beep, the corresponding LED will light up and all the other LEDs will go out. If you want to start another round, press button 4 to reset.
Page 336
SunFounder uno-and-mega-kit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. Now, first press button 4 to start. If you press button 1 first, you will see the corresponding LED light up and the buzzer will beep.
Page 337
SunFounder uno-and-mega-kit 7.21.5 Code 7.21.6 Code Analysis The code for this experiment may be a bit long. But the syntax is very simple. This code uses 6 nested if statements. • The first if statement is used to determine if button 4 is pressed.
SunFounder uno-and-mega-kit void Alarm() for(int i=0;i<100;i++){ digitalWrite(buzzerPin,HIGH); //the buzzer sound delay(2); digitalWrite(buzzerPin,LOW); //without sound delay(2); //when delay time changed,the frequency changed This function is used to set the length and frequency of the sound emitted by the buzzer. 7.22 Lesson 22 Simple Creation-Small Fan 7.22.1 Introduction...
Page 340
SunFounder uno-and-mega-kit 7.22.3 Schematic Diagram The Enable pin 1,2EN of the L293D are connected to 5V already, so L293D is always in the working state. Connect pin 1A and 2A to pin 9 and 10 of the control board respectively. The two pins of the motor are connected to pin 1Y and 2Y respectively.
Page 341
SunFounder uno-and-mega-kit Step 2: Open the code file. Step 3: Select the Board and Port. 7.22. Lesson 22 Simple Creation-Small Fan...
Page 342
SunFounder uno-and-mega-kit Step 4: Upload the sketch to the board. The blade of the DC motor will begin rotating left and right, in a speed that varies accordingly. 7.22.5 Code 7.22.6 Code Analysis This code nests five if statements to determine the button press status.
SunFounder uno-and-mega-kit (continued from previous page) break; case clockwise(rank2);// When stat=2, set the rotate speed of the motor as rank1=200 break; case clockwise(rank3);// When stat=3, set the rotate speed of the motor as rank1=250 break; default: clockwise(0); The switch statement, like the if statement, switch case allows the programmer to control the flow of the program with different code executed under various conditions.
Page 345
SunFounder uno-and-mega-kit 7.23.3 Schematic Diagram The idea behind a digital dice is very simple: a 7-segment display circularly jumps from 1 to 7 rapidly. When the button is pressed, the jumping will slow down until it stops on a number. When the button is pressed again, the process will repeat.
Page 346
SunFounder uno-and-mega-kit Step 2: Open the code file. Step 3: Select the Board and Port. Step 4: Upload the sketch to the board. You can now see the 7-segment display jump between numbers from 1 to 6. Press the button, and the jumping will slow down until it stops three seconds later.
Page 347
SunFounder uno-and-mega-kit 7.23.5 Code 7.23.6 Code Analysis The initial random number comes from A0 randomSeed(analogRead(0)); The initial random number is generated from A0 and the range for the random numbers is 0-1023. Digital Dice void loop() stat digitalRead(keyIn); //store value read from keyIn...
Page 348
SunFounder uno-and-mega-kit num ++; // num adds 1 if(num > If num > 1, clear the value. This is to prevent repeated pressing. So just count it as once no matter how many times you press. Serial.println(num); // print the num on serial monitor...
Page 349
SunFounder uno-and-mega-kit (continued from previous page) //return the latch pin high to signal chip that it //no longer needs to listen for information digitalWrite(latchPin,HIGH); //pull the latchPin to save the data This function is to display the number in dataArray[] on the 7-segment display.
Page 350
SunFounder uno-and-mega-kit Chapter 7. For Uno User...
CHAPTER EIGHT PLAY WITH SCRATCH Besides programming on the Arduino IDE with Uno/Mega2560 boards, we can also use them for graphical program- ming. Here we recommend programming with Scratch, but the official Scratch is currently only compatible with Raspberry Pi, so we have partnered with a company, STEMPedia, who has developed a Scratch 3 based graphical programming software for Arduino boards (Uno, Mega2560 and Nano) - PictoBlox.
SunFounder uno-and-mega-kit Now let’s start the journey of discovery! 8.1 Install and Introduce PictoBlox 8.1.1 Install PictoBlox Click this linkhttps://thestempedia.com/product/pictoblox/download-pictoblox/choose the appropriate Operating Sys- tem (Windows, macOS, Linux) and follow the steps to install. Chapter 8. Play with Scratch...
Page 353
SunFounder uno-and-mega-kit 8.1.2 Interface Introduction Sprites A sprite is an object, or a character, that performs different actions in a project. It understands and obeys the commands given to it. Each sprite has specific costumes and sounds that you can also customize.
SunFounder uno-and-mega-kit For more information, please refer to: https://thestempedia.com/tutorials/getting-started-pictoblox 8.2 Projects The following projects are written in order of programming difficulty, so we recommend reading them in order. In each project, there are very detailed steps to teach you how to build the circuit and how to program it step by step to achieve the final result.
Page 355
SunFounder uno-and-mega-kit You Will Learn • Stage and Upload mode • Set HIGH/LOW to a digital pin • Set the time interval and let the script loop infinitely Stage Mode 1. Connect to Arduino Board Connect your Arduino board to the computer with a USB cable, usually the computer will automatically recognize your board and finally assign a COM port.
Page 356
SunFounder uno-and-mega-kit For example, choose Arduino Uno. A connection window will then pop up for you to select the port to connect to, and return to the home page when the connection is complete. If you break the connection during use, you can also click Connect to reconnect.
Page 357
SunFounder uno-and-mega-kit At the same time, Arduino Uno related palettes, such as Arduino Uno, Actuators, etc., will appear in the Block Palette. 8.2. Projects...
Page 358
SunFounder uno-and-mega-kit 2. Upload Firmware Since we’re going to work in the Stage mode, we must upload the firmware to the board. It will ensure real-time communication between the board and the computer. Uploading the firmware it is a one-time process. To do so, click on the Upload Firmware button.
Page 359
You can click on File in the top right corner and then choose Open. Choose Open from Computer. Then go to the path of sunfounder-uno-and-mega-kit\scratch code, and open 1. Stage Mode.sb3. Please ensure that you have downloaded the required code by referring to Download the Code.
Page 360
SunFounder uno-and-mega-kit Click directly on the script to run it, some projects are click on the green flag or click on the sprite. • Program step by step You can also write the script step by step by following these steps.
Page 361
SunFounder uno-and-mega-kit The LED on the Arduino board is controlled by the digital pin 13 (only 2 states, HIGH or LOW), so drag the [set digital pin out as] block to the script area. Since the default state of the LED is lit, now set pin 13 to LOW and click on this block and you will see the LED go off.
Page 362
SunFounder uno-and-mega-kit running. • [Wait 1 seconds]: from the Control palette, used to set the time interval between 2 blocks. • [forever]: from the Control palette, allows the script to keep running unless manually paused. Upload Mode 1. Connect to Arduino Board Connect your Arduino board to the computer with a USB cable, usually the computer will automatically recognize your board and finally assign a COM port.
Page 363
SunFounder uno-and-mega-kit A connection window will then pop up for you to select the port to connect to, and return to the home page when the connection is complete. If you break the connection during use, you can also click Connect to reconnect.
Page 364
SunFounder uno-and-mega-kit At the same time, Arduino Uno related palettes, such as Arduino Uno, Actuators, etc., will appear in the Block Palette. Chapter 8. Play with Scratch...
Page 365
SunFounder uno-and-mega-kit After selecting Upload mode, the stage will switch to the original Arduino code area. 8.2. Projects...
Page 366
You can click on File in the top right corner. Choose Open from Computer. Then go to the path of sunfounder-uno-and-mega-kit\scratch code, and open 1. Upload Mode.sb3. Please ensure that you have downloaded the required code by referring to Download the Code.
Page 367
SunFounder uno-and-mega-kit Finally, click the Upload Code button. • Program step by step You can also write the script step by step by following these steps. Click on the Arduino Uno palette. 8.2. Projects...
Page 368
SunFounder uno-and-mega-kit Drag [when Arduino Uno starts up] to the script area, which is required for every script. The LEDs on the Arduino board are controlled by the digital pins (only 2 states HIGH or LOW) 13, so drag the [set digital pin out as] block to the script area.
Page 369
SunFounder uno-and-mega-kit At this point you will see the Arduino code appear on the right side, if you want to edit this code, then you can turn Edit mode on. In order to see the effect of continuous blinking LED, you need to use the [Wait 1 seconds] and [forever] blocks in the Control palette, as shown in the figure below, click on these blocks after writing, there is a yellow halo means it is...
Page 370
SunFounder uno-and-mega-kit Finally, click the Upload Code button. Chapter 8. Play with Scratch...
Page 371
SunFounder uno-and-mega-kit 8.2.2 2. Table Lamp The last project was to make the built-in LED on the Arduino board light up. Here, we connect an LED on the breadboard and have the sprite control the blinking of this LED. When the Button sprite on the stage is clicked, the LED will blink 5 times and then stop.
Page 372
SunFounder uno-and-mega-kit You Will Learn • Breadboard, LEDs and Resistors • Building a circuit on a breadboard • Delete and select sprites • Switching costumes • Set a limited number of repeat loops Chapter 8. Play with Scratch...
Page 373
SunFounder uno-and-mega-kit Build the Circuit Follow the diagram below to build the circuit on the breadboard. Since the anode of the LED (the longer pin) is connected to pin 9 through a 220 resistor, and the cathode of the LED is connected to GND, you can light up the LED by giving pin 9 a high level.
Page 374
SunFounder uno-and-mega-kit • Breadboard • • Resistor Programming The whole programming is divided into 3 parts, the first part is to select the desired sprite, the second part is to switch the costume for the sprite to make it look clickable, and the third part is to make the LED blink.
Page 375
SunFounder uno-and-mega-kit Click on Costumes in the top right corner and you will see that the Button3 sprite has 2 costumes, we set button3-a to be released and button3-b to be pressed. 2. Switching costumes. When the sprite is clicked (Events palette), it switches to costume for button3-b (looks palette).
Page 376
SunFounder uno-and-mega-kit 3. Make the LED blink 5 times Use the [Repeat] block to make the LED blink 5 times (High-> LOW cycle), remember to change pin 13 to pin 9, and finally switch the costume back to button3-a. • [Repeat 10]: limited number of repeat loops, you can set the number of repeats yourself, from the Control palette.
Page 377
SunFounder uno-and-mega-kit 8.2.3 3. Breathing LED Now use another method to control the brightness of the LED. Unlike the previous project, here the brightness of the LED is made to slowly diminish until it disappears. When the sprite on the stage is clicked, the brightness of the LED slowly increases and then goes out instantly.
Page 378
SunFounder uno-and-mega-kit • Breadboard • • Resistor Chapter 8. Play with Scratch...
Page 379
SunFounder uno-and-mega-kit Programming 1. Select a sprite Delete the default sprite, click the Choose a Sprite button in the lower right corner of the sprite area, enter button3 in the search box, and then click to add it. 2. Creating a variable.
Page 380
SunFounder uno-and-mega-kit Enter the name of the variable, it can be any name, but it is recommended to describe its function. The data type is number and For all sprites. Once created, you will see pwm inside the Variables palette and in the checked state, which means this variable will appear on the stage.
Page 381
SunFounder uno-and-mega-kit 3. Set the initial state When the button3 sprite is clicked, switch the costume to button-b (clicked state), and set the initial value of the variable pwm to 0. • [set pwm to 0]: from Variables palette, used to set the value of the variable.
Page 382
SunFounder uno-and-mega-kit Finally, switch the costume of button3 back to button-a and make the PWM pin value 0, so that the LED will light up slowly and then turn off again. Chapter 8. Play with Scratch...
Page 383
SunFounder uno-and-mega-kit 8.2.4 4. Colorful Balls In this project, we will make the RGB LEDs display different colors. Clicking on different colored balls on the stage area will cause the RGB LED to light up in different colors. 8.2. Projects...
Page 384
SunFounder uno-and-mega-kit You Will Learn • The principle of RGB LED • Copy sprites and select different costumes • Three primary colors superimposed Build the Circuit An RGB LED packages three LEDs of red, green, and blue into a transparent or semitransparent plastic shell. It can display various colors by changing the input voltage of the three pins and superimpose them, which, according to statistics, can create 16,777,216 different colors.
Page 386
SunFounder uno-and-mega-kit • Breadboard • Resistor • RGB LED Chapter 8. Play with Scratch...
Page 387
SunFounder uno-and-mega-kit Programming 1. Select sprite Delete the default sprite, then choose the Ball sprite. And duplicate it 5 times. Choose different costumes for these 5 Ball sprites and move them to the corresponding positions. Note: Ball3 sprite costume color needs to be manually changed to red.
Page 388
SunFounder uno-and-mega-kit 2. Make RGB LEDs light up in the appropriate color Before understanding the code, we need to understand the RGB color model. The RGB color model is an additive color model in which red, green, and blue light are added together in various ways to reproduce a broad array of colors.
Page 389
SunFounder uno-and-mega-kit So the code to make the RGB LED light yellow is as follows. When the Ball sprite (yellow ball) is clicked, we set pin 11 high (red LED on), pin 10 high (green LED on) and pin 9 low (blue LED off) so that the RGB LED will light yellow.
Page 390
SunFounder uno-and-mega-kit 4. Ball3 sprite (red) 5. Ball4 sprite (green) Chapter 8. Play with Scratch...
Page 391
SunFounder uno-and-mega-kit 6. Ball5 sprite (purple) 8.2.5 5. LCD1602 LCD1602 can be used to display 2x16 characters, now we let it display the corresponding characters with the character sprites on the stage. When you click the Hello on the stage one by one, they will have different animation effects and the characters will be displayed on the LCD1602 at the same time.
Page 392
SunFounder uno-and-mega-kit You Will Learn • Using the LCD1602 • Select multiple different sprites • Change sprite size, rotation angle, color and show or hide. Build the Circuit • Connect K to GND and A to 3.3 V, and then the backlight of the LCD1602 will be turned on.
Page 394
SunFounder uno-and-mega-kit Programming 1. Select sprite Delete the default sprite, click Choose a Sprite, then click letters and select the sprite you want. For example, I chose Hello, as shown below. Chapter 8. Play with Scratch...
Page 395
SunFounder uno-and-mega-kit Now to set different effects for these sprites and display them on the LCD1602 while clicking. 2. H is zoom in and zoom out Click on the H sprite, and now write a script for it. When the sprite H is clicked, make its size to 50%, then restore it; while displaying H on the first row and column of the LCD1602.
Page 396
SunFounder uno-and-mega-kit The distribution of rows and columns on the LCD1602 is shown in the figure. 3. E is flipping left and right Click on the E sprite, and now write a script for it. When the sprite E is clicked, have it turn 180 degrees clockwise, then 180 degrees counterclockwise so you can see it flip left and right;...
Page 397
SunFounder uno-and-mega-kit 4. L is slowly shrinking and zooming in Click on the first L sprite and now write a script for it. When the sprite L is clicked, use the [repeat] block to increase its size by 50% (5 times, 10 each time), then shrink it back to its original size in the same way, while displaying L in the first row and column 3 of the LCD1602.
Page 398
SunFounder uno-and-mega-kit 5. The second L is changing color Click on the second L sprite and now write a script for it. When the sprite L is clicked, use the [repeat] block to repeat 10 times at a rate of 20 increments to switch between colors and return to the original color.
Page 399
SunFounder uno-and-mega-kit 6. O is hide and show Click on the O sprite and now write a script for it. When the O sprite is clicked, it repeats the hide and show process 3 times, while displaying O in the first row and column 5 of the LCD1602.
Page 400
SunFounder uno-and-mega-kit 8.2.6 6. Moving Mouse Today we are going to make a mouse toy controlled by a potentiometer. When the green flag is clicked, the mouse on the stage moves forward, and when you rotate the potentiometer, the mouse will change the direction of movement.
Page 401
SunFounder uno-and-mega-kit You Will Learn • Potentiometer principle • Read analog pin and ranges • Mapping one range to another • Moving and changing the direction of sprite Build the Circuit The potentiometer is a resistive element with 3 terminals, the 2 side pins are connected to 5V and GND, and the middle pin is connected to A0.
Page 402
SunFounder uno-and-mega-kit • Breadboard Chapter 8. Play with Scratch...
Page 403
SunFounder uno-and-mega-kit • Potentiometer Programming 1. Choose a sprite Delete the default sprite, click the Choose a Sprite button in the lower right corner of the sprite area, enter mouse in the search box, and then click to add it.
Page 404
SunFounder uno-and-mega-kit 3. Read the value of A0 Store the value of A0 read into the variable value. • [set my variable to 0]: Set the value of the variable. • [read analog pin A0]: Read the value of A0~A5 in the range of 0-1023.
Page 405
SunFounder uno-and-mega-kit 4. Move the sprite Use the [move steps] block to move the sprite, run the script and you will see the sprite move from the middle to the right. 5. Changing the sprite’s direction Now change the direction of the sprite’s movement by the value of A0. Since the value of A0 ranges from 0-1023, but the sprite’s rotation direction is -180~180, a [map] block needs to be used.
Page 406
SunFounder uno-and-mega-kit 8.2.7 7. Doorbell Here, we will use the button and the bell on the stage to make a doorbell. When the green flag is clicked, you can press the button and the bell on the stage will make a sound.
Page 407
SunFounder uno-and-mega-kit You Will Learn • How the button work • Reading digital pin and ranges • Creating a conditional loop • Adding a backdrop • Playing sound Build the Circuit The button is a 4-pin device, since the pin 1 is connected to pin 2, and pin 3 to pin 4, when the button is pressed, the 4 pins are connected, thus closing the circuit.
Page 408
SunFounder uno-and-mega-kit • Breadboard • Button Chapter 8. Play with Scratch...
Page 409
SunFounder uno-and-mega-kit • Resistor • Capacitor Programming 1. Add a Backdrop Click the Choose a Backdrop button in the lower right corner. Choose Bedroom 1. 2. Select the sprite Delete the default sprite, click the Choose a Sprite button in the lower right corner of the sprite area, enter bell in the search box, and then click to add it.
Page 410
SunFounder uno-and-mega-kit Then select the bell sprite on the stage and move it to the right position. Chapter 8. Play with Scratch...
Page 411
SunFounder uno-and-mega-kit 3. Press the button and the bell makes a sound Use [if then] to make a conditional statement that when the value of the pin12 read is equal to 1 (the key is pressed), the sound xylo1 will be played.
Page 412
SunFounder uno-and-mega-kit 8.2.8 8. Tumbler Now we use a tilt switch to control tumbler on the stage, so that the switch tilted, tumbler also tilted. Chapter 8. Play with Scratch...
Page 413
SunFounder uno-and-mega-kit You Will Learn • How the tilt switch works • [if then else] block • Adding external sprite Build the circuit The tilt switch used here is a ball with a metal ball inside. When it is upright, the 2 pins are connected together, and when it is tilted, they are separate.
Page 414
SunFounder uno-and-mega-kit • Breadboard • Tilt Switch Chapter 8. Play with Scratch...
Page 415
Select the Tobi sprite and go to the Costumes page. Select the icon in the bottom left corner and then select Upload Costume. Then open tumbler1.png and tumbler2.png in the sunfounder-uno-and-mega-kit\scratch\ picture path and make sure you have downloaded the relevant material, see Download the Code.
Page 416
SunFounder uno-and-mega-kit 2. Tilt the switch If the value of pin12 is read as 0 (the switch is tilted), switch the sprite costume to tumbler2, which is also in the tilted state. Otherwise, switch the sprite costume to tumbler1, upright.
Page 417
SunFounder uno-and-mega-kit 8.2.9 9. Low Temperature Alarm In this project, we will make a low temperature alarm system, when the temperature is below the threshold, the Snowflake sprite will appear on the stage. 8.2. Projects...
Page 418
SunFounder uno-and-mega-kit You Will Learn • Thermistor working principle • Multivariable and Subtractive Operations Build the Circuit A thermistor is a type of resistor whose resistance is strongly dependent on temperature, more so than in standard resistors, and there are two types of resistors, PTC (resistance increases as temperature increases) and PTC (resistance decreases as temperature increases).
Page 420
SunFounder uno-and-mega-kit • Resistor Programming 1. Select a sprite Delete the default sprite, click the Choose a Sprite button in the lower right corner of the sprite area, enter Snowflake in the search box, and then click to add it.
Page 421
SunFounder uno-and-mega-kit 3. Read the value of A0 When the green flag is clicked, the value of A0 is read and stored in the variable before. 4. Read the value of A0 again In [forever], read the value of A0 again and store it in the variable current.
Page 422
SunFounder uno-and-mega-kit 5. Determining temperature changes Using the [if else] block, determine if the current value of A0 is 50 greater than before, which represents a decrease in temperature. At this point let Snowflake sprite show, otherwise hide. • [-] & [>]: subtraction and comparison operators from Operators platette.
Page 423
SunFounder uno-and-mega-kit 8.2.10 10. Light Alarm Clock In life, there are various kinds of time alarm clocks. Now let’s make a light-controlled alarm clock. When morning comes, the brightness of light increases and this light-controlled alarm clock will remind you that it’s time to get up.
Page 424
SunFounder uno-and-mega-kit You Will Learn • Photoresistor working principle • Stopping sound playback and stopping scripts from running Build the Circuit A photoresistor or photocell is a light-controlled variable resistor. The resistance of a photoresistor decreases with increasing incident light intensity.
Page 426
SunFounder uno-and-mega-kit Programming 1. Select a sprite Delete the default sprite, click the Choose a Sprite button in the lower right corner of the sprite area, enter bell in the search box, and then click to add it. 2. Read the value of A0 Create two variables before and current.
Page 427
SunFounder uno-and-mega-kit 3. Make a sound When the value of current A0 is greater than the previous 50, which represents the current light intensity is greater than the threshold, then let the sprite make a sound. 4. Turning the sprite Use [turn block] to make the bell sprite turn left and right to achieve the alarm effect.
Page 428
SunFounder uno-and-mega-kit 5. stop all Stops the alarm when it has been ringing for a while. Chapter 8. Play with Scratch...
Page 429
SunFounder uno-and-mega-kit 8.2.11 11. Read Temperature and Humidity Previous projects have been using stage mode, but some functions are only available in upload mode, such as serial communication function. In this project, we will print the temperature and humidity of the DHT11 using the Serial...
Page 430
SunFounder uno-and-mega-kit You Will Learn • Get the temperature and humidity from the DHT11 module • Serial Monitor for Upload Mode • Add extension Build the Circuit The digital temperature and humidity sensor DHT11 is a composite sensor that contains a calibrated digital signal output of temperature and humidity.
Page 431
SunFounder uno-and-mega-kit Programming 1. Adding Extensions Switch to Upload mode, click the Add Extension button in the bottom left corner, then select Communication to add it, and it will appear at the end of the palette area. 2. Initializing the Arduino Uno and Serial Monitor In Upload mode, start Arduino Uno and then set the serial port baud rate.
Page 432
SunFounder uno-and-mega-kit 3. Read temperature and humidity Create 2 variables tem and humi to store the temperature and humidity respectively, the code will appear on the right side while you drag and drop the block. 4. Print them on the Serial Monitor Write the read temperature and humidity to the Serial Monitor.
Page 433
SunFounder uno-and-mega-kit 5. Uploading code Unlike the Stage mode, the code in Upload mode needs to be uploaded to the Arduino board using the Upload Code button to see the effect. This also allows you to unplug the USB cable and still have the program running.
Page 434
SunFounder uno-and-mega-kit 8.2.12 12. Pendulum In this project, we will make an arrow pendulum while the servo will follow the rotation. Chapter 8. Play with Scratch...
Page 435
SunFounder uno-and-mega-kit You Will Learn • How the servo works and the angle range • Draw a sprite and put the center point on the tail. Build the Circuit A servo is a geared motor that can only rotate 180 degrees. It is controlled by sending electrical pulses from your circuit board.
Page 436
SunFounder uno-and-mega-kit • Breadboard • Servo Chapter 8. Play with Scratch...
Page 437
SunFounder uno-and-mega-kit Programming 1. Paint a sprite Delete the default sprite, select the Sprite button and click Paint, a blank sprite Sprite1 will appear. On the open Costumes page, use the Line tool to draw an arrow. Note: • Be sure to start drawing the arrow from the center of the canvas outward so that the arrow is turning in a circle with the center point as the origin.
Page 438
SunFounder uno-and-mega-kit After drawing, the arrow sprite will be displayed on the stage, name it arrow. Then click on the number after Direction, a circular dial will appear, now drag this arrow and see if the arrow sprite on the stage turns with the tail as the origin.
Page 439
SunFounder uno-and-mega-kit To make the arrow sprite swing from the left to the right, the angle range is -90 to -180, 180 to 90. 8.2. Projects...
Page 440
SunFounder uno-and-mega-kit 2. Creating a variable. Create a variable called servo, which stores the angle value and sets the initial value to 270. 3. Swing from the left to the right Now let the arrow sprite swing from the left -90 degree position to the right 90 degree position.
Page 441
SunFounder uno-and-mega-kit 4. Turning the Servo When you click on the green flag, you will see the arrow quickly turn to the right and then back to the left, so use a [wait seconds] block here to make the rotation slower. Also use the [set servo on to angle] block to make the servo connected to the Arduino board turn to a specific angle.
Page 442
SunFounder uno-and-mega-kit 5. Swinging from right to left By the same method, make the servo and arrow sprite slowly rotate from the right to the left. • If angle > 180, then angle -360. Chapter 8. Play with Scratch...
Page 443
SunFounder uno-and-mega-kit 8.2.13 13. Rotating Fan In this project, we will make a spinning star sprite and fan. Clicking on the left and right arrow sprites on the stage will control the clockwise and counterclockwise rotation of the motor and star sprite, click on the star sprite to stop the rotation.
Page 444
SunFounder uno-and-mega-kit You Will Learn • Motor working principle • Broadcast function • Stop other script in sprite block Build the Circuit In this project, the motor driver chip L293D is used to make the motor rotate. L293D is a 4-channel motor driver integrated by chip with high voltage and high current.
Page 445
SunFounder uno-and-mega-kit Now build the circuit according to the following diagram. • The Enable pin 1,2EN of the L293D are connected to 3.3V already, so L293D is always in the working state. • Connect pin 1A and 2A to pin 9 and 10 of the control board respectively.
Page 446
SunFounder uno-and-mega-kit • Breadboard • DC Motor Chapter 8. Play with Scratch...
Page 447
SunFounder uno-and-mega-kit • L293D Programming The effect we want to achieve is to use 2 arrow sprites to control the clockwise and counterclockwise rotation of the motor and the star sprite respectively, clicking on the star sprite will stop the motor from rotating.
Page 448
SunFounder uno-and-mega-kit Adjust the size and position of the sprite appropriately. Chapter 8. Play with Scratch...
Page 449
SunFounder uno-and-mega-kit 2. Left arrow sprite When this sprite is clicked, it broadcasts a message - turn, then sets digital pin 9 to low and pin 10 to high, and sets the variable flag to 1. If you click the left arrow sprite, you will find that the motor turns counterclockwise, if your turn is clockwise, then you swap the positions of pin 9 and pin 10.
Page 450
SunFounder uno-and-mega-kit 3. right-arrow sprite When this sprite is clicked, broadcast a message turn, then set digital pin 9 high and pin 10 low to make the motor turn clockwise and set the flag variable to 0. 4. star sprite There are 2 events included here.
Page 451
SunFounder uno-and-mega-kit 8.2.14 14. GAME - Star-Crossed In the next projects, we will play some fun mini-games in PictoBlox. Here we use Joystick module to play a Star-Crossed game. After the script is run, stars will appear randomly on the stage, you need to use Joystick to control Rocketship to avoid the stars, if you touch it, the game will be over.
Page 452
SunFounder uno-and-mega-kit You Will Learn • How Joystick works • Set the x and y coordinates of the sprite • Let the sprite go to a random position • Touch events between sprites Build the Circuit A joystick is an input device consisting of a stick that pivots on a base and reports its angle or direction to the device it is controlling.
Page 453
SunFounder uno-and-mega-kit Now build the circuit according to the following diagram. • Breadboard • Joystick Module 8.2. Projects...
Page 454
SunFounder uno-and-mega-kit Programming The whole script is to achieve the effect that when the green flag is clicked, the Stars sprite moves in a curve on the stage and you need to use the joystick to move the Rocketship, so that it will not be touched by the Star sprite.
Page 455
SunFounder uno-and-mega-kit 2. Scripting for Rocketship The Rocketship sprite is to achieve the effect that it will appear at a random position and then be controlled by the joystick to move it up, down, left, and right. The workflow is as follows.
Page 456
SunFounder uno-and-mega-kit toggling to the right, and if so, make the x coordinate of the sprite +30 (to move the sprite to the right). • If the Joystick is toggled to the left (x-512<-200), let the x coordinate of the sprite be -30 (let the sprite move to the left).
Page 457
SunFounder uno-and-mega-kit • Since the Joystick’s y coordinate is from up (0) to down (1023), and the sprite’s y coordinate is from down to up. So in order to move the Joystick upwards and the sprite upwards, the y-coordinate must be -30 in the script.
Page 458
SunFounder uno-and-mega-kit 3. Scripting for Star The effect to be achieved by the Star sprite is to appear at a random location, and if it hits Rocketship, the script stops running and the game ends. • When the green flag is clicked and the sprite goes to a random location, the [turn degrees] block is to make the Star sprite move forward with a bit of an angle change so you can see that it is moving in a curve and if on edge, bounce.
Page 459
SunFounder uno-and-mega-kit 8.2.15 15. GAME - Eat Apple In this project, we play a game that uses button to control Beetle to eat apple. When the green flag is clicked, press the button and Beetle will rotate, press the button again and Beetle stops running and goes forward at that angle.
Page 460
SunFounder uno-and-mega-kit Build the circuit according to the following diagram. • Connect one of the pins on the left side of the button to pin 12, which is connected to a pull-down resistor and a 0.1uF (104) capacitor (to eliminate jitter and output a stable level when the button is working).
Page 462
SunFounder uno-and-mega-kit • Resistor • Capacitor Programming The effect we want to achieve is to use the button to control the direction of the Beetle sprite to move forward and eat the apple without touching the black line on the Maze backdrop, which will switch the backdrop when eaten.
Page 463
SunFounder uno-and-mega-kit Place the Beetle sprite at the entrance of the Maze sprite, remembering the x,y coordinate values at this point, and resize the sprite to 40%. 8.2. Projects...
Page 464
SunFounder uno-and-mega-kit 2. Draw a backdrop Now it’s time to simply draw a backdrop with the WIN! character appearing on it. First click on the backdrop thumbnail to go to the Backdrops page and click on the blank backdrop1. Chapter 8. Play with Scratch...
Page 465
SunFounder uno-and-mega-kit Now start drawing, you can refer to the picture below to draw, or you can draw a backdrop on your own, as long as the expression is winning. • Using the Draw Circle tool, draw an ellipse with the color set to red and no outline.
Page 466
SunFounder uno-and-mega-kit 3. Scripting for the backdrop The backdrop needs to be switched to Maze every time the game starts. 4. Writing scripts for the sprite Beetle Now write a script for the sprite Beetle to be able to move forward and turn direction under the control of a button.
Page 467
SunFounder uno-and-mega-kit Next, in the [forever] block, four [if] blocks are used to determine various possible scenarios. • If the key is 1 (pressed), use the [mod] block to toggle the value of the variable flag between 0 and 1 (alternating between 0 for this press and 1 for the next press).
Page 468
SunFounder uno-and-mega-kit • If the Beetle sprite touches black (the black line on the Maze backdrop), the game ends and the script stops running. Note: You need to click on the color area in the [Touch color] block, and then select the eyedropper tool to pick up the color of the black line on the stage.
Page 469
SunFounder uno-and-mega-kit • If Beetle touches red (Also use the straw tool to pick up the red color of the apple), the backdrop will be switched to Win, which means the game succeeds and stops the script from running. 8.2. Projects...
Page 470
SunFounder uno-and-mega-kit 8.2.16 16. GAME - Flappy Parrot Here we use the ultrasonic module to play a flappy parrot game. After the script runs, the green bamboo will slowly move from the right to the left at a random height. Now place your hand on top of the ultrasonic module, if the distance between your hand and the ultrasonic module is less than 10, the parrot will fly upwards, otherwise it will fall downwards.
Page 471
SunFounder uno-and-mega-kit You Will Learn • How the ultrasonic module works • Cloning the sprite itself Build the Circuit An ultrasonic sensor module is an instrument that measures the distance to an object using ultrasonic sound waves. It has two probes. One is to send ultrasonic waves and the other is to receive the waves and transform the time of sending and receiving into a distance, thus detecting the distance between the device and an obstacle.
Page 472
SunFounder uno-and-mega-kit • Breadboard • Ultrasonic Module Programming The effect we want to achieve is to use the ultrasonic module to control the flight height of the sprite Parrot, while avoiding the Paddle sprite. 1. Add a sprite Delete the default sprite, and use the Choose a Sprite button to add the Parrot sprite. Set its size to 50%, and move its position to the left center.
Page 473
SunFounder uno-and-mega-kit Now add the Paddle sprite, set its size to 150%, set its angle to 180, and move its initial position to the top right corner. 8.2. Projects...
Page 474
SunFounder uno-and-mega-kit Go to the Costumes page of the Paddle sprite and remove the Outline. Chapter 8. Play with Scratch...
Page 475
SunFounder uno-and-mega-kit 2. Scripting for the Parrot Sprite Now script the Parrot sprite, which is in flight and the flight altitude is determined by the detection distance of the ultrasonic module. • When the green flag is clicked, switch the costume every 0.2s so that it is always in flight.
Page 476
SunFounder uno-and-mega-kit • If the ultrasonic detection distance is less than 10cm, let the y coordinate increase by 50, the Parrot sprite will fly upwards. Otherwise, the y-coordinate value is decreased by 40, Parrot will fall down. • If the Parrot sprite touches the Paddle sprite, the game ends and the script stops running.
Page 477
SunFounder uno-and-mega-kit 3. Scripting for the Paddle sprite Now write the script for the Paddle sprite, which needs to appear randomly on the stage. • Hide the sprite Paddle when the green flag is clicked, and clone itself at the same time. The [create clone block is a control block and a stack block.
Page 478
SunFounder uno-and-mega-kit • Use the [repeat] block to make its x coordinate value slowly decrease, so you can see the clone of the Paddle sprite slowly move from the right to the left until it disappears. • Re-clone a new Paddle sprite and delete the previous clone.
Page 479
SunFounder uno-and-mega-kit 8.2.17 17. GAME - Breakout Clone Here we use the potentiometer to play a Breakout Clone game. After clicking the green flag, you need to use the potentiometer to control the paddle on the stage to catch the ball so that it can go up and hit the bricks, all the bricks disappear then the game is won, if you don’t catch the ball, the game...
Page 480
SunFounder uno-and-mega-kit Build the Circuit The potentiometer is a resistive element with 3 terminals, the 2 side pins are connected to 5V and GND, and the middle pin is connected to A0. After the conversion by the ADC converter of the Arduino board, the value range is 0-1023.
Page 482
SunFounder uno-and-mega-kit • Potentiometer Programming There are 3 sprites on the stage. 1. Paddle sprite The effect to be achieved by the Paddle is that the initial position is in the middle of the bottom of the stage, and it is controlled by a potentiometer to move it to the left or to the right.
Page 483
SunFounder uno-and-mega-kit at x-coordinates -195~195, you need to use the [map] block to map the variable a0 range 0~1023 to -195~195. • Now you can rotate the potentiometer to see if the Paddle can move left and right on the stage.
Page 484
SunFounder uno-and-mega-kit • Now let the Ball sprite move around the stage and bounce when it touches the edge, and you can click on the green flag to see the effect. • When the Ball sprite touches the Paddle sprite, do a reflection. The easy way to do this is to let the angle be directly inverted, but then you’ll find that the path of the ball is completely fixed, which is too boring.
Page 485
SunFounder uno-and-mega-kit • When the Ball sprite falls to the edge of the stage, the script stops running and the game ends. 3. Block1 sprite The Block1 sprite is to appear with the effect of cloning 4x8 of itself above the stage in a random color, and deleting a clone if it is touched by the Ball sprite.
Page 486
SunFounder uno-and-mega-kit The Block1 sprite is not available in the PictoBlox library, you need to draw it yourself or modify it with an existing sprite. Here we are going to modify it with the Button3 sprite. • After adding the Button3 sprite, go to the Costumes page. Now delete button-a first, then reduce both the width and height of button-b, and change the sprite name to Block1, as shown in the following image.
Page 487
SunFounder uno-and-mega-kit • We need to make a clone of the Block1 sprite, so that it displays from left to right, top to bottom, one by one, 4x8 in total, with random colors. 8.2. Projects...
Page 488
SunFounder uno-and-mega-kit • After the script is written, click on the green flag and look at the display on the stage, if it is too compact or too small, you can change the size. Chapter 8. Play with Scratch...
Page 489
SunFounder uno-and-mega-kit • Now write the trigger event. If the cloned Block1 sprite touches the Ball sprite, delete the clone and broadcast the message crush. 8.2. Projects...
Page 490
SunFounder uno-and-mega-kit • Back to the Ball sprite, when the broadcast crush is received (the Ball sprite touches the clone of Block1 sprite), the Ball is popped from the opposite direction. Chapter 8. Play with Scratch...
Page 491
SunFounder uno-and-mega-kit 8.2.18 18. GAME - Fishing Here, we play a fishing game with a button. When the script is running, the fish swim left and right on the stage, you need to press the button when the fish is almost close to the hook (it is recommended to press it for a longer time) to catch the fish, and the number of fish...
Page 492
SunFounder uno-and-mega-kit Build the circuit according to the following diagram. • Connect one of the pins on the left side of the button to pin 12, which is connected to a pull-down resistor and a 0.1uF (104) capacitor (to eliminate jitter and output a stable level when the button is working).
Page 494
SunFounder uno-and-mega-kit • Resistor • Capacitor Programming We need to select an Underwater backdrop first, then add a Fish sprite and let it swim back and forth on the stage. Then draw a Fishhook sprite and control it by a button to start fishing. When the Fish sprite touches the Fishhook sprite in the hooked state (turns red), it will be hooked.
Page 495
SunFounder uno-and-mega-kit • Now go to the Costumes page of the Glow-J sprite, select Cyan’s fill in the screen and remove it. Then change the J color to red and also reduce its width. The most important point to note is that you need to have the top of it just at the center point.
Page 496
SunFounder uno-and-mega-kit • When the green flag is clicked, set the sprite’s color effect to 30 (yellow), and set its initial position. • If the button is pressed, set the color effect to 0 (red, start fishing state), wait for 0.1 and then move the Fishhook sprite to the top of the stage.
Page 497
SunFounder uno-and-mega-kit 3. Fish sprite The effect to be achieved by the Fish sprite is to move left and right on the stage, and when it encounters a Fishhook sprite in the fishing state, it shrinks and moves to a specific position and then disappears, and then clones a new fish sprite again.
Page 498
SunFounder uno-and-mega-kit • Create a variable score to store the number of fish caught, hide this sprite and clone it. • Show the clone of the fish sprite, switch its costume and finally set the initial position. Chapter 8. Play with Scratch...
Page 499
SunFounder uno-and-mega-kit • Make the fish sprite’s clone move left and right and bounce back when it touches the edge. • The fish sprite (of the clone) will not react when it passes the Fishhook sprite; when it touches the Fishhook sprite in the fishing state (turns red), it will be caught, at which point the score (variable score) +1, and it will...
Page 500
SunFounder uno-and-mega-kit the red color of the Fishhook sprite on the stage. If you choose a color arbitrarily, this [Touch color] block will not work. 8.2.19 19. GAME - Kill Dragon Here, we use the joystick to play a game of dragon killing.
Page 501
SunFounder uno-and-mega-kit Build the Circuit A joystick is an input device consisting of a stick that pivots on a base and reports its angle or direction to the device it is controlling. Joysticks are often used to control video games and robots.
Page 502
SunFounder uno-and-mega-kit Now build the circuit according to the following diagram. • Breadboard • Joystick Module Chapter 8. Play with Scratch...
Page 503
SunFounder uno-and-mega-kit Programming 1. Dragon Woods backdrop added via the Choose a Backdrop button. • Delete the default sprite and add the Dragon sprite. • Go to the Costumes page and flip the dragon-b and dragon-c horizontally. 8.2. Projects...
Page 504
SunFounder uno-and-mega-kit • Set the size to 50%. Chapter 8. Play with Scratch...
Page 505
SunFounder uno-and-mega-kit • Now create a variable - dragon to record the dragon’s life points, and set the initial value to 50. • Next, switch the sprite costume to dragon-b and have the Dragon sprite up and down in a range.
Page 506
SunFounder uno-and-mega-kit • Add a Lightning sprite as the fire blown by the Dragon sprite. You need to rotate it 90° clockwise in the Costumes page, this is to make the Lightning sprite move in the right direction. Note: When adjusting the Lightning sprite’s costume, you may move it off-center, which must be avoided! The center point must be right in the middle of the sprite! Chapter 8.
Page 507
SunFounder uno-and-mega-kit • Then adjust the dragon-c costume of the Dragon sprite so that its center point should be at the tail of the fire. This will make the positions of the Dragon sprite and the Lightning sprite correct, and prevent Lightning from launching from the dragon’s feet.
Page 508
SunFounder uno-and-mega-kit • Adjust the size and orientation of the Lightning sprite to make the image look more harmonious. Chapter 8. Play with Scratch...
Page 509
SunFounder uno-and-mega-kit • Now script the Lightning sprite. This is easy, just have it follow the Dragon sprite all the time. At this point, click on the green flag and you will see Dragon moving around with lightning in its mouth.
Page 510
SunFounder uno-and-mega-kit to create a clone for the Lightning sprite. • Click on the Lightning sprite and let the Lightning clone shoot out at a random angle, it will bounce off the wall and disappear after a certain amount of time.
Page 511
SunFounder uno-and-mega-kit • In the Lightning sprite, hide its body and show the clone. Now the dragon can move up and down and blow out fire. 8.2. Projects...
Page 512
SunFounder uno-and-mega-kit 2.Wand • Create a Wand sprite and rotate its direction to 180 to point to the right. • Now create a variable hp to record its life value, initially set to 3. Then read the Joystick’s value, which is used to control the wand’s movement.
Page 513
SunFounder uno-and-mega-kit • The dragon has lightning, and the wand that crushes it has its “magic bullet”! Create a Star sprite, resize it, and script it to always follow the Wand sprite, and limit the number of stars to three.
Page 514
SunFounder uno-and-mega-kit • Make the Wand sprite shoot stars automatically. The Wand sprite shoots stars the same way the dragon blows fire – by creating clones. Chapter 8. Play with Scratch...
Page 515
SunFounder uno-and-mega-kit • Go back to the Star sprite and script its clone to spin and shoot to the right, disappear after going beyond the stage and restoring the number of stars. Same as Lightning sprite, hide the body and show the clone.
Page 516
SunFounder uno-and-mega-kit Now we have a wand that shoots star bullets. 3. Fight! The wand and the dragon are currently still at odds with each other, and we’re going to make them fight. The dragon is strong, and the wand is the brave man who crusades against the dragon. The interaction between them consists of the following parts.
Page 517
SunFounder uno-and-mega-kit • If Lightning (a Lightning sprite clone) hits the Wand sprite, it will make a pop sound and disappear, and the Wand will lose life points. 8.2. Projects...
Page 518
SunFounder uno-and-mega-kit • If a Star (clone of the Star sprite) hits the Dragon, it will emit a collect sound and disappear, while restoring the Star count, and the Dragon will lose life points. Chapter 8. Play with Scratch...
Page 519
SunFounder uno-and-mega-kit 4. stage The battle between the Wand and the Dragon will eventually be divided into winners and losers, which we represent with the stage. • Add Blue Sky backgdrop, and write the character “WIN!” on it to represent that the dragon has been defeated and the dawn has come.
Page 520
SunFounder uno-and-mega-kit • And modify the blank backdrop as follows, to represent that the game has failed and everything will be in darkness. Chapter 8. Play with Scratch...
Page 521
SunFounder uno-and-mega-kit • Now write a script to switch these backgdrops, when the green flag is clicked, switch to Woods backgdrop; if the dragon’s life point is less than 1 , then the game succeeds and switch the backdrop to Blue Sky; if the life value point of the Wand is less than 1, then switch to Night backdrop and the game fails.
Page 522
SunFounder uno-and-mega-kit Chapter 8. Play with Scratch...
CHAPTER NINE 9.1 1. the board does not work? If you have clicked the green flag or sprite in PictoBlox’ stage mode, you cannot send data to or receive data from the Arduino board. You need to do the following. 1) Check if the correct board is selected and already connected.
CHAPTER THANK YOU Thanks to the evaluators who evaluated our products, the veterans who provided suggestions for the tutorial, and the users who have been following and supporting us. Your valuable suggestions to us are our motivation to provide better products! Particular Thanks •...
ELEVEN COPYRIGHT NOTICE All contents including but not limited to texts, images, and code in this manual are owned by the SunFounder Company. You should only use it for personal study, investigation, enjoyment, or other non-commercial or nonprofit purposes, under the related regulations and copyrights laws, without infringing the legal rights of the author and relevant right holders.
Need help?
Do you have a question about the R3 and is the answer not in the manual?
Questions and answers