4 Arduino Programming
4 Arduino Programming
Arduino Programming
• Variable declaration
• Setup function
• Other variable types are used in later examples (i.e., float, long,
unsigned int, char, byte, etc.) a
.
The Loop Function
• This function is where the main code is placed and will run over and
over again continuously until the Arduino is powered off
Signals
• Digital signals : The Arduino Uno/Diecimila/Duemilanove has 14 digital
input/output pins labeled D0-D13
• Hight (1) : 5V
• Low (0) : 0V
• Analog signals
Digital Signals
• Input : value = digitalRead(pin)
• Output : digitalWrite(pin)
• digitalWrite(pin)
• This function is where the main code is placed and will run over and
over again continuously until the Arduino is powered off
1-9
Digital Signals : Example
Breadboard
1-12
Digital Signals
Button : PullUp and PullDown
#define Button 2
int Counter=0;
int buttonState;
int lastButtonState = HIGHnhấn.
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
pinMode(Button, INPUT); // digitalWrite(Button,HIGH);
}
Software Switch Debouncing
void loop() {
int reading = digitalRead(Button);
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading != buttonState) {
buttonState = reading;
if (buttonState == LOW) {
Counter++;
Serial.println(Counter);
}
}
}
lastButtonState = reading;
}
Analog Input
• The input is looking for a voltage level between 0-5vdc and will scale
that voltage into a 10-bit value, or from 0-1023.
int pot_val; // use variable "pot_val" to store the value of the potentiometer
void setup() {
Serial.begin(9600); // start Arduino serial communication at 9600 bps
}
void loop() {
pot_value = analogRead(0); // use analogRead on analog pin 0
Serial.println(pot_val); // use the Serial.print() command to send the value
to the monitor
}
Analog output : PMW
• PMW(Pulse Width
Modulation) is a technique
for getting analog results
with digital means