Button Push turning on an OLED ESP32 - c++

I am working on getting a DHT22 sensor which displays a reading onto an OLED when a button is pushed. I am using Arduino IDE. Right now I have the sensor working and displaying on the screen, but I am having difficulty getting it to only turn on when the button is pushed. GPIO 13 is currently getting the signal from the sensor, and GPIO 26 is connected to the physical button along with power and ground. All of the code with "//added" is the new code I added in order to get the button to work. Any help is greatly appreciated!
At the top I added:
const int ButtonPin = 26; //added
const int PushButton; //added
I am getting the error:
exit status 1
uninitialized const 'PushButton' [-fpermissive]
In setup function I added:
pinMode(ButtonPin, OUTPUT); //added
pinMode(PushButton, INPUT)://added
And in loop function I added:
int Push_button_state = digitalRead(PushButton); //added
if (Push_button_state == HIGH) //added
float h = dht.readHumidity();
// Read temperature as Celsius
float t = dht.readTemperature();
u8g2.firstPage();
do {
draw();
} while ( u8g2.nextPage() );
delay(1000);
}
else { //added

I think you are not clear about what you want to achieve. First of all, you only need ButtonPin variable to work with the button. As your button is connected to GPIO 26, you must declare this pin as an INPUT.
Later, you shoould use the digitalWrite function to get the state of the pin. Depending on how you connect your button, you will receive a '0' or a '1' when it is pressed. Anyways, I have been using a really comfortable library to work with buttons on Arduino, check it here. I hope this could help

Related

SAMD21 doesn't wake up after deep sleep

I'am working on a personnal board build with an atsamd21e18a. I'am actually working on sleep mode. I make a function to put samd21 in sleep mode like that. I use RTCZero library.
So in my setup function I've something like this
RTCZero rtc;
void setup(){
// Set the XOSC32K to run in standby
SYSCTRL->XOSC32K.bit.RUNSTDBY = 1;
rtc.begin();
.... other line code ....
attachInterrupt(digitalPinToInterrupt(PIN_USER_BUTTON), wakeUpButtonUser, CHANGE);
...other line....
}
So in my setup I intialise rtc and I attach an interrupt in my user button. This button is used to power on or power off my board.
My function goTosleep() :
SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk;
__DSB();
__WFI();
In my function wakeUpButtonUser I have a simple if/else statement. If the user pressed the button more than 3 seconds samd21 go to sleep with goToSleep() function, else if it's less than 3 seconds I want wake up the board and light up my led but it's doesn't work.
Here my wakeUpButtonUser function, user_button is object create from C++ for my button.
void wakeUpButtonUser(){
if (userButton.isPressed())
{
userButton.setTimeStartPressed(millis());
PRINT_DEBUG_LN("Pressed");
}
else
{
userButton.setTimeEndPressed(millis());
PRINT_DEBUG_LN("Released");
uint32_t time_pressed = userButton.getTimePressed();
if (time_pressed >= temps_on && time_pressed < temps_off)
{
PRINT_DEBUG_LN("ON");
//here I have code to light up a led
}
else
{
PRINT_DEBUG_LN("STOP");
goSleepMode();
}
}
}
This fuction works because if I comment the line goToSleep(), I can read on my serial ON or OFF depending the time I pressed my button and the led works also because I can light up led before going to sleep. But when my board go to sleep, she's never wake up I don't understand why, I missed something?

Arduino, Run Time Code Error in Debouncing Voltage Time Delay Code

I am Ansh Goel, I was learning Arduino from Udemy. I am beginner to this field. I was creating a code for Debouncing the button to solve the issues of bouncing voltage. But there is error in the code. There is no Compile time error but it is run time error.
I also tried to check the code using the Serial.print() to find the where the error is, then I found that the error is in the second nested if condition. I have also mention where there is the error in the code for ease. There I am not able to get the Serial.print("A") function too to the Serial Monitor.
My main motive is to run the code so that I am able to stop bouncing voltages when a button is pressed using some delay.
It is from line 41
This is the code I used to debounce the button
const int btn_pin = 2;
const int debounce_delay = 50; //ms
// We need to remember the previous button state between loops
int btn_prev = HIGH;
int btn_state = HIGH;
unsigned long last_debounce_time = 0;
// Counter
int counter = 0;
void setup() {
Serial.begin(9600);
// Set up pins
pinMode(btn_pin, INPUT_PULLUP);
pinMode(13, OUTPUT);
}
void loop() {
int btn_read;
// Read current button state
btn_read = digitalRead(btn_pin);
//Remember when the button change state
// If the button was previously HIGH and now LOW, it's been pressed
if ( (btn_prev == HIGH) && (btn_read == LOW )) {
//Store the time it took to take the action for button press
last_debounce_time = millis();
}
//Wait before changing the state of the button
// IN THIS CONDITION THERE IS ERROR SOMEWHERE I AM NOT GETTING IT
if(millis() > (last_debounce_time + debounce_delay)){
if(btn_read != btn_state) {
Serial.println("A");
// Then store the button change value to the global variable
btn_state = btn_read;
if(btn_state == LOW) {
// Increment and print counter
counter++;
Serial.println(counter);
digitalWrite(13,HIGH);
delay(500);
digitalWrite(13,LOW);
delay(500);
}
}
}
// Remember the previous button state for the next loop iteration
btn_prev = btn_state;
}
For testing purposes, this is the circuit design on TinkerCad, that you can check online.
TinkerCad Circuit Design
Please Help me solve the issue, it will be a great help from your side for me.
There are several locations where your code could malfunction:
you're not looping properly for loop
your logic doesn't work
digitalRead doesn't work
print doesn't work
first, remove the debounce check and see if this works:
//if(millis() > (last_debounce_time + debounce_delay)){
to check all other issues, add the following right before the remaining if:
delay so you don't get endless data
print millis, last_debounce_time, debounce_delay and btn_read
end line
then run and press the button. The output will let you know what's the issue

Why doesn't my arduino button work on ports other than 0 and 1?

I have a button that turns on a LED but it only works when I assign the button the port 0 and 1. If I try port 2 it doesn't work. Therefore I am only able to use two buttons. On the board 0 and 1 seems to be special compared to the other ones. How do I get around that to be able to use the other ports?
Here is a simple program that models what I think you were describing.
In your code, if you want to turn on an LED when you press a button:
You need to make sure that the LED pin is set to output.
The button pin needs to be set to input.
sample program:
#define LED 13
#define BUTTON 5
void setup()
{
pinMode(LED, OUTPUT);
pinMode(BUTTON, INPUT);
}
void loop()
{
if ( digitalRead(BUTTON) )
{
digitalWrite(LED, HIGH);
}
else
{
digitalWrite(LED, LOW);
}
}
Regarding the circuit,
you need to have a current limiting resistor in series with the LED.
make sure the LED is facing the right way.
The button needs to be connected from +5V to the button pin.
You need to have a pulldown resistor between the button pin and ground.

Arduino Uno to Particle Photon - Converting Code

Please bear with me. I am an amateur programmer at Arduino, and have never used Particle photon before.
I used an Arduino Uno and wrote the attached code that detects heart beat and temperature using the Grove Ear clip heart beat sensor and the Grove Temperature sensor and then prints them in the console every 20 seconds. Previously, this code was written to show in an Grove OLED screen but later simplified it back to using it without the OLED screen.
I am now looking into using the same application and function using the same sensor on a Particle Photon (as it is smaller and has WiFi capability). I have never previously used this technology before but I saw online that it, more or less, uses the same code application. I have been through the sample codes for this online available on its website but I have no idea how to convert my code for the Arduino into code for the photon (Photon console compiles the code without any error but does not show any sensor data). Can someone either point me to the right direction/ appropriate online resources / help me change this code here to make it work on the Photon? (I just added the Particle.publish() wherever I was using Arduino's Serial.println() but it still doesn't print anything).
The result in the console shows:
Please be ready
This will now begin
then it prints number 1 to 20 every second followed by sensor readings.
Again sorry for the inconvenience and thank you for your help.
I used direct codes from the documentation blog of the sensors (bottom of the page of the linked page):
Grove heart bear sensor
Grove Temperature sensor
#define LED 4//indicator, Grove - LED is connected with D4 of Arduino
boolean led_state = LOW;//state of LED, each time an external interrupt
//will change the state of LED
float tempa;
int tempPin = 0;
unsigned char counter;
unsigned long temp[21];
unsigned long sub;
bool data_effect=true;
unsigned int heart_rate;//the measurement result of heart rate
const int max_heartpluse_duty = 2000;//you can change it follow your system's request.
//2000 meams 2 seconds. System return error
//if the duty overtrip 2 second.
void setup()
{
pinMode(LED, OUTPUT);
Serial.begin(9600);
while (!Serial){
;
}
Serial.println("Please be ready");
delay(5000);
arrayInit();
Serial.println("This will now begin.");
attachInterrupt(0, interrupt, RISING);//set interrupt 0,digital port 2
}
void loop()
{
digitalWrite(LED, led_state);//Update the state of the indicator
}
/*Function: calculate the heart rate*/
void sum()
{
if(data_effect)
{
heart_rate=1200000/(temp[20]-temp[0]);//60*20*1000/20_total_time
Serial.print("Heart_rate_is:\t");
Serial.println(heart_rate);
tempa = analogRead(tempPin);
tempa = tempa * 0.11;
Serial.print("Body Temperature = ");
Serial.print(tempa);
Serial.print("*C");
Serial.println();
delay(1000);
}
data_effect=1;//sign bit
}
/*Function: Interrupt service routine.Get the sigal from the external interrupt*/
void interrupt()
{
temp[counter]=millis();
Serial.println(counter,DEC);
switch(counter)
{
case 0:
sub=temp[counter]-temp[20];
break;
default:
sub=temp[counter]-temp[counter-1];
break;
}
if(sub>max_heartpluse_duty)//set 2 seconds as max heart pluse duty
{
data_effect=0;//sign bit
counter=0;
Serial.println("measurement error,test will restart!" );
arrayInit();
}
else if (counter==20&&data_effect)
{
counter=0;
sum();
}
else if(counter!=20&&data_effect)
{
counter++;
}
else
{
counter=0;
data_effect=1;
}
}
/*Function: Initialization for the array(temp)*/
void arrayInit()
{
for(unsigned char i=0;i < 20;i ++)
{
temp[i]=0;
}
temp[20]=millis();
}

Arduino not reading float level switch signal

Hey I am trying to set up a project at the moment, I have a float level switch connected to pin 2 of my Arduino board, the other end is connected to the 5v in on the arduino.
I want to have the software display a message when the switch goes high but at the moment it goes straight to the message and I know that the switch is not set high as I have it in my hand.
In future it will send a text message when the signal goes high, being used for flood monitoring using a float level switch.
#include "SIM900.h"
#include <SoftwareSerial.h>
#include "sms.h"
SMSGSM sms;
//To change pins for Software Serial, use the two lines in GSM.cpp.
int numdata;
boolean started=false;
char smsbuffer[160];
char n[20];
int closed=0;//Sets initial signal to 0
const int switchPin = 2;
int switchState = 0; // current state of the button
int lastswitchState = 0; // previous state of the button
void setup()
{
//Serial connection.
Serial.begin(9600);
Serial.println("GSM Shield for Flood Early Warning System \n");
pinMode(switchPin, INPUT);
//Start configuration of shield with baudrate.
//For http uses is recommended to use 4800 or slower.
}
void loop() {
closed=digitalRead(switchPin);
// compare the buttonState to its previous state
if (switchState != lastswitchState) {
// if the state has changed, increment the counter
if (switchState == HIGH) {
// if the current state is HIGH then the button
// wend from off to on:
Serial.println("on");
} else {
// if the current state is LOW then the button
// wend from on to off:
Serial.println("off");
}
// Delay a little bit to avoid bouncing
delay(50);
}
// save the current state as the last state,
//for next time through the loop
lastswitchState = switchState;
if (closed == HIGH) {
Serial.println ("Switch signal received");
if (gsm.begin(2400)){
Serial.println("\n status=READY");
started=true;
}
else Serial.println("\n status=IDLE");
if(started){
//Enable this two lines if you want to send an SMS.
if (sms.SendSMS("0871234567", "Arduino SMS"))//Number you wish to text and the message to be sent
Serial.println("\nSMS sent OK");//Alert for Serial monitor once sms sent
}
}
}
You should connect your input pin to GND via a 10KOhm resistor. See https://www.arduino.cc/en/Tutorial/DigitalPins :
"This also means however, that pins configured as pinMode(pin, INPUT) with nothing connected to them, ... will report seemingly random changes in pin state, picking up electrical noise from the environment, or capacitively coupling the state of a nearby pin. ".
And https://www.arduino.cc/en/Reference/DigitalRead :
If the pin isn't connected to anything, digitalRead() can return either HIGH or LOW (and this can change randomly).
In other words, when your switch is open, the input pin is not in a defined state (either on or off). By adding a pulldown resistor (a 10 KOhm resistor between your input pin and GND, the resistor "pulls down" (=toward the ground) your pin, unless the switch is closed, in which case the connection to +5V prevails (because it is a direct connection, without a resistor).