CNCShieldServer Arduino Sketch

This sketch can generate basic motion for three stepper motors from ASCII commands sent from a host. It uses the TimerOne library to set up a fast timer interrupt for generating step pulses.

The TimerOne library can be installed from within the Arduino IDE by opening the Library Manager via the Sketch/Include Library/Manage Libraries... menu option.

The sketch files can be found in the CNCShieldServer folder, and are also available in a single zip file.

For an example of scripting motions over a serial port from a host using Python, please see Python Stepper Scripting.

Top-Level Functions

void setup(void)

Standard Arduino initialization function to configure the system.

void loop(void)

Standard Arduino polling function to handle all I/O and periodic processing. This loop should never be allowed to stall or block so that all tasks can be constantly serviced.

void stepper_output_interrupt(void)

Interrupt handler to update all the stepper motor channels. Note that this is called from a timer interrupt context, so it should take as little time as feasible and cannot use serial I/O (i.e. no debugging messages).

Global Values

CncStepper x_axis(X_AXIS_STEP_PIN, X_AXIS_DIR_PIN)

Control objects for the stepper channels. The declaration statically initializes the global state objects for the channels. Note that this does not initialize the hardware; that is performed in setup().

CncStepper y_axis(Y_AXIS_STEP_PIN, Y_AXIS_DIR_PIN)
CncStepper z_axis(Z_AXIS_STEP_PIN, Z_AXIS_DIR_PIN)

ASCII Messaging Protocol

static void parse_input_message(int argc, char *argv[])

Process an input message. Unrecognized commands are silently ignored. argc - number of argument tokens argv - array of pointers to strings, one per token

static void hardware_input_poll(void)

Polling function to read and send specific input values at periodic intervals.

static void serial_input_poll(void)

Polling function to process messages arriving over the serial port. Each iteration through this polling function processes at most one character. It records the input message line into a buffer while simultaneously dividing it into ‘tokens’ delimited by whitespace. Each token is a string of non-whitespace characters, and might represent either a symbol or an integer. Once a message is complete, parse_input_message() is called.

CncStepper Step Generator Class

class CncStepper

An instance of this class manages generation of step and direction signals for one stepper motor.

Public Functions

CncStepper(uint8_t step_pin, uint8_t dir_pin)

Main constructor. The arguments are the pin numbers for the step and direction outputs. Note: this does not initialize the underlying hardware.

void pollForInterval(unsigned long interval)

Main polling function to be called as often as possible. This may be called from a timer interrupt. The interval argument is the duration in microseconds since the last call.

void incrementTarget(long offset)

Add a signed offset to the target position. The units are dimensionless ‘steps’. If using a microstepping driver, these may be less than a physical motor step.

void setTarget(long position)

Set the absolute target position.

long currentPosition(void)

Return the current position in dimensionless ‘steps’.

void setSpeed(int speed)

Set a constant speed in steps/second. Note that the value must be non-zero and positive. The maximum rate available is a function of the polling rate.

Private Members

uint8_t step_pin

the I/O pins for this channel designated using the Arduino convention

uint8_t dir_pin
long target

the target position in dimensionless step counts

unsigned long step_interval

the interval in microseconds between steps

long position

the current position in dimensionless step counts

unsigned long elapsed

the time elapsed in microseconds since the last step occurred

Main Source Code

The main top-level code is in CNCShieldServer.ino.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
/// \file CNCShieldServer.ino
/// \ingroup CNCShieldServer
/// \brief Simplified hardware I/O server for the CNC Arduino Shield using a simple message protocol.

/// \copyright Written over 2014-2018 by Garth Zeglin <garthz@cmu.edu>.  To the
///            extent possible under law, the author has dedicated all copyright
///            and related and neighboring rights to this software to the public
///            domain worldwide.  This software is distributed without any
///            warranty.  You should have received a copy of the CC0 Public
///            Domain Dedication along with this software.  If not, see
///            <http://creativecommons.org/publicdomain/zero/1.0/>.
///
/// \details This example is intended as a starting point for creating custom
///          firmware for the CNC Shield with A4988 stepper motor drivers.  It
///          includes a simple ASCII protocol for sending motion commands to
///          ease connecting to dynamic code (e.g. Python) running on a laptop
///          or Raspberry Pi.

// This program assumes that:

//  1. three A4988 stepper motor drivers are connected following the CNC Shield pin conventions.
//  2. the TimerOne library is installed

#include "cnc_shield.h"
#include "CncStepper.h"
#include "TimerOne.h"

/****************************************************************/
/**** ASCII messaging scheme ************************************/
/****************************************************************/

