Hi Dag,
Here's something that might get you started. It's based on 1m distance and 4MHz oscillator for the PIC. It compiles for 16F877 but it's not tested.
It gives you 0.1km/h resolution but due to rounding errors the accuraqcy will be +/-0.1km/h. It's likely possible to improve that though but lets start with this and see if works at all.
See if it makes any sense:
Code:
'****************************************************************
'* Name : Speedometer.pbp *
'* Author : Henrik Olsson *
'* Notice : Copyright (c) 2013 *
'* : All Rights Reserved *
'* Date : 2013-08-01 *
'* Version : 1.0 *
'* Notes : *
'* : *
'****************************************************************
DEFINE OSC 4
' If the PIC is running at 4MHz and we run TMR2 with a prescaler of
' 1:4 it'll "tick" every 4us. Setting PR2 to 225 will make it overflow
' every 225*4=900us.
T2CON = %00000001 ' 1:4 Prescale, timer is off
PR2 = 225 ' Overflow every 225*4=900us
StartSignal VAR PortB.0
StopSignal VAR PortB.1
TMR2ON VAR T2CON.2 ' Alias to TMR2ON bit
T2INT VAR PIR1.1 ' Alias to TMR2 Interrupt flag
Time VAR WORD ' This is the measured velocity in units on 0.1km/h
Velocity VAR WORD ' Calculated velocity
Main:
TMR2ON = 0 ' Timer is OFF
TMR2 = 0 ' Reset timer
Time = 0
Velocity = 0
WaitForStartSignal:
While NOT StartSignal : WEND ' Wait for start input.
TMR2ON = 1 ' Start the timer
WaitForStopSignal:
WHILE NOT StopSignal
IF T2INT = 1 THEN ' 900us has passed
T2INT = 0 ' Clear flag
Time = Time + 1 ' Count up, units of 900us
IF Time = 4500 THEN ABORT ' ~4 seconds has passed, lets stop.
ENDIF
WEND
TMR2ON = 0 ' Stop the timer
' At this point the variable Time contains the time from start signal
' to stop signal in units of 900us.
' Velocity in km/h = 3.6 / time in seconds
' If Time is 200 it took 200 * 900us = 180ms which equals 20km/h.
' If Time is 745 it took 745 * 900us = 670ms which eqauls 5.4km/h.
' IF Time is 2000 it took 2000 * 900us = 1800ms which equals 2km/h.
' If Time is 4000 it took 4000 * 900us = 3600ms which eqauls 1km/h.
' If we do 40000/200 we get 200 = 20.0km/h
' If we do 40000/745 we get 53 = 5.3km/h
' If we do 40000/2000 we get 20 = 2.0km/h
' If we do 40000/4000 we get 10 = 1.0km/h
Velocity = 40000 / Time
LCDOUT $FE, 1, "Velocity: ", DEC Velocity/10, ".", DEC Velocity // 10, "km/h."
Goto Main
Abort:
LCDOUT $FE, 1, "Timing aborted after ~4s"
Goto Main
/Henrik.
Bookmarks