Professional Documents
Culture Documents
TinyG Report - Final
TinyG Report - Final
TinyG Report - Final
Carmelo Gonzales
Abstract
In this report, TinyG CNC machining methods are explored in
detail. The TinyG is a multi-axis controller primarily used in CNC
machines that require precision motion. Different firmware and hard-
ware aspects of the controller and machine setup are examined and
presented in a ground-up format to lay out the infrastructure and
capabilities of the TinyG and motion system.
1 Introduction
Multi-axis CNC machining is becoming a more integral part of everyday life,
especially as machines become smaller, more accurate, and available to the
general population. With this shift in capabilities comes the inherent shift
in controllers. At a first glance, CNC machining can seem mysterious. Most
people could explain how a machine operates from a computer program,
and may even talk about G-Code, but the foundational principals that CNC
machine is build upon is often lost in the weeds. A typical flowchart in the
design process may cover the following steps:
1. Design idea
2. CAD model
3. CNC machining
4. Finished part
1
1. CAD model
2. G-Code generation
4. Trajectory planning
5. Pulse generation
6. Motor movements
The steps 2-5 account for the previously stated mystery in the old flowchart,
and 6 is a part of CNC machining. This CNC machining can also be broken
into smaller bits which consist of hardware, and design intent, and objec-
tives. Although this set of steps is more accurate and revealing, it is still a
broad picture, and requires much more attention. To examine this process
and learn more about what is happening inside the black box, we will use a
Synthesos TinyG. The TinyG is a multi-axis motion controller that uses a
jerk based motion planning system for clean and fast motor movements. The
controller relies on open source software, allowing easy access to the firmware
helping to break down each step of the process in more detail.
2 Introduction to TinyG
The TinyG project was originally based around the grbl project which de-
scribes itself as the industry standard for maker based CNC projects[10].
This project was designed to be an easy to use, open source controller soft-
ware for CNC applications, all powered from an Arduino Uno, or similar
ATMEGA328 powered device. The original project was designed for a 3 axis
machine with acceleration managed trajectory planning, and for interpreting
a handful of G-Codes. Since its first implementation, the grbl code has been
replicated all over the do-it-yourself CNC scene from common 3D printing
firmware (Marlin), to new projects such as the TinyG. Around 2010, TinyG
began to use grbl as a base for their new jerk controlled, 6 axis CNC con-
troller. The existing architecture of the grbl firmware has been built upon
and improved to deliver enhanced capability, with the TinyG team focusing
primarily on motion planning. In addition to the improved motion plan-
ning, TinyG is designed to operate six axes of motion, and has support for
2
up to four motors. The TinyG then allows more configuration parameters
and availably for user interaction than grbl has to offer. Since its develop-
ment, TinyG has been tested and utilized in many different applications that
require highly precise motion control.
3 TinyG FlowChart
The whole process of CNC machining can be broken down using the following
flowchart, which is primarily based around the TinyG, although the process
is essentially the same for other control boards and CNC processes. Each
section is covered in more detail in the follwoing subsections.
3
Figure 1: TinyG FlowChart
4
coordinate systems, etc. G-Code generation happens after a part has been
designed in a CAD program such as SolidWorks, and the file is ready to be
converted into a toolpath for a CNC machine. Three dimensional G-Code
generation programs work with parts in a particular file type: STL, OBJ,
STEP, DXF, and some others. Once the part is loaded into a generation pro-
gram, it is broken down into a set of layers which will be cut by the machine.
Each layer corresponds to one specific z-axis height from which material will
be removed. From these layers, tool path coordinates are generated in the
G-Code language. This path generation uses the parts geometry, tool sizes,
material properties, machine settings, and many other factors to generate a
set of X-Y-Z coordinates for the machine to travel along.
In this project, only two dimensional parts are considered for simplicity,
however the process is the same as for a three dimensional object. G-Codes
consist of many lines specifying where the machine needs to move, and how
it needs to get there. The most basic of these commands are: traveling coor-
dinates, clockwise and counterclockwise circle directions, and travel speeds.
The following G-Code example shows a breakdown of the G-Code structure
for a two dimensional drawing and what each command is doing.
5
Figure 3: G-Code Example
Once the G-Code has been generated and saved, it is ready to be passed
to the TinyG via serial communication. Once received, the commands are
interpreted and path trajectories are generated.
6
sent to the planner, while commands involving parameters like coordinate
systems, unit modes, and tooling offsets are set immediately. Each com-
mand from the G-Code file helps set up different models for the machine.
These can be broken down into static, and dynamic models that govern the
overall machine behavior. A core G-Code model is initialized as a big picture
representation of the state of the machine. All changes to the G-Code model
are run through the canonical machining firmware module before being sent
off to additional machine models kept elsewhere, such as the runtime model
managed by the planning functions.
7
3.4 Planner Modules
Inside the planner module is where all of the lines, arcs, dwells and other
dynamic commands are planned and executed. The planners also carry with
them different models of the machine state (move-model, runtime execution
model), and 28 planning buffers. After CM sends in a new move, the plan-
ner performs a series of operations to determine how the move should be
executed. Lines are sent to plan line, and arcs are sent to plan arc. The
next move is checked against the move-model and current moves that have
been queued to determine a set of conditions that govern the dynamics of the
move. For each new move, the planner figures out the initial velocity, maxi-
mum velocity, and always sets the exit velocity to zero. This is because the
planner does not know that there are any other moves that may be queued in
after the current move is planned. Along with calculating conditions for the
current move, previous move conditions may also be recalculated to account
for the addition of a new last move. To illustrate this, consider the planner
taking in a very first move. All of the conditions may be calculated, with
initial velocity (zero), cruise velocity (max allowable) and final velocity (also
zero) well defined. As soon as another move is appended to the end of the
previous move, it can now recalculate the first moves final velocity because
the planner knows that it can continue, or redirect the motion. The planning
between subsequent moves happens extremely fast and it is important for the
planner to be optimally loaded with moves, around 20-24 (leaving four-eight
unused buffers). With the continual addition of more moves, the true maxi-
mum velocity can be reached, opposed to the physically allowable maximum
that can be achieved within the duration of one planned segment. Along with
planning for the previously stated conditions, the planner takes acceleration
and cornering limits into account. Once this planning is complete, the move
is queued into the buffer again for further iteration.
Planning for different types of movement happens in sub modules of the
planner. Plan line is designed to plan linear moves, and plan arc is designed
for arcs. Along with figuring out individual move dynamics, these functions
figure out move times, jerk limiting axes, and manages the buffer. Once a
move is ready to be executed, the planner copies the data from the buffer into
the move runtime model. Inside of the plan execution and plan trapezoid
modules is where the trajcetory generation acutally happens. These two
modues figure out the move dynamics, which join different segments of the
move together. From here, the planner generates 5ms of trajectory data and
8
is sent to the stepper module to generate pulses for the motor movements.
9
and the same process continues from here. If it is decided that real encoders
will be implemented, positional readings can be taken at any point during
the run, simplifying the process of keeping the machine on track, allowing for
more accurate positioning as well as increased control over the whole process.
This type of behavior can cause significant wear and tear on motors,
bearings, belts and other mechanical components. Along with wear and
tear, this non-ideal control method directly impacts part quality and surface
finishes. To combat this behavior, the TinyG team has developed a 6th
10
order jerk controlled motion planning system that helps to eliminate all of
the negative effects of a constant acceleration based system. This allows a
steady ramping up of acceleration from zero, up to a maximum acceleration,
and then back down to zero. Running the system this way utilizes more of the
motors capability, and provides smoother movements. Although acceleration
curves start and end at zero, the steady ramping up allows a higher peak
acceleration to be reached while keeping the average acceleration the same
as for a constant acceleration control method. This means that the motors
run smoother, parts finish better, and the job is completed in the same
amount of time.
Figure 5: Trajectory (red) based on 6th order jerk equations, giving zero
initial and final acceleration.
[3]
For linear moves, the jerk controlled curves are generated according to Ed
Reds Course notes [8]. This paper highlights important trajectory generation
strategies that are used for a variety of cases that are contained within the
trapezoid which defines the start and end points of a move. A full trapezoid
is divided into five different segments. One and two are the concave and
convex portions of the acceleration ramp, four and five are the same but for
deceleration, and the third is for a constant velocity portion of the motion.
11
Each segment is determined in the firmware using a set of conditions testing
velocities at each point. After the correct segment is determined the coor-
dinates are broken down into intermediate trajectory points that are used
along with a 5th order Bezier polynomial to produce the velocity curve. The
equations that govern the acceleration and deceleration are:
t2
v = vi + jm (1)
2
t2
v = vh + as t − jm (2)
2
t2
v = vi − jm (3)
2
t2
v = vh + as t + jm (4)
2
The Bezier polynomial takes the form:
where P1 − Pn represent the control points, and B1-Bn are the Bernstein
basis.
The Bezier curve is used in many applications from computer graphics,
to automobile body representations. This type of curve is chosen for TinyG
trajectory generation because the curves allow the toolpath to be specified
as a piecewise polynomial with continuously differentiable connections. This
property of Bezier curves couples nicely with jerk controlled motion plan-
ning to create smooth transitions between all points in the trajectory. With
a velocity profile specified using the Bezier curve strategy, forward differ-
encing is used to calculate each position through the curve. This requires a
polynomical of the form:
The coefficients A-F can be found by expanding the Bezier polynomial using
the Bernstein basis. In addition to the trajectory planning methods specified
in the previously discusses course notes, a special cornering algorithm is used
to compute the maximum acceptable junction speed between two connection
points [7]. Instantaneous changes in velocity are not possible with any motor,
so it is necessary to find limits which will keep stress levels on the machine
12
to a minimum. The method used is based around a constant centripetal
acceleration of a virtual circular path connection between two line segments
joined at a common point. A parameter, delta, is specified by the user as the
maximum allowable deviation from the true path that the machine can take.
This parameter places a limit on the circle radius, centripetal acceleration
and hence the junction velocity. This approach takes junction velocities to
or very near zero for moves of greater than 90 degrees, while allowing the
machine to cruise right through nearly straight moves. Below is a diagram
with parameters that the math is based off of.
5 Hardware
5.1 ATXMEGA192
TinyG utilizes an Atmel ATxmega192 microcontroller. This microcontroller
provides the power and speed necessary to function as a complete motion
control system. These microcontrollers are popular amongst many different
areas of control, ranging from industrial to medical applications. The Atx
comes equipped with 50 programmable I/O pins. TinyG utilizes this to fit
in one of its most impressive features, the ability to control up to 6 indepen-
dent axes. The Atx also has an incredibly high 32MHz clock rate, allowing
precise timing of operations. The TinyG uses one of the many timing pins
13
to operate at a constant rate of 50kHz at all times. There was debate as to
whether the TinyG should have a dynamic operation speed to account for
moves that do not need such a fast operation speed. It was decided that
because the capability was there, and did not cause any lag in the system,
the TinyG would always run at 50kHz. Most of the other pins on the Atx
are programmable and can be altered with the firmware.
5.2 DRV8818
The Atx microcontroller interfaces with DRV8818 stepper motor controllers.
This integrated circuit is what allows the stepper motors to move as desired.
The chips accept a variety of signals that tell the motors which direction to
go, how fast to move, and how long to move for. Two integrated H-Bridge
drivers allows the motors to receive their instructions from the output of
the Atx microcontroller. STEP, DIR, and ENABLE pins allow the driver to
delegate the necessary PWM signals to the motors that need to be activated.
Once the signals are received on the driver chip, an internal indexer is able
execute high accuracy microstepping without requiring the Atx controller
to manage the current regulation loop [6]. The microstepping ability allows
the stepper motor to take more precise revolution increments, and operate
smoothly. In a microstepping mode set to 1, the stepper motor would take
200, have high torque for each step but operate with less precision. 1/2
microsteps takes it up to 400 steps per revolution with less torque and more
accuracy. Up to 1/8 microsteps can be achieved for the smoothest motion.
Many other controllers allow up to 1/16 microstepping. The TinyG motion
is very accurately planned and controlled, so their max of 1/8 microsteps
can often be better than some of the competition who operate at a 1/16
microstepping mode.
14
17s, with 200 steps/revolution. This positioning resolution directly transfers
into part accuracy and can be further refined by changing the amount of
microsteps implemented by the firmware and on the stepper motor drivers.
A stepper motor achieves this stepping using pairs of energized coils of wire
inside the motor, which in turn attract different the permanently magnetized
motor shaft. In the motors used in this project, there are four different coils,
A1, A2, B1 and B2. Figure 7 shows a rough approximation of how stepping
in the motor works. First, A1 is energized while A2,B1, and B2 are turned
off. Next, B1 is energized causing a torque on the motor shaft and aligning
the poles of the induced and permanent magnets.
This incremental unit is one step. In the rough diagram, there is four
steps per revolution. In addition to doing single steps, fractional steps (or
microsteps) can also be achieved. This effect is created by energizing two
adjacent coils to swing the motor shaft to a position between the energized
coils. If this process of energizing two adjacent coils is repeated, the motors
would still only operate at 4 steps per revolution. To fully achieve half mi-
crostepping, the energizing pattern must follow a one-two phase excitation
mode. Figure 8 shows how one-two phasing is used to achieve half-steps. Us-
ing a fractional step system with stepper motors greatly helps reduce machine
resonances and positioning resolution. Single stepping does provide higher
15
torque but can have large overshoot, and cause overall machine impact which
reduces machine lifetime.
In this example, a motor with only 4 steps per revolution is explored. In
reality, the motors that are used in CNC application normally have 200, or
even 400 steps per revolution. Although there are significantly more steps,
this does not mean that there are 200 different coils used. The desired effect
is achieved by putting notches in both the drive shaft and the stationary
energized outer portion of the motor. The YouTube video titled Stepper
Motor Basics and Control How it Works covers this process in more detail
[2].
16
5.4 ATX to DRV/Motor Schematic
The electrical schematic of the Atx and DRV chips are show with connections
electrical connections highlighted in the following table. Breakout ports J17-
20 are also covered. Connections between the Atx and DRV chips go through
ports A, D, E and F. For simplicity, only port A is covered, with the other
ports being almost identical. The main signals coming from the Atx chip are
direction, step, enable, and microstep mode. First, the enable pin is turned
to a low level if the motor is activated, and set to high when the motor is not
active. The direction pin, connected through PA1, sets which way current
flows through the H-Bridge circuit inside the stepper driver. A high or low
level signal is used to determine direction, where going to a larger coordinate
is high voltage, and a smaller coordinate is low voltage. This parameter is
determined in the firmware based on the G-Code block that was previously
decomposed into its respective set of output coordinates. Microstepping
mode is also set into the firmware directly by the user, and the code uses
this to convert the desired coordinates into pulses, which the motor driver
receives. Once these pulses are received, the driver chip amplifies the signal to
the correct current level to make the motors rotate to their desired position.
After all of the required information is received by the motor driver, the
voltage on pins for AOUT1, AOUT2, BOUT1, and BOUT2 are set to allow
the coils inside the stepper motor to activate and turn the motor the desired
amount.
17
Incorporated into the TinyG between the Atx chip and stepper drivers is
a set of breakout ports designated by J17-J20 on the schematic. These ports
consist of four breakouts for: ground, direction, step and enable signals. The
main purpose of this breakout is to allow the user to incorporate different
motor drivers if the permanent drivers on the TinyG are not suitable for the
intended application. Doing this allows the user to utilize the TinyG for all
of its other features but output signals to external drivers. Some users of
the TinyG have explored this feature but it is still relatively new with little
documentation. The TinyG wiki goes into more depth of considerations to
keep in mind when going down this path [5].
When examining these ports, another question that came to mind was
whether or not these ports could be used to control the TinyG independently
of the Atx microcontroller. This process would essentially do the opposite
of breaking out signals from the ports that was described earlier. Using
the ports as inputs would allow the user to implement control via a function
generator or a different microcontroller. Although this process may be helpful
for debugging, it is not a trivial process. The main holdback is the high level
signal implemented by the TinyG when the motors are not active. This
signal is sent to the driver chips as soon as power is connected. Changing
this in the firmware would require significant modification to the code and
would likely prove to be more time consuming then getting a DRV8818 chip
separately and building a circuit completely independent from the TinyG.
18
19
20
6 Hardware Implementation
Parallel to understanding the firmware and TinyG board hardware, large
scale hardware implementation is also explored to see how the TinyG func-
tions with actual equipment. Two stages of hardware integration were per-
formed. First, the TinyG was hooked up with one, two and then three NEMA
17 stepper motors to get movements, speeds, and other general s settings cal-
ibrated. From this configuration, different G-Codes were sent to the board
using CoolTerm to verify correct operation of the setup. After the initial
tests passes, the TinyG was hooked up to an X-Y stage, which was originally
an Argentum setup. This setup incorporates limit switches, a NEMA 17 and
23 stepper motor, and a movable end effector.
21
Figure 12: TinyG Board
22
6.2 Motor Movements and CoolTerm
With the preliminary setup, it is easiest to use the application CoolTerm to
send G-Codes to the TinyG. With this application, single moves can be sent
line by line to ensure the desired movements are actually going through. To
initially start control with CoolTerm, a movement command with a specified
federate must be passed through. For example, G1X0F100 would initialize
the full motor control over all motors connected. Once the federate is speci-
fied, linear rapid moves can be sent, as well as linear traverse, and arc moves.
All machine parameters can be set through CoolTerm was well. Parameters
that were changed during initial setup were maximum velocity, travel mil-
limeters per revolution, and microsteps. Potentiometers were also calibrated
directly on the TinyG board of optimal motor current, following the proce-
dure outlined on the TinyG wiki [4]. The procedures highlighted above were
repeated for motors two and three. Additionally, different motor mapping
settings were changed to allow motors one and two to correspond to the x
axis, representing a dual drive mechanism.
23
notation fails, and was recommended that full circles be constructed by ei-
ther two semicircles or four quarter-circles. Other roundabout answers were
found while browsing NIST Standards [9], which states that sometimes G-
Code interpreters cannot fully realize full circles due to computational errors,
where the start and end point end up being different by some tiny factory
that causes the G-Code interpretation to fail. Aside from this complication,
the motors and TinyG setup functioned well with all other G-Codes send
through CoolTerm.
24
for testing, rebuilding the frame and carriage system is recommended. The
amount of slop in the machine can directly be correlated to the performance
of cutting drawing or printing. Building a more rigid machine would help to
eliminate this and would produce better experimental test results.
25
Figure 14: Third axis pen holder desing used with the TinyG setup to pro-
duce physical results from testing.
26
7 Testing TinyG and Firmware
Testing of the TinyG and hardware has been one of the most important and
exciting aspects of this project. TinyG hypes up the constant jerk trajectory
planning and 6th order trajectory generation aspects of the firmware, as well
as providing all of the necessary functionalities that make CNC machines
highly precise such as microstepping modes. To test the TinyG and x-y
stage setup, a simple L-Bracket design is used. An L-Bracket was chosen
because of it captures lots many important aspects of parts that will be
manufactured in a real works scenario. The combination of linear moves,
coupled with radius’s on corners, provides a good scenario to test the machine
with. To create the L-Bracket G-Code, a m-file is used which allows the users
to specify the length, width, and radius of corner to be used. G-Code is then
automatically written and saved to a .txt file that in then fed into CoolTerm.
For testing, a constant length and width are used with varying corner radius.
The first test performed was with varying jerk values. Jerk can be thought
of as a measure of machine impact, and directly impacts how the machine
behaves. Having a low jerk value means the machine responds very slowly,
and does not change acceleration, velocity or position too quickly. This
parameter also directly affects the time it takes to complete execution of a G-
Code file. Many different jerk values were tested within the ranges of 5 million
mm/s3 to 1 trillion mm/s2 . These values are hard to interpret physically,
mostly because of the tremendous size of the numbers. It is often easier
to think about this parameter in terms of acceleration, and how its profile
changes. When the jerk value is incredibly high, the acceleration changes
very fast, and reaches its max almost instantly. This essentially replicates the
traditional controllers which use constant acceleration trajectory planning,
aka infinite jerk. Because jerk is a measure of how fast the acceleration is
changing, having an infinite jerk means the acceleration goes from zero to its
max instantaneously. The is the effect that TinyG aims to eliminate. Testing
the TinyG with an incredibly low jerk produces the opposite effect. A low
jerk value means the acceleration will change very slowly until it reaches its
maximum. When testing this parameter, the machine maximum velocity
was often not reached by the end of the L-Bracket, because the acceleration
was still ramping up, and changed so slowly it could not move the tool very
fast. This low value did produce minimal machine impact compared to the
high jerk values, because it allows the acceleration to change much slower.
The best results of a varying jerk value came from the middle of the range,
27
50-500million mm/s3 . This range allows the machine to accelerate at a rate
that is suitable to complete the move fast enough while minimizing impact
to the machine due to the changing acceleration.
Second, different velocity values were tested with the TinyG, as well as
changing the maximum velocity limit in the firmware. Changing this value
has a direct impact on how fast parts are made, as well as a direct impact on
part quality. Using a low value would result in cleaner parts, however the ma-
chine time would be much longer than using a high velocity. To start, a value
of 500mm/min was set as both the machine max, as well as the speed to make
the L-Bracket. Running the setup at this speed is incredibly underwhelming,
however this is the most realistic configuration. When operating CNC ma-
chinery, there are well defined speeds and feeds for cutting operations, which
translates directly into how the G-Code is written. The subsequent velocity
tests are conducted with the assumption that the machine can reach the de-
sired speeds, and its operation can be completed using the desired speeds.
Speeds of 2,500, 5,000, and 10,00 mm/min were used for both machine max
and as the speed in the G-Code. There was no significant deviation in path
trajectory until 5,000mm/min and 10,000mm/min. At these speeds, the ma-
chine began to vibrate, causing small ripples in the L-Bracket. Even at these
speeds, which are far higher than any CNC mill operations are running at,
the deviations from the path were minor and resulted primarily from lack of
rigidity in the system.
For the third test, different microstepping modes were used to understand
how this parameter impacts the machine. When changing microstepping
modes, the user is increasing the number of steps taken to complete a full
revolution. In the case of this project, the stepper motors nominally have
200 steps per revolution. This standard steps per revolution corresponds to
the microstepping mode of 1, meaning there is one microstep per step. The
TinyG will accept any value for microstepping, however it is desirable to use
1, 1/2, 1/4, or 1/8 microstepping. These fractional values mean that for each
nominal step, there will be an additional number of sub steps in between.
For example, 1/8 microstepping means there are 8 additional steps per step,
increasing the total number of steps per revolution from 200 to 1,600. This
additional stepping between steps results in an increased resolution of the x-y
stage, however positioning the rotor between the nominal step values means
there will also be a decrease in torque, although stepper motors and their
drivers help to significantly reduce this loss in torque. Testing the stage with
a 1/8 microstepping mode produces a cleaner and less jittery motion of the
28
effector, as well as increased resolution. At this mode, the current x-y stage
achieves a resolution of 0.02mm. The formula for calculating resulution is as
follows.
P Nt
Resolution = (7)
Srev fm
Where P is pitch of the pulley, Nt is number of teeth, Srev is steps per revolu-
tion and fm is microstepping mode. As microstepping modes are decreased,
the machine begins to become more jittery, and has a more impactful mo-
tion to the machine. When operating at full microstepping, (mode of 1),
the machine vibrates vigorously, and the resulting trajectories contain much
more path deviation than operating at 1/8 microstepping. At this mode,
the resolution is also decreased to 0.16mm. Additional effects can be seen
when coupling the full step mode with different velocities. When operating
at the lower end of the velocity spectrum (500mm/min), there is even more
vibration and impact as compared to a higher velocity coupled with the full
step mode.
Figure 15: Microstepping mode of 1/8, showing how the trajectories are
smooth and do not deviate much from the desired path.
29
Figure 16: Microstepping mode of 1, showing how vibrations are introduced
into the machine, espeically around corners.
Finally, different sized of the L-Bracket radius were tested. In this test,
there was a significant performance change between radius sizes. When op-
erating the machine with a radius of 20mm, all cornering moves (G2, G3)
were executed as planned, however when decreasing the radius to 5mm, the
machine began to fail, and depending on the velocity value, would skip the
corner all together and just connect the dots between the start and end points
of the curve. At an intermediate velocity, the corners became extremely jit-
tery, and did not maintain the correct trajectory. The cause of this is not
explicitly known, however there are a few key parameters that are in play.
First, the moves may be performed so quickly that the TinyG does not have
time to plan the arc, resulting in a connect the dots trajectory. This could
also be the reason for the jittery skipping motion that occurs in the inter-
mediate range for velocities. Another parameter that may be in play is the
maximum allowable jerk. Because the effector begins accelerating once is
enters a corner, its maximum velocity and the corner radius may produce
an accusation that is not achievable using the maximum jerk specified in the
firmware. Additional testing of this is needed to get a deeper understanding
of what is going wrong in the firmware, and what parameters help alleviate
30
this issue.
8 Trajectory Generation
The whole reason TinyG is so hyped up is because of its trajectory generation
methods. It uses constant jerk acceleration planning, coupled with 6th order
trajectory generation to produce smooth and fast motion transitions. The
reason for using constant jerk planning and 6th order trajectory generation
is to reduce the overall impact to the machine. Jerk is a measure of machine
impact, and can be a huge factor in machine lifetime. A machine that oper-
ates on constant acceleration planning has an infinite jerk at the start and
end of a move, meaning there is a huge impact to the machine. The name
speaks for itself, as jerk measures how hard the system is being tugged on,
or how fast the acceleration is changing.
To implement this trajectory generation, there is a large set of instruc-
tions that must be executed for every move that the TinyG makes. When a
move is put into the planner buffer, TinyG must find the start and end posi-
tion of the move segment, and make decisions based on machine parameters
set by the user. In this decision tree, the move can fall into one of many
different categories based on length, velocity, acceleration and jerk require-
ments. In the most basic example, the velocity profile will be an S, where at
the transition point, the acceleration is less than or equal to the maximum
machine acceleration. One step further from this case is when the machine
reaches its maximum acceleration and must use a constant acceleration for
some time before completing the deceleration segment. The first part of
TinyGs decision making process determines which category the move falls
into, and by using the set of standard kinematics equations, determines a set
of Control Points. Once these control points are determined, they are used in
conjunction with a Bezier curve generation program which creates the actual
velocity profile using a fifth order Bezier curve.
The following excerpt from the firmware describes different cases that a
move can fall into. The firmware takes in the kinematic information and
decides where any move will fall.
31
* HB Ve<Vt=Vx head accelerates to cruise - exits at full speed (corner case: H’)
* BT Ve=Vt>Vx enter at full speed and decelerate (corner case: T’)
* HT Ve & Vx perfect fit HT (very rare). May be symmetric or asymmetric
* H Ve<Vx perfect fit H (common, results from planning)
* T Ve>Vx perfect fit T (common, results from planning)
* B Ve=Vt=Vx Velocities are close to each other and within matching tolerance
*
* Rate-Limited cases - Ve and Vx can be satisfied but Vt cannot
* HT (Ve=Vx)<Vt symmetric case. Split the length and compute Vt.
* HT’(Ve!=Vx)<Vt asymmetric case. Find H and T by successive approximation.
* HBT’ body length < min body length - treated as an HT case
* H’ body length < min body length - subsume body into head length
* T’ body length < min body length - subsume body into tail length
*
* Degraded fit cases - line is too short to satisfy both Ve and Vx
* H" Ve<Vx Ve is degraded (velocity step). Vx is met
* T" Ve>Vx Ve is degraded (velocity step). Vx is met
* B" <short>line is very short but drawable; is treated as a body only
* F <too short>force fit: This block is slowed down until it can be executed}
32
generation algorithm. Below is a visual representation of the two basic cases
that a velocity profile can follow, per [8].
Figure 17: Ideal case where velocity profile is a pure S curve, with a transition
acceleration that is less than the machine maximum.
Figure 18: Non-ideal but more likely case where velocity profile includes a
linear velocity section with acceleration equal to the machine maximum.
With the math laid out, new trajectory generation methods can be imple-
mented with slight tweaks in the firmware. Testing new trajectory firmware
can also provide a means to test how well TinyGs trajectory generation
firmware improves machine performance.
33
8.1 Custom Trajectory Generation Program
A trajectory generation firmware with a third order velocity profile is used to
compare the originally TinyG firmware too. This third order curve uses the
same control points as the 5th order version, however now instead of having a
continuous jerk and acceleration profile, the jerk will be discontinuous at the
half way point, and acceleration will be discontinuous at middle of the move.
To create the Bezier curve representation of this order, the notes found here
[1] as well as the TinyG firmware, are used to implement the new program.
After changing the form of the curve, new initial conditions are needed
to keep the kinematics physically realizable. The following excerpt from the
new firmware explains the math needed to obtain the form for a third order
Bezier curve, built by forward difference.
34
* we could assign t=0 and use a-f values to gt initital value, however we would like to
* average each segement and take initial V to be at t=h/2 and iterate I-1 times.
*
* F_1=3*A*h+(3*A*h^2+2*B*h)+(A*h^3+B*h^2+C*h)
* F_2=6*A*h^2+6*A*h^3+2*B*h^2
* F_3=6*A*h^3
*
* here, B=C=0 with current control points
*
*/
35
Figure 19: Regualr kinematics equations plotted against custom written third
order Bezier curve generation with control points highlighted.
From here, the firmware was directly integrated into the TinyG firmware,
replacing the existing program that created trajectories previously. Most
the changes were implemented in plan-exec.c. In the firmware, this is the
part where trajectories are built up using forward difference of Bezier curves.
One additional change was made in plan-line.c to replace forward-difference-
5c with forward-difference-3c.
Although the new firmware produces the correct results in MATLAB,
testing the new firmware with the x-y stage was unsuccessful. The ma-
chine had a drastic overestimation in position, and would sometimes pro-
duce erratic motion for more complicated moves. Further investigation of
the firmware, trajectory planning algorithm, and implementation is needed
before a comprehensive test can be performed to compare trajectory gener-
ation methods.
36
9 Conclusion
Overall, it is overwhelmingly apparent that the TinyG team has put in a
tremendous amount of effort to create one of the best, and most affordable
industrial grade motion controllers. The high level of detail spans all aspects
of this project, from firmware to hardware to community support and docu-
mentation. The TinyG offers a slice of pie for anyone looking to delve deeper
into the CNC world. For more advanced users, the hack-ability of this project
is off the charts. Firmware is open source and well documented. Addition-
ally, the community forums have acquired many important Q/A threads, and
remain active to date. The TinyG offers a high level of usability for begin-
ners as well, making it easy to plug and play with the appropriate hardware.
When comparing TinyG to other big names in the motion controller world
such as Rambo, Azteeg, RAMPS, or Smoothieboard, the basic functionality
remains consistent across the proverbial board. Where TinyG differs is in its
firmware, and trajectory generation methods. It is common to find constant
acceleration motion planning, slightly less common to find jerk controlled
motion planning, and very rare to find motion planning to an order higher
than the fourth. This is where TinyG steps in and takes over. As far as
Synthetos knows, sixth order motion planning has not been used anywhere
else in commercial CNC products. This is also where this TinyG project has
concluded. New trajectory generation algorithms were developed at a point
where there as not adequate time to refine, and implement a new method.
Because of this, testing the TinyG trajectory method against methods that
should be lower tier was not possible, and no conclusions can be drawn about
the effect of their revolutionary 6th order trajectory generation methods.
37
and revolutionary method to older more common methods. In addition to
this, understanding how the Encoder section of TinyGs firmware works is
important, especially if this technology ever transfers to a servomotor based
machine as opposed to stepper motor based.
Appendices
A Using the Hardware
Setting up the TinyG and hardware is straightforward if a going for a plug
and play session. There are a few important steps in the process that must
be done carefully to ensure proper function of the TinyG and hardware. Ad-
ditional steps are highlighted after the general setup to cover cases involving
changing firmware, setting up CoolTerm, and configuring TinyG parameters.
Connecting the TinyG to a power source is the first step to getting things
up and running. It is designed to work best with a 24V source, but can
operate anywhere between 12-30V. When connecting power to the TinyG,
it is important to get the polarity right to prevent burning out the board.
Sometimes, the power supplies in the ITLL fail to power the TinyG correctly.
If everything looks to be hooked up correctly, but the machine will not move
when given commands, it is likely a power supply issue. Trying a different
power supply may fix the problem.
After powering the TinyG, open CoolTerm and click the connect button
at the top-middle of the screen. This could automatically connect CoolTerm
to the TinyG. Note that TinyG needs to be powered before this connection
can be established. Now select options, and set the Baudrate to 115200, and
select XON flow control. Navigate to the terminal tab and select Line Mode
under terminal options. This allows you to enter single line commands to
send to the TinyG to execute moves or set parameters.
Next, check to make sure all the important parameters of the TinyG are
what they should be. These include: microstepping mode, max velocity, max
feedrate, max jerk, motor polarity, motor mapping, and limit switch mode.
If changing firmware version, these will need to be changed back to correct
parameters for this setup. If these values have been set in a previous session,
and the same firmware is being used, there is no need to re-enter these values.
For this setup, the following values should be used.
38
Figure 20: Table with important parmaeters to set in the TinyG firmware.
Note that to enable limit switch functionality, all eight limit switch pa-
rameters must be configured. After these parameters have been set, manually
move the effector to the bottom right corner of the machine without hitting
the limit switches. This is the lowest point on the bed, and is used to set
the zero position for the z axis if the pen is to be used. Because the bed
is not level, and there is no z limit switch, this procedure must be followed
every time there is a manual, or limit switch shutdown. Make sure the power
management mode for the z axis is set to 2. This can be done by typing
$3pm=2 in the command line. This sets the z motor to only be active dur-
ing a move, and disabled when not moving. Next, send the command G1
Z0.2 F1000. This will move the z position up by 0.2mm. Because the pen
holder is under compression, the holder will be pushed back down once the
z motor is disabled, essentially returning the z axis back to 0, even though
the controller thinks it is at 0. From here, loosen the screw holding the pen
in position, and push down one of the colors. The tip of the pen should now
be resting on the bed. Push the pen holder up until it hits the top of the
compression mechanism.
39
Figure 21: Pictoral representation of how to adjust the pen holder to aviod
any slippage.
Apply a small amount of pressure to the top of the pen and tighten the
screw back up to secure the pen in place, without over tightening. Send the
command 3pm=1. This make the z motor active if the machine is turned
on, allowing the pen holder to be rigidly held in place by the motor. Now,
when the z axis is in its zero positon, it will be under a small amount of
compression by about 0.2mm, keeping the tip of the pen on the surface of
the bed. This compression distance increases as the effector is moved from
the bottom right to top left, however the compression mechanism is designed
to account for this change.
With all values configured correctly and the z axis set, the TinyG and
hardware is ready to be used. To send the effector to the home position, the
command G28.2 X0Y0 is used. The TinyG will automatically home itself,
and establish a set of machine coordinates, with (0,0) being the position of
the effector after homing. Now, a G-Code file in .txt format can be sent to the
TinyG by clicking and dragging the .txt file into CoolTerm. Once dropped
in, it will automatically start executing the commands. Alternatively, line
by line commands can be sent directly from CoolTerm.
40
B Updating Firmware
Updating the TinyG firmware can be done several different ways. If updating
to a Synthetos release, the TinyG updater app is recommended, which can be
downloaded from the TinyG wiki. This app has detailed instructions and is
simple to use. There are three different firmware versions to select from. The
master branch will be the bug free version, and edge/dev branches are new
developments that are not quite ready for release. When updating custom
written firmware, it is recommended to use Atmel Studio 7.0, along with the
avrdude tool. Atmel Studio is used to generate the .hex file that is needed
to reprogram the TinyG. To create the .hex file, all of the TinyG firmware
files must be compiled together. The firmware can be downloaded from the
Synthetos website, and opened as a new project in Atmel Studio. With the
firmware downloaded open Atmel Studio and select open project/solution
file. Navigate to the folder containing
\firmware\tinyg.
In this folder, there should be a .cproj file. Open this, and all the files
for the firmware will be opened up. These can now be modified. When
ready to save as a hex file, select the Build tab, and click the Build tinyg
option. This will go through the code to verify there are no syntax errors in
the code. Next, click build, and compile. From here, navigate to Solution
Files-Output files and double click tinyg.hex. The file can then be found
by right clicking the tap in Atmel Studio, and selection open containing
folder. Copy this file to the desktop. Next, download or open up the avrdude
file directiory (https://github.com/synthetos/arduino-flash-tools). Copy and
paste the .hex file into the folder:
arduino-flash-tools-master\arduino-flash-tools
-master\tools\_windows\avrdude\bin
Next, open the command prompt and navigate to the folder with the .hex
file. In my case, this was accomplished by typing
cd Desktop\arduino-flash-tools-master (1)\arduino-flash-tools-master
\tools\_windows\avrdude\bin
Now, the file can be uploaded to the TinyG using another specific com-
mand. It is recommended to follow the steps on the TinyG wiki for this
section to avoid error. The final command that ended up working for me was
41
avrdude -C ../etc/avrdude.conf -p x192a3 -c avr109 -b
115200 -P COM3 -e -U flash:w:tinyg_carmelo.hex.
Before sending the command, press the reset button on the TinyG. This
sends TinyG into a mode that allows firmware to be uploaded. From here
there is three seconds to issue the firmware upload command in the command
prompt. There should now be a message saying the firmware is uploading
and the LEDs on the TinyG should be blinking. To verify the firmware
was uploaded correctly, check the version in CoolTerm by typing $FV. Note
that the version number should be changed before compiling the hex file to
provide a means for verification.
t2=-1:h:0;jm=-jm;a0=-a(end);vo=v(end);xo=x(end);
a2=ao+jm*t2;v2=vo+ao*t2+jm*t2.^2/2;
t2=0:h:1;x2=xo+vo*t2+ao*t2.^2/2+jm*t2.^3/6;
ctrl=[0 0;
t(end) v(end);
t(end)+t(end) v2(end)+v(end)];
time=[t t+t(end)];
velocity=[v v2+v(end)];
ty=scatter(ctrl(:,1),ctrl(:,2),’LineWidth’,3,’SizeData’...
,40,’MarkerEdgeColor’,[1 0 0]);
% % % %
% % bezier
% % % %
Vi=0;
Vm=v(end);
k0=Vi;k1=Vi;k2=Vi;k3=Vm;
A=-k0+3*k1-3*k2+k3;
B=3*k0-6*k1+3*k2;C=-3*k0+3*k1;
D=k0;t0=0;p=[D];ii=0;
ffd=[(3*A*h)*ii^2+(3*A*h^2+2*B*h)*ii+(A*h^3+B*h^2+C*h)];
sfd=[6*A*h^2*ii+6*A*h^3+2*B*h^2];
tfd=[6*A*h^3];
num_steps=0:h:time(end)/2;
tb=[0];
for ii=1:(length(num_steps)-2)
ii=ii*h;
ffd2=[(3*A(1)*h)*ii^2+(3*A(1)*h^2+2*B(1)*h)...
*ii+(A(1)*h^3+B(1)*h^2+C(1)*h)];
sfd2=[6*A(1)*h^2*ii+6*A(1)*h^3+2*B(1)*h^2];
tfd2=[6*A(1)*h^3];
42
p=[p p(end)+ffd(end)];
ffd=[ffd ffd2+sfd(end)];
sfd=[sfd tfd(end)+sfd2];
tb=[tb ii];
end
tb1=tb;
bvel=[p];
% convex
Vi=Vm;Vm=velocity(end);
k0=Vi;k1=Vi;k2=Vi;k3=Vm;
A=-k0+3*k1-3*k2+k3;
B=3*k0-6*k1+3*k2;
C=-3*k0+3*k1;D=k0;
t0=(time(end))/2;p2=[D];
ii=0;
ffd=[(3*A*h)*ii^2+(3*A*h^2+2*B*h)*ii+(A*h^3+B*h^2+C*h)];
sfd=[6*A*h^2*ii+6*A*h^3+2*B*h^2];
tfd=[6*A*h^3];
num_steps=0:h:time(end)/2;
tb=[tb t(end)-h];
tb2=[t(end)-h];
for ii=-(length(num_steps)):1:0
ii=ii*h;
ffd2=[(3*A(1)*h)*ii^2+(3*A(1)*h^2+2*B(1)*h)...
*ii+(A(1)*h^3+B(1)*h^2+C(1)*h)];
sfd2=[6*A(1)*h^2*ii+6*A(1)*h^3+2*B(1)*h^2];
tfd2=[6*A(1)*h^3];
p2=[p2 p2(end)+ffd(end)];
ffd=[ffd ffd2+sfd(end)];
sfd=[sfd tfd(end)+sfd2];
tb=[tb ii+2*t(end)];
tb2=[tb2 ii+2*t(end)];
end
bvel=[p p2];
hold on
plot(tb,bvel,’b’,’linewidth’,2);plot(time,velocity,’k’,’linewidth’,2)
legend(’Control Points’,’Bezier’,’Regular Equations’,’location’,’northwest’)
box on;xlabel(’Time’);ylabel(’Velocity’)
References
[1] Curtis Bartley. Forward difference calculation of bezier
curves. http://www.drdobbs.com/forward-difference-calculation-
of-bezier/184403417.
[2] digitalPimple. Stepper motor basics and control - how it works.
https://www.youtube.com/watch?v=bngx2dKl5jU.
[3] Rob Giseburt. Jerk controlled motion explained.
https://github.com/synthetos/TinyG/wiki/Jerk-Controlled-Motion-
Explained.
43
[4] Alden Hart. Setting motor current.
https://github.com/synthetos/TinyG/wiki/Connecting-TinyGsetting-
motor-current.
44