# Writing the Code

2,621

1

2

The following information is a single lesson in a larger project. Find more great projects here.

Lesson Overview:

Now we'll write our crystal ball software!

## Step 1: Import the LiquidCrystal Library

The first thing you will do is import the LiquidCrystal library. In the simulator, you can go to the Libraries tab in the Code Editor and press "include." You can also simply copy the code below.

You will also initialize the library, somewhat similar to the way you did with the Servo library, telling the Arduino which pins will communicate with the LCD.

1. Copy the code below into the Code Editor.
```#include
LiquidCrystal lcd(12,11,5,4,3,2);
```
2. Continue to the next step.

## Step 2: Create Constants

Now that you’ve set up the library, it’s time to create some variables and constants.

Create a constant to define the tilt switch pin (switchPin) and a variable for the current state of the switch. You will also create a variable for the previous state of the switch, and one more variable to choose which reply the screen will show.

1. Copy the code below into the Code Editor.

```const int switchPin = 6;
int switchState = 0;
int prevSwitchState = 0;
```

2. Continue to the next step.

## Step 3: Initialize the Switch

At the beginning of the setup() function, define the switchPin as an input.

1. Copy the code into the Code Editor.

```void setup(){
pinMode(switchPin, INPUT);```

2. Continue to the next step.

## Step 4: Print Your First Line

Next you will initialize the LCD by telling the Arduino how large the screen is (16 x 2 cells) and then printing the phrase "Ask the Crystal Ball!"

The lcd.print() function writes to the LCD screen. You’re going to write the words “Ask the” on the top line of the screen. The cursor is automatically at the beginning of the top line. In order to print "Crystal Ball" on the next line, you will need to move the cursor from the top left corner (0,0) to the cell below (0,1). Use the function lcd.setCursor() to move to the right coordinates.

1. Copy the code into the Code Editor.

```	lcd.begin(16, 2);
lcd.setCursor(0, 1);
lcd.print("Crystal Ball!");
}```

2. Now when you start the program, the LCD will say "Ask the Crystal Ball!"

3. This is the end of the setup() function.

4. Continue to the next step.

## Step 5: Start the Loop()

In the loop(), you’re going to check the switch first, and put the value in the switchState variable.

1. Copy the code below into the Code Editor.

```void loop(){

2. Continue to the next step.

## Step 6: Choose a Random Answer

If you haven't guessed already, the digital Crystal Ball doesn't not really predict the future. It just chooses a response at random from a list!

Use an if() statement to determine if the switch is in a different position than it was previously - this indicates that you moved the tilt sensor.

If it has changed, and it is currently LOW, then it’s time to choose a random reply. The random() function returns a number based on the argument you provide to it (responses are defined in step 8).

1. Copy the code below into the Code Editor.

```	if(switchState != prevSwitchState){
if(switchState == LOW){
reply = random(8); //pick a number from 0 to 7```

2. To start, you’ll have a total number of 8 different responses for the ball. Whenever the statement random(8) is called, it will give a number between 0-7. Store that number in your reply variable.

3. The if() statement is not over! There is a lot more code to go in this section, including defining the possible replies.

4. Continue to the next step.

## Step 7: Clear the Screen

Within the if() statement, clear the screen with the function lcd.clear() to get it ready for displaying a response.

This also moves the cursor back to location 0,0; the first column in the first row of the LCD. Print out the line “ The ball says:” and move the cursor to 0,1 for the output.

1. Copy the code below into the Code Editor.

```			lcd.clear();
lcd.setCursor(0, 0);
lcd.print("The ball says: ");
lcd.setCursor(0,1 );```

2. Continue to the next step.

## Step 8: Predict the Future!

The switch() statement executes different pieces of code depending on the value you give it. Each of these different pieces of code is called a "case."

switch() takes the variable reply as an argument, which we previously gave a random value between 0 and 7. Whatever value reply holds will determine what response is displayed!

For example, if reply has a value of 2, then case 2 will be executed.

1. Copy the code below into the Code Editor.

```			switch(reply){
case 0: lcd.print("Yes");
break;
case 1: lcd.print("Most likely");
break;
case 2: lcd.print("Certainly");
break;
case 3: lcd.print("Outlook good");
break;
case 4: lcd.print("Unsure");
break;
break;
case 6: lcd.print("Doubtful");
break;
case 7: lcd.print("No");
break;
} //end of switch
} //end of nested if()
} //end of outer if()```

2. After each lcd.print() function, there’s another command: break. It tells the Arduino where the end of the case is. When the program hits break, it skips to the end of the switch statement, so it doesn't try to print more than one statement!

3. Continue to the next step.

## Step 9: Update the Switch State

￼The last thing to do in your loop() is to assign switchState’s value to the variable prevSwitchState. This enables you to track changes in the switch the next time the loop() function runs.

1. Copy the code below into the Code Editor.

```	//update the tilt switch status
prevSwitchState = switchState;
} //end of loop()```

2. You're done writing the code! Now it is time to ask the Crystal Ball a question.

3. Continue to the next step.

## Step 10: Use It!

Now you can Upload & Run the code in the simulator, or plug in and program your Arduino Uno.

1. After uploading and running your code, check the screen to make sure it says Ask the Crystal ball! If you cant see the characters, try turning the potentiometer. It will adjust the contrast of the screen.
2. Ask a question of your crystal ball, and try tilting the switch upside down and back again. You should get an answer to your question on the LCD. If the answer doesnt suit you, ask again!
3. Instruction image Recall that in the circuit simulator, you can move the tilt sensor by highlighting it and dragging the slider back and forth. You will have to slide it in both directions to change the answer on the LCD.
4. Instruction image Continue to the next step.
5. Stuck? HINT: Notice that we didn't need to write any code for the potentiometer! It operates directly as a voltage divider at pin V0 on the LCD to control the screen brightness.

## Step 11: Customize Your Project

Try adding your own sayings to the print() statements, but be mindful of the fact that there are only 16 characters to use per line. You can also try adding more responses. Make sure when you add additional switch cases, you adjust the number of options that will randomly populate the reply variable.

The code pictured below enables you to choose from 12 responses at random.

1. Continue to the next step.

## Step 12: Think About It...

The functions covered here for changing the LCD screen’s text are fairly simple. Once you have a handle on how it works, look at some of the other functions the LiquidCrystal library has. Try getting text to scroll, or continually update. To find out more about how the LiquidCrystal library works, visit: arduino.cc/lcd

1. Continue to the next step.

## Step 13: Review

Congratulations on completing the Crystal Ball project! We hope that it always gives you positive responses.

In this project, you used a liquid crystal display (LCD) to show text on a screen. The LiquidCrystal library made it easy to control, although the LCD itself required a lot of wire connections with the Arduino.

You also used switch casestatements to generate a list of possible outputs for the LCD. This can be used to define outputs for any kind of variable, not just one generated at random! For more information, visitarduino.cc/SwitchCase

Congratulations, you have completed this project!

Check out other great projects here.

## Recommendations

• ### Arduino Class

77,779 Enrolled

## 2 Discussions

Dear sir/medem,

I made ur project but when i run is it wil only show some weird characters ( see image)

bw,
Jasper_2106