Help on Enum code (array involved)

Hi community, I am running into some difficulties here.

This code is adapted from one shared by J-M-L,

uint8_t numOfFloor = {12};                                // Input number of floors

enum dataType {bike1 , bike2, bike3, bike4, maxItems};    // Declare item1, item2, item3, etc.

float maxAlt = 36;

struct measure_t {
  dataType type;
  float value;
};

struct measure_t measures[] = {
  {bike1, 10.0},
  {bike2, 22.0},
  {bike2, 22.5},
  {bike3, 31.0},
  {bike3, 33.0},
  {bike2, 21.0},
  {bike1, 11.2},
  {bike1, 10.7},
};

const uint16_t nbMeasures = sizeof(measures) / sizeof(measures[0]);

float  measureSum[maxItems]  = {0L};
float  measureCount[maxItems] = {0};

void setup() {
  Serial.begin(57600);

  for (uint16_t i = 0; i < nbMeasures; i++) {
    measureSum[measures[i].type] += measures[i].value;
    measureCount[measures[i].type]++;
  }

  for (byte i = 0; i < maxItems; i++) {        
    if (measureCount[i] != 0) {

float avgAltPerItem = {measureSum[i] / measureCount[i]};
float estFloorPerItem = {(avgAltPerItem / maxAlt)*numOfFloor};

      Serial.print(F("Average Alt for Item"));
      Serial.print(i+1);
      Serial.print(F(" = "));
      Serial.println(avgAltPerItem);
      Serial.print(F("Estimated floor for Item"));
      Serial.print(i+1);
      Serial.print(F(" is "));
      Serial.println(estFloorPerItem);
      Serial.println();
    } else {
      Serial.print(F("No measure exists for Item"));
      Serial.println(i+1);
      Serial.println();
    }
  }
  Serial.print(F("Total height of building is "));
  Serial.print(maxAlt);
  Serial.println(F(" meters."));
}



void loop() {}

And I have tried to change it to become a array for my separate microcontroller to write into, which looks like this:

uint8_t numOfFloor = {12};      // Input number of floors
// Declare item1, item2, item3, etc. (Do Not Remove "maxItems")
enum dataType : char {bike1 , bike2, bike3, bike4, maxItems};

// Please fill in information for above
// Code under this line is automated

String dataIn;                  // String to temporarily store data from UART
int cueToOutput = 8;            // Pin 8 indicates drone has landed
int altInput = 4;               // Pin 4 used for Altitude input from pixhawk
float altIn;                    // altIn stores current altitude of pixhawk
int sonarInput = 5;             // Pin 5 activated when signal received from sonar
int rows = 0;                   // Variables for rows/columns of data array
float maxAlt = 36;                   // maxAlt stores height of building


struct measure_t 
{
    dataType type;
    int value;
};

measure_t measures[10][2];

void setup() 
{
  pinMode(cueToOutput, INPUT_PULLUP);
  pinMode(altInput, INPUT);
  pinMode(sonarInput, INPUT_PULLUP);
  Serial.begin(57600);
  Serial.println("Start");
}

void loop() 
{ 
/*  measure_t measures[] = {
  {bike1, 10},
  {bike2, 22},
  {bike2, 22.5},
  {bike3, 31},
  {bike3, 33},
  {bike2, 21},
  {bike1, 11.2},
  {bike1, 10.7},
};
*/
  altIn = analogRead(altInput);

  while (Serial.available())
  {  
    char UART;
    UART = Serial.read();
    dataIn += UART;

    //Process message only when new line character is received
    if (UART == '\n')
    {
//      Serial.print(dataIn);
      rows ++;
      measures[rows][1] = dataIn;
      measures[rows][2] = altIn;
      
      dataIn = "";            // Clear received buffer
    }
    
  }

  if (digitalRead(sonarInput) == 0)
  {
    maxAlt = altIn;
  }

  if (digitalRead(cueToOutput) == 0)
  {
  const uint16_t nbMeasures = sizeof(measures) / sizeof(measures[0]);

  float  measureSum[maxItems]  = {0L};
  float  measureCount[maxItems] = {0};  

  for (uint16_t i = 0; i < nbMeasures; i++) 
  {
    measureSum[measures[i][1].value] += measures[i].value;
    measureCount[measures[i][1].value]++;
  }

  for (byte i = 0; i < maxItems; i++) 
  {        
    if (measureCount[i] != 0) 
    {

      float avgAltPerItem = {measureSum[i] / measureCount[i]};
      float estFloorPerItem = {(avgAltPerItem / maxAlt)*numOfFloor};

      Serial.print(F("Average Alt for Item"));
      Serial.print(i+1);
      Serial.print(F(" = "));
      Serial.println(avgAltPerItem);
      Serial.print(F("Estimated floor for Item"));
      Serial.print(i+1);
      Serial.print(F(" is "));
      Serial.println(estFloorPerItem);
      Serial.println();
    } 
    else 
    {
      Serial.print(F("No measure exists for Item"));
      Serial.println(i+1);
      Serial.println();
    }
  }
  Serial.print(F("Total height of building is "));
  Serial.print(maxAlt);
  Serial.println(F(" meters."));

    while(1){}
}
}

