I wanted to write a library representing a sensor to later on have an array of sensors. I generated a file MoistureSensor.h:
#ifndef MoistureSensor_h
#define MoistureSensor_h
#include <Arduino.h>
class MoistureSensor {
private:
uint8_t sensPin;
int sensValue;
int sensId;
public:
MoistureSensor(uint8_t pin,int id);
int getValue();
int getId();
};
#endif
and MoistureSensor.cpp:
// MoistureSensor.cpp
#include "MoistureSensor.h"
MoistureSensor::MoistureSensor(uint8_t pin, int id) {
sensPin = pin;
sensId = id;
}
int MoistureSensor::getValue() {
sensValue = analogRead(sensPin);
return sensValue;
}
int MoistureSensor::getId() {
return sensId;
}
this is the main sketch running on a Arduino Mega:
#include "MoistureSensor.h"
MoistureSensor sens1("A0", 1);
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println("Value from analogread:");
Serial.println(analogRead(A1));
Serial.println("Value from library:");
Serial.println(sens1.getValue());
Serial.println("End");
delay(1000);
}
So when I run this the serial monitor shows:
Value from analogread:
600
Value from library:
496
End
Why doesn't this print the same value?
Does the .cpp file interpret the data from analogRead()
different than the sketch?
Also both values where moving up and down depending on the response of the sensor.
Thanks in advance.
2 Answers 2
Trying to compile your sketch, I get the following compiler warning:
warning: invalid conversion from 'const char*' to 'uint8_t {aka unsigned char}'
MoistureSensor sens1("A0", 1);
^
note: initializing argument 1 of 'MoistureSensor::MoistureSensor(uint8_t, int)'
This means that, whereas the MoistureSensor()
constructor expected its
first argument to be of type uint8_t
, you provided a const char*
instead. Indeed, a string literal like "A0"
decays to a const char*
pointer when you pass it as a function argument.
The fix is to pass the actual pin number to your constructor:
MoistureSensor sens1(A0, 1);
But then, there is a second issue. In your test sketch, you have your
MoistureSensor
object read A0
, whereas the direct analogRead()
reads pin A1
. If you want to get the same value, you should read the
same pin.
Side note: the change from uint8_t
to byte
has absolutely
nothing to do with your issue. These two types are synonyms.
I found a solution:
changing the parameter of the constructor
MoistureSensor::MoistureSensor(uint8_t pin, int id, int rawMax, int rawMin)`` from
uint8_t to
bytesolved this issue for me. I also changed the parameterization to
MoistureSensor sens1(1, 1);`
-
2there is no difference between byte and uint8_. it just a different name for the same thing.2023年06月18日 14:48:51 +00:00Commented Jun 18, 2023 at 14:48
MoistureSensor sens1(A0, 1);
, notMoistureSensor sens1("A0", 1);
. we don't writeanalogRead("A0")