Motor Algorithm – Part 1 – Trapezoidal

I will try to annotate the motor driver algorithms starting with a simple, brute force Trapezoidal algorithm. If you try to read papers on motor drivers you will see a lot of advanced math, but you will find very few papers explaining how simple it actually is, so I will try to do that here.

I borrowed the excellent drawing below that illustrate the 3-phase motors with windiings A,B and C. Actual motors have more windigs. You will find 6, 9, 12 windings and more on actual motors, but the concept is the same. To drive this we need to apply a pulse on A, B and C in sequence.

If you look at the windings you will see that A alone can’t drive anything, so to actually have a coil you will need to apply + on A and – on B or C. This leads us to the simplest of the algorithms where you just apply pulses in sequences over and over again.

  1. A+ B- (C is off)
  2. A+ C- (B is off)
  3. B+ C- (A is off)
  4. B+ A- (C is off)
  5. C+ A- (B is off)
  6. C+ B- (A is off)

A simple Trapezoidal will apply the pulse in sufficient length so the motor is garanteed to step one step. But, as you don’t know the current position you might have 5 steps before your motor starts. As we drive blindfolded we increase speed by making the steps faster. To drive the other direction we just reverse the sequence.

Trapezoldal is excellent to drive a motor very slowly and it is easy to code a working example. As we in this example drive without any sensors whatsoever we just have to assume that the motor follow our directions. This can be a bit tricky as we will not detect if the motor stalls and as the sequence goes wrong we just add the the problem. To cope with this we can add sensors.

BEMF basically measure the voltage on the phase we don’t use as this can tell us the actual position.

Phase Current is the current in/out of each coil that can be used to compute the rotor position. The challenge with this is that it needs a bit of speed before the currents become notifyable + it can be very sensitive for noise situations.

Hall sensors are magnetic delectors that will create a sinus as the motor rotates. This can be measured and used to compute rotor position.

Encoders can be put on shafts to accurate measure position.

Lawn Mover – Motor Algorithm

Running a BLDC (3-phase motor) you need to insert and tune some parameters with regards to size of motor, number of winding, how much current do you output etc. But, more important is the algorithm and technique you chose matching the job at hand. You have three different algorithms (FOC, Sinusoidal, Trapezoidal) and a variety of input sensors techiques (BEMF, Hall, Current and position encoders).

FOC (Field Oriented Vector) is excellent for running fast motors, but the algorithm requires heavy math and current sensors that don’t work that well on slow speeds giving me a problem on the lawn mower wheels. Classic Trapezoidal or Sinusoidal combined with Hall sensors do actually have an advantage at very low speeds. Both are also table driven, meaning we can act more or less as a stepper motor. The accuracy of Hall sensors are not even close to that of a stepper, but we have a belt that introduce a gear ratio that in effect will increase the accuracy.

Sinusoidal can be calculated, but a neat trick is to pre-calculate x number of vectors in a table.

Vector driven means we use current, hall, bemf or a position encoder to detect rotator position and calculate an output vector that is 90 degrees – this is where FOC is good as it is more efficient than the other algorithms assuming it has accurate current sensors. All methods can be used without any sensor input – running a BLDC with Trapezoidal with no sensors is very easy as you just rotate the field based on timing outputting one PWM combination at the time. It work decently well assuming the motor follow your output, but as you are blind for the actual position you get a glitch at start or if the motor is stuck. It is also very difficult to get up in higher speeds, but this work excellent at low speeds.

I have current sensors on the drivers, but as I will be driving slow I expect there to be more noise than input on the wheel drivers. Hall Sensors are far more reliable as they work even at stand-still.

In my case I will just use Trapezoidal on the wheels for now since it is dead easy to code up and fits well with what I need to do. Trapezoidal combined with Hall sensors should work just fine. Having three Hall sensors I will get an encoder that givers me 0 to 7 as input – 8 positions. These will give me the ca position of the rotor and should be sufficient to index the next step in a Trapezoidal algorithm that easily can be adjusted to this.

Changing subject to the grass cutter I basically need a different approach as I in this case is interested in running at 80% possible speed (80% speed is ca 50% efficiency) on a 1,5KW motor. In this case I don’t have hall sensors, but as I run faster I should have working current sensors.