I have another portion (not added here) which is able to get altitude data to input into this array.

However, I am not able to get any values like the first code.
The response I received is:

Average Alt for Item1 = 0.00
Estimated floor for Item1 is 0.00

No measure exists for Item2

No measure exists for Item3

Total height of building is 36 meters.

I think my array should be the problem, but I searched a lot and am really lost already.. Please help, thank you!

what is your code supposed to even do?

you've got some strange syntax:

float avgAltPerItem = {measureSum[i] / measureCount[i]};

The original code (first one right at the top), will give me the average altitude for each bike. That one uses a pre-defined data set.

However, I progressed to create a 2d array (2nd code) which in column 1, stores the bike number received from my radio-microcontroller. And column 2 stores the altitude received from my drone.
Then it is unable to provide me the average altitude for each bike.
This is the problem I am facing

AdrianCFL:
Then it is unable to provide me the average altitude for each bike.

flying bikes?

your confusing variable naming scheme is throwing me off.

I guess you have some number (is it 8?) of different types of bikes?

I cannot imagine what the height of a bike has to do with the height of a building.

XD

The bikes are actually placed on random floors within an apartment building. That’s why the variables.

Each bike has a radio attached, which will pulse back its serial number once the radio on the drone activates it by sending a certain phrase.

Then the radio will UART this serial number to the arduino board, and then this array will be filled in accordingly.

I like flying bikes better.

It seems to me that you've created a 2D array of a struct. What error messages are you getting? I try to compile it and can't get past your scoped data type. The problem certainly seems to center on the enum.

Each bike has a radio attached, which will pulse back its serial number once the radio on the drone activates it by sending a certain phrase.

Then the radio will UART this serial number to the arduino board, and then this array will be filled in accordingly.

Can you clarify this?
what is the format of the data transmitted to the central element?

Hi all, sorry for the late reply.

This is my data set, and the result I got. The numbers are off, doesn't make sense. I tested 3 times with different altitude readings but the results returned are exactly the same. I'm not sure if the problem is with the array storage, the enumeration, or the calculation after this line: if (digitalRead(cueToOutput) == 0).

Code is attached below: (I have omitted the protocols to retrieve altitude. But altitude part is working)

uint8_t numOfFloor = {10};      // Input number of floors
// Declare item1, item2, item3, etc. (Do Not Remove "maxItems")
enum dataType {bikeObike1 , bikeObike2, bikeObike3, maxItems};

// Please fill in information for above

#include <mavlink.h>


// Integration variables
String dataIn;                  // String to temporarily store data from UART
int cueToOutput = 8;            // Pin 8 indicates drone has landed
//int altInput = 4;               // Pin 4 used for Altitude input from pixhawk
float altIn;                    // altIn stores current altitude of pixhawk
int sonarInput = 5;             // Pin 5 activated when signal received from sonar
int rows = 0;                   // Variables for rows/columns of data array
int columns = 2;
float maxAlt = 2;                   // maxAlt stores height of building
float altPixhawk;

struct measure_t 
{
    String serialNum;
    int value;
};
measure_t measures[100][2];

void setup() 
{
  // Pin Config
  pinMode(cueToOutput, INPUT_PULLUP);
//  pinMode(altInput, INPUT);
  pinMode(sonarInput, INPUT_PULLUP);
  
  
  Serial.begin(57600);
  Serial2.begin(57600);
  Serial3.begin(57600);
  Serial.println("Start");
}

