firtel

Untitled

Jan 28th, 2022 (edited)
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <U8g2lib.h>
  2. #include <Wire.h>
  3.  
  4. #define joyStickY A0
  5. #define joyStickX A1
  6. #define motorDriver1 9//PWMピン
  7. #define motorDriver2 10//PWMピン
  8. #define sensorPin 7
  9.  
  10.  
  11. U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);
  12.  
  13. //ポーリング用
  14. unsigned long lastupdate = 0;
  15. unsigned long lastupdate2 = 0;
  16.  
  17. //カウンタ用
  18. volatile int count = 0;
  19. int dir = 0;
  20.  
  21.  
  22. void setup() {
  23.   Serial.begin(9600);//デバッグ用
  24.   //液晶初期化
  25.   u8g2.begin();
  26.   //割り込み開始
  27.   attachInterrupt(sensorPin, counter, RISING);
  28.  
  29. }
  30.  
  31. void loop() {
  32.   //前回実行時の時間を今の時間と比較
  33.   if (lastupdate + 200 <= millis()) {
  34.     lastupdate = millis();//次の実行のために時間更新
  35.     int sensor = analogRead(joyStickY);
  36.     int out = map(sensor, 0, 1023, -255, 255);
  37.     motor(out);//モーター用関数を読み出す
  38.   }
  39.   if (lastupdate2 + 200 <= millis()) {
  40.     lastupdate2 = millis();//次の実行のために時間更新
  41.     u8g2.clearBuffer();
  42.     u8g2.setFont(u8g2_font_ncenB08_tr);
  43.     u8g2.drawStr(0,10,count);
  44.     u8g2.sendBuffer();
  45.     }
  46. }
  47.  
  48. //モーター用関数
  49. void motor() {
  50.   if (output > 0) {
  51.     analogWrite(motorDriver1, output);
  52.     analogWrite(motorDriver2, 0);
  53.     dir = 1;
  54.   } else if (output <= 0) {
  55.     analogWrite(motorDriver1, 0);
  56.     analogWrite(motorDriver2, output * -1);
  57.     dir = -1
  58.   }
  59. }
  60.  
  61. void counter() {
  62.   count = count + 1 * dir;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment