- Project Setup
- Arduino Software
- Starting with the code
- Sensors and Actuators
- Button & IF statement
- Serial Communication
- Connect Sensors and Actuators
- Button States
- FOR Loop
- Traffic Light
At the end of the previous tutorial we launched a challenge: try to light up the LED at its mid brightness. If you looked in the reference, the solution is quite intuitive; the TKLed class, in fact, has a method called .brightness() where we can write the desired brightness value inside the parenthesis.
The value that we can write goes from 0 to 1023, where 0 is OFF and 1023 is ON at full brightness.
If you already used Arduino before, you probably noticed that the TinkerKit ouptut PWM goes on a scale from 0 to 1023 instead of the 0 to 255 that you’re used to. This is because of the TinkerKit library, that in order to simplify the process, automatically converts the value in the .brightness() method.
What it does is converting led.brightness(value) to analogWrite(ledPin, value/4).
Actually, the LED is always at his maximum brightness but it blinks very fast and our human eye is not able to see the blink. The result we perceive is a less bright LED. This is called PWM and is a way to simulate analog outputs with digital signals, if you’re curious about the theory, there’s a nice article on the Arduino website or the full explanation on wikipedia.
For each actuator, you just need to know that the value to write inside the method’s parenthesis, goes from 0 to 1023.
For sensors it’s a bit different, first of all there are two main categories: digital and analog.
Digital sensors can only be in two states, usually called HIGH and LOW. Some examples are buttons, tilt sensors or touch sensors; in fact, they can only read two values. Buttons, like touch sensors, can only say if they’re pressed or not. If you write the button method .read(), it’s like if you’re asking “hey button what are you reading?” and the answer would only be HIGH if pressed and LOW if not pressed.
When NOT pressed:
- Code: button.read() Return Value: LOW
- Code: button.readSwitch() Return Value: 0
- Code: button.read() Return Value: HIGH
- Code: button.readSwitch() Return Value: 1
Analog sensors on the other hand can read all the values in-between. Most of the TinkerKit! sensors are analog, their range of values is between 0 and 1023. In the previous examples we called the .read() method on a button, what if we do the same with a potentiometer or a light sensor?
What we get is an integer value from 0 to 1023. If we do the same with a light sensor, the values will range from 0 (no light perceived) to 1023 (max light perceived).