void loop() 
{


   altIn = altPixhawk;                               // altPixhawk is a working variable for altitude from Pixhawk

    while (Serial2.available())
  {  
    char UART;
    UART = Serial2.read();
    dataIn += UART;

    //Process message only when new line character is received
    if (UART == '\n')
    {
      
      measures[rows][0].serialNum = dataIn;
      measures[rows][1].value = altIn;
      rows++;
//      measures[rows] = {dataIn, altIn};

      Serial.print(dataIn);
      Serial.println(altIn);
      
      dataIn = "";            // Clear received buffer

//      Serial.println(measures[rows][0]);
    }
}

  if (digitalRead(sonarInput) == 0)
  {
    maxAlt = altIn;
  }

  if (digitalRead(cueToOutput) == 0)
  {
  const uint16_t nbMeasures = sizeof(measures) / sizeof(measures[0]); // Determine number of elements in array

  float  measureSum[maxItems]  = {0L};
  float  measureCount[maxItems] = {0};  

  for (uint16_t i = 0; i < nbMeasures; i++) 
  {
    measureSum[measures[i][1].value] += measures[i][1].value;
    measureCount[measures[i][1].value]++;
//    measureSum[measures[i].value] += measures[i].value;
//    measureCount[measures[i].value]++;
  }

  for (byte i = 0; i < maxItems; i++) 
  {        
    if (measureCount[i] != 0) 
    {

      float avgAltPerItem = {measureSum[i] / measureCount[i]};
      float estFloorPerItem = {(avgAltPerItem / maxAlt)*numOfFloor};

      Serial.print(F("Average Alt for Item"));
      Serial.print(i+1);
      Serial.print(F(" = "));
      Serial.println(avgAltPerItem);
      Serial.print(F("Estimated floor for Item"));
      Serial.print(i+1);
      Serial.print(F(" is "));
      Serial.println(estFloorPerItem);
      Serial.println();
    } 
    else 
    {
      Serial.print(F("No measure exists for Item"));
      Serial.println(i+1);
      Serial.println();
    }
  }
  Serial.print(F("Total height of building is "));
  Serial.print(maxAlt);
  Serial.println(F(" meters."));

  {
/* int i;
    for (i=0; i<rows; i++)
    { Serial.print(measures[i][0]);
      Serial.print(measures[i][1]);
    }
*/  
  }

    while(1){}
}
}

So you seem to have a steady flow of input in the form of a bikeObike ID and a value. then it's easy to accumulate (if you know the max number of bikeObike)

I made a small program that reads the Serial monitor (set at 115200 and sends JUST NewLine for line validation)

the program awaits input as a succession of space (or \n) separated pairs in the following form

bikeObike[color=blue]nn[/color] [color=blue]x.y[/color]

where [color=blue]nn[/color] is the ID of your bike and [color=blue]x.y[/color] the value as a floating point

The program handles at max maxBikes IDs, (from 0 to maxBikes-1)

The program also recognizes if you type reset in the console and will empty the existing data set

Every time you enter successfully a new pair of data, you'll see the average going through the console.

to compute the average I just accumulate the actual values and number of values received for a given ID

so if I enter

[color=blue]bikeObike0 10
bikeObike1 11
bikeObike2 12
bikeObike3 13
bikeObike4 14[/color]

the Serial console says

[sub][color=purple]bikeObike0 No measure
bikeObike1 No measure
bikeObike2 No measure
bikeObike3 No measure
bikeObike4 No measure
------------------------------------------------------
bikeObike0 average = 10.000000 (count = 1)
bikeObike1 No measure
bikeObike2 No measure
bikeObike3 No measure
bikeObike4 No measure
------------------------------------------------------
bikeObike0 average = 10.000000 (count = 1)
bikeObike1 average = 11.000000 (count = 1)
bikeObike2 No measure
bikeObike3 No measure
bikeObike4 No measure
------------------------------------------------------
bikeObike0 average = 10.000000 (count = 1)
bikeObike1 average = 11.000000 (count = 1)
bikeObike2 average = 12.000000 (count = 1)
bikeObike3 No measure
bikeObike4 No measure
------------------------------------------------------
bikeObike0 average = 10.000000 (count = 1)
bikeObike1 average = 11.000000 (count = 1)
bikeObike2 average = 12.000000 (count = 1)
bikeObike3 average = 13.000000 (count = 1)
bikeObike4 No measure
------------------------------------------------------
bikeObike0 average = 10.000000 (count = 1)
bikeObike1 average = 11.000000 (count = 1)
bikeObike2 average = 12.000000 (count = 1)
bikeObike3 average = 13.000000 (count = 1)
bikeObike4 average = 14.000000 (count = 1)
------------------------------------------------------
[/color][/sub]

