Topics Covered:
This code is a demonstration of how you can combine code concepts, hardware, and built-in functions to make something unique out of a speaker and a button.
Read the Code Walkthrough Text (click to open)
New Concept: Combining Conditions with AND && and OR ||
Sometimes, you want to create the same outcome from two different actions. For example, you may want to turn on a fan if a room gets too warm or if there is smoke in a room. Rather than write two separate if statements, you can combine these conditions with a Boolean OR. It's simple- you simply type the first condition inside an if or while loop, then type the 'pipes' and type the second condition. After you've typed the conditions, you can close the condition portion of your loop. This can get complex when there are many parentheses involved, so remember the order of operations. The 'pipes' are found below the delete or backspace key on most keyboards.
In other cases, you may want to do an action only if two things are true at the same time. For example, you may want to turn off a light only when two buttons are pressed, but not either of the buttons alone. To combine conditions this way, you use the Boolean AND, which is two ampersands side by side: &&. Both conditions that you put in the statement must be true before the action runs.
New Concept: Not Equal To Comparator
You're probably familiar with most of the comparators you see in code- < , >, <=, >=, and = are all used in other fields. The not-equal-to comparator is more rare. When using this comparator in an if statement, the condition is true when the two things being compared are not equal.
This comparator is useful when you're not sure how a variable may change. Imagine you're holding a very precise level of light on a plant. You're measuring the light with a light sensor and you have an alarm to go off if the light level changes. You don't care if the light increases or decreases or the amount that the light changes- you just need to know it's changed. By using a != comparator comparing your reading and the perfect light value you need, an if statement will be true any time the light value doesn't match your perfect light value.
New Concept: It's All Building Blocks
Code is complex, but it's made up of simple parts. You've seen how to combine them creatively to get something new and sometimes unexpected to happen. By paying attention to the basics and breaking down your problems until they're small enough to solve, you can create some wonderful things with code!