0

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 the setup().

I also tried declaring the variable before the setup() and changing it inside the setup(), but it didn't change when I used it in the loop().

How can I solve this?

8
  • how are we to know that you actually changed it in loop()?
    – jsotola
    Nov 10 '20 at 18:41
  • I didn't change it in loop(), I have to access it there. I want to change it in setup()
    – Vooxe
    Nov 10 '20 at 18:43
  • look at the fade sketch in arduino IDE example sketches
    – jsotola
    Nov 10 '20 at 18:44
  • how are we to know that you actually changed it in setup()?
    – jsotola
    Nov 10 '20 at 18:45
  • I want to use it in loop(): I need the startpressure (declared in setup()) and compare it to the current pressure
    – Vooxe
    Nov 10 '20 at 18:46
0

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();
}
5
  • 1
    I'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
    Nov 10 '20 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
    Nov 10 '20 at 20:07
  • 1
    difference does not need to be static. Nov 10 '20 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
    Nov 10 '20 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
    Nov 10 '20 at 20:26

This site is temporarily in read only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .