跳至內容

Arduino/應用實例

維基教科書,自由的教學讀本

點亮LED

[編輯]
void setup() {
    pinMode(13, OUTPUT);
}

void loop() {
    digitalWrite(13, HIGH);    
}

LED閃爍

[編輯]
void setup() {
    pinMode(13, OUTPUT);
}

void loop() {
    digitalWrite(13, HIGH);
    delay(1000);
    digitalWrite(13, LOW);
    delay(1000);
}

雙色LED

[編輯]
int redPin = 9;
int greenPin = 10;
int value = 0;
void setup() {
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  for(value=255; value>0; value--){
    analogWrite(redPin, value);
    analogWrite(greenPin, 255-value);
    Serial.println(value, DEC);
    delay(5);
  }
  
  for(value=0; value<255; value++){
    analogWrite(redPin, value);
    analogWrite(greenPin, 255-value);
    Serial.println(value, DEC);
    delay(5);
  }
}

RGB三色LED

[編輯]
int redPin = 11;
int greenPin = 10;
int bluePin = 9;

void setup() {
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
}

void loop() {
  color(255, 0, 0); //red
  delay(1000);
  color(0, 255, 0); //green
  delay(1000);
  color(0, 0, 255); //blue
  delay(1000);
}

void color(unsigned char red, unsigned char green, unsigned char blue) {
  analogWrite(redPin, red);
  analogWrite(greenPin, green);
  analogWrite(bluePin, blue);
}

用脈衝寬度調制(PWM)決定LED亮度

[編輯]
/* 只有DIGITAL(PWM~) PIN 3,5,6,9,10,11可以用作PWM
   用的函數為analogWrite(x,y)
*/
void setup() {
    pinMode(3, OUTPUT);
}

void loop() {
    for(int i = 0; i<256; i++) {
        analogWrite(3, i);
        delay(10);
    }
    for(int i = 255; i>0; i--) {
        analogWrite(3, i);
        delay(10);
    }
}

串列埠通信1

[編輯]
void setup() {
    Serial.begin(9600);
    Serial.println("Hello World, I'm Arduino");
}

void loop() {
    
}

讀取類比訊號

[編輯]
void setup() {
    Serial.begin(9600);
}

void loop() {
    int value = analogRead(A0);
    Serial.println(value);
    delay(100);
}