One challenge is however that as I start the cutter I don’t know the position, so I do a trick and start running the motor Trapezoidal until I get readings and from there I run FOC (or sinusoidal). By doing this I take advantage of the fact that slow Trapezoidal will more or less force the motor from stand-still up in a minimum speed where I can start accelerating based on phase current readings.

At this point I am only interested in spinning the motors – I will implement more optimized algorithm’s later. My decition is basically not to use time on this at precent because motor algorithms and optimization can be very time consuming.

BasicPI Firmware Stack – Abstraction Layer

This is the block diagram of AL (Abstraction Layer) modules I drew som time ago. I need to review this as the list is far longer, but you get the idea. I actually started on the AL a year ago and managed to destroy my work due to a bug in STM32CubeIDE at the time, so I need to start from scratch more or less – yes I do feel the pain! But, I have myself to blame for bad backup procedures.

alOS Overview

alOS embed a RTOS (Real Time Operating System) so that the rest of the code can be independent of what OS we use. The terminology Thread and Task is used to distinguish between actual Threads that need a stack and Tasks running within a thread or main.

alOS provides four bulks of functionality that is important in any system. These are static functions so they can be called anywhere in code and guarantee portability of code. Their actual implementation is different from OS to OS.

Embedded will typically use FreeRTOS (or similar) to create a threading OS, while we use a linear scheduler for tasks. Timers are a combination of HS and SW timers.

Windows will use WinAPI for threads and the same linear scheduler for Tasks and Timers.

Static Member Description
alOS::sleep() Sleep in ms.
alOS::millis() Get time in ms.
alOS::micros() Get time in ys.

Create a one way byte or message FIFO. The array used must be created before calling this function. typically a uint8_t array should be declared and used as FIFO buffer.


Send bytes or a message. Will also signal the Receive Task (if any) to execute. Will either insert all bytes in the fifo or none. The caller must handle full fifo signals (returning false).


Receive bytes or a message. Can be used polling in which case it will return 0 if no bytes/messages was found.

alOS::FIFOReceiveTask() Set Task to receive a signal for each call to Send.

Add a thread. A thread execute in parallel on a timer interrupt and need a separate stack.

alOS::StartThread() Start thread. This enables the thread to be called.
alOS::StopThread() Stop a thread. This stops the thread from executing.
alOS::SignalThread() This signals the thread to execute once.

Add a function callback that can be executed on time or signals.  A Task need to execute and return so the next task can execute.

alOS::StartTask() Start a task.
alOS::StopTask(); Stop a Task.
alOS::SignalTask(); Signal a task to execute.

Start a timer. alOS will run itself as a task checking timers and signals ca 1000 times per second.

alOS::StartTimer() Start a timer that will call a task in n ms. This is excellent for timeout style functionality.
alOS::StartLongTimer() Start a long timer lasting more than a day.
alOS::StopTimer() Stop a timer.

FIFO, Timer, Task and Thread reference numbers are unique.


All systems will as a minimum have an elapsed timer counting uS from MCU start. The accuracy of this depends on crystals used and what source is used to maintain the clocks.

alOS guarantee a set of functions related to elapsed timers with uS accuracy. See alRTC for Real Time Clock options.

Threads and Tasks

alOS uses Thread and Task as described here.

A thread need a separate stack and is executed on a system interrupt. It needs to run in a loop and can use techniques like delay() since this allows the OS to execute another thread. Basically threads execute in “parallel” with the RTOS using a time interrupt to switch content usually 1000 times a sec.

A Task is a single function that must do its job and exit before the scheduler can start the next Task. Tasks are lists of functions that are called on timers or signals within a thread. The difference is that they run in a loop executing in sequence and must be written different from a thread. Tasks are however far more scalable than Threads since you only use a single stack. Usually you will have multiple Tasks running in a Thread.


alOS support 3 types of timers:

  • Hardware timers supported by the MCU.
  • RTOS Timers supported by FreeRTOS.
  • SW Task Timers supported by the linear scheduler.

Using RTOS timers are not recommended, but FreeRTOS (as an example) have their own proprietary timers that can be used if needed.

Hardware timers are  subject to the MCU involved, but STM32F405RG (as an example) have 14 hardware timers. Keep in mind that these are called on actual HW interrupts, so they need an ISR type of function.

