-static uint16_t pwm_vals[N_PWMLEDS*N_PWMLED_MODES];
-static uint16_t pwm_max[N_PWMLEDS] = { 0x70, 0x70, 0x1F0 };
-static uint16_t adc_max[N_PWMLEDS] = { 0x70, 0x70, 0xF0 };
-static uint16_t adc_vals[N_PWMLEDS*N_PWMLED_MODES] = {
- /* pwmled0 */
- 0x04, 0x14, 0x24, 0x38,
- /* pwmled1 */
- 0x04, 0x14, 0x24, 0x38,
- /* pwmled2 */
- 0x0c, 0x24, 0x48, 0x90,
+typedef struct {
+ uint16_t target, pwm;
+ int16_t err_sum;
+ unsigned char mode, state;
+ union {
+ unsigned char probe_steady, mode_changed;
+ };
+ uint16_t mode_pwm[N_PWMLED_MODES];
+ int16_t err_sums[N_PWMLED_MODES];
+ unsigned char modes_not_yet_stable;
+} pwmled_t;
+
+pwmled_t pwmleds[N_PWMLEDS];
+
+/*
+ * Mode stabilization:
+ * when changing brightness via pwmled_set_brightness() below,
+ * we want to converge to the target value as fast as possible. Also,
+ * we would like to somehow initialize the mode 3, which is used as
+ * "mode 2 + other PWMLED on". So after the brightness is set,
+ * we also set pwmleds[n].modes_not_yet_stable to MODE_STABILIZATION_TIME.
+ * When modes_not_yet_stable is non-zero, we allow only mode 2 to be set
+ * regardless of what is fed to pwmled_set_mode. We will then converge
+ * to the target value of mode 2 only, and after MODE_STABILIZATION_TIME
+ * ADC measurements, we copy the mode_pwm value to all other modes.
+ * Only then it is allowed to set the other modes.
+ */
+#define MODE_STABILIZATION_TIME (2*16) // two seconds worth of measurements
+
+#define PWMLED2_TESTING_WITH_350MA_LED
+
+#define SENSE_MOHM 33 /* 0.033 Ohm */
+/*
+ * Voltage in uV at ADC reading == 1 is 1100/gain/1024
+ * ADC module returns sum of 1 << PWMLED_ADC_SHIFT measurements
+ * Voltage in uV measured is current in mA * sense resistance in mOhm
+ */
+#define MA_GAIN_TO_ADC(ma, gain) ((uint16_t) \
+ ((uint32_t)(ma) \
+ * (SENSE_MOHM) \
+ * (1 << (PWMLED_ADC_SHIFT)) \
+ * 1024 \
+ / (1100000/(gain))))
+
+static uint16_t adc_max[N_PWMLEDS] = {
+#ifdef TESTING_FW
+ MA_GAIN_TO_ADC( 400, 20),
+ MA_GAIN_TO_ADC( 30, 20),
+ MA_GAIN_TO_ADC( 800, 1)
+#else
+ MA_GAIN_TO_ADC( 900, 20),
+ MA_GAIN_TO_ADC( 30, 20),
+ MA_GAIN_TO_ADC(2500, 1)
+#endif
+};
+
+static uint16_t adc_targets_0[] = {
+ MA_GAIN_TO_ADC( 50, 20),
+ MA_GAIN_TO_ADC( 80, 20),
+ MA_GAIN_TO_ADC( 160, 20),
+ MA_GAIN_TO_ADC( 350, 20),
+};
+
+static uint16_t adc_targets_1[] = {
+ MA_GAIN_TO_ADC( 5, 20),
+ MA_GAIN_TO_ADC( 10, 20),
+ MA_GAIN_TO_ADC( 20, 20),
+};
+
+static uint16_t adc_targets_2[] = {
+#ifdef TESTING_FW
+ MA_GAIN_TO_ADC( 120, 1),
+ MA_GAIN_TO_ADC( 160, 1),
+ MA_GAIN_TO_ADC( 240, 1),
+ MA_GAIN_TO_ADC( 320, 1),
+ MA_GAIN_TO_ADC( 460, 1),
+#else
+ MA_GAIN_TO_ADC( 150, 1),
+ MA_GAIN_TO_ADC( 300, 1),
+ MA_GAIN_TO_ADC( 500, 1),
+ MA_GAIN_TO_ADC( 700, 1),
+ MA_GAIN_TO_ADC(1500, 1),
+ MA_GAIN_TO_ADC(2500, 1),
+#endif