HI All
I am a bit puzzled by the result of my sketch. I am building a class to create sine waves so that I can create different waves and then use them to modulate each other. I got stuckl early in the process though as I am observing a behaviour that I did not expect. If I create one sine wave it works as expected, but if in my sketch I create a second wave, it seems to affect the first one . Look at this simple sketch:
#include "Sinewave.h"
SineWave mainWave(100, 0.05);
SineWave modulatingWave(50, 0.5);
void setup() {
Serial.begin(115200);
}
void loop() {
float main = mainWave.getSineValue();
float modulator = modulatingWave.getSineValue();
Serial.print("main wave: ");
Serial.println(main);
// Serial.print("modulator: ");
// Serial.println(modulator);
}
if I comment out this line:float modulator = modulatingWave.getSineValue();
the putput of this sketch is:
however, if I leave that line in the sketch, the outcome becomes:
even though I am only priting out the first wave (the second one (modulator) is not being printed out).
these are my class files:
#ifndef SINEWAVE_H
#define SINEWAVE_H
#include<Arduino.h>
class SineWave {
private:
int _amplitude = 100; // Amplitude of the sine wave max 255, but offset needs to follow
float _frequency = 0.001; // Frequency of the sine wave - try value bewteewn 0.5 and 0.001
int _offset = 127; // Offset to ensure the sine wave is always positive
float _angle = 0; // Angle in radians
const uint8_t _updateInterval = 20; // Update interval in milliseconds
unsigned long _previousMillis = 0; // Stores the last time the sine value was updated
public:
SineWave(){}
SineWave(int amplitude);
SineWave(int amplitude,float frequency);
SineWave(int amplitude,float frequency, int offset);
float getSineValue();
void setAmplitude(int amplitude);
void setFrequency(float frequency);
void setOffset(int offset);
};
#endif
#include "Sinewave.h"
SineWave::SineWave(int amplitude){
_amplitude = amplitude;
}
SineWave::SineWave(int amplitude,float frequency){
_amplitude = amplitude;
_frequency = frequency;
}
SineWave::SineWave(int amplitude,float frequency, int offset){
_amplitude = amplitude;
_frequency = frequency;
_offset = offset;
}
float SineWave::getSineValue(){
unsigned long currentMillis = millis();
if (currentMillis - _previousMillis >= _updateInterval) {
_previousMillis = currentMillis;
float sineValue = _amplitude * sin(_angle) + _offset;
_angle += _frequency;
if (_angle >= TWO_PI) {
_angle -= TWO_PI;
}
return sineValue;
}
}
void SineWave::setAmplitude(int amplitude){
_amplitude = amplitude;
}
void SineWave::setFrequency(float frequency){
_frequency = frequency;
}
void SineWave::setOffset(int offset){
_offset = offset;
}



