Ebike problems

bhanlon56

New Member
Hi,
I'm building an ebike.
The motor for the bike is a 24V, 250Watt brushed DC motor running off a 24V lithium battery.
I'm controlling the motor with the circuit attached.
The circuit has been cobbled together from snippets found on the net. Probably not good design practice. However, it seems to work, despite the fact it looks like a ratsnest on matrix board.
If I try this code:
Code:
start:
pwmout 2, 199, 400   ;50% duty at 5000Hz
goto start
the motor runs but pulses visibly.

However, using this code, the motor runs much more smoothly:
Code:
start:
high c.2
pauseus 10
low c.2
pauseus 10
goto start
Why is this? The second piece of code has the same duty cycle and (approximately) same frequency.
Is there a recommended pwm frequency for the motor size I'm using? I'm going to control the motor speed by polling pin4 (c.3). This pin connects to a momentary switch on the bike handlebars. Each time I push the switch the motor speed increases from (for example) 10% to 50% and then to 100%. Another momentary switch connected at pin3 (c.4) resets the motor to 0% speed. I haven't figured out this bit yet. I think I'll do some reading on interrupts unless someone has a better idea.
Lastly, could my circuit be the cause of the motor pulsating? Is there anything wrong with?
Thanks in advance.
Brendan
 

Attachments

lbenson

Senior Member
Might get more views if you post the image:
23391
Your glitches are probably because of the loop:

start:
pwmout 2, 199, 400 ;50% duty at 5000Hz
goto start

You don't need to repeatedly redo the pwmout command--it runs until you turn it off or change the duty cycle with PWMDUTY or otherwise adjust it.
 

bhanlon56

New Member
Thanks.
That was my understanding also: the goto statement is not needed. But if I leave it out, the motor does not run at all. Weird.
 

techElder

Well-known member
But if I leave it out, the motor does not run at all.
Not "Weird". The snippet you posted just ENDS.

