PROGRAM=firmware
-SRC=firmware.c modbus.c
+SRC=firmware.c modbus.c clock.c
OBJ=$(SRC:.c=.o)
MCU=atmega328p
--- /dev/null
+#include <avr/io.h>
+#include "clock.h"
+
+void init_clock()
+{
+ // use the 16-bit Timer/Counter1 with 1024x prescaling
+ TCCR1B = _BV(CS12)|_BV(CS10); // CLK/1024
+}
+
--- /dev/null
+#ifndef CLOCK_H__
+#define CLOCK_H__ 1
+
+typedef uint16_t clock_t;
+#define get_clock() (TCNT1)
+#define CLOCK_HZ (F_CPU/1024)
+extern void init_clock();
+
+#endif /* !CLOCK_H__ */
#include <avr/interrupt.h>
#include <util/delay.h>
#include <stdio.h>
+#include "clock.h"
#include "modbus.h"
-#define TIMEOUT 0x2FF
+#define ECHO_TIMEOUT (CLOCK_HZ/10) // 10 ms
+#define MEASUREMENT_WAIT (CLOCK_HZ/3) // three triggers per second
#define N_TRIGGERS 3
#define N_SENSORS 12
pull_trigger(trig);
- starttime = TCNT1;
+ starttime = get_clock();
while (to_start || to_measure) {
uint8_t bits = 0;
- uint16_t now = TCNT1;
+ uint16_t now = get_clock();
- if (now-starttime >= TIMEOUT)
+ if (now-starttime >= ECHO_TIMEOUT)
break;
bits = get_pin(trig);
for (trig = 0; trig < N_TRIGGERS; trig++) {
uint16_t now;
do_measurement(trig);
- now = TCNT1;
- while (TCNT1-now < 200)
+ now = get_clock();
+ while (get_clock()-now < MEASUREMENT_WAIT)
modbus_poll();
}
#include <util/atomic.h>
#include <util/delay.h>
+#include "clock.h"
#include "modbus.h"
#define BUFSIZE 128 // must be a power of two
#define UBRR_VAL ((F_CPU + 8UL * UART_BAUD) / (16UL*UART_BAUD) - 1)
#define wait_one_byte() _delay_us(10*1000000/UART_BAUD)
-#define get_clock() (TCNT1)
-#define CLOCK_SPEED (F_CPU/1024)
/*
* According to Wikipedia, it is indeed 28 bits = 3.5 bytes without
* start- and stopbits.
*/
-#define TIMEOUT (28*CLOCK_SPEED/UART_BAUD)
+#define REQ_TIMEOUT (28*CLOCK_HZ/UART_BAUD)
uint16_t hold_regs[MB_N_HOLD_REGS];
if (rx_bytes == 0) // nothing received yet
return;
- if (get_clock() - last_rx < TIMEOUT) // still receiving
+ if (get_clock() - last_rx < REQ_TIMEOUT) // still receiving
return;
if (rx_bytes < 4) { // too short