• Hello ES! We could use some help to get us past the finish line on building the new knowledgebase for the forum.
    Can you donate? Please see our fundraising page. Thank you!

FOC Open Source Firmware for Bafang CAN bus controllers with GD32F303 processor

stancecoke

Minor legend
Joined
Aug 2, 2017
Messages
3,421
Location
Bavaria, Germany
In the last weeks I've ported the EBiCS firmware for the Lishuis to this Bafang hub motor controller:

1759430642636.png

The processor is a GD32F303RCT6, that is mainly a clone of the STM32F103, but is much faster and has a floating point unit (ARM Cortex M4 instead of M3). The firmware uses the original GD standard periheral libraries. GD provides code examples for many typical applications, so it was quite easy to set up timers, ADC, CAN, Clock etc. without having a graphical tool like MXCube.

As I don't know, how the Bafang Bootloader works, it is necessary to open the housing to connect the STLinkV2 (yes, you can flash the GD processor with the STM programmer ;)) directly to the PCB at the moment.

Most pin functions are identified, just the quadrature PAS input and the light output is missing.

1759429537716.png
The motor is running by throttle with FOC at the moment. In the video the controller drives a Shengyi middrive motor, the load is a BionX direct drive in generator mode.


The CAN bus is only used for debug messages at the moment, but implementing the BAFANG CAN display protocol is just simple diligent work.
A little a way to go for having torquesensor based riding modes, but no witchwork.
The biggest hurdle for a widely use of this firmware is the bootloader. Pressing the PCB out of the housing and removing the potting to get access to the SWD port will deter most potential users...
I wonder if this processor is used in some newer BAFANG middrive controllers.

 
Last edited:
that is mainly a clone of the STM32F103, but is much faster
I found that Bafang uses a 12MHz oszillator, the standard is 8MHz. With my clock setup the processor ran with 180MHz. So overclocked by 50% :eek:. It ran flawlessly, but I corrected the clock setting, so it runs now at the specified 120MHz.

 
Last edited:
I was curious what was inside old CRS10F 1.0 and inside older M400 1.0 controller after removing grey stuff. Both have NXP S32K142H ARM Cortex-M4F 80Mhz 256K flash. So no STM or GD.... for those.
 
Here is the processor from the newest Bafang Markhor M560RS motor controller
I just received a defective M510 motor, it has the same processor also :cool:

1759766426085.png
1759766521667.png

So I will be able to try the firmware on it and as there are many original firmware files available, I'll be able to analyze the firmware update procedure via CAN and the bootloader also, hopefully.
But as the PCB isn't potted, it's quite easy to flash via the SWD port also.
 
Last edited:
An old article that makes some mention of GD:
The GD32F303 is not just a dumb clone. It works flawlessly and GD offers the complete tool chain with IDE, debugger, specific libraries, tutorials and example code, so you don't have to use STM IP to work with them. 🤷‍♂️
 
Last edited:
So I will be able to try the firmware on it
Success! 😎
The firmware runs with some small adaptions. The main difference to the hub motor controller is the encoder for the rotor position. It has a resolution of about 0.5 electrical degrees. I don't extrapolate the position actually, maybe the motor runs a little quieter, if I would do so.
I can't compare the noise to the original firmware at the moment, as I have no suitable speed sensor and the system throws an error without it after a very short time.

I've pushed it into a new branch:
 
Last edited:
Can you disable the error in the firmware?

Does the torque sensor work? What are the outputs of the torque sensor?
 
Can you disable the error in the firmware?
Which error?

Does the torque sensor work? What are the outputs of the torque sensor?
The torque sensor in the middrive works with CAN, @casainho has analyzed it here:

For the hub motor controller, the bottom bracket torquesensor works with analogue and digital signals for torque and cadence.

 
Last edited:
The torque sensor in the middrive works with CAN, @casainho has analyzed it here:
Yes, but this is new Bafang M510 motor and the torque sensor is different so I am wondering this new torque sensor still works the same and generates the same signals.

Like for instance can I just plug torque sensor from Bafang M510 to Luna M600 controller (which is designed for Bafang M600 torque sensor) and it will work just the same?
 
@stancecoke this is huge, big kudos to you.
I think given the schematic of the m560 controller we should be able to also have a working OSF firmware for it sooner rather than later + new VESC options for more power.
Bafang integrated motors became more and more interesting to me personally thanks to these efforts of yours and @TPEHAK
 
Bafang integrated motors
My next steps will be with the hub motor controller, as I have no frame for the Bafang middrives. So adding the torquesensor signals in the firmware to calculate the motor current setpoint is the next step to do.
I wonder, why average speed, ODO and trip stay zero on my display, while I send a steady 25km/h speed information to the display.
Is this information stored in the display, or in the controller? I tried several CAN commands to set this parameters by a controller message, but was not successful :(
 
Мои следующие шаги будут связаны с контроллером мотор-колеса, поскольку у меня нет рамы для приводов Bafang Middrive. Поэтому следующим шагом будет добавление сигналов датчика крутящего момента в прошивку для расчета уставки тока двигателя.
Интересно, почему средняя скорость, ODO и пробег остаются на моем дисплее нулевыми, хотя я отправляю на дисплей постоянную информацию о скорости 25 км/ч.
Эта информация хранится на дисплее или в контроллере? Я пробовал несколько CAN-команд, чтобы настроить эти параметры с помощью сообщения контроллера, но безуспешно.:(
Saved in display
 
Saved in display
Hm, looking in the Luna Code, it seems to be a little tricky. They send a distance information with Byte 1 of command 0x3200.
There have to be send zeros at the beginning, then an increasing value that resets after reaching the value of 100. :unsure:


Edit:
I've implemented it according to the Luna comments, it works :cool:

1000163272.jpg
 
Last edited:
I've implemented the torquesensor reading now. The PAS signal of the green wire on PA15 is processed by the EXTI_15 interrupt.
By a hint of windmeile.com I've installed the BAFANG GO APP V2.5.3 on my smartphone. It has the "Drive Data" screen with several sensor data, that's very helpful for debugging :cool:

1762533579323.png

The little thing in the middle is a torquesensor emulator, you can set cadence and torque with the two potis. Very helpful for developing also ;)
 
That little thing in the middle is interesting, torque sensor emulator can it be used as a standalone device to test if one suspects a bottom bracket sensor is faulty?
 
can it be used as a standalone device to test if one suspects a bottom bracket sensor is faulty?
Yes, it can be plugged in instead of the real BB sensor. But only for the analogue version so far. I don't know, if a CAN version exists for hubmotors also. But it would be no problem to emulate the torque sensor CAN message with the Blackpill also. Only an additional CAN transceiver module would be necessary.
The cadence signal can be set from 30 to 120 rpm, the torque signal from 700 to 3300 mV. The user button on the Blackpill board is used to start/stop the signal generation, the green LED toggles with each PAS pulse.
 
Last edited:
Bummer, the black controllers i have seen for front motors and the one i have here have a square/ trapezium like connector so that looks as one for a sensor ending with ST.C with the C for canbus. (Pin connection in that pdf).
I looked also at the bafang workbook for 2026 and no mention anymore for those black hub controllers or the bottom bracket sensors with canbus. Looks like they going more the analog sensors with round connector for which your device can be real handy.
 
Back
Top