A Simple Guide to Using a Hall Sensor measuring RPM - Arduino



#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);

volatile byte half_revolutions;
 unsigned int rpm;
 unsigned long timeold;

#if (SSD1306_LCDHEIGHT != 64)
#error("Height incorrect, please fix Adafruit_SSD1306.h!");
#endif

 void setup()
 {

   Serial.begin(9600);
   attachInterrupt(0, rpm_fun, RISING);
   half_revolutions = 0;
   rpm = 0;
   timeold = 0;

    display.begin(SSD1306_SWITCHCAPVCC, 0x3C);  // initialize with the I2C addr 0x3D (for the 128x64)
  // init done

  // Show image buffer on the display hardware.
  // Since the buffer is intialized with an Adafruit splashscreen
  // internally, this will display the splashscreen.
  display.display();
  delay(2000);

  // Clear the buffer.
  display.clearDisplay();
  displayRPM();
 }
 void loop()
 {
   if (half_revolutions >= 10) {
     //Update RPM every 20 counts, increase this for better RPM resolution,
     //decrease for faster update
     rpm = 30*1000/(millis() - timeold)*half_revolutions;
     timeold = millis();
     half_revolutions = 0;
     displayRPM();
   }
 }
 void rpm_fun()
 {
   half_revolutions++;
   //Each rotation, this interrupt function is run twice
 }

 void displayRPM()
 {
    // text display tests
  display.clearDisplay();
  display.setRotation(2);
  display.setTextSize(5);
  display.setTextColor(WHITE);
  display.setCursor(0,0);
  display.println(rpm,DEC);

  display.setTextColor(BLACK, WHITE); // 'inverted' text
  display.setCursor(0,40);
  display.setTextSize(2);
 // display.setTextColor(WHITE);
  display.print(" rpm ");

  display.display();


 }

ความคิดเห็น