7 static uint16_t track_current_samples[16] = { 0 };
8 static uint8_t track_current_head = 0;
9 static volatile uint16_t track_current_sum = 0;
10 static uint16_t overcurrent_limit = 9707;
11 static uint8_t overcurrent_sent = 0;
13 static uint16_t input_voltage_samples[16] = { 0 };
14 static uint8_t input_voltage_head = 0;
15 static volatile uint16_t input_voltage_sum = 0;
17 static volatile uint8_t adc_state = 0;
18 static volatile uint16_t adc_value = 0;
20 static uint16_t track_current_milliamps(void);
21 static uint16_t input_voltage_millivolts(void);
23 void monitor_init(void)
29 void monitor_check(void)
33 uint16_t value = adc_value;
37 uint8_t i = track_current_head;
38 track_current_sum -= track_current_samples[i];
39 track_current_samples[i] = value;
40 track_current_sum += value;
41 track_current_head = (i+1)&15;
43 if(track_current_sum>overcurrent_limit)
50 interface_send1(OVERCURRENT);
53 else if(overcurrent_sent && output_is_power_on())
61 uint8_t i = input_voltage_head;
62 input_voltage_sum -= input_voltage_samples[i];
63 input_voltage_samples[i] = value;
64 input_voltage_sum += value;
65 input_voltage_head = (i+1)&15;
68 adc_state = (adc_state+1)&3;
69 adc_read_async(adc_state>>1);
73 uint8_t monitor_command(const uint8_t *cmd_buf, uint8_t cmd_length)
75 if(cmd_buf[0]==READ_TRACK_CURRENT)
80 uint16_t value = track_current_milliamps();
82 reply[0] = TRACK_CURRENT;
85 interface_send(reply, sizeof(reply));
87 else if(cmd_buf[0]==SET_OVERCURRENT_LIMIT)
92 uint16_t value = (cmd_buf[1]<<8) | cmd_buf[2];
93 if(value>4000) // Safe maximum value
96 // Convert from milliamps: (512+v/1000*0.185/5*1024)*16
97 // multiply by 16384*0.185/5000 = 0.1001101100110b
98 uint16_t v_3 = value*3;
99 overcurrent_limit = 8192+(value>>1)+(v_3>>5)+(v_3>>8)+(v_3>>12);
101 else if(cmd_buf[0]==READ_INPUT_VOLTAGE)
106 uint16_t value = input_voltage_millivolts();
108 reply[0] = INPUT_VOLTAGE;
111 interface_send(reply, sizeof(reply));
114 return INVALID_COMMAND;
119 static uint16_t track_current_milliamps(void)
121 uint16_t value = track_current_sum;
123 // Convert to milliamps: (v/16*5/1024-2.5)*1000/0.185
124 if(value<8192) // Ignore negative current readings
130 // multiply by 5000/0.185/16384 = 1.1010011001001b
131 int16_t v_3 = value*3;
132 return (v_3>>1)+(value>>3)+(v_3>>7)+(value>>10)+(v_3>>13);
136 static uint16_t input_voltage_millivolts(void)
138 uint16_t value = input_voltage_sum;
140 // Convert to millivolts: (v/16*5/1024)*1000*11
141 // multiply by 55000/16384 = 11.0101101101100b
142 uint16_t v_3 = value*3;
143 return v_3+(value>>2)+(v_3>>5)+(v_3>>8)+(v_3>>11);
146 static inline void adc_complete(uint16_t value)
152 ADC_SET_CALLBACK(adc_complete)