pwmled: verify the input of pwmled_set_brightness
authorJan "Yenya" Kasprzak <kas@fi.muni.cz>
Wed, 26 Jun 2013 21:53:11 +0000 (23:53 +0200)
committerJan "Yenya" Kasprzak <kas@fi.muni.cz>
Wed, 26 Jun 2013 21:53:11 +0000 (23:53 +0200)
Also allow different number of current levels for each output

firmware/pwmled.c

index 6158067..c156d81 100644 (file)
@@ -122,20 +122,32 @@ void pwmled_set_mode(unsigned char n, unsigned char mode)
        }
 }
 
+#define CHECK_BRIGHTNESS(var, expr, array) \
+       do { \
+               (var) = (expr); \
+               if ((var) >= sizeof(array)/sizeof(array[0])) \
+                       (var) = sizeof(array)/sizeof(array[0]) - 1; \
+       } while (0)
+
 void pwmled_set_brightness(uint16_t brightness)
 {
        unsigned char i;
 
-       adc_vals[0] = adc_targets_0[brightness & 0x7];
-       adc_vals[1] = adc_targets_0[(brightness >> 3) & 0x7];
+       CHECK_BRIGHTNESS(i, brightness & 0x7, adc_targets_0);
+       adc_vals[0] = adc_targets_0[i];
+       CHECK_BRIGHTNESS(i, (brightness >> 3) & 0x7, adc_targets_0);
+       adc_vals[1] = adc_targets_0[i];
        adc_vals[2] = adc_vals[1];
 
-       adc_vals[3] = adc_targets_1[(brightness >> 6) & 0x7];
+       CHECK_BRIGHTNESS(i, (brightness >> 6) & 0x7, adc_targets_1);
+       adc_vals[3] = adc_targets_1[i];
        adc_vals[4] = adc_vals[3];
        adc_vals[5] = adc_vals[3];
 
-       adc_vals[6] = adc_targets_2[(brightness >> 9) & 0x7];
-       adc_vals[7] = adc_targets_2[(brightness >> 12) & 0x7];
+       CHECK_BRIGHTNESS(i, (brightness >> 9) & 0x7, adc_targets_2);
+       adc_vals[6] = adc_targets_2[i];
+       CHECK_BRIGHTNESS(i, (brightness >> 12) & 0x7, adc_targets_2);
+       adc_vals[7] = adc_targets_2[i];
        adc_vals[8] = adc_vals[7];
 
        for (i = 0; i < N_PWMLEDS; i++) {