Wednesday, 13 June 2018

Master clock 2 Millis() - OLED display

My previous attempt at making a master clock used the delay function.

The problem with delay() is that everything stops until the delay time is over.
Not useful for multi tasking. 



 
This second attempt uses the millis function.
It turns on and off a light emitting diode (LED) connected to a digital pin,
  without using the delay() function. This means that other code can run at the
  same time without being interrupted by the LED code. 
 
PinWiring to Arduino Uno
Vin5V
GNDGND
SCLA5
SDAA4
 
This uses a combination of a few blog posts
 
The POT is wired thus:
centre (wiper) to A0
Right to GND
Left to 5V
 
The LED
Cathode to gnd via a 220 ohm resistor
Anode to pin 8
 
 
The end result is similar the the delay version, but is more accurate I think.
Hopefully I can also run other bits of code.
 

I got the idea from this post:
 
 

 
The code is here
//&&&&&&&&&&&&&&&&&&&&&&&

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

const int ledPin =  8;// the number of the LED pin

#define MIN_BPM 20      /*write here the min BPM that you want */
 #define MAX_BPM 300     /* write here the max BPM that you want */
 #define POT A0          // the potentiometer connects to analog pin A0

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

// Variables
int bpm;
int ledState = LOW;             // ledState used to set the LED
unsigned long previousMillis = 0;        // will store last time LED was updated

const long interval = 60000;           // interval at which to blink (milliseconds)

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin,ledState);// set initial state of pin 8 LED
 
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // initialize with the I2C addr 0x3C
  display.clearDisplay(); // Clear the buffer.
}

void loop() {

   bpm = map(analogRead(POT), 0, 1023, MIN_BPM, MAX_BPM);  
    display.clearDisplay();
    display.setTextSize(3);
    display.setTextColor(WHITE);
    display.setCursor(0,0);
    display.println(bpm);
    display.setTextSize(2);
    display.setTextColor(WHITE);
    display.println("    BPM");
    display.display();
    
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval/bpm) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

// &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&


 ---------------------------------
-------------------------------------

No comments:

Post a Comment