Objects and Properties

Hello,

I am fairly new to programming an arduino using the IDE and C/C++. Im familiar with javascript, and what im trying to do is have a data object and have it contain sensor values for example the code would be something like this in javascript, an object and then assigning values to it's properties.

Is there anything equivalent in arduino?

var data = {
sensor1,
sensor2,
sensor3
}

while(1){
data.sensor1 = analogRead(1);
data.sensor2 = analogRead(2);
data.sensor3 = analogRead(3);
console.log(data);
wait(1000);
}

How would I do this in Arduino I have tried the following but I am getting errors on the data.property

class data{
public:
float sensor1;
float sensor2;
float sensor3;
}

void setup(){
Serial.begin(9600);
}

void loop(){
data.sensor1 = analogRead(1);
data.sensor2 = analogRead(2);
data.sensor3 = analogRead(3);

Serial.print(data);

delay(1000);
}

Thank You Community!

It looks like you've declared a class but not any instances of that class.
Also, analog reads are integers with a range of 0-1023, not floating points.

Code tested on Uno.

class Data  //class names are capitalized
{
public:
int sensor1;  //per bDeters (analog read returns an int)
int sensor2;
int sensor3;
};  // note semicolon ends declaration

Data data;  // construct an instance of the Data class

void setup(){
Serial.begin(9600);
}

void loop(){
data.sensor1 = analogRead(A1); // it makes it more clear if you use the Ax notation for analog inputs
data.sensor2 = analogRead(A2);
data.sensor3 = analogRead(A3);

Serial.print(" sensor 1 data  ");  //you will need to print the member variables individually
Serial.println(data.sensor1);  // trying to print just data will cause an error

delay(1000);

you can just use an array:

const byte sensor[] = {1, 2, 3};
int data[sizeof(sensor)];

void setup() 
{
  Serial.begin(9600);
}

void loop() 
{
  int j = 0;
  for(auto& i : data)
  {
    Serial.println(i = analogRead(sensor[j]));
    j++;
  }
  delay(1000);
}

Or use a struct. Lots of ways to skin that cat.

And some indentation really makes it a lot more readable.

And just to hold data a simple array will do. You can make it into a class but then it would make sense to include methods to do all the stuff with it. Like readSensor() or something.

class data{
public:
float sensor1;
float sensor2;
float sensor3;
}

A class, like its idiot sibling the struct, needs a semicolon after the closing brace.

Edit: oops, just noticed groundFungus' comment.

A class, like its idiot sibling the struct, needs a semicolon after the closing brace.

In C++, the difference between a class and a struct is the default scope of its members. Hardly makes a struct an idiot sibling.

That's not that weird is it? Just like other type definitions it has the possibility to define and declare in one go :slight_smile: