Arduino tutorial #01 | Input / Output
Contents
- Getting started
- Bread board
- Output
- Digital out – Blink
- Analog out – Fade
- Analog out – Servo
- Input
- Digital in – Tact switch
- Analog in – CdS cell (Light sensor)
Getting Started
Bread board
Bread board enable us to build circuits without soldering. We can connect pins by insert them into holes of bread boards.
Output
There are two functions for output:
- digitalWrite( ,)
- analogWrite( ,)
Digital out – Blink
int ledPin = 13; int interval = 1000; void setup() { pinMode(ledPin, OUTPUT); } void loop() { digitalWrite(ledPin, HIGH); delay(interval); digitalWrite(ledPin, LOW); delay(interval); }Analog out - fade
In fact, Arduino doesn't have the function to output analog value. To control LED (or other output devices for example DC motors) gradually , we can use "PWM - Pulse Width Modulation" as a control method. By PWM control, we can change apparent voltage by changing duty rate instead of changing peek voltage. For example, when the peek voltage is fixed in 5V, 10% duty rate appears as 0.5V. We can use analogWrite function for PWM control.int ledPin = 9; int step = 5; int val; void setup() { pinMode(ledPin, OUTPUT); val = 0; } void loop() { analogWrite(ledPin, val); val+=step; if(val>255-step || val<step){ step*=-1; } delay(10); }Analog out - servo
We can control servos by using PWM as well.
int servoPin = 9; int step = 32; int val; void setup() { pinMode(servoPin, OUTPUT); val = 0; } void loop() { analogWrite(servoPin, val-1); val+=step; if(val>256-step || val<step){ step*=-1; } delay(500); }Input
Same as output, there are two functions for input:
- digitalRead(<pin number>)
- analogRead(<pin number>)
Digital read - Tact switch
int ledPin = 13; int swPin = 7; void setup() { pinMode(ledPin, OUTPUT); pinMode(swPin, INPUT); } void loop() { digitalWrite(ledPin, digitalRead(swPin)); }
Analog read - CdS cell (Light sensor)
int ledPin = 11; int cdsPin = A0; void setup() { pinMode(ledPin, OUTPUT); pinMode(cdsPin, INPUT); } void loop() { analogWrite(ledPin, analogRead(cdsPin)/4); }
int ledPin = 11; int cdsPin = A0; void setup() { Serial.begin(9600); pinMode(ledPin, OUTPUT); pinMode(cdsPin, INPUT); } void loop() { Serial.println(analogRead(cdsPin)); int value = map(analogRead(cdsPin), 0, 300, 0, 50); analogWrite(ledPin, value); }