Alexandre Michaud
Alexandre Michaud

Reputation: 241

analogRead return 0 in a library

i want to create a library for a project, and i have to do a analogRead at one moment. I created a library for this, and it compile without any errors. But when i want to call this function, it return me 0, but it is working fine in the .ino file..

Here are my files :

the .ino file

#include <Filoguidage.h>
Filoguidage filoguidage;
int pin = A11;

void setup() {
  Serial.begin(115200);
  pinMode(pin,INPUT);
  filoguidage.init(pin,10,10);
}
void loop() {
  int test = filoguidage.getPosition();
  Serial.println(test);
}

The .h of my library :

#ifndef Filoguidage_h
#define Filoguidage_h
#include "Energia.h"
class Filoguidage
{
    public:
        void init(int PinCapteur,int valeurCentrale, int interval);
        int getPosition();

    private:
        int _PinCapteur;

};
#endif

And finally the .cpp :

#include "Energia.h"
#include "Filoguidage.h"


void Filoguidage::init(int PinCapteur,int valeurCentrale,int interval){
  int _PinCapteur = PinCapteur;
    pinMode(_PinCapteur, INPUT);
}
int Filoguidage::getPosition(){
  return analogRead( _PinCapteur );
}

I think thats because pinMode and analogRead are not recognized, but i don't know how to solve it. If somebody can help me i would be very happy, thanks

Upvotes: 0

Views: 217

Answers (1)

0x400921FB54442D18
0x400921FB54442D18

Reputation: 735

In Filoguidage::init you are redeclaring the _PinCapteur class member as a local variable, so when you set a value to it, only the local one in the function will be set and the actual class member that you want to set will remain unaffected.

To fix this, change int _PinCapteur = PinCapteur; to _PinCapteur = PinCapteur; in Filoguidage::init.

Upvotes: 2

Related Questions