Help me find a interger overlow in the TLC 5940 library

TLC5940 is a 16 channel PWM chip. I am currently using the library: GitHub - PaulStoffregen/Tlc5940: 16 channel PWM LED driver based on the Texas Instruments TLC5940 chip.

There is a integer somewhere in this code such that the width 466 is the maximum you can set, and any number greater will cause an integer overflow and reset the angle values.

In example:

The code below will move to the upper limits. (all the way left then right)

// 1ms pulse is 204
#define SERVO_MIN_WIDTH 102

// 1.5 ms is 307

// 2ms pulse is 410
#define SERVO_MAX_WIDTH 466
//#define SERVO_MAX_WIDTH 467

#include <tlc_servos.h>
#include <Tlc5940.h>

int pinval = 0;

void setup(){ tlc_initServos();  }
void loop(){

tlc_setServo(pinval, 0);
Tlc.update();
delay(2000)
tlc_setServo(pinval, 180);
Tlc.update();
delay(2000);
}

The code below will move to one direction and stay there.

// 1ms pulse is 204
#define SERVO_MIN_WIDTH 102

// 1.5 ms is 307

// 2ms pulse is 410
//#define SERVO_MAX_WIDTH 466
#define SERVO_MAX_WIDTH 467

#include <tlc_servos.h>
#include <Tlc5940.h>

int pinval = 0;

void setup(){ tlc_initServos();  }
void loop(){

tlc_setServo(pinval, 0);
Tlc.update();
delay(2000)
tlc_setServo(pinval, 180);
Tlc.update();
delay(2000);
}

also there 2 codes are functionally equivalent:

// 1ms pulse is 204
#define SERVO_MIN_WIDTH 102

// 1.5 ms is 307

// 2ms pulse is 410
#define SERVO_MAX_WIDTH 466+ 307 - 102
//#define SERVO_MAX_WIDTH 307
#include <tlc_servos.h>
#include <Tlc5940.h>

int pinval = 0;

void setup(){ tlc_initServos();  }
void loop(){

tlc_setServo(pinval, 0);
Tlc.update();
delay(2000);
tlc_setServo(pinval, 180);
Tlc.update();
delay(2000);
}
// 1ms pulse is 204
#define SERVO_MIN_WIDTH 102

// 1.5 ms is 307

// 2ms pulse is 410
//#define SERVO_MAX_WIDTH 466+ 307 - 102
#define SERVO_MAX_WIDTH 307
#include <tlc_servos.h>
#include <Tlc5940.h>

int pinval = 0;

void setup(){ tlc_initServos();  }
void loop(){

tlc_setServo(pinval, 0);
Tlc.update();
delay(2000);
tlc_setServo(pinval, 180);
Tlc.update();
delay(2000);
}

Help me out.

Doing this is calling for trouble

#define SERVO_MAX_WIDTH 466+ 307 - 102

Imagine someone writing this code X = 2 * SERVO_MAX_WIDTH;You would expect the answer to be 2 * 671 thus 1342

But the pee processor replaces the #define textually so you get X = 2 * 466+ 307 - 102;and with operator precedence you only multiply by 2 the 466 and not the full thing...

Makes sense?

I hate define.

Instead of this:

#define SERVO_MAX_WIDTH 466+ 307 - 102

use this:

const int SERVO_MAX_WIDTH = 466+ 307 - 102;

or even

const int SERVO_MAX_WIDTH = 671; // I did the math

Even if const takes up a lousy two bytes more of RAM than define, it is worth it for the peace of mind. And depending on what the compiler does, it might not even take up that much.