-
Notifications
You must be signed in to change notification settings - Fork 11
/
main.c
476 lines (388 loc) · 12.5 KB
/
main.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
//
// main.c : init functions and primary interrupt routines
//
// Copyright (c) 2010-2011 bart.vandermeerssche@flukso.net
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
// $Id$
#include <stdlib.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/eeprom.h>
#include <avr/power.h>
#include <util/delay.h>
#include "debug.h"
#include "main.h"
#include "uart.h"
#include "spi.h"
#include "ctrl.h"
#include "global.h"
#include "encode.h"
register uint8_t spi_status asm("r7");
uint8_t spi_high_hex;
uint8_t EEMEM first_EEPROM_byte_not_used_to_protect_from_brownout_corruption = 0xbe;
struct version_struct EEMEM EEPROM_version =
{HW_VERSION_MAJOR, HW_VERSION_MINOR, SW_VERSION_MAJOR, SW_VERSION_MINOR};
struct version_struct version;
struct event_struct EEMEM EEPROM_event = {0, 0};
struct event_struct event;
uint8_t EEMEM EEPROM_enabled = DISABLE_ALL_SENSORS;
uint8_t enabled;
uint8_t EEMEM EEPROM_phy_to_log[MAX_SENSORS] =
{DISABLE_PORT, DISABLE_PORT, DISABLE_PORT, DISABLE_PORT, DISABLE_PORT, DISABLE_PORT};
uint8_t phy_to_log[MAX_SENSORS];
struct sensor_struct EEMEM EEPROM_sensor[MAX_SENSORS];
volatile struct sensor_struct sensor[MAX_SENSORS];
volatile struct state_struct state[MAX_SENSORS];
uint8_t muxn = 0;
uint16_t timer = 0;
struct time_struct time = {0, 0};
ISR(SPI_STC_vect)
{
uint8_t spi_rx, spi_tx, rx, tx;
DBG_ISR_BEGIN();
// the SPI is double-buffered, requiring two NO_OPs when switching from Tx to Rx
if (spi_status & (SPI_NO_OP_1 | SPI_NO_OP_2)) {
spi_status--;
DBG_LED_ON();
goto finish;
}
// do we have to transmit the first byte?
if (spi_status & SPI_START_TX) {
received_from_spi(SPI_FORWARD_TO_CTRL_PORT);
spi_status &= ~SPI_START_TX;
goto finish;
}
// are we in Tx mode?
if (spi_status & SPI_TRANSMIT) {
if (spi_status & SPI_HIGH_HEX) {
received_from_spi(spi_high_hex); /* actually low hex ! */
spi_status &= ~SPI_HIGH_HEX;
goto finish;
}
if (spi_status & SPI_TO_FROM_UART) {
if (!uartReceiveByte(&tx)) {
received_from_spi(SPI_END_OF_TX);
spi_status &= ~SPI_TRANSMIT;
spi_status |= SPI_NO_OP_2;
goto finish;
}
}
else {
if (ctrlGetFromTxBuffer(&tx)) {
received_from_spi(tx);
goto finish;
}
else {
received_from_spi(SPI_FORWARD_TO_UART_PORT);
spi_status |= SPI_TO_FROM_UART;
goto finish;
}
}
btoh(tx, &spi_tx, (uint8_t *)&spi_high_hex); /* actually low hex ! */
spi_status |= SPI_HIGH_HEX;
received_from_spi(spi_tx);
goto finish;
}
// we're in Rx mode
switch (spi_rx = received_from_spi(0x00)) {
case SPI_END_OF_TX:
spi_status |= SPI_TRANSMIT | SPI_START_TX;
spi_status &= ~(SPI_HIGH_HEX | SPI_TO_FROM_UART);
break;
case SPI_END_OF_MESSAGE:
if (!(spi_status & SPI_TO_FROM_UART)) {
spi_status |= SPI_NEW_CTRL_MSG;
}
break;
case SPI_FORWARD_TO_UART_PORT:
spi_status |= SPI_TO_FROM_UART;
DBG_LED_OFF();
break;
case SPI_FORWARD_TO_CTRL_PORT:
spi_status &= ~SPI_TO_FROM_UART;
DBG_LED_OFF();
break;
default:
if (spi_status & SPI_HIGH_HEX) {
htob(spi_high_hex, spi_rx, &rx);
uartAddToTxBuffer(rx);
}
else {
if (spi_status & SPI_TO_FROM_UART) {
spi_high_hex = spi_rx;
}
else {
ctrlAddToRxBuffer(spi_rx);
goto finish;
}
}
// toggle the HEX bit in spi_status
spi_status ^= SPI_HIGH_HEX;
}
finish:
DBG_ISR_END();
}
ISR(INT0_vect)
{
DBG_ISR_BEGIN();
uint8_t sensor_id = phy_to_log[PORT_PULSE_1];
if (ENABLED(sensor_id))
register_pulse(&sensor[sensor_id], &state[sensor_id]);
DBG_ISR_END();
}
ISR(INT1_vect)
{
DBG_ISR_BEGIN();
uint8_t sensor_id = phy_to_log[PORT_PULSE_2];
if (ENABLED(sensor_id))
register_pulse(&sensor[sensor_id], &state[sensor_id]);
DBG_ISR_END();
}
void register_pulse(volatile struct sensor_struct *psensor, volatile struct state_struct *pstate)
{
psensor->counter += psensor->meterconst;
pstate->milli += psensor->fraction;
if (pstate->milli >= M_UNIT) {
pstate->milli -= M_UNIT;
psensor->counter++;
}
pstate->flags |= STATE_PULSE;
pstate->timestamp = time.ms;
}
ISR(TIMER1_COMPA_vect)
{
DBG_ISR_BEGIN();
uint8_t sensor_id = phy_to_log[muxn];
if (ENABLED(sensor_id)) {
/* clear the power calculation lock when starting a new 1sec cycle */
if (timer == 0)
state[sensor_id].flags &= ~STATE_POWER_LOCK;
MacU16X16to32(state[sensor_id].nano, sensor[sensor_id].meterconst, ADC);
if (state[sensor_id].nano >= N_UNIT) {
sensor[sensor_id].counter++;
state[sensor_id].flags |= STATE_PULSE;
state[sensor_id].nano -= N_UNIT;
state[sensor_id].pulse_count++;
}
if ((timer == SECOND) && !(state[sensor_id].flags & STATE_POWER_LOCK)) {
state[sensor_id].nano_start = state[sensor_id].nano_end;
state[sensor_id].nano_end = state[sensor_id].nano;
state[sensor_id].pulse_count_final = state[sensor_id].pulse_count;
state[sensor_id].pulse_count = 0;
state[sensor_id].flags |= STATE_POWER_CALC | STATE_POWER_LOCK;
}
}
/* Cycle through the available ADC input channels (0/1/2). */
muxn++;
if (!(muxn %= 3)) timer++;
if (timer > SECOND) timer = 0;
/* In order to map this to 1000Hz (=ms) we have to skip every second interrupt. */
if (!time.skip) time.ms++ ;
time.skip ^= 1;
ADMUX &= 0xF8;
ADMUX |= muxn;
/* Start a new ADC conversion. */
ADCSRA |= (1<<ADSC);
DBG_ISR_END();
}
ISR(TIMER1_CAPT_vect)
{
disable_led();
// throttle the cpu clock to draw less amps
// raises the number of bytes that can be written to EEPROM from 43 to 48
clock_prescale_set(clock_div_16);
event.brown_out++;
#if DBG > 0
uint8_t i;
eeprom_update_block((const void*)&event, (void*)&EEPROM_event, sizeof(event));
for (i=0; i<128; i++)
eeprom_write_byte((uint8_t *)(i + 0x0100), i);
#else
eeprom_update_block((const void*)&sensor, (void*)&EEPROM_sensor, sizeof(sensor));
eeprom_update_block((const void*)&event, (void*)&EEPROM_event, sizeof(event));
#endif
// restore the original clock setting
clock_prescale_set(clock_div_1);
setup_led();
FLAG_CLR_ICF1();
}
void setup_datastructs(void)
{
eeprom_read_block((void*)&version, (const void*)&EEPROM_version, sizeof(version));
eeprom_read_block((void*)&event, (const void*)&EEPROM_event, sizeof(event));
eeprom_read_block((void*)&enabled, (const void*)&EEPROM_enabled, sizeof(enabled));
eeprom_read_block((void*)&phy_to_log, (const void*)&EEPROM_phy_to_log, sizeof(phy_to_log));
eeprom_read_block((void*)&sensor, (const void*)&EEPROM_sensor, sizeof(sensor));
for (uint8_t i=0; i<MAX_SENSORS; i++)
state[i].milli = 0;
}
void setup_led(void)
{
// set output low (= LED enabled)
PORTB &= ~(1<<PB0);
// set LED pin (PB0) as output pin
DDRB |= (1<<DDB0);
}
void disable_led(void)
{
// set LED pin (PB0) as input pin
DDRB &= ~(1<<DDB0);
// disable pull-up
PORTB &= ~(1<<PB0);
}
void setup_pulse_input(void)
{
// PD2=INT0 and PD3=INT1 configuration
// set as input pin with 20k pull-up enabled
PORTD |= (1<<PD2) | (1<<PD3);
// INT0 and INT1 to trigger an interrupt on a falling edge
EICRA = (1<<ISC01) | (1<<ISC11);
// enable INT0 and INT1 interrupts
EIMSK = (1<<INT0) | (1<<INT1);
}
void setup_adc(void)
{
// disable digital input cicuitry on ADCx pins to reduce leakage current
DIDR0 |= (1<<ADC5D) | (1<<ADC4D) | (1<<ADC3D) | (1<<ADC2D) | (1<<ADC1D) | (1<<ADC0D);
// select VBG as reference for ADC
ADMUX |= (1<<REFS1) | (1<<REFS0);
// ADC prescaler set to 32 => 3686.4kHz / 32 = 115.2kHz (DS p.258)
ADCSRA |= (1<<ADPS2) | (1<<ADPS0);
// enable ADC and start a first ADC conversion
ADCSRA |= (1<<ADEN) | (1<<ADSC);
}
void setup_timer1(void)
{
// Timer1 clock prescaler set to 1 => fTOV1 = 3686.4kHz / 65536 = 56.25Hz (DS p.134)
TCCR1B |= (1<<CS10);
// Increase sampling frequency to 2kHz (= 667Hz per channel) with an error of 0.01% (DS p.122)
OCR1A = 0x0732;
// Timer1 set to CTC mode (DS p.133)
TCCR1B |= 1<<WGM12;
// Enable output compare match interrupt for timer1 (DS p.136)
TIMSK1 |= (1<<OCIE1A);
// Activate the input capture noise canceler and trigger the IC on a positive edge (DS p.133)
TCCR1B |= (1<<ICNC1) | (1<<ICES1);
// Enable input capture interrupt (DS p.136)
TIMSK1 |= (1<<ICIE1);
DBG_OC1A_TOGGLE();
}
void setup_analog_comparator(void)
{
// analog comparator setup for brown-out detection
// PD7=AIN1 configured by default as input to obtain high impedance
// disable digital input cicuitry on AIN0 and AIN1 pins to reduce leakage current
DIDR1 |= (1<<AIN1D) | (1<<AIN0D);
// comparing AIN1 (Vcc/4.4) to bandgap reference (1.1V)
// select bandgap reference and enable input capture function in timer1 (DS p.244 & 116)
ACSR |= (1<<ACBG) | (1<<ACIC);
}
void setup_rs485(void)
{
uint8_t sensor_id = phy_to_log[PORT_UART];
// Configure PD5=DE as output pin with low as default
DDRD |= (1<<DDD5);
if (ENABLED(sensor_id)) {
/* If the UART port is enabled, put the RS485 in rx mode by setting DE low.
* We're doing this explicitely to allow live re-configuration.
*/
PORTD &= ~(1<<PD5);
}
else {
/* If the UART port is disabled, we put the RS485 into tx by setting DE high.
* A UART idle line corresponds to a logic 1 data bit = logic high voltage.
* A logic high TTL input on the RS485 results in a > b, which means
* the RS485 'a' terminal can now be used as a 3.3V rail.
* We make sure that no data is ever transmitted on the UART by looping back
* all UART data received on the SPI itf (see uartAddToTxBuffer function).
*/
PORTD |= (1<<PD5);
}
}
void calculate_power(volatile struct state_struct *pstate)
{
int32_t rest;
uint32_t pulse_power, urest, power = 0;
uint8_t pulse_count;
cli();
rest = pstate->nano_end - pstate->nano_start;
pulse_count = pstate->pulse_count_final;
sei();
urest = labs(rest);
// Since the AVR has no dedicated floating-point hardware, we need
// to resort to fixed-point calculations for converting nWh/s to W.
// 1W = 10^6/3.6 nWh/s
// power[watt] = 3.6/10^6 * rest[nWh/s]
// power[watt] = 3.6/10^6 * 65536 * (rest[nWh/s] / 65536)
// power[watt] = 3.6/10^6 * 65536 * 262144 / 262144 * (rest[nWh/s] / 65536)
// power[watt] = 61847.53 / 262144 * (rest[nWh/s] / 65536)
// We have to correct for only using 666 samples iso 2000/3, so:
// power[watt] = 61847.53 * 1/666 * 2000/3 / 262144 * (rest[nWh/s] / 65536)
// power[watt] = 61909.44 / 262144 * (rest[nWh/s] / 65536)
// We round the constant down to 61909 to prevent 'underflow' in the
// consecutive else statement.
// The error introduced in the fixed-point rounding equals 7.1*10^-6.
MacU16X16to32(power, (uint16_t)(urest/65536U), 61909U);
power /= 262144U;
pulse_power = pulse_count*3600UL;
if (rest >= 0) {
power += pulse_power;
}
else {
power = pulse_power - power;
// guard against unsigned integer wrapping
if (power > pulse_power) {
power = 0;
}
}
pstate->power = power;
}
int main(void)
{
uint8_t i;
cli();
setup_datastructs();
setup_led();
setup_adc();
setup_pulse_input();
setup_analog_comparator();
setup_timer1();
// initialize the CTRL buffers
ctrlInit();
// initialize the UART hardware and buffers
uartInit();
// initialize the RS485 chip
setup_rs485();
// initialize the SPI in slave mode
setup_spi(SPI_MODE_2, SPI_MSB, SPI_INTERRUPT, SPI_SLAVE);
FLAG_CLR_ICF1();
sei();
for(;;) {
if (spi_status & SPI_NEW_CTRL_MSG) {
ctrlDecode();
spi_status &= ~SPI_NEW_CTRL_MSG;
}
for (i = 0; i < MAX_ANALOG_SENSORS; i++) {
if (state[i].flags & STATE_POWER_CALC) {
calculate_power(&state[i]);
state[i].flags &= ~STATE_POWER_CALC;
state[i].flags |= STATE_POWER;
}
}
}
return 0;
}