// The message protocol is based on commands encoded as a sequence of string
// tokens and integers in a line of text.  One line is one message.  All the
// input message formats begin with a string naming a specific command or
// destination followed by one or two argument integers.  The output formats are
// similar but include more general debugging output with a variable number of
// tokens.

// The following message formats are recognized by this program.

// Command	Arguments		Meaning
// ping                                 query whether the server is running
// poll         <value>                 set the input polling rate, value is milliseconds
// enable       <value>                 enable or disable driver output, value is 0 or non-zero
// goto         <x> <y> <z>             move to the absolute position in steps
// x            <position>              absolute X axis move
// y            <position>              absolute Y axis move
// z            <position>              absolute Z axis move
// dx           <offset>                incremental X axis move
// dy           <offset>                incremental Y axis move
// dz           <offset>                incremental Z axis move
// sx           <speed>                 set the X axis speed in steps/second
// sy           <speed>                 set the Y axis speed in steps/second
// sz           <speed>                 set the Z axis speed in steps/second
// led		<value>			controls the built-in LED, value is 0 or non-zero
// pwm		<pin> <value>		PWM control on given pin
// dig		<pin> <value>		digital output on given pin, value is 0 or non-zero

// Additional messages can be added by inserting code in the user_message_#() functions below.

// This program generates the following messages:

// Command	Arguments		Meaning
// awake                                initialization has completed or ping was received
// txyz         <usec> <x> <y> <z>      Arduino clock time in microseconds, followed by absolute step position
// dbg		<value-or-token>+	debugging message to print for user
// led		<value>			reply with current LED state

/****************************************************************/
/**** Global variables and constants ****************************/
/****************************************************************/

// The baud rate is the number of bits per second transmitted over the serial port.
#define BAUD_RATE 115200

// Interval in milliseconds between status messages.
static unsigned int hardware_polling_interval = 200; // 5 Hz message rate to start

// Some versions of the Arduino IDE don't correctly define this symbol for an
// Arduino Uno.  Note that this pin definition is potentially shared with
// SPINDLE_DIR_PIN.
#ifndef LED_BUILTIN
#define LED_BUILTIN 13
#endif

/// Control objects for the stepper channels.  The declaration statically
/// initializes the global state objects for the channels.  Note that this does
/// not initialize the hardware; that is performed in setup().
static CncStepper x_axis( X_AXIS_STEP_PIN, X_AXIS_DIR_PIN );
static CncStepper y_axis( Y_AXIS_STEP_PIN, Y_AXIS_DIR_PIN );
static CncStepper z_axis( Z_AXIS_STEP_PIN, Z_AXIS_DIR_PIN );

/// The timestamp in microseconds for the last polling cycle, used to compute
/// the exact interval between stepper motor updates.
static unsigned long last_interrupt_clock = 0;

/****************************************************************/
/****************************************************************/
/// Interrupt handler to update all the stepper motor channels.  Note that this
/// is called from a timer interrupt context, so it should take as little time as
/// feasible and cannot use serial I/O (i.e. no debugging messages).
void stepper_output_interrupt(void)
{
  // read the clock
  unsigned long now = micros();

  // Compute the time elapsed since the last poll.  This will correctly handle wrapround of
  // the 32-bit long time value given the properties of twos-complement arithmetic.
  unsigned long interval = now - last_interrupt_clock;
  last_interrupt_clock = now;

  // Update all the stepper channels. This may emit step signals or simply
  // update the timing and state variables.
  x_axis.pollForInterval(interval);
  y_axis.pollForInterval(interval);
  z_axis.pollForInterval(interval);
}

/****************************************************************/
/****************************************************************/
/// Process an input message.  Unrecognized commands are silently ignored.
///   argc - number of argument tokens
///   argv - array of pointers to strings, one per token

