---
# System prepended metadata

title: NRF Mega2560馬達控制程式
tags: [Arduino 實作, Arduino]

---

###### tags: `Arduino` `Arduino 實作`
# NRF Mega2560馬達控制程式
```cpp=
#include<Streaming.h>

const int motorR[4] = {22, 23, 24, 25};
const int motorL[4] = {26, 27, 28, 29};
bool dtr[4] = {0, 0, 0, 0};  //(1,0) forward (0,1) backward
bool dtl[4] = {0, 0, 0, 0};
const int dtpin[8] = {2,3,4,5,6,7,A0,A1};   //pin read

void setup() {
  //
  Serial.begin(9600);
  for (int i = 0; i < 4; i++) {
    pinMode(motorR[i], OUTPUT);
    pinMode(motorL[i], OUTPUT);
  }
  for (int i = 0; i < 8; i++) {
    pinMode(dtpin[i], INPUT_PULLUP);
  }
  //
}

void loop() {
  for(int i=0;i<4;i++){
    dtr[i] = digitalRead(dtpin[i]);
    Serial << dtr[i] << ' ';
  }
  for(int i=0;i<4;i++){
    dtl[i] = digitalRead(dtpin[i+4]);
    Serial << dtl[i] << ' ';
  }
  Serial << endl;
  for(int i=0;i<4;i++){
    digitalWrite(motorR[i],dtr[i]);
    digitalWrite(motorL[i],dtl[i]);
  }
  delay(10);
}
```