TheMadMonk
New Member
I have an electric Moped style bicycle in which the main controller has failed. Since I am time rich and cash poor I decided to try to roll my own replacement.
I've figured out the electronics side of things and I think the code below will do what I want it to do, but i've never programed a micro-controller before and it has been a fair while since I've programmed anything else.
I would really appreciate it if someone could give my code a once over and make sure I haven't missed something obvious or have done something stupid.
Thanks in advance, BJ
I've figured out the electronics side of things and I think the code below will do what I want it to do, but i've never programed a micro-controller before and it has been a fair while since I've programmed anything else.
I would really appreciate it if someone could give my code a once over and make sure I haven't missed something obvious or have done something stupid.
Thanks in advance, BJ
Code:
'Motor controller for electric bicycle with active low inhibit and hall effect throttle
'sensor
setint %00010000,%00000000 ‘ activate interrupt when pin4 only goes low
low 2 ‘ Motor Off
let b1 = 128 ' force acceleration from 0
main:
readadc 1,b0 ‘ read Throttle (values 128 - 169, 2.5 - 3.3V)
if b0 > b1 then ' if higher than previous reading
gosub accelerate ' accelerate smoothly
else if b0 < b1 then ' if lower than previous reading
let b3 = b0 ' set motor speed directly
gosub setspeed
endif
b1 = b0 ' save throttle setting for comparision with next reading
goto main ‘ loop back to start
accelerate:
for b3 = b1 to b0
readadc 1,b2 ' test for throttle movement during acceleration
let b2 = b2 + 2 ' small bugger factor
if b2 < b0 then ' if throttle backed off
setint OFF ' bad stuff may happen if interrupt occurs in next 3 lines
let b0 = b2 - 2 '
let b1 = b3
let b2 = 0
setint %00010000,%00000000
exit ' exit if throttle has been backed off
endif
gosub setspeed
pause 50 ' 2 seconds to accelerate from 0 to max
if b0 = b1 then exit ' trap in case braking interrupt occured during pause
next
if b2 = 0 and b0 > b1 then accelerate 'if throttle backed off accelerate to new setting.
return
setspeed:
let w2 = b3 - 128 MIN 0
let w2 = w2 * 10 MAX 400
if b0 = b1 then leave ' make sure brake hasn't been applied
pwmout 2,99,w2
leave:
return
interrupt:
let b1 = 128 ' force accelleration
let b0 = 128 ' from 0
low 2 ‘ Motor Off
Pause 10 ' Debounce wait
do loop until pin4 = 1 ' loop until brake is released
pause 100 ‘ wait 1/10 second
setint %00010000,%00000000 ‘ re-activate interrupt
return ‘ return from interrupt