Floats in array

I've written a sketch to remote control my Rover 5 with another Arduino with an analog joystick attached. That code works. My motor controller has 4 pins that give a 0-5V output depending on the current the 4 motors draw (5V = 5A). So I wrote some code to sent the values to the serial monitor and I'm having some problems.
The sketch that works can be found here -> Remote controlling the Dagu Rover 5 with a joystick - Bajdi electronics
When I add the following code to that sketch it stops working.

float current[3];   // Array with the 4 motor current values, to sent to remote control

void loop()
{
// 4 analog readings from motor controller = motor current
  int m1 = analogRead(A1);
  current[0] = m1 / 1024.0 * 5.0;      // 1024 = 5A
  Serial.print("current motor 1 = ");
  Serial.println(current[0]);
  
  int m2 = analogRead(A2);
  current[1] = m2 / 1024.0 * 5.0;
  Serial.print("current motor 2 = ");
  Serial.println(current[1]);
  
  int m3 = analogRead(A3);
  current[2] = m3 / 1024.0 * 5.0;
  Serial.print("current motor 3 = ");
  Serial.println(current[2]);
  
  int m4 = analogRead(A4);
  current[3] = m4 / 1024.0 * 5.0;
  Serial.print("current motor 4 = ");
  Serial.println(current[3]);
}

What am I doing wrong? I would like to sent the current[3] array to the remote control to display it on an LCD.

float current[3];   // Array with the 4 motor current values, to sent to remote control

This defines an array of three elements, not four.

Oh damned, forgot about that :~

There is an often occuring semantic error in your code. You need to divide by 1023.0 as 1023 is the max value of m1. There are 1024 values but the max is 1023.
You can easy check this as when the ADC has max value 1023 the current will be 1023/1024 * 5 is slightly less than 5.

furthermore the m* vars are used very short, and the code has a repeating pattern so you could compact your code to

int apin[] = { A0, A1, A2, A3 };  // analog pin array
float current[4];   

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

void loop()
{
  for (int i=0; i<4 i++)
  {
    current[i] = analogRead( apin[i] )/ 1023.0 * 5.0;   // or analogRead * 0.004887586; multiply is faster than division
    Serial.print("current motor ");
    Serial.print(i+1);
    Serial.print(" = ");
    Serial.println(current[i]);
  }
  // optional other code here...
  
}

If you want to do some averaging change loop to

void loop()
{
  for (int i=0; i<4 i++)
  {
    int sum = 0;
    for (r=0; r<16; r++) sum += analogRead( apin[i] );

    current[i] = (5.0 * sum)/ (16 * 1023.0);  // include the averaging in the final formula!
    Serial.print("current motor ");
    Serial.print(i+1);
    Serial.print(" = ");
    Serial.println(current[i]);
  }
  // optional other code here...
  
}

Thank you Rob, that code does look a lot cleaner :slight_smile: