第3回

プログラム

明るさセンサーを使って、モーターの動きを操作する

ソースコード

  1. const int DIR = 8;
  2. const int STEP = 9;
  3. void setup() {
  4.   pinMode(DIR, OUTPUT);
  5.   pinMode(STEP, OUTPUT);
  6.   digitalWrite(DIR, LOW);
  7.   digitalWrite(STEP, LOW);
  8.    // put your setup code here, to run once:
  9.   Serial.begin(9600);
  10. }
  11. void loop() {
  12.   // put your main code here, to run repeatedly:
  13.   int val=0;
  14.   val=analogRead(1);
  15.   Serial.println(val);
  16.   delay(500);
  17.   if(val<200){
  18.     for (int i=0; i <= 50; i++){
  19.     clockwise(0);
  20.   }
  21.   for (int i=0; i <= 50; i++){
  22.     counter_clockwise(0);
  23.   }
  24.   }
  25.   else{
  26.     for (int i=0; i <= 50; i++){
  27.     clockwise(5000);
  28.   }
  29.   for (int i=0; i <= 50; i++){
  30.     counter_clockwise(5000);
  31.   }
  32.   }
  33. }
  34. void clockwise(int delaytime){
  35.   digitalWrite(DIR, HIGH);//HIGHは時計回り
  36.   digitalWrite(STEP, HIGH);
  37.   delayMicroseconds(delaytime);
  38.   digitalWrite(STEP, LOW);
  39.   delayMicroseconds(delaytime);
  40. }
  41. void counter_clockwise(int delaytime){
  42.   digitalWrite(DIR, LOW);//はLOWは反時計回り
  43.   digitalWrite(STEP, HIGH);
  44.   delayMicroseconds(delaytime);
  45.   digitalWrite(STEP, LOW);
  46.   delayMicroseconds(delaytime);
  47. }

グループワークまとめ