Inspiration
Arduino Inputs & Outputs
Digital Inputs and Outputs
- The basic Arduino board has 14 digital pins that can be used either as inputs or outputs
- Digital inputs are used to read buttons/switches and other digital signals
- Digital outputs are used to control other electric components or devices (LEDs, motors etc.)
- You set the pin as INPUT or OUTPUT with the pinMode() function
Analog Output
The basic Arduino board does not have real analog output, but some of the pins support PWM (pulse-width modulation). PWM lets us to “fake” an analog signal with digital outputs. It can be used to fade lights, control the speed of motors etc.
Analog Input
The Arduino Duemilanove/UNO/Leonardo boards have 6 analog inputs. They are 10-bit ADCs (analog-to-digital converters). The analog inputs are used to read analog sensors.
Logic Level and the Resolution of Inputs and Outputs.
Function | 0V | 5V |
---|---|---|
digitalRead() | LOW (0) | HIGH (1) |
digitalWrite() | LOW (0) | HIGH (1) |
analogRead() | 0 | 1023 |
analogWrite() | 0 | 255 |
Serial Communication
The Arduino uses a serial port to send/receive data between the board and the computer (or any other device that supports serial communication).
- Serial.begin() opens the serial port
- Serial.print() or Serial.println() are used to send values from the Arduino
- Serial.read() is used to read messages sent to the Arduino board
How to Read Sensors
Many sensors are just resistors that change their resistance value based on some external input (light, temperature, force etc.). The Arduino is not able to read the change in resistance directly, but we can convert that resistance change into a change in voltage using a voltage divider.
Voltage Divider
If you connect two resistors in series as in the image below, the voltage read from Vout depends on the values of the two resistors. Read the Wikipedia article if you want to learn how to calculate the values.
This can be used to read the values from various sensors, such as the light sensor we are using.
// Read and display the value from the light sensor. int lightSensor = 0; void setup() { // put your setup code here, to run once: Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: lightSensor = analogRead(A0); Serial.print("light: "); Serial.println(lightSensor); }
Controlling the Brightness of an LED With the Light Sensor
int lightSensor = 0; int b = 0; void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(9,OUTPUT); } void loop() { // put your main code here, to run repeatedly: lightSensor = analogRead(A0); Serial.print("light: "); Serial.print(lightSensor); b = map(lightSensor,450,850,255,0); b = constrain(b,0,255); Serial.print(" led: "); Serial.println(b); analogWrite(9,b);
Note that we use the map() command to scale the input values from the sensor to a range more suitable for the LED. The constrain() makes sure that we never send invalid values (under 0 or over 255) to the LED.