After having trouble making switchmode battery chargers, I decided to build one using an LM317 adjustable regulator and series resistor as a constant current source. Gets hot but works well. Schematic designed on Eagle. PCB produced with Oshpark.
Code:
#terminal 4800
init:
;set up inputs and outputs
symbol battery = c.4
symbol chargeoutput = c.2
symbol led = c.1
;set up variables
symbol current = w0
symbol flashcount = w1
symbol currentsum = w2
symbol dutycyc = w3
symbol voltcount = w4
symbol volts = w5
symbol voltavg1 = w6
symbol voltsum = w7
symbol peakvolt = w8
symbol deltapeak = w9
symbol modulus = w10
symbol highvolt = w11
symbol endcount = w12
;set everything to zero
dutycyc = 0
current = 0
currentsum = 0
voltcount = 0
volts = 0
voltavg1 = 0
voltsum = 0
peakvolt = 0
deltapeak = 0
;flash led to signify startup
low led
for flashcount = 1 to 20
toggle led
pause 100
next flashcount
start:
;detect battery inserted
gosub battdetect
main:
;main charge loop
high chargeoutput
;for next loop to run for about 30 seconds between checking battery voltage
for voltcount = 0 to 2399
pause 10
;blink led to signify charging
modulus = voltcount // 20
if modulus = 0 then
toggle led
endif
next voltcount
;measure voltage of battery
gosub verifyvolts
;check voltage, and go to beginning if battery is removed
if volts < 400 then init
;update peakvolt variable if voltage reading is higher than the last reading
if volts > peakvolt then
peakvolt = volts
deltapeak = 0
endif
;check if voltage dropped below peak, then increment a counter
if volts < peakvolt then
inc deltapeak
endif
;check counter value to end charge after battery voltage drops below peak for two cycles
if deltapeak > 1 then endchg
;send voltage adc value to terminal
sertxd (#volts, cr)
goto main
battdetect:
;check voltage to detect inserted battery
gosub verifyvolts
if volts <400 then start
low chargeoutput
return
endchg:
;turn off charging current when charging complete
low chargeoutput
endchg1:
;loop to detect removal of charged battery and go to start if battery is removed. LED lit solid to signify charging complete.
high led
gosub verifyvolts
sertxd (#volts, cr)
if volts < 400 then init
goto endchg1
verifyvolts:
;measure battery voltage
;shut off charging current to get accurate battery voltage
low chargeoutput
;use internal voltage reference
fvrsetup FVR2048 ; set to 2.048V
adcconfig %011
volts = 0
voltsum = 0
voltavg1 = 0
;take several readings and average
for voltavg1 = 0 to 19
readadc10 battery, volts
voltsum = volts + voltsum
next voltavg1
volts = voltsum / 20
;measurement done, turn on charging current
high chargeoutput
return