What you need to do is put the pwm before the "start:" then put some other code after the "start:" (BTW, that isn't a good general purpose label since it means something in multitasking programs. Use "Main:" instead.)

Use variables in the PWM line. then set and change those variables within your main code loop.
 

bhanlon56

New Member
Thanks.
If I use this:
Code:
pwmout 2, 199, 400 ;50% duty at 5000Hz
The motor does not run.
This also does not work:
Code:
pwmout 2, 199, 400 ;50% duty at 5000Hz
main:
if pinC.0 = 1 then
goto main
endif
 

bhanlon56

New Member
I setup a second circuit. It simply has c.2 connected to an LED.
The LED illuminates with this code:
Code:
main:
pwmout pwmdiv64, 2, 239, 96  ;10% at 65Hz
goto main
But the LED is off if the 08M2 is programmed with the pwm statement only.
It doesn't matter if I need to use the goto statement, but I need the motor to turn smoothly.
 

AllyCat

Senior Member
Hi,

As already said, you need to be aware of the difference between the END (default) and STOP commands, as described in the Command Reference .

Also, if you are putting the PWMOUT command in a loop, then strictly you should use PWMDUTY. However, it's unlikely to make much difference at 5 kHz, which IMHO is too high, unless you use a more sophisticated motor-drive circuit.

It's also worth putting a SERTXD("Starting") command at the top of your program (or a hardware/LED equivalent) , to indicate if the PICaxe is spontaneously resetting (which could cause "pulsating" of the motor).

Cheers, Alan.
 
Last edited:

hippy

Technical Support
Staff member
Code:
start:
pwmout 2, 199, 400   ;50% duty at 5000Hz
goto start
As stated that code will continually reset the PWM output which can cause things to judder.

What you want for continuously output PWM is -
Code:
pwmout 2, 199, 400   ;50% duty at 5000Hz
donothing:
goto donothing
That 'donothing: goto donothing" can be replaced by "do : loop" or "stop".

With nothing after the PWMOUT command or an END the program comes to an end and the PWM stops. That's why you see nothing with just a PWMOUT command.

The other possibility for judder is that electrical noise is causing the PICAXE to reset and restart.

The easiest way to check for that is a PAUSE 5000 at the very start of the program. When the PICAXE starts there will be a 5 second delay before PWM starts, but if it runs continually after that, even if juddering, it's likely not electrical noise which is causing the problem. If it just blips or runs but with 5 second pauses there's a reset happening, and electrical noise may be the cause.
 

mortifyu

New Member
For control I’d be inclined to use a quality potentiometer across the 5v rail and GND with the wiper pin connected to PICAXE pin C.1 that you currently aren’t using and do a READADC in a loop. By using the ADC value you could provide yourself with a usual motorbike throttle arrangement by simply adjusting the PWMDUTY dependent to the potentiometer.

With a bit of mechanical ingenuity and the addition of a H-bridge you could even make it have a reversing function 😁

Additionally having the potentiometer/throttle spring loaded, it could be arranged to drop back to motor stopped if you let go or heaven forbid fell off your e-bike.


Regards,
Mort.
 

AllyCat

Senior Member
Hi,

I don't think I'd want to bother with a reversing facility, but you might want to consider "Regenerative Braking". And you should certainly use a "failsafe" control method (e.g. spring-loaded) akin to a "dead man's handle".

Looking at the schematic diagram in more detail, it seems strange to use the digital-only input (i.e. on/off) Leg 4 for "speed" when the ADC-compatible Leg 6 appears to be unused. Also, you have made the classic mistake of connecting the 10k "Programming resistor" (R2) directly to the PICaxe Leg 2, forming a potential divider, which may prevent reliable communications.

Cheers, Alan.
 

bhanlon56

New Member
Tried a different motor. I was using a 12V motor on my workbench. (The 250W motor is attached to my bike.) A 18V cordless drill motor works with the code suggested by techElder. It still hunts a bit but nowhere near as bad. Thanks again for the replies.
 

premelec

Senior Member
A brushed motor is a pretty complex load with varying inductance and effective resistance - you might look for a technical paper on what works.... in regard to frequencies and perhaps filtering of the PWM to look more like a varying DC current going into the motor... Note that the rotational speed and commutator has it's own pulsing frequency which varies with RPM... If you have an oscilloscope look at the voltage across a very small resistor [short piece of wire] from V- to transistor source while running at various PWM and load.
 
Last edited:

mortifyu

New Member
Tried a different motor. I was using a 12V motor on my workbench. (The 250W motor is attached to my bike.) A 18V cordless drill motor works with the code suggested by techElder. It still hunts a bit but nowhere near as bad. Thanks again for the replies.
For absolute clarity, could you please post the new CODE that you are now using.


Regards,
Mort.
 

bhanlon56

New Member
Allycat and Hippy: read the END command link. I was unaware (from reading the pwmout command in the manual) that the timer and therefore the pwm module would reset. First circuit and code in about 4 years and I get the programming resistors wrong!
Mortifyu/Allycat: I wanted to ride a bike in the Australian summer without getting heat stroke. I just want a bit of a hand along the flats and a push up the hills. The idea of using a picaxe is that I can fine tune the amount of help I get from the motor. Using a throttle is an alternative I might use in the future. Its a bit awkward as I move my hands around on the handlebars to reduce the stress on my wrists. Microswitches I can place anywhere.
TechElder: Did a quick search of mosfet failures modes and dead short could happen. I could get hit by a car. I could fall off (especially after being attacked by !@#$ magpies in October). Life is a risk. I could add another mosfet in parallel.
TechElder: I tried using a variable in the pwmout statement like below but couldn't get it to work. Can you post what you meant?
Code:
pwmout 2, 99, b0
Premelec: I'm discovering that controlling motors is not as easy as connecting a mosfet to the output of a micro-controller. An oscilloscope would be nice. The original circuit (from Silicon Chip) used a 7555 to control the mosfet at about 210Hz. The code below has the pwm at 5kHz. I don't know what relationship there is between motor efficiency and pwm frequency.
Mortifyu: Current code is below. In case you're wondering, I'm not buzzing around on my ebike. I bought a freewheel to drive a chain connected to the smallest chainring (front gear) on the bike. It has a thread so you can screw it onto a 34mm axle diameter (like a BMX rear wheel). My motor has a 10mm axle. Cost me $6 from an asian website. Gave it to a machine shop to make an adapter. They quoted $40. When I checked with them yesterday the owner me a descriptive Australian comment about the quality of the freewheel. It was threaded without the wheel being exactly perpendicular to the axle. To remachine the freewheel and a new adapter is now $100.
Current code. My first idea was to use c.3 and c.4 to control an interrupt. I couldn't figure it out without two interrupts going. I dabbled with the idea of parallel processing and also using TechElders idea of using a variable in the pwm statement. Eventually gave up and used this. It works but has a slow response time. For my application its OK but I think there are better solutions.
Code:
#no_data
let b1=0
pwmout 2, 199, 0    ;start at 0%. Could use pwmout 2,OFF?

main:
if pinC.3=0 then    ;c.3 connected to speed micro-switch    
    b1=b1+1
    pause 500        ;switch debounce
endif

if pinC.4=1 then    ;c.4 connected to stop switch
    b1=0
    pause 500
endif

if b1=0 then goto stop_motor
if b1=1 then goto slow
if b1=2 then goto medium
if b1>=3 then goto fast

goto main

stop_motor:
pwmout 2,OFF
goto main

slow:
pwmout 2, 199, 80    ;10% at 5kHz
goto main

medium:
pwmout 2, 199, 400    ;50% at 5kHz
goto main

fast:
pwmout 2, 199, 720    ;90% at 5kHz        
goto main
 

bhanlon56

New Member
I forgot to mention that the switches I'm using to test the circuit and code are momentary on (ie normally off) for c.4 and momentary off (ie normally on) for c.3. Explains the difference in the two if..then statements. The micro-switches I've ordered are momentary on.
 

premelec

Senior Member
Glad you've got it working... try changing the PAUSE 500 to lower value - half a second is along time... looks like you've got the basic ideas going ok. It is common to put a kill switch on the brake handle on ebikes... I've been bicycling for over 50 years in traffic and at age 83 am considering an ebike! [just now ice on the streets is my main impediment] . Controlling high currents always has some repercussions like voltage spikes on the power lines which may reset the PICAXE. Ride on!
 

lbenson

Senior Member
I tried using a variable in the pwmout statement like below but couldn't get it to work.

pwmout 2, 99, b0
What variety of "didn't work"? Duty cycle runs 0-1023, so needs a word variable (although that in itself would not make it fail to work--just not work as expected, e.g., if you said b0=512, expecting half speed, you would actually end up with b0 equal to 0).

If you reach "fast", how do you ever get back to medium or slow without going through "stop"?

If you want to limit b1 to a maximum of 3, you could use: b1=b1 max 2 + 1
Then you could implement a "slow down" button.
 
Last edited:

bhanlon56

New Member
Premelec: At 83, I'm impressed!
Ibenson: Can't remember what I did. But this works with an LED at 65Hz.
Code:
main:
let w0=10
pwmout pwmdiv64, 2, 239, w0
pause 1000
let w0=96
pwmout pwmdiv64, 2, 239, w0
pause 1000
let w0=481
pwmout pwmdiv64, 2, 239, w0
pause 1000
let w0=962
pwmout pwmdiv64, 2, 239, w0
pause 1000
goto main
You're right. I was going to use the stop button to slow down. With only 3 speeds it would be easy to cycle through them.
Do you mean something like this:
Code:
let b0=0
main:
if pinc.4=1 then
    b0=b0+1 MAX 4
endif
if b0=0 then goto stop1
if b0=1 then goto slow
if b0=2 then goto medium
if b0=3 then goto fast
if b0=4 then goto slowdown
    goto main
    
stop1:
slow:
medium:
fast:
    
slowdown:
if pinc.4=1 then
    b0=b0-1 MIN 0
endif
if b0=0 then goto stop1
if b0=1 then goto slow
if b0=2 then goto medium
if b0=3 then goto fast
    goto main
Implementing a slowdown means I might be able to connect the stop button to the brakes eg via a reed switch/magnet setup.
Thanks for the ideas,
Brendan
 

inglewoodpete

Senior Member
Code:
pwmout 2, 99, b0
In the example you suggested (above), you need to be aware that the duty cycle (controlled by the variable) needs to be 4 times the period value to reach 100%. b0, a byte register, cannot hold a value of 399, so will never be able to control the PWM up to 100%.
Code:
pwmout 2, 99, b0
Premelec: I'm discovering that controlling motors is not as easy as connecting a mosfet to the output of a micro-controller. An oscilloscope would be nice. The original circuit (from Silicon Chip) used a 7555 to control the mosfet at about 210Hz. The code below has the pwm at 5kHz. I don't know what relationship there is between motor efficiency and pwm frequency.
Driving a power MOSFET with a microcontroller, particularly with PWM, is not straightforward.

Firstly, if you are driving the MOSFET with 5v then you need to use a logic-level MOSFET (I haven't checked the suitability of the MOSFET in your circuit), otherwise the MOSFET will never turn on fully.

Secondly, power MOSFETs have a large gate area since their 'on' resistance is very low due to the large piece of silicon doing the switching. This translates to a (relatively) large input capacitance. With a higher drive frequency, the MOSFET will spend a lot of its duty cycle (time) partly 'on', behaving like a resistor and generating a lot of heat rather than driving the motor. The 10 ohm resistor you have drawn in your circuit will help protect PIC's output pin but will not help turning the MOSFET 'on' quickly either. You need to insert a MOSFET driver between the PICAXE and the MOSFET. The driver has a low impedance (Ie high current) output that dumps a large charge into the gate and also discharges it quickly. This reduces the proportion of the time that the MOSFET spends in the transition area. I use Microchip TC4426, 27 or 28 MOSFET drivers (these offer various options) in my projects.

Finally, the lower the PWM frequency the better, since the fewer transitions per second between 'off' and 'on' means that the MOSFET spends less time in the 'transition' (resistive) phase between 'off' and 'on'.
 

bhanlon56

New Member
Inglewoodpete: TechElder suggested a word variable in the pwmout statement to get around the byte limit. My circuit uses a MCP-1407 which is (or is advertised as) a 6A Mosfet driver. My previous circuit had the 08M2 buffered by a BD139-BD140 emitter follower pair. It didn't work. Don't know why. I suspected that the transistors are not fast enough even with a pwm frequency of 5kHz. My understanding was that the 10 ohm resistor was there to decrease the time needed to charge the gate-source mosfet capacitance and thereby reduce the gate current. Since I was using a mosfet driver, I thought about leaving it out but wasn't sure and left it in. The MCP-1407 also provides about 12V of gate voltage. This is turning on the mosfet. So, for a 24V, 10A brushed motor, is there a ballpark pwm frequency I should use? Should the pwm frequency be decreased until I feel that the individual pulses can be felt?
 

inglewoodpete

Senior Member
Sorry, I mis-read your circuit diagram. I should have taken more time! Yes, a 6A MOSFET driver, now that I realise you were using one, is ample.

I have used frequencies as low as 488Hz (For my project, the lowest you can get out of a 28X2 @8MHz clock). There is minimal heating of the MOSFET (with a reasonable heatsink attached), although my current was limited to around 2A. Drawing up to 10A, with MOSFET heating being the square of the current, your circuit could generate 25 times the heat for the same MOSFET (I was using a IRF9540 P-channel, so not as efficient as an IRL3705).
 

hippy

Technical Support
Staff member
You're right. I was going to use the stop button to slow down. With only 3 speeds it would be easy to cycle through them.
If you want to have a scheme where 'up' increases the throttle/speed, 'down' decreases it, that should be easy enough to do.

It would also be fairly easy to smooth out speed changes so you don't have sudden kicks.

The best way to develop that is to do it in parts. Get the button handling to control the throttle setting going first. The following, untested but should work with you hardware, shows one way to handle up and down buttons -
Code:
#Picaxe 08M2
#Terminal 4800
#No_Data

Symbol MAX_THROTTLE = 3  ; 0 to 3

Symbol BUTTON_UP    = pinC.3
Symbol BUTTON_DOWN  = pinC.4

Symbol PUSHED       = 1  ; Active high

Symbol reserveW0    = w0 ; b1:b0
Symbol reserveW1    = w1 ; b3:b2
Symbol reserveW2    = w2 ; b5:b4

Symbol currentUp    = b6
Symbol currentDown  = b7
Symbol lastUp       = b8
Symbol lastDown     = b9
Symbol throttle     = b10

PowerOnReset:
  #IfNDef SIMULATING
    Pause 2000
  #EndIf
  SerTxd( "Started", CR, LF )
  Gosub ThrottleChanged

Main:
  Do
    currentUp   = BUTTON_UP
    currentDown = BUTTON_DOWN
    If currentUp <> lastUp And currentUp = PUSHED Then
      throttle = throttle + 1 Max MAX_THROTTLE
      Gosub ThrottleChanged
    End If
    If currentDown <> lastDown And currentDown = PUSHED Then
      throttle = throttle Min 1 - 1
      Gosub ThrottleChanged
    End If
    lastUp   = currentUp
    lastDown = currentDown
    Pause 100
  Loop

ThrottleChanged:
  SerTxd( "Throttle = ", #throttle, CR, LF )
  Return
 

mortifyu

New Member
This would make use of PWMDUTY and provide a totally variable speed option...

You could also add an instant kill switch with a wrist strap similar to a jetski setup to C.1 that you have not used.

Code:
#no_data
w0=0                        ;just to be certain throttle level begins at zero.
pwmout 2, 199, w0                ;start at 0% throttle.

main:
if pinC.1=0 then                ;c.1 connected to wrist strap kill switch.
    goto stop_motor
endif
    
if pinC.3=0 then                ;c.3 connected to speed micro-switch
    goto increase_speed
endif

if pinC.4=1 then                ;c.4 connected to stop switch
    goto decrease_speed
endif

goto main



increase_speed:
if pinC.1=0 then                ;kill motor immediately if wrist strap disengaged.
    goto stop_motor
endif
w1=w1+1 max 720                ;vary the +1 to suit whatever graduation change you prefer.
pwmduty 2, w1
goto main


decrease_speed:
if pinC.1=0 then                ;kill motor immediately if wrist strap disengaged.
    goto stop_motor
endif
if w1=0 then goto main            ;this line simply avoids underflow if throttle is already at 0.
w1=w1-1                    ;vary the -1 to suit whatever graduation change you prefer.
pwmduty 2, w1
if w1>0 then goto decrease_speed    ;Automatic return to ZERO throttle. Remove this line for manual gradual speed reduction.
goto main


stop_motor:                    ;instantly reduce throttle to ZERO.
w1=0
pwmduty 2,w0
goto main


Regards,
Mort.
 

lbenson

Senior Member
Do you mean something like this
I was actually thinking of a second "slow down" button, such as hippy has. And mortifyu's "dead man's switch" or "fallen off switch" also seems good.

Using MIN with subtraction can be tricky. In your code, "b0=b0-1 MIN 0", what happens when b0 is 0 and then has 1 subtracted from it (considering that picaxe doesn't have negative numbers)? This should do what you intend: b0=b0 min 1 - 1.
 

premelec

Senior Member
@bhanlon56 if you make a kill with brake connection you might also make a resume function so that if brake is only on briefly it starts motor power back where it was - and only kills motor to restart if brake held, say, more than 3 seconds... so many wonderful features to make.. fun with programming! [fall off switch is good too - I recall the bike race fall where a wheel accelerated after bike on ground indicating a cheater motor... ;-0]
 
Last edited:

bhanlon56

New Member
inglewoodpete said:
your circuit could generate 25 times the heat for the same MOSFET
The L3705N has an on resistance of 8milliohm (at 25C). This gives a dissipation of 0.8W. I found a formula to calculate switching power loss on the ElectronicsDesign website. But it needs the gate current at mosfet turn-on. There's a formula on StackExchange to find the current if you know the gate capacitance (from the datasheet) and the time constant or RC value. My best guess from these equations is 0.003W. It looks too small. I'll bolt the mosfet to large piece of aluminum and hope for the best. If it gets hot, I'll add a finned heatsink.
 

bhanlon56

New Member
hippy said:
Get the button handling to control the throttle setting going first
This is a neat piece of code. Putting more than one condition in an if..then statement is something I've never used. Also never used the #IfNdef command. What does it do? I would have just used the SerTxd command. Thanks for the code lesson.
 

bhanlon56

New Member
mortifyu said:
This would make use of PWMDUTY and provide a totally variable speed option...
This is another really useful piece of code. Thanks. I'll add your code and hippy's suggestions to my program.
 

bhanlon56

New Member
ibenson said:
And mortifyu's "dead man's switch" or "fallen off switch" also seems good
I've bought a couple of reed switches and a hall effect switch to play with. I ride with a wrist mounted rear view mirror. I have a 5mm disc super magnet with a mounting hole. By joining the magnet to the mirror with some string, I think I can come up with a deadman/fallen off switch. If I implement Hippy and Mort's ideas I still have c.1 for the switch.
 

bhanlon56

New Member
ibenson said:
Using MIN with subtraction can be tricky
I don't get it. If b0=b0-1 MIN 0, would the count not stop at zero if b0=0 and I went through the cycle again?
I had a look at the manual (pages 22-23) and it wasn't helpful.
Does your code b0=b0 min 1 - 1 read let b0 equal b0 (with a minimum of1) but subtract 1. Isn't mine the same if I write b0=b0-1 MIN 1?
 

mortifyu

New Member
If you had C.3 and C.4 both of the same polarity, ie If pinC.x=1 then..., you could add a couple diodes with your dead mans kill switch making it that if BOTH buttons were pressed, that then means GOTO STOP_MOTOR. You can then also stop the motor by pressing both buttons and additionally keeping C.1 spare for any future thoughts you may have.

If you had C.1 available, you could add a cheap little Chinese serial controlled MP3 player to play Cucaracha horns for a horn. But then, that just something nuts I'd do for fun while I was at it. :p



Regards,
Mort.
 

inglewoodpete

Senior Member
You need an isolator switch to disconnect the power. If the MOSFET fails with a short circuit condition, no input or code to/in the PICAXE is going to make any difference to your high-speed joy ride. 🚀
 

hippy

Technical Support
Staff member
I don't get it. If b0=b0-1 MIN 0, would the count not stop at zero if b0=0 and I went through the cycle again?
No. The issue is PICAXE doesn't natively deal with negative numbers, only positive integers. Like a car odometer which, after 99999, ticks over to 00000 and, going backwards, one less than 0 is 99999.

So zero minus one means a big positive number which is always greater than zero so the "Min 0" is ineffective, doesn't cap subtraction at zero.

But, by ensuring the number having one subtracted from it can never be less than one, subtracting a one from that cannot ever go less than zero. Hence -

b0 = b0 Min1 - 1
 

mortifyu

New Member
Really, would anyone care if a dead man fell off his bike? :D

This bike is starting to weigh heavily on the rider with all the accessories! :D
Accessories... Now there's an idea for your E-Bike... Skip using C.1 for a Cucaracha horn, instead use it to communicate to a bluetooth module to answer your phone so you can ride hands free ;)
 

lbenson

Senior Member
I don't get it. If b0=b0-1 MIN 0, would the count not stop at zero if b0=0 and I went through the cycle again?
As hippy said--but in addition, this would have been a good line of code to try in the simulator. You could have seen what the problem was.

Tex--glad I added "or fallen off" after originally having typed only "dead man's switch". I just think "dead man's switch" is such a cool idea. I wonder if it was practical experience which led locomotive engineers to put one in, or did some smart person just figure it out? And if practical experience, what was the actual event. Maybe it started as an "asleep at the throttle" switch.
 

Hemi345

Senior Member
I wonder if it was practical experience which led locomotive engineers to put one in, or did some smart person just figure it out? And if practical experience, what was the actual event. Maybe it started as an "asleep at the throttle" switch.
Didn't they make a movie about that train engineer that hopped off the train to switch a track and then he couldn't get back on?

Ahh yes, Unstoppable. That was about 1hr 38minutes of my life I'm never getting back. haha
 
Last edited:

Dartmoor

Member
I just think "dead man's switch" is such a cool idea. I wonder if it was practical experience which led locomotive engineers to put one in, or did some smart person just figure it out? And if practical experience, what was the actual event. Maybe it started as an "asleep at the throttle" switch.
"Dead man's handle" has only really existed with diesel & electric traction. With a steam loco there would be a driver/engineer & a fireman, both of whom would be looking at the signals & track ahead. In the UK, the dead man's handle has gradually been replaced by the driver's vigilance device which involves a random 'beep' that sounds and requires a pedal to be operated in response.
For many years electric & diesel trains in the UK needed a second man in the cab (union rules?) and I suspect that the dead man's handle was to avoid the cost of a second man (just a guess)?
I have seen electric bikes with spring return throttle that stops the bike if the rider lets go (either falloff or hopefully just applying the brakes?). Also, I have seen a very sensitive (low pressure) pushbutton used on miniature passenger carrying locomotives.
 
Top