Thanks Darrel. This worked for me but...
When I add it to my code which initiates movement of the thing I wish to measure I get the timeout error T0IF at the 101st reading. I've tried understanding your code but the details are above my level! Any ideas where I'm going wrong? Here is the code:
@ DEVICE HS_OSC,LVP_OFF,WDT_OFF,PROTECT_OFF,BOD_OFF,PWRT_OF F
DEFINE OSC 20
DEFINE HSER_EVEN 1 'serial
DEFINE HSER_BITS 7 'serial
DEFINE HSER_BAUD 115200 'serial
DEFINE CCP1_REG PORTC ' Hpwm 1 pin port
DEFINE CCP1_BIT 2 ' Hpwm 1 pin bit
DEFINE HSER_RCSTA 90h ' Enable serial port & continuous receive
DEFINE HSER_TXSTA 24h ' Enable transmit, BRGH = 1
DEFINE HSER_SPBRG 10 ' 115200 Baud @ 20MHz, -1.36%
DEFINE HSER_CLROERR 1 ' serial automatic clear overrun error
trisb = %11000000 ' set port b 0-5 o/ps 6&7 i/ps
OPTION_REG = %11010100 ; TMR0 1:32 prescaler, internal clk
ADCON0 = %10001001 ; Fosc/32, AN1, DONE, module ON
'declare variables
GoDone VAR ADCON0.2 ; A/D start conversion bit
T0IF VAR INTCON.2 ; TMR0 overflow flag
x var word
RCIF VAR PIR1.5
VB_TO_PIC VAR byte ' data from VB to PIC
PIC_TO_VB var byte ' data from PIC to VB
'initialise
portb.0 = 0
portb.1 = 0
portb.2 = 0
portb.3 = 0
hpwm 1,0,2000
PAUSE 100
MAIN:
portb.0 = 0
IF RCIF THEN
pause 100
sound portb.0,[60,10]
portb.0 = 0 'to avoid buzzer continuing...?
HSERIN [VB_TO_PIC] 'RCIF is reset by reading HSERIN (need twice??)
select case VB_TO_PIC
case "1"
gosub open_response
case "2"
HSEROUT [VB_TO_PIC," TWO",13,10]
case else
HSEROUT [VB_TO_PIC," Error",13,10]
end select
ENDIF
GOTO MAIN
open_response:
portb.1 = 1 'enable
portb.3 = 0 'open direction
hpwm 1,255,2000
'sample data
FOR x = 1 to 1000
WHILE !T0IF : WEND
TMR0 = 101 ; load timer for 1ms ##time out here##
T0IF = 0 ; reset the overflow flag
GoDone = 1 ; start the A/D conversion
; The time it takes for the A/D conversion (~20us) is less than the
; time to send a single byte from the USART (~87us). So the conversion
; will always be complete by the time it gets to DEC ADRESH
HSEROUT [DEC x," ",DEC ADRESH,13,10]
; The longest hserout line would be "1000 255",13,10 (10 bytes)
; @ 115200 baud each byte takes 86.8us for a total of 868us (under 1ms)
IF T0IF THEN HSEROUT [13,10, _
"ERROR: Loop time too SLOW. T0IF bit already set.",13,10]
NEXT x
gosub power_down
return
power_down:
portb.1 = 0 'disable H-Bridge
hpwm 1,0,2000 'Set PWM to zero
return
end
Bookmarks