0

I'm pretty bad at coding (I know the basics), and I'm trying to create an array of servos in Arduino to control via Serial with Processing. I vaguely remember something about Arduino microcontrollers having really limited memory, so I'm not sure if creating an array of Servo objects would work. Here's the code I have so far:

#include <Servo.h>

Servo[] servos = new Servo[6]; //holds the servo objects

int[] servoPos = {90,112,149,45,75,8}; //holds the current position of each servo

char serialVal; //store the serialValue received from serial

void setup()
{
  for(int i = 0; i < servos.length; i++) //attach servos to pins
  {
    servos[i].attach(i+8);
  }

  Serial.begin(115200); //initialize serial
}

Would an Arduino Uno board be able to support this array and utilize it like in Java? Before now, I've been creating each object separately, which was very inefficient and time-consuming to type and read.

Also, if there's anything that would stop this code from executing, please tell me. I appreciate your help.

Jason Chen
  • 312
  • 1
  • 4
  • 12
  • The `Servo` array should be: `Servo servos[6];`. This will create array of 6 elements and calls default constructors as the underlying language is C++. – KIIV Jan 05 '17 at 10:00

1 Answers1

0

My advice is to fire up your Arduino IDE and give it a try. First off you're going to find that you have some problems in your code:

Your array syntax is incorrect. For example:

int[] servoPos = {90,112,149,45,75,8}; //holds the current position of each servo

should be written:

int servoPos[] = {90,112,149,45,75,8}; //holds the current position of each servo

I guess this servos.length is a Java thing? Instead you should determine that value by:

sizeof(servos) / sizeof(servos[0])

After you get it to compile you'll see a message in the black console window at the bottom of the Arduino IDE window:

Sketch uses 2408 bytes (7%) of program storage space. Maximum is 32256 bytes. Global variables use 242 bytes (11%) of dynamic memory, leaving 1806 bytes for local variables. Maximum is 2048 bytes.

So that will give you some idea of the memory usage. To check free memory at run time I use this library: https://github.com/McNeight/MemoryFree

per1234
  • 878
  • 5
  • 13
  • So the length is either sizeof(servos) or sizeof(servos[0])? – Jason Chen Jan 05 '17 at 07:29
  • Would the syntax also have to be changed for the servo array? – Jason Chen Jan 05 '17 at 07:32
  • 2
    @JasonChen `sizeof(servos)` is size of `servos` array in Bytes and `sizeof(servos[0])` is size of one element in Bytes. So you have to divide size of array by size of element to get number of elements. However there is possibility to get [the number of elements by template function](http://stackoverflow.com/questions/437150/can-someone-explain-this-template-code-that-gives-me-the-size-of-an-array). And the syntax for servo array must be changed too. – KIIV Jan 05 '17 at 09:55