Task Timers are basically tasks called on time intervals. A normal task will execute once per ms or each 10th ms depending on what you set, but a timer will execute once the timeout event is raised. Task timers can also exist in much higher numbers and it is not any real difference between a task and a task timer. A timer task can be signalled etc.

Hardware timers should however be used for things that require exact timing. Servo pulse control is an example. A SW timer will have some variance in accuracy causing the pulse to vary from second to second. On a servo this will be observed as the servo making small, unexpected moves. A hardware timer is more exact and capable of giving the same pulse from second to second making the servo stable – this is just one example. But, keep in mind that a HW timer is far more expensive to use than a SW timer, so it is not recommended to use a HW timer to blink a led etc.

Task signals

alOS support a scheme with signal counters, meaning that a task is executed once for each signal you send. This was designed with message queues in mind there you need to process once per message received. Since the timer function will prevent other tasks in the same thread it is healthy to process in bulks – hence the signal counter scheme.


The main queuing mechanism in alOS is easyIPC, meaning you can create a queue between local tasks, threads or to a different device.

PScript – Part 9 – Streams

Both Ethernet, UART, USART, USB, SPI, I2C, I2S and CAN might be used as a serial 2-way, buffered byte stream. This is an important abstraction as it allow for an easy, uniform usage of byte streams regardless of underlying technology. To support this I create the same interface on all technologies and an object “stream” that contain the buffers.

open Open a stream.
close Close a stream.
send Send bytes through the stream.
receive Receive Bytes from the stream.
Event onreceive Receive bytes through event.

The open function dictate if the stream is continuous bytes or packages. CAN (as an example) have max 8 byte packages on the messages, but it is easy enough to create virtual byte streams or larger packages if that is what you want.

CAN also have IDE, RTR, Standard and extended ID that is part of layer 1 header. I need to allow the user to control those and at the same time abstract away from CAN. This is what stream does. If you want to access raw CAN you access the CAN1 or CAN2 objects, but declaring a stream on CAN1 convert that to a buffered, 2-way byte stream where the details of the underlying CANbus is hidden from us.


Stream1.Open(CAN1, 115200)
Stream1.Send("Hello World")

In this case I connect Stream1 to CAN1, but I could have connected it to any object capable of serial stream support. Receiving bytes can be done in two ways. You can call “receive” as follows:

uint8 buf[40]
Stream1.Open(CAN1, 115200)
int x = Stream1.Receive(buf)

This will receive a maximum of 40 bytes from Stream1. But, a more elegant way of receiving is using the event as follows:

Event Stream1.OnReceive(uint8 bytes[])

I sneaked in empty brackets here to indicate that this is an array of uint8 passed as a parameter. In effect we will only pass a hidden pointer to the location in the buffer. This location will be destroyed as the event finish, so we need to copy the bytes to a local storage that survive the scope of the event.

uint8 myCopy[20]
Event Stream1.OnReceive(reference uint8 bytes[])
      myCopy = bytes

The empty brackets are used to indicate that we receive an array of bytes. The keyword reference indicate that this is a reference to an array, not the array itself. I do however still have one issue here – I need to tell stream1 how many bytes I accepted.

As I end the event, Stream1 will by default mark all bytes that was in the reference as received. This is ok if you receive packets or want to receive everything, but it is not ok if you need to examine the stream and receive only some of the bytes now, waiting for more to arrive later.

uint8 myCopy[20]
Event Stream1.OnReceive(reference uint8 bytes[]) : uint16 bytesReceived
     myCopy = bytes
     bytesReceived = myCopy.length;

The change above solves that. I add a return value to the event that is bytesReceived and set this default to the same number as inserted allowing the event to specify a different number if needed.

myCopy = bytes will in effect transfer max 20 bytes, but it might transfer less.

Again, I need to experiment a little with syntax, but I think this starts to look good.

PScript – Part 8 – Functions

Functions are a critical part of any modern language, also in PScript. Functions must be declared before they area used. A PScript will start executing the first global statement it find, but it will parse and tag functions on it’s way – so a general good rule is to put the global PScript code at bottom of a file.

Func MyFunc(uint32 v1, uint32 v2) : uint32
   return v1*v2

uint32 x = MyFunc(2,2)
print (x)

This example should print 4.

