I want to change or declare a constant in the setup()
and then, I want to access it in the loop()
.
I have searched a lot, but the only questions I found could be solved by declaring the constant in the beginning of the program. That doesn't work for me because I am using the Adafruit BMP388 and I can't use the pressure before setup()
.
I also tried declaring the variable before setup()
and changing it inside setup()
, but it didn't change when I used it in loop()
.
How can I solve this?
1 Answer 1
You are not going to get good answers without showing your code, but maybe this is a good guess of what you want:
why not try something roughly like this (untested and incomplete)?
Adafruit_BMP3XX bmp;
float startPressure;
float difference;
void setup() {
bmp.begin_I2C();
startPressure = bmp.readPressure();
}
void loop() {
difference = startPressure - bmp.readPressure();
}
Or, better:
Adafruit_BMP3XX bmp;
void setup() {
bmp.begin_I2C();
}
void loop() {
static const float startPressure = bmp.readPressure();
static float difference;
difference = startPressure - bmp.readPressure();
}
-
1I'm not entirely sure this is the direction he's going in. But if he is, you could move float startPressure; into the loop(), perform startPressure = bmp.readPressure(); as part of its initialization, and make it static and const. As in: static const float startPressure = bmp.readPressure(); This would behave as what you have but would limit startPressure to the only scope it's used in.timemage– timemage2020年11月10日 19:54:51 +00:00Commented Nov 10, 2020 at 19:54
-
@timemage: True, and better, but it would require an explanation of "static", and I don't feel up to it 8-). I will add it though.ocrdu– ocrdu2020年11月10日 20:07:52 +00:00Commented Nov 10, 2020 at 20:07
-
1
difference
does not need to bestatic
.Edgar Bonet– Edgar Bonet2020年11月10日 20:21:49 +00:00Commented Nov 10, 2020 at 20:21 -
Yeah, and it technically isn't "constant" in C++ terms. But it seems to be in the spirit of the question so far as I understand the question.timemage– timemage2020年11月10日 20:23:23 +00:00Commented Nov 10, 2020 at 20:23
-
@Edgar-Bonet: No, doesn't have to be in the example, but who knows if he wants it to remain the same over several loops in his code.ocrdu– ocrdu2020年11月10日 20:26:38 +00:00Commented Nov 10, 2020 at 20:26
fade
sketch in arduino IDE example sketches