Introduction: Physical Computing - Scratch for Arduino
This is the first of my four tutorials focusing Scratch and Physical Computing. I have also published:
- Physical Computing - Scratch 2.0 for Raspberry Pi
- Physical Computing - Scratch for Raspberry Pi (using Scratch V.1.4)
- Electronic Playground With Arduino and Scratch 2 (Using Scratch 2.0)
Scratch is a great tool to teach beginners how to code. You can learn more about Scratch here: Scratch
With Scratch, you can program your own interactive stories, games, and animations — and share your creations with others in the online community. Scratch helps young people learn to think creatively, reason systematically, and work collaboratively — essential skills for life in the 21st century. Scratch is a project of the Lifelong Kindergarten Group at the MIT Media Lab. It is provided free of charge.
and not only learn how to program interactive stories but also do Physical Computing!
But what is Physical Computing?
According Wikipedia, Physical computing means building interactive physical systems by the use of software and hardware that can sense and respond to the analog world. While this definition is broad enough to encompass systems such as smart automotive traffic control systems or factory automation processes, it is not commonly used to describe them. In a broader sense, physical computing is a creative framework for understanding human beings' relationship to the digital world. In practical use, the term most often describes handmade art, design or DIY hobby projects that use sensors and microcontrollers to translate analog input to a software system, and/or control electro-mechanical devices such as motors, servos, lighting or other hardware.
Physical Computing intersects the range of activities often referred to in academia and industry as electrical engineering, mechatronics, robotics, computer science, and especially embedded development.
Cool! So, what we will learn here in this tutorial is how to use SCRATCH to program an ARDUINO to interact with our physical world!
In short, we will learn how to:
- Read digital inputs as buttons and motion sensors
- Read analog sensors as LDR (to measure light) and temperature
- Generate digital outputs, turning ON/OFF LEDs
- Actuate on analog devices, controlling, for example, a LED brightness using PWM technics
The above diagram shows all the sensors and actuators will be connected to our Arduino. But do not worry, we will go step by step on each component.
Here, you can see a video with an example developed during this tutorial:
Before you start, I really recommend that you go to Scratch site and familiarize yourself with the language, following some basic tutorials. Doing that will help you to better understand how to use an Arduino for Physical Computing.
Step 1: Bill of Material (BoM)
- Arduino UNO
- LEDs (Red and Blue)
- 1 Button
- 1 LDR
- 1 LM35 Temperature Sensor
- 1 HC-SR501 - Passive infrared sensor (PIR)
- Resistors: 2x 10Kohm and 1x 220 ohm
- Full Breadboard
Step 2: Installing S4A
According to Arduino official page, you can program an Arduino using an experimental online tool: ScratchX, and a previous (desktop) version of Scratch that was modified by another team to produce S4A which reads Scratch programs but contains extensions to utilize a subset of an Arduino's input/output facilities. On this tutorial, I decided to use S4A due its stability and simplicity. Also, the Scratch desktop version used by S4A is based on the 1.6 version, same as used on Raspberry Pi. Comparing with the standard desktop version of Scratch, S4A provides new blocks for managing sensors and actuators connected to Arduino.
Components have to be connected in a particular way. S4A allows for:
- 6 analog inputs (analog pins),
- 2 digital inputs (digital pins 2 and 3),
- 3 analog outputs (digital pins 5, 6 and 9),
- 3 digital outputs (pins 10, 11 and 13) and
- 4 special outputs to connect Parallax continuous rotation servo motors (digital pins 4, 7, 8 and 12).
S4A interacts with Arduino by sending the actuator states and receiving sensor states every 75 ms, therefore the pulse width needs to be greater than this time period.
Download and Install
Installing S4A requires you to install software both in your PC and your Arduino board.
- Download and install the appropriate S4A version for your Operational System. There are 3 available programs: For MAC, Windows and Linux (including Raspberry Pi)
- Use this link to download the last S4A program (version 16): S4A Dropbox
- Download the .ino code to be uploaded on your Arduino (S4AFirmware16.ino). The code can be found at same Dropbox link above.
In my case, I installed the MAC version (S4A16.dmg). I am using the macOS Sierra. Only it is important to note that you must allow apps to be installed from "Anywhere", changing your Security Settings, otherwise your Mac will say that the code is "broken". I installed without a problem.
Once you have installed the S4A, first open the S4AFirmware16.ino on your Arduino IDE and upload it to your Arduino UNO. Once the code ("firmware") is loaded on Arduino, open the S4A program (S4A.image).
It is important to have your Arduino UNO running the firmware BEFORE you open the S4A program, otherwise, you will a conflict on the USB port and the Arduino will not run properly. Also do not use the Serial Monitor on you IDE. Its will also generate confict.
Step 3: Digital Output - Blinking a LED
Let's start connecting a LED to pin 13 of our Arduino UNO.
if you go to "Motion menu"(blue blocks), you will find the special blocks designed for Arduino. We will use:
- digital:  on
- digital:  off
Note that at same block you can select the digital pins that can be used as output: 10, 11, 12 and 13.
- You can drag the blocks to the code area at the center.
- If you click on individual blocks, you can turn on or turn off the LED, try that.
OK. Now, let's create a real blink code using Scratch.
- Start your program when the "Green Flag" is clicked, for that you will need the block:
- When "green flag" clicked (it is the first block of Control menu - Yellow)
- Drag the loop block "Forever"
- Inside the loop Forever, put the blocks that you tested before.
- if you run your code, you will see that nothing happens, or better, the LED will be ON and OFF so quickly that you will not realize it. So, you must some delay, let's say 1 second after each block. And that's it!
The screenshot above will show you the final program and on below link, you can download the code used here:
Try some changes, explore the code!
Step 4: Analog Output - Controlling a LED Brightness
Now, let's start with writing problems a little more complex to explore the potential of Arduino.
First, let's follow the diagram and add a new LED to our circuit. We must connect the LED cathode (the shorter leg) to GND via a 220 ohm resistor and the anode to our Arduino UNO pin 9.
The Arduino UNO can provide on several of its pins, a PWM signal (Pulse Width modulation). See this link for more details: Tutorial/PWM. In short, you can "emulate" an analog signal using a digital output. The S4A has a specific block for that:
- analog  value <255>
On this same block, you can select the PWM pins that can be used as output: 5, 6 and 9.
The value can be changed from 0 to 255
The Same way that we did with digital pins, you can drag the block to the code area and click on it. Change the value 255 for other values. You will see that with zero, the LED will be off and with 255, the LED will be on its maximum brightness. Try intermediate values and see what happen.
Let's create a code that will do the following:
- Change the PWM value from 0 to 255, returning to zero after that.
- When the Blue LED brightness will at its maximum, let's turn on the Red LED for 1 second.
On the code shown above, 2 new things were introduced:
- Variables were defined (the orange menu)
- pwmLED: a variable that will receive the values from 0 to 255
- Red LED: a variable that will receive 2 values: ON and OFF
- An IF Block < > will be used for testing proposes.
Together with each variable, the following blocks can be used:
- set [variable] to < > will be used to assign a value to a specific variable. For example:
- set [Red LED] to <OFF>
- set [pwmLED] to <0>
Saying that you can analyze the code shown above and figure out how its work.
Below the code:
Analog outputs can be used to control motors or position servos for example. You can try it.
Step 5: Digital Input: Push-button
Let's begin with connecting a push-button to Arduino pin 2. Follow the above diagrams and make the proper connections.
The important new block introduced here is:
- sensor [digital 2] pressed?:
This block has 2 possible parameters: [digital 2] and [digital 3], what correspond to the 2 possible digital inputs, pins D2 and D3.
This block will return "True" if on the pin D2 or D3 we have a logical level "1" and "False" if it is a "0".
So, let's introduce a variable "button", that will be set up to "1" or "0" depending on the push-button condition.
Also, note that we have 2 blocks of code that will run in parallel (the set of blocks that starts with the green flag)
- One that will constantly check the push-button condition, setting the "button" variable
- Another that will set up the second variable, "Red LED", ON or OFF =, depending on "button" variable. The Red LED will turn on or off depending on push-button condition.
A great feature with S4A that helps a lot when you are testing a code, is "to check" a variable (with a "v" mark) on the variable menu. Doing that, the variable value will appear on the right panel, as shown on the above screenshot.
Below the correspondent code:
Step 6: Digital Input - Push-button With "Memory"
Let's change the previous code, so, each time that the push-button is pressed:
- Blue LED will be "toggled", or better, if its state was previously "ON", it will be changed to "OFF" and vice-versa.
- Red LED will follow its state, as coded in the previous step.
For that, the 3rd block of code was created with 2 new variables:
Also on this block, a small delay was introduced each time that the push-button change its state. This is due the fact that we need "to debounce" the state of the push-button.
the video below shows the code working:
and below the code:
Step 7: Analog Input - LDR
For testing how to use the Arduino analog inputs, we will start connecting an LDR, that is a Light Dependent Resistor on Analog Pin A0.
What is an LDR?
LDR, also known as " Photoresistor", is a device that has its electrical resistance varying with light. As you can see above diagram, higher the light, lower the resistance. So, because we will assemble the LDR as a "voltage divider", we will get at Arduino pin A0 an analog signal inversely proportional to light variation:
- High light ==> Lower internal resistance ==> higher voltage input at A0
- Low light ==> higher internal resistance ==> lower voltage input at A0
This way, the pin A0 of Arduino UNO will receive a signal varying from 0 to 5V. The Analog Pins of UNO are internally connected to a 10bits ADC (Analog Digital Converter), that it is a device that as the name shows, will convert the analog value to digital values to be reading internally by the processor (from 0 to 1023).
So, on a limit we considered:
- LOW LIGHT ==> HIGH RESISTANCE ==> 0V ==> 0
- HIGH LIGHT ==> LOW RESISTANCE ==> 5V ==> 1023
of course in a practice, the values will be between those extremes. Let's see it working:
The block to be used here is:
- value of sensor [Analog0]
This block has 6 possible parameters: from [Analog0] to [Analog5], what correspond to the 6 UNO analog inputs, pins A0 to A5.
"Check' this block to see the value of pin A0, it will appear on the screen or drag it to program area and click on it, the value will appear on a small balloon. In my case, I got the following range for the LDR:
- Normal light: More than 800
- Dark (I covered the sensor with my hand): Less than 250
As we did before, we will define a new variable, "LDR" that will take the A0 value. we will include it on the "Forever Loop" that is part of the "setup set of blocks".
look for the code:
- set [LDR] to Analog0]>
Now that we have the variable LDR constantly updated with the sensor value, let's create a new set of blocks with the following idea:
- IF Blue LED is ON and LDR value is lower than 300 (some safety here. Your value can be another)
- Then do: Red LED must be ON
- do: REd LED must be OFF
Note that we used here the block "IF-Then-Else" and 2 operator's block (green):
- < > and < >
- < > = < >
The code is simple. You can use it to automatically turn on an external light in your house (here the Red LED) when is dark, but you only want to do this if you are traveling, so you will turn on or off your project, using the push-button.
Below the complete code:
Step 8: Analog Input - Temperature
Let's use what we learned on the last step and explore another type of sensor that generates an analog output, the LM35, a temperature sensor.
The LM35 series are precision integrated-circuit temperature sensors, whose output voltage is linearly proportional to the Celsius (Centigrade) temperature and so, does not need external calibration. Its output is 10mV/oC. So, for a temperature of 19 oC for example, the LM35 will generate 190mV.
As we did before, we will define a new variable, "Temp" that will take the A1 value. we will also include it on the "Forever Loop" that is part of the "setup set of blocks".
look for the code:
- set [Temp] to Analog1]>
Ops, but when you click on this block (or see it on the screen), we realize that the temperature is not really correct (it shows "39", but I know that the temperature here in my lab is in fact 19oC).
Remember that each Analog Input will vary from 0 to 5V (or 5,000mV). So, let's calculate for 19oC what should be the output of internal ADC:
Applying proportion, we have:
- 5,000 [mV] ==> 1024
- 190 [mv] ==> x
x = (190 [mV] x 1023) / 5,000 [mV] = 39
So, this is exactly what we are getting internally from A1. But what should we do have the variable "Temp" showing the correct Celsius temperature?
Taking the reading, find what percentage of the range (1024) it is, multiplying that by the range itself (5000 mV), and dividing by ten (10 mV per degree Celcius, according to the datasheet):
The temperature in Celcius will be so calculated:
Temp = (5V x A1_Value x 100%) / 1024 =
Temp = A1_Value (500/1024)
Temp = A1_Value / 2.048
So, let's use blocks below to calculate it:
- set [Temp] to Analog1]> / <2.048>>
When you click on it, the correct "19oC" will appear associated with variable "Temp".
Same as we did with LDR and now that we have the variable Temp constantly updated with the sensor value, let's create a new set of blocks with the following idea:
- IF Blue LED is ON and Temp value is bigger than 30oC
- Then do: Red LED must be ON
- do: REd LED must be OFF
In this case, you can use your project to automatically turn on a fan or conditioner air equipment in your house (here the Red LED) when is hot. Again, you will only turn on or off your project, using the push-button.
The video show the code working:
Below the complete code for downloading:
Step 9: A Bulb Thermometer
On this step try playing with pen blocks and create a "virtual" Bulb temperature using the LM35, as shown at above print screen.
Below the code:
Step 10: Another Digital Input Example - Motion Detector
PIR sensors allow you to sense motion, almost always used to detect whether a human has moved in or out of the sensors range. They are small, inexpensive, low-power, easy to use and don't wear out. For that reason, they are commonly found in appliances and gadgets used in homes or businesses. They are often referred to as PIR, "Passive Infrared", "Pyroelectric", or "IR motion" sensors.
They are "Digital Sensors", being very easy to use them in your projects.:
- If you have a "movement" in front of the sensor, its will generate a 5V in its output and the Arduino will understand it as logical level "1".
- With "no movement" a 0V will be at Arduino's digital pin, what means a logical level "0".
You can "think" that the sensor is a "push-button", what means that what we have learned before will apply to it.
So, let's begin with connecting the PIR sensor to Arduino pin 3. Follow the above diagrams and make the proper connections.
Same as we did with the Push-Button, we will use the below block:
- sensor [digital 3] pressed?:
This block will return "True" if on the pin D3 we have a logical level "1" and "False" if it is a "0".
So, let's introduce a new variable "motion", that will be set up to "ON" or "OFF" depending on the PIR condition:
- motion = ON ==> There is a movement detected
- motion = OFF ==> There is no movement detected
As we did before, the variable, "motion" will take the D3 status. We will include it on the "Forever Loop" that is part of the "setup set of blocks", same code that we used with the push-button.
Now, let's think about something useful to do with this sensor. Its more common use is on home alarms. If an alarm is on (remember the Blue LED?) and a person enter in your home, the sensor will detect it and will fire an alarm for example. In our case, this alarm is represented by Red LED. The code is similar to the one developed for the last sensors.
Try it for yourself. But anyway, the code is below:
Step 11: To Boldly Go Where No One Has Gone Before......
It is time, now! Be creative! Mix the sensors, including new ones! The sky is the limit. After you learn about how to control "things" using an Arduino and Scratch, try doing the same using the Arduino IDE.
Step 12: Conclusion
As always, I hope this project can help others find their way in the exciting world of electronics, robotics, and IoT!
Please visit my GitHub for updated files:
For more projects, please visit my blog: MJRoBot.org
Saludos from the south of the world!
See you at my next instructable!
Participated in the
Explore Science Contest 2017
1 Person Made This Project!
- mjrovai made it!