The return value is optional.

3-Phase Motor Driver w/Hall Sensors – 60V/50A

Many of you have seen this before – it’s my 60V/50A 3-Phase Motor Driver “Thunderstick”. It was a messy first assembly with greece coming through PCB holes, but I am all in all very happy with this design and will be using three of these controllers on the lawn mower. These are quite advanced drivers and similar to the Vedder (VESC) design so we can borrow that code – except that I will be using the Hall Sensors, so I need to verify if these works.

  1. RS485 Interface. I am seriously considering replacing that with a 2nd CAN interface.
  2. Terminator for RS485.
  3. CAN HS interface.
  4. Terminator jumper for CAN.
  5. STM32F405RG
  6. IO port
  7. IO port
  8. SWD. This is compatible with my other SWD ports, but it is a weird design that I will not use again.
  9. Power lane – designed so I can add a wire to take more current In.
  10. MOSFET’s.
  11. Ground Power In.
  12. Current Shunts. This only have 2 current sensors.
  13. Mounting holes.
  14. Ground power lane.
  15. Temperature sensors.
  16. +60V Power In.
  17. DRV8301 – 3-Phase driver.
  18. PSU + Buick Converter. DRV8301 contains a Buick Converter that gives 5V and we use SPX3819 to deliver 3.3V.
  19. Crystal.
  20. Hall Sensors w/5V Output.

This show my drone motor that is perfect for the grass cutter.

This shows the larger 3KW Scooter motor with hall sensors. The picture says 190KV, but I have 2 x 280KV. Will be running them at either 18V or 36V so I can use standard – off the shelf battery packages for DIY tools. These should fit perfectly with the wheel frames I have ordered.

I will need to make a revision of this driver and port it to KiKad in the process. At this point I also need to consider 4 or even 6 layers + I need to consider galvanic isolation as I add 3 motor controllers, several sensors and a main controller into a network.

3D Position System

A module like ZED-F9P cost 148.- EUR and cover all these with an accuracy of 10 cm.

The cost of thus module is currently a limitations, but cost will come down. I am more interested in the fact that it announce 10cm accuracy which open up a lot of usability options. The classic 2.5 meters are ok for many applications, but not for a lawn mover.

With two of these units you can also detect the direction of the unit. But, I am planning to add two or three “3D sensors” on my lawn mower. Satellite position is only one option here as I can add Ultra sound /LIDAR to detect surroundings, 9 DOF to detect acceleration, gyroscope and compass signals as well as temperature, humidity, pressure etc.

The last trick is to fix reference signals on house corners using ultrasound, light or rf signals. The idea is that the robot will detect these and be able to detect difference between the signals. I need to dig a bit into this, but it should be doable.

I have so far focused on using Raspberry PI Hat format on many of my modules and I believe this still is optional for a 3D module since it might be advantageous to actually add a RPI with camera and more advanced position algorithms.

3D sensors like Acceleration, gyro and compass will help tracking relative movement once they have a reference position. This is why a 2m accuracy on GPS still can be workable. To compensate for errors I can add multiple units + I plan to test multiple cameras to see if I can reference IR light positions. Cameras also have the option that we can teach the robot to actually see and recognize it’s surroundings – that said the later is complicated and require a bit of work.

I think position accuracy looks doable, but it will be some work. I also think multiple systems is a must together with the capability to detect/reject errors.

Building my own Robotic Lawn Mover

I recently studied a robotic lawn mover and realized that I can easily build one of those myself.

To get started I need two wheels with separate motors and the picture above is the driving mechanism for an electric scateboard. The wheels are 200mm in diameter and entire construction is ca 400mm wide. It is perfect as base for a lawn mover. It will cost ca 300 USD. The motors on this picture is 350W 3-phase and I would prefer stepper motors or motors with hall sensors in this case, so I will try to buy components separate + I am not fuzzed about that scateboard mounting in the middle.

To make this work I can either add a 3rd supporting wheel or simply attempt a balancing robot design. The later would be cool, but I am not sure how stable it would be with the cutter below, so I will probably use a 3 wheel design. A 4 wheel design would also be cool and add some value as my garden is large and have several levels.