and if I now enter the following (basically removing the integral part in the values and only setting the decimal)

[color=blue]bikeObike0 -10
bikeObike1 -11.2
bikeObike2 -12.4
bikeObike3 -13.6
bikeObike4 -14.8[/color]

I see in the console

[sub][color=purple]bikeObike0 average = 0.000000 (count = 2)
bikeObike1 average = 11.000000 (count = 1)
bikeObike2 average = 12.000000 (count = 1)
bikeObike3 average = 13.000000 (count = 1)
bikeObike4 average = 14.000000 (count = 1)
------------------------------------------------------
bikeObike0 average = 0.000000 (count = 2)
bikeObike1 average = -0.100000 (count = 2)
bikeObike2 average = 12.000000 (count = 1)
bikeObike3 average = 13.000000 (count = 1)
bikeObike4 average = 14.000000 (count = 1)
------------------------------------------------------
bikeObike0 average = 0.000000 (count = 2)
bikeObike1 average = -0.100000 (count = 2)
bikeObike2 average = -0.200000 (count = 2)
bikeObike3 average = 13.000000 (count = 1)
bikeObike4 average = 14.000000 (count = 1)
------------------------------------------------------
bikeObike0 average = 0.000000 (count = 2)
bikeObike1 average = -0.100000 (count = 2)
bikeObike2 average = -0.200000 (count = 2)
bikeObike3 average = -0.300000 (count = 2)
bikeObike4 average = 14.000000 (count = 1)
------------------------------------------------------
bikeObike0 average = 0.000000 (count = 2)
bikeObike1 average = -0.100000 (count = 2)
bikeObike2 average = -0.200000 (count = 2)
bikeObike3 average = -0.300000 (count = 2)
bikeObike4 average = -0.400000 (count = 2)
------------------------------------------------------[/color][/sub]

and if I type

[color=blue]reset[/color]

then I see

[sub][color=purple]bikeObike0 No measure
bikeObike1 No measure
bikeObike2 No measure
bikeObike3 No measure
bikeObike4 No measure
------------------------------------------------------
[/color][/sub]

--> so seems to work as expected

Here is the code for you to study

enum : byte {WAITING_FOR_BIKE_ID, WAITING_FOR_VALUE} state;

const char bikePrefix[] = "bikeObike";
const size_t prefixLength = sizeof(bikePrefix) - 1;

struct measure_t
{
  float totalValue;
  unsigned int count;
};

const byte maxBikes = 5;
measure_t bikeMeasures[maxBikes];

void printAverage()
{
  Serial.println(F("------------------------------------------------------"));
  for (byte i = 0; i < maxBikes; i++) {
    Serial.print(F("bikeObike"));
    Serial.print(i);

    if (bikeMeasures[i].count != 0) {
      Serial.print(F("\taverage = "));
      Serial.print(bikeMeasures[i].totalValue / bikeMeasures[i].count, 6);
      Serial.print(F("\t(count = "));
      Serial.print(bikeMeasures[i].count);
      Serial.println(F(")"));
    } else {
      Serial.println(F("\tNo measure"));
    }
  }
}

// ------------------ SERIAL INPUT MANAGEMENT ------------------
const byte messageSizeMax = 50;
char message[messageSizeMax + 1];

const char endMarker = ' ';

boolean getMessage()
{
  static byte indexMessage = 0;
  boolean incomingMessage = true;

  while (Serial.available() && incomingMessage) {
    int c = Serial.read();
    if (c != -1) {
      switch (c) {
        case endMarker:
        case '\r': // ignore \r
        case '\n': // ignore \n
          message[indexMessage] = '\0';
          indexMessage = 0;
          incomingMessage = false;
          break;
        default:
          if (indexMessage <= messageSizeMax - 1) message[indexMessage++] = (char) c;
          break;
      }
    }
  }
  return incomingMessage;
}

