+/* which state (output on or output off) are we measuring now */
+static volatile unsigned char adc_type, adc_drop;
+#define ADC_RUNAVG_SHIFT 5 // running average shift on batt_on, batt_off
+static volatile uint16_t batt_on, batt_off; // measured voltage
+
+/*
+ * The voltage divider has 1M5 and 300K resistors (i.e. it measures 1/6th of
+ * the real voltage), ADC uses 1.1V internal reference.
+ * Macro to calculate upper eight bits of the ADC running-averaged value
+ * from the voltage in milivolts.
+ */
+#define ADC_1100MV_VALUE 1071 // measured, not exactly 1100
+#define MV_TO_ADC8(mV) ((unsigned char)(((uint32_t)(1UL << ADC_RUNAVG_SHIFT) \
+ * (1024UL * (mV)) \
+ / (6UL * ADC_1100MV_VALUE)) >> 8))
+static unsigned char batt_levels[] = {
+ MV_TO_ADC8(3350),
+ MV_TO_ADC8(3700),
+ MV_TO_ADC8(3900),
+};
+#define BATT_N_LEVELS (sizeof(batt_levels) / sizeof(batt_levels[0]))
+
+/* output power and PWM calculation */
+#define PWM_TOP 255
+#define PWM_MAX (PWM_TOP - 8) // to allow for ADC "batt_off" measurements
+#define PWM_MIN 8 // to allow for ADC "batt_on" measurements
+
+/*
+ * The values in power_levels[] array are voltages at which the load
+ * would give the expected power (we don't have sqrt() function,
+ * so we cannot use mW values directly. They can be calculated as
+ * voltage[V] = sqrt(load_resistance[Ohm] * expected_power[W])
+ * or
+ * voltage[mV] = sqrt(load_resistance[mOhm] * expected_power[mW])
+ *
+ * I use 1.25 W as minimum power, each step is sqrt(2)*previous_step,
+ * so the 5th step is 5 W.
+ */
+static unsigned char power_levels[] = {
+ MV_TO_ADC8(1581), // 1250 mW for 2 Ohm load
+ MV_TO_ADC8(1880), // 1768 mW for 2 Ohm load
+ MV_TO_ADC8(2236), // 2500 mW for 2 Ohm load
+ MV_TO_ADC8(2659), // 3536 mW for 2 Ohm load
+ MV_TO_ADC8(3162), // 5000 mW for 2 Ohm load
+};
+#define N_POWER_LEVELS (sizeof(power_levels) / sizeof(power_levels[0]))
+
+static unsigned char power_level = 0; // selected power level
+static unsigned char power_level_changed; // for visual feedback
+
+#define LED_PWRCHANGE_COUNT 3
+#define LED_BATTEMPTY_COUNT 60
+
+/* timing by WDT */
+static volatile unsigned char jiffies, next_clock_tick;
+
+/* button press duration (in jiffies) */
+#define BUTTON_SHORT_MIN 1
+#define BUTTON_LONG_MIN 10
+
+
+/* ========= Analog to Digital Converter (battery voltage) ========== */
+static void adc_init()