LoginSignup
0
0

More than 1 year has passed since last update.

ATtiny1616でエンコーダーモーターを動かす2

Posted at

ATtiny1616でエンコーダーモーターを動かすの続きです。
https://qiita.com/usashirou/items/4dc1c7c28c142e90bd5b
今回は、ADCを追加します。

ADCを追加

ADCを追加します。
ADCにより電圧を測ることが可能です。
今回は1番ピンの電圧を測ります。

sensorValue = analogRead(ADC);

プログラム

analogReadでピンを指定して、毎回読み込んでいます。

#define ENCA 2 // YELLOW
#define ENCB 3 // WHITE
#define IN2 8
#define IN1 9
int pos = 0;
int sensorValue = 0;        // value read from the pot

void setup() {
  Serial.begin(9600);
  pinMode(ENCA, INPUT);
  pinMode(ENCB, INPUT);
  attachInterrupt(digitalPinToInterrupt(ENCA), readEncoder, RISING);
}

void loop() {
  setMotor(1, 150, IN1, IN2);
  delay(2000);
  Serial.println(pos);
  setMotor(0, 0, IN1, IN2);
  Serial.println(pos);
  sensorValue = analogRead(1);
  Serial.print("sensor = ");
  Serial.print(sensorValue);
  Serial.print("\n");
  delay(500);
  setMotor(-1, 350, IN1, IN2);
  delay(2000);
  Serial.println(pos);
  setMotor(0, 0, IN1, IN2);
  sensorValue = analogRead(1);
  Serial.print("sensor = ");
  Serial.print(sensorValue);
  delay(1500);
  Serial.println(pos);
  sensorValue = analogRead(1);
  Serial.print("sensor = ");
  Serial.print(sensorValue);
  Serial.print("\n");
}

void setMotor(int dir, int pwmVal,  int in1, int in2) {
  if (dir == 1) {
    analogWrite(in1, pwmVal);
    digitalWrite(in2, LOW);
  }
  else if (dir == -1) {
    digitalWrite(in1, LOW);
    analogWrite(in2, pwmVal);
  }
  else {
    digitalWrite(in1, LOW);
    digitalWrite(in2, LOW);
  }
}

void readEncoder() {
  int b = digitalRead(ENCB);
  if (b > 0) {
    pos++;
  }
  else {
    pos--;
  }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0