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);
}