working of define and integer

Hello i have question about working of this 2 things. I found a code by Andrea Toscano.

#define LED_PIN 10
#define SERIAL_BAUD 115200
#define PERIOD 2000
#define OMEGA 2*PI/PERIOD
#define PHASE 0
#define OFFSET 128
#define AMPLITUDE 127
unsigned long timer = 0;

void setup() {
Serial.begin(SERIAL_BAUD);
}
void loop() {
timer = millis();
int ledValue = ledValue = OFFSET + AMPLITUDE*(cos(OMEGA*timer)+PHASE);
analogWrite(LED_PIN, checkValue(ledValue));
}
int checkValue(int val) {
if (val > 255)
val = 255;
else if(val < 0)
val = 0;
return val;
}

So,if i delete some of those define syntax (not all but only that written below)and replace it with
const int OFFSET = 127;
const int AMPLITUDE = 128;
const int PERIOD = 2000;
const int OMEGA = (2*PI)/PERIOD;

than the program doesnt work properly.Led isnt blinking but its only turned on.
Please what does make that mess?

Please what does make that mess?

It means that you need to post the code you are actually running. Do NOT expect us to guess what you changed.

i didnt changed anything else just deleted

#define PERIOD 2000
#define OMEGA 2*PI/PERIOD
#define OFFSET 128
#define AMPLITUDE 127

and replaced it with

const int OFFSET = 127;
int AMPLITUDE = 128;
const int PERIOD = 2000;
const int OMEGA = (2*PI)/PERIOD;

and i meant fading not blinking in post above sorry :slight_smile:

Why did you change the values of AMPLITUDE and OFFSET?

What IS the value in OMEGA now that you have forced it to have a type? Is int the proper type?

robot_chobot:
i didnt changed anything else just deleted

#define PERIOD 2000
#define OMEGA 2*PI/PERIOD
#define OFFSET 128
#define AMPLITUDE 127

and replaced it with

const int OFFSET = 127;
int AMPLITUDE = 128;
const int PERIOD = 2000;
const int OMEGA = (2*PI)/PERIOD;

and i meant fading not blinking in post above sorry :slight_smile:

I call BS.
The code won't even compile with the changes you said you made.

You made OMEGA a const int then try to change it with your calculation. Even if that did work it should probably be a float not an int.

You made OMEGA a const int then try to change it with your calculation.

The value is resolvable at compile time, so the calculation is OK.

The type should probably not be int.

I stand corrected. Learn something new every day.

Hello

I noticed that (with arduino uno) the sketch with #define size is 3478 bytes , the one with constants only 2066.

I disassembled the two files.

In the second there is no cosinus calculous at all.

I can't explain it.

Regards,
bidouilleelec

OFFSET, PERIOD, PHASE and OMEGA are all integer constants. OMEGA is 2PI/2000 and as an integer is 0.
Zero times timer (anything) will always be zero so cos(OMEGAtimer)+PHASE will always be 1. Nothing in
int ledValue = ledValue = OFFSET + AMPLITUDE
(cos(OMEGA*timer)+PHASE);
will ever change so it’s calculated once at compile and replace with a constant. No further calculations necessary, optimized out.

That makes sense