Hello, I’m having a confusing time with functions. I have 2 functions that are declared after the void loop, but one of them doesn’t get declared in the void loop function for some reason. Here is the code:
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define triggerPin 10
#define echoPin 11
#define buttonPin 2
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT);
//---------------------------------------------------------------------------------
//variables
bool buttonState = HIGH;
bool ledState = LOW;
void setup() {
Serial.begin(9600);
pinMode (triggerPin, OUTPUT);
pinMode (echoPin, INPUT);
pinMode (buttonPin, INPUT);
digitalWrite(buttonPin, HIGH);
// SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3D for 128x64
Serial.println(F("SSD1306 allocation failed"));
for (;;); // Don't proceed, loop forever
}
display.setTextColor(WHITE);
}
//---------------------------------------------------------------------------------
void loop() {
printMsg("Press Button to Measure", 1);
while (buttonState == HIGH) {
buttonState = digitalRead(buttonPin);
}
buttonState = HIGH;
Serial.println(buttonState);
display.setCursor(0, 0);
display.println(calcDist());
display.display();
}
//-----------------------------------------------------------------------------------
void printMsg(String text, int fontSize = 7) {
display.setTextSize(fontSize);
display.setCursor(0, 0);
display.println(text);
display.display();
}
float calcDist() {
float bucket = 0, avg = 0, time, distance;
for (int j = 1; j <= 50; j++) {
digitalWrite (triggerPin, HIGH);
delayMicroseconds (10);
digitalWrite (triggerPin, LOW);
time = pulseIn (echoPin, HIGH);
bucket += (time * 0.034) / 2;
}
avg = bucket / 50;
return avg;
}
The function I’m talking about is void printMsg(). calcDist() works fine, but for some reason, printMsg doesnt get declared and I get an error. It’s probably something obvious and I’m being dumb, so feel free to explain this to me and/or refer me to some sources about this.
Thanks.
EDIT: Got it fixed by declaring a prototype, but I’m still wondering why didn’t Arduino do it for me by itself. Any ideas?