In the code below, my logic does not change the value of the boolean variable 'recordingstatus'.
The pushbutton wired to PIN4 works fine, changing from 0-5 V when pressed. The associated boolean variable 'buttonstate' changes as expected when the button is pressed.
Any assistance will be much appreciated!
#include <SPI.h>
//#include <SD.h>
#include <Wire.h>
#include "RTClib.h"
#include <SeeedOLED.h>
#define redLEDpin 2 // digital 2
#define greenLEDpin 3 // digital 3
#define pushbuttonpin 4 // digital 4
#define tempPCBpin 1 // analog 1
bool recordingstatus;
bool buttonstate;
void setup(void)
{
Serial.begin(9600);
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,INPUT);
recordingstatus=0; // set recording status to OFF
}
void loop()
{
buttonstate=digitalRead(pushbuttonpin);
if ((buttonstate==true) && (recordingstatus==false)){recordingstatus=true;}
if ((buttonstate==true) && (recordingstatus==true)){recordingstatus=false;}
// red LED indicates not recording
if (recordingstatus==false){digitalWrite(redLEDpin,HIGH);}
//if (recordingstatus==false){digitalWrite(greenLEDpin,LOW);}
//if (recordingstatus==true){digitalWrite(greenLEDpin,HIGH);}
if (recordingstatus==true){digitalWrite(redLEDpin,LOW);}
delay(1000);
Serial.print(buttonstate);
Serial.print(recordingstatus);
analogRead(tempPCBpin);
delay(10);
int tempReading = analogRead(tempPCBpin);
}
Hi guys
Amazingly quick response - thank you!
Its my first day of Arduino coding. I now know not to spend 3 hours trying to debug syntax and logic errors when there are willing helpers like you out there.
I revised the code (as below) and it works!
Cheers for now....
if ((buttonstate==true) && (recordingstatus==true)){recordingstatus=false;}
else if ((buttonstate==true) && (recordingstatus==false)){recordingstatus=true;}
My advice is that, for best code readability, bool variables should be given names that reflect what true means.
bool recording;
bool buttonPressed;
for example.
And rather than
if ((buttonstate==true) && (recordingstatus==false)){recordingstatus=true;}
Write more readable code like
if (buttonPressed and not recording) {
recording=true;
}
because and, or and not are more readable and it is unnecessary to compare a bool variable with true. Also remove unnecessary brackets, which also reduce readability.