static void parse_input_message(int argc, char *argv[])
{
  // Interpret the first token as a command symbol.
  char *command = argv[0];

  /* -- process zero-argument commands --------------------------- */
  if (argc == 1) {
    if ( string_equal( command, "ping" )) {
      send_message("awake");
    }
  }

  /* -- process one-argument commands --------------------------- */
  else if (argc == 2) {
    long value = atol(argv[1] );

    // Process the 'led' command.
    if ( string_equal( command, "led" )) {
#ifdef LED_BUILTIN
      // turn on the LED if that value is true, then echo it back as a handshake
      digitalWrite(LED_BUILTIN, (value != 0) ? HIGH : LOW);
#endif
      send_message( "led", value );
    }
    
    else if ( string_equal( command, "enable" )) {
      // Enable or disable the stepper motor drivers.  The output is active-low,
      // so this inverts the sense.
      digitalWrite( STEPPER_ENABLE_PIN, (value != 0) ? LOW : HIGH );
    }

    // Set the individual absolute position targets.
    else if ( string_equal( command, "x" ))  x_axis.setTarget(value);
    else if ( string_equal( command, "y" ))  y_axis.setTarget(value);
    else if ( string_equal( command, "z" ))  z_axis.setTarget(value);

    // Apply incremental motion offsets to the stepper target positions.
    else if ( string_equal( command, "dx" ))  x_axis.incrementTarget(value);
    else if ( string_equal( command, "dy" ))  y_axis.incrementTarget(value);
    else if ( string_equal( command, "dz" ))  z_axis.incrementTarget(value);

    // Set the speed for each channel.
    else if ( string_equal( command, "sx" )) x_axis.setSpeed(value);
    else if ( string_equal( command, "sy" )) y_axis.setSpeed(value);
    else if ( string_equal( command, "sz" )) z_axis.setSpeed(value);

    else if ( string_equal( command, "poll" )) {
      // set the hardware polling interval in milliseconds
      if (value > 0)  hardware_polling_interval = value;
      else send_debug_message("invalid poll value");
    }
  } 

  /* -- process two-argument commands --------------------------- */
  else if (argc == 3) {
    int pin   = atoi(argv[1] );
    int value = atoi(argv[2] );

    // Process the 'pwm' command to generate a variable duty-cycle PWM signal on
    // any digital pin.  The value must be between 0 and 255.
    if ( string_equal( command, "pwm" )) {
      analogWrite( pin, value );
      return;
    }

    // Process the 'dig' command to set a pin to output mode and control its level.
    else if ( string_equal( command, "dig" )) {
      pinMode( pin, OUTPUT );
      digitalWrite( pin, value );
      return;
    }
  }

  /* -- process three-argument commands --------------------------- */
  else if (argc == 4 ) {
    long x = atol(argv[1]);
    long y = atol(argv[2]);
    long z = atol(argv[3]);
    
    // Set the absolute target position.
    if ( string_equal( command, "goto" )) {
      x_axis.setTarget(x);
      y_axis.setTarget(y);
      z_axis.setTarget(z);
    }
  }
}

/****************************************************************/
/// Polling function to read and send specific input values at periodic
/// intervals.

// N.B. The timing calculation could be improved to reduce jitter.

static void hardware_input_poll(void)
{
  static unsigned long last_time = 0;
  unsigned long now = millis();

  if ((now - last_time) > hardware_polling_interval) {
    last_time = now;

    // send a time and position reading
    long clock = micros();
    long x = x_axis.currentPosition();
    long y = y_axis.currentPosition();
    long z = z_axis.currentPosition();
    send_message( "txyz", clock, x, y, z );
  }
}

/****************************************************************/
/**** Standard entry points for Arduino system ******************/
/****************************************************************/

/// Standard Arduino initialization function to configure the system.
void setup(void)
{
  // set up the CNC Shield I/O
  digitalWrite( STEPPER_ENABLE_PIN, HIGH ); // initialize drivers in disabled state
  pinMode( STEPPER_ENABLE_PIN, OUTPUT );

  pinMode( X_AXIS_STEP_PIN, OUTPUT );
  pinMode( Y_AXIS_STEP_PIN, OUTPUT );
  pinMode( Z_AXIS_STEP_PIN, OUTPUT );
  pinMode( X_AXIS_DIR_PIN, OUTPUT );
  pinMode( Y_AXIS_DIR_PIN, OUTPUT );
  pinMode( Z_AXIS_DIR_PIN, OUTPUT );

#ifdef LED_BUILTIN
  pinMode( LED_BUILTIN, OUTPUT );
#endif

  // initialize the Serial port
  Serial.begin( BAUD_RATE );

  // set up the timer1 interrupt and attach it to the stepper motor controls
  last_interrupt_clock = micros();
  Timer1.initialize(100); // 100 microsecond intervals, e.g. 10kHz
  Timer1.attachInterrupt( stepper_output_interrupt );

  // additional hardware configuration can go here


  // send a wakeup message
  send_message("awake");
}

/****************************************************************/
/// Standard Arduino polling function to handle all I/O and periodic processing.
/// This loop should never be allowed to stall or block so that all tasks can be
/// constantly serviced.
void loop(void)
{
  serial_input_poll();
  hardware_input_poll();

  // other polled tasks can go here
}

/****************************************************************/
/****************************************************************/