# Control Scratch With an Accelerometer

5,336

22

2

The Scratch programming environment is very popular with kids. Using the Arduino, we can introduce accelerometer control so your games can react to the tilting of the accelerometer.

I covered the basics in the instructable below:
https://www.instructables.com/id/A-Gentle-Introduction-to-Arduino-for-Scratch-Users/

For people comfortable with Arduino and Python, I covered the use of an accelerometer to control a flight simulator in the following Instructable:
https://www.instructables.com/id/Flight-Simulator-with-Arduino-and-Python/

Let's Get Started

If you haven't done it already, follow the instructions on this linked page http://goo.gl/4pU2h to download and install :

1.  S4A ( Scratch 4 Arduino) and

2. the Firmware for Arduino to talk to S4A

## Step 1: You Will Need

You will need:

* An Arduino
* An Accelerometer (e.g. http://goo.gl/ZddGy )
* A prototyping system or breadboard to wire the Accelerometer to the Arduino (e.g. http://goo.gl/1E1iI)

## Step 2: Wire the Accelerometer to the Arduino

Wire the Accelerometer to the Arduino as shown in the Diagrams:

* 3V => 3.3V
* GND => GND
* X => A0
* Y => A1
* Z => A2

BEWARE:  The Power to the ADXL335 is 3.3V.  Connecting it to 5V will KILL it.

## Step 3: Reading the Accelerometer in Scratch

The Arduino Code we Uploaded earlier allows S4A to communicate with Arduino.

We've just wired the accelerometer signals to A0, A1, A2 on the Arduino.

So all we need now is a Scratch Program to read A0, A1 and A2 and make it do something like moving a Character.

Start S4A.

Once S4A connects to the Arduino notice how the Arduino pin readings are shown on the right hand side.

Tilt the Board with Accelerometer on it and notice how the A0, A1 and A2 readings change. That's because the Accelerometer is wired to those pins on the Arduino and the accelerometer outputs different voltages as it's tilted.

( * You may wonder why an accelerometer would do this. Hint: Gravity is an acceleration and always points down).

Tilt the board fully forward and back. Write down the readings for Level, Forward, Backwards.
Do the same for Left and Right.

Now you have some numbers for the range of A0, A1 and A2 as you tilt the board.

Now go and write a Program controlled by A0, A1 and A2.

## Step 4: Example Scratch

Here's an example of how to move a Sprite with the Accelerometer.

I'm sure you can do much better. But this shows the basic idea.

In the Arduino Scratch code we read the A0 and A1 channels from Arduino and stick them in Global variable x and y so they can be read by other Sprites. We do some scaling of A0 and A1 before we put them into x and y so the x,y values are on the screen.

In the Bee Scratch we move the Sprite based on the x and y variables.

Have fun!