It doesn't help you're trying to measure an AC signal with a DC converter, you're never going to get a sensible reading - you first need to convert the signal to DC.
The true average of an AC signal should be zero. But the way you are doing it I think it will be treating all the negative values as zero so your result would be about half the average of the positive samples. As Nigel has told you you should use an active rectifier to convert the AC signal into a DC signal. An alternative would be at add an offset value equal to half the full scale reading of your ADC to your AC input signal. You would then need to use software to convert all readings less than half the ADC full scale to the corresponding positive value. You would also need to subtract half the ADC full scale value fro all the readings greater than half the full scale value.
You can use constexpr to mark the typed variable as a compile-time constant, if you wanted; this also honours variable namespaces/scoping/etc., unlike #define.
You can use constexpr to mark the typed variable as a compile-time constant, if you wanted; this also honours variable namespaces/scoping/etc., unlike #define.
But the OP had it as a global variable. Obviously, the Arduino compiler optimises it to the same code but if you did this on XC8 (without optimisation as most people use it) it will reserve two bytes of memory(RAM) for it. However, I do like this method.
Locally-scoped variables (or class members) with the same name as the global variable are possible. Try that where a #define exists. As an example:
C++:
#ifdef USE_DEFINE
#define dataPin 1 // <-- this will cause issues if 'dataPin' is used elsewhere in code
#else
constexpr int dataPin = 1; // <-- this is fine
#endif
class MyHardware
{
int dataPin;
public:
MyHardware(int dataPin) : dataPin(dataPin) {}
};
Obviously, the Arduino compiler optimises it to the same code but if you did this on XC8 (without optimisation as most people use it) it will reserve two bytes of memory(RAM) for it.
I used to believe that but now think it's just the way it compiles and leaves it to the optimiser to tidy up. I have a friend who wrote a C compiler and that is the method he used.
BTW, I always define constants in upper case and variables in camel case.
So in my case (N.P.I.) I'd have,
Code:
#define DATAPIN 1
or, more probably
#define DATA_PIN 1
And, of course, variables as in your example (camel case).
I also think that's the case. I remember the output of the old hitech picc was better than the current XC8 output; they must've stripped out _ALL_ of the optimisations.
Fair enough; there'll be no name conflicts that way. I'll still avoid preprocessor substitution where possible.
It used to add loads of extra rubbish, presumably deliberately to make it large and slow, as the extra code had no function at all (other than wasting space and cycles) - but it seems rather better now than it used to be.