serve decoder/encoder

I have some trouble generating an array with servo objects, and does anyone think this code is fast enough?

Thanks for any comments

Kim

(Marked the error in the code)

#include <ServoTimer2.h>    // the servo library


byte antallServoer = 9;

//Which pins the servo in are connected to
byte servoIn [9] = {
  2,4,5,6,7,8,9,11,12};
//Which pins the servo out are connected to
byte servoOut [9] = {
  3,10,14,15,16,13,17,18,19};    

long startPulse = 0;
long pulseWidth = 0;

int pulsMin   = 1000;
int pulsMax   = 2000;
int pulsNeutral = 1500;



// Array that holds the 9 servo out objects.. Here it fails
ServoTimer2 servo[antallServoer];



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

  for(byte i=0;i<antallServoer ;i++){
    servo[i].attach(servoOut[i]);     // attach a pin to the servos 
    pinMode(servoIn[i], INPUT);     // declare pushbutton as input
  }
  
  Serial.println("Setup Done");

}
////////////////////////////////////////////////////////////

void loop()
{ 

  for(byte i=0;i<antallServoer ;i++){
    if(digitalRead(servoIn[i])==HIGH){
      startPulse = millis();
    }
    while(digitalRead(servoIn[i])==HIGH){
      //communicate over serial
    }
    pulseWidth = millis()-startPulse;
    if(pulseWidth >= pulsMax){
      pulseWidth  = pulsMax;
      //write warning on serial
    }


    if(pulseWidth <= pulsMin){
      pulseWidth  = pulsMin;
      //write warning on serial
    }
    servo[i].write(pulseWidth);


  }

}
byte antallServoer = 9;

Should be

#define antallServoer 9

or even

#define antallServoer (sizeof (servoIn) / sizeof (servoin [0]))

(probably)

AWOL is right.

I would opt for:

const byte antallServoer = 9;

[edit]You might be wondering why this is, and the answer is that the compiler hesitates/refuses to try to predict the value antallServoer will have at runtime, so the compiler will not accept anything that is not a constant, for determining the bounds of the array. (In other words, a variable that won't change)

By using either the keyword const or declaring this with #define will ensure that the value of the variable will stay the same throughout the execution of the program.[/edit]

Norske variabelnavn!? Er du norsk, eller er koden copypastet? :slight_smile:

Yupp, norsk...

I will change antallServoer to numberOfServos and repost the code with the define

#define antallServoer (sizeof (servoIn) / sizeof (servoin [0]))

why do u need to divide by SevoIn[0]?

Will there be any timing problems with this code on atmega 328?

thanks for the tips...

why do u need to divide by SevoIn[0]?

It's a general-purpose macro for finding the number of elements in an array.
"sizeof" by itself won't work in all cases, because it returns the total number of bytes in a structure.
If the type of the array elements is "char" or "byte", then the divide is not needed, but if they were, say, "long", then the value returned would be four times as big as required.