Arduino小車基礎-前進後退和串列埠監視器

蜗牛的礼物發表於2024-07-10
//前進
void Forward(){
  digitalWrite(2,LOW);
  digitalWrite(3,HIGH);
  digitalWrite(4,HIGH);
  digitalWrite(5,LOW);
}
//後退
void BackOff(){
  digitalWrite(2,HIGH);
  digitalWrite(3,LOW);
  digitalWrite(4,LOW);
  digitalWrite(5,HIGH);
}
//左轉
void TurnLeft(){
  //小車左轉(左輪後退)
  digitalWrite(2,HIGH);
  digitalWrite(3,LOW);
  //小車左轉(右輪前進)
  digitalWrite(4,HIGH);
  digitalWrite(5,LOW);
}
//右轉
void TurnRight(){
  //小車右轉(右輪後退)
  digitalWrite(4,LOW);
  digitalWrite(5,HIGH);
  //小車右轉(左輪前進)
  digitalWrite(2,LOW);
  digitalWrite(3,HIGH);
}

void setup() {
  // put your setup code here, to run once:
  //配置2,3口為輸出引腳(左輪初始化)
  pinMode(2,OUTPUT);
  pinMode(3,OUTPUT);
  //配置4,5口為輸出引腳(右輪初始化)
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);
  //pinMode(LED_BUILTIN,OUTPUT);
  //串列埠初始化
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println("前進");
  Forward();
  delay(1000);
  Serial.println("後退");
  BackOff();
  delay(1000);
  Serial.println("右轉");
  TurnRight();
  delay(1000);
  Serial.println("左轉");
  TurnLeft();
  delay(1000);
}

使用的是Arduino Uno開發板(初始化2,3,4,5介面,波特率:9600)

相關文章