void emptyDataSet()
{
  state = WAITING_FOR_BIKE_ID;
  for (byte i = 0; i < maxBikes; i++) {
    bikeMeasures[i].totalValue = 0;
    bikeMeasures[i].count = 0;
  }
}

// --------------------------------------------------------
void setup() {
  Serial.begin(115200);
  emptyDataSet();
  printAverage();
}

void loop() {
  static byte bikeID;

  if (! getMessage()) {

    if (strcmp(message, "reset") == 0) {
      emptyDataSet();
      printAverage();
    } else {
      switch (state) {
        case WAITING_FOR_BIKE_ID:
          if (strncmp(message, bikePrefix, prefixLength) == 0) { // we got a correct name
            bikeID = atoi(message + prefixLength);
            // Identified bikeObike => bikeID
            if (bikeID >= maxBikes) {
              Serial.print(F("Error: bikeObike ID too large (received: "));
              Serial.print(message);
              Serial.println(F(")"));
            } else  state = WAITING_FOR_VALUE;
          } else {
            Serial.print(F("Error: entry is not a bikeObike ID. (received: "));
            Serial.print(message);
            Serial.println(F(")"));
          }
          break;

        case WAITING_FOR_VALUE:
          char * endPtr = NULL;
          double v = strtod(message, &endPtr);
          if (endPtr != message) { // the function did read something
            bikeMeasures[bikeID].totalValue += v;
            bikeMeasures[bikeID].count++;
            printAverage();
            state = WAITING_FOR_BIKE_ID;
          } else {
            Serial.print(F("Error: entry is not a bikeObike Value. (received: "));
            Serial.print(message);
            Serial.println(F(")"));
          }
          break;
      }
    }
  }
  // here you can do other stuff

}

Hi, it seems to not work on my end :frowning:

The info I input:
bikeObike0 1.2
bikeObike1 3.4
bikeObike2 5.6
bikeObike3 7.8
bikeObike4 9.0

The results:
JML 2nd code test1.JPG

Also, the values of printaverage() doesn't appear when I typed bikeObike0 1.2
Instead, it appeared when I typed bikeObike1 3.4

JML 2nd code test1.JPG

AdrianCFL:
Hi, it seems to not work on my end :frowning:

how did you set up your Serial console? and how did you type in the data?

cf from post above

I made a small program that reads the Serial monitor (set at 115200 and sends JUST NewLine for line validation)

J-M-L:
how did you set up your Serial console? and how did you type in the data?

115200 Baud and typed through the serial monitor input bar

Sorry I didn't think of it earlier.

Here is a flowchart of how I hope the program can work:

Sonar part can be ignored. (It obtains maxAlt for calculation only)
Data from cc1350 is a UART combined to form a string, this part:

  while (Serial2.available())
  {  
    char UART;
    UART = Serial2.read();
    dataIn += UART;

    //Process message only when new line character is received
    if (UART == '\n')
    {
      
      measures[rows][0].serialNum = dataIn;

How to merge it with the latest code I provided at (Apr 05, 2018, 01:04 pm)?
Am I doing it right by using 2 column array?

AdrianCFL:
115200 Baud and typed through the serial monitor input bar

The point is what do you send as a line validation code ? it needs to be JUST NewLine (NL) not CR+NL or nothing

J-M-L:
The point is what do you send as a line validation code ? it needs to be JUST NewLine (NL) not CR+NL or nothing

Oh ya, oops it works now. I left it at "no line ending".

Is it possible for this code to be merged into the other code though?

Data from cc1350 is like "bikeObike1" compiled into a string

Is it possible for this code to be merged into the other code though?

why don't you give it a try :slight_smile:

J-M-L:
why don't you give it a try :slight_smile:

Haha, am still trying, thanks!

Hmmm, seems to be working alright, but I have a small problem here.

My data "bikeObikenn" is coming in from Serial2
And my Altitude float is coming in from Serial3

Therefore its giving me this error over and over.
Error: entry is not a bikeObike Value. (received: bikeObike2)

Is there any workaround to combine into the format you specified?

How do you ensure they will be synchronized ?