How to add analogRead () to our own written library

Hello!
I tried to make a library for analog inputs, but it doesn’t work for me.
Can you help me with some advice? Thanks!

Analog.cpp

#include "Analog.h"

AI::AI(byte pin) {
  this->pin = pin;
  init();
}
void AI::init() {
	analogRead(pin);
}

Analog.h

#ifndef Analog_H
#define Analog_H

#include <Arduino.h>
// A N A L O G  I N P U T
class AI {
	private:
	byte pin;
	
	public:
	AI(byte pin);
	
	void init();
};

#endif

Please provide a detailed description of what you mean by "it doesn't work".

I tried this example:

#include <Analog.h>

#define Ana1 0
AI ai1(Ana1);

int val = 0;

void setup() { 
Serial.begin(9600);
}
void loop() {
  val = ai1; // <- Error 

  Serial.println(val);
  Serial.println(' ');
}

Error:
exit status 1
cannot convert ‘AI’ to ‘int’ in assignment

To start with, a function named init() that reads a pin makes no sense

Try this
The .h

#ifndef Analog_H
#define Analog_H

#include <Arduino.h>

class AI
{
  private:
    byte _pin;

  public:
    AI::AI(byte pin);  //constructor
    int read();  //read and return analogue value
};

#endif

The .cpp

#include "Analog.h"

AI::AI(byte pin)
{
  _pin = pin;
}

int AI::read()
{
  return analogRead(_pin);
}

Test sketch

#include "Analog.h"

AI ax(7);

void setup()
{
  Serial.begin(115200);
  while (!Serial);
}

void loop()
{
  Serial.println(ax.read());
  delay(500);
}

Thanks UKHeliBob for the first step!
The library is functional, but the reading code has a problem. It only shows me the maximum value:
1023
1023
1023
...

Post a full example that illustrates the problem

This is the code:

#include "Analog.h"

AI ax(0);

void setup()
{
  Serial.begin(115200);
  while (!Serial);
}

void loop()
{
  Serial.println(ax.read());
  delay(500);
}

And this is the result in the simulator:

Did you use the .h and .cpp files exactly as I posted them ?

And this is the result in the simulator:

I know that my example works with real hardware

What does the emulator show if you print the raw value read from A0 without involving the library ?

I used your library:

And if I use a fixed value, it shows me that variable:

#include "Analog.h"

AI ax(0);

int val = 10;

void setup()
{
  Serial.begin(115200);
  while (!Serial);
}

void loop()
{
  //val = ax.read();
  Serial.println(val);
  delay(500);
}

display:
10
10
10
...

It works. I had to put the NANO module to GND.
Thank you very much UKHeliBob !

I know that you have it fixed, but when you said

And if I use a fixed value, it shows me that variable:

that should be no surprise

What I had in mind was

Serial.println(analogRead(0));

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.