The cutter itself is dead easy – most robots use a rotating plate with 4 loose blades that cut the grass. You can buy those blades in most DIY shops now, and making a round plate fixed to a motor that can spin with some speed is not difficult. I can also make the bottom of the robot flat to avoid grass coming in everywhere – with only the cutter sticking out below.

To box this I can easily find a plastic storage unit of correct size and mount it over the design.

Batteries are no challenge as you can buy tool batteries in most shops. I accidentally bought 36V/4Ah today for 70.- USD – this is for standard DIY tools and I can make a fitting for these. I can just add as many batteries I want or even build my own using 18650 or similar cells. I like the idea of having these replaceable.

The next is the sensors. A standard GPS have ca 2.5meter accuracy so that alone is not sufficient. I can buy separate kits to put down cables, but as I have a large and complicated garden I would like an easier system where I teach the robot where to cut and in what pattern. To do so I need a position system accurate down to ca 100mm. I need to return to this part.

This leaves the charger – I am thinking of making an inductive charger – where one coil is in my house wall and the other on the unit – not exactly rocket science.

As for control system I can use 3 x Thunder sticks and a rack of Hat’s as needed – this is actually a very cool project and parts have been ordered. It would have been cheaper to just buy a ready to go lawn mover, but I would have needed 5 of them to cover my entire garden. This one I hope to be able to program to cover it all.  It will take me a while to get parts, assemnble and program this unit, but it will be fun.

The position system on the lawn mover is critical. I would like an accurate position system so I can teach the robot the limits of my garden.

The first and obvious is to use 2 x GPS modules located in each end of the robot. They will only be 40 cm apart, but that together with the standard set of sensors (3 axis gyro, 3 axis accelerometer, 3 axis magnetometer, temperature, humidity, pressure) will all give me info on position.

The next is to add “eyes” in form of ultrasonic sensors as well as lasers and obviously cameras. I want one of these at each corner mounted of a pan & tilt camera unit so it can do a 180 degree coverage on each corner. Lasers and ultrasonic can detect surrounding terrain, but camera can detect IR leds I put on the house and based on them triangulate it’s own position. This means I need to set up IR senders that send a blink sequence. That blink sequence is reasonable to detect in a picture and by measuring the distance to other signals you should be able to triangulate it’s position. The blink sequence identify the sender and thus it’s reference position.

I can also put up IR senders on places in the garden if I need to + I can use BLE sensors. Needless to say, my robot will use Wifi to connect to a control unit inside the house.

I am just spinning ideas here, so I need to work a bit on the position system.

A normal lawn mover work more or less as an old fasioned “bump & go” car – it runs in one direction until the sensor detect a cable at which point it turn in a rando direction and continue. But, they are able to find their “home”. More expensive units can do more, but to really do this properly you need an accurat position system. If you got a position system then the rest is easy.

PScript – Part 7 – Practical limitations

With PScript being an interpreter running on the embedded device we need to be realistic about how much we can get in. Plain is a complex language in full, so we need to limit and adjust content with Flasgh size of the package in mind. One example is CAN on STM32. CAN is ca 50 registers with up to 32 bit fields each. To enable all this in detail to PScript would require a table with up to 1600 entries. This is a typical area where I have to accept that while this would be nice to have, it will use to much space.

So to access CAN I end up with only an abstracted interface of a few functions. I believe this is a good compromize and a needed one.


PScript – Part 6 – Datatypes

I have decided on a set of datatypes that I want to support.

bit Bit is a 1 bit data variable. Used as a separate variable it will minimum be 8 bits, but used inside a record it get bit packed.
uint8 8 bit unsigned integer
int8 8 bit signed integer
uint16 16 bit unsigned integer
int16 16 bit signed integer
uint32 32 but unsigned integer
int32 32 bit signed integer
real32 32 bit float
real64 32 bit double
string Text string. Text strings have a dynamic size.
numeric Number with exact size/precision. Unlike reals this uses BCD to encode exact decimal numbers.
blob Binary Large Object. A binary object of dynamic size and with a few static header variables like size etc. The objective is that this is often needed and as a consequence implemented special purpose in code. I believe declaring a blob datatype will save some space.
class reserved for a possible object oriented version of PScript later.
record Record is a data structure that hold a selected address in memory. It is a collection of variables that is bit packed on that address. In this context it is designed to overlay registers creating a way for PScript to access registers directly.