Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Nikolay-Kha committed May 10, 2017
0 parents commit b70dd3c
Show file tree
Hide file tree
Showing 23 changed files with 1,594 additions and 0 deletions.
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
*.pyc
__pycache__
.iws
workspace.xml
tasks.xml
.idea/dictionaries
pycnc.tar.bz2
12 changes: 12 additions & 0 deletions .idea/PyCNC.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions .idea/inspectionProfiles/Project_Default.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions .idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2017 Nikolay Khabarov

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
59 changes: 59 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
This project bring CNC control for ARM based Linux boards like Raspberry Pi.
Typically there is no way to control stepper motors from Linux runtime
environment due to the lack of real time GPIO control. Even kernel based
modules can not guarantee precise control of pulses for steppers. There is
always way out. DMA(Direct Memory Access) is a separated hardware module which
provides high precision for GPIO outputs. This module can copy bytes which
represent GPIO states from RAM buffer directly to GPIO with some clock based
on main chip internal oscillator without using CPU's cores. Using such approach
this project generates impulses for moving stepper motors and that is very
precise way regardless CPU load and OS time jitter.
This approach also allows to use Python language for this project. Typically,
Python is not good choice for real time application, but since project just
needs to set up DMA buffers and hardware will do the rest, Python become the
perfect choice for easy development of this project.

Video demo - [YouTube video](https://youtu.be/vcedo59raS4)

#Current command support
G0, G1, G4, G20, G21, G28, G90, G91, G92, M2, M3, M5, M30
Commands can be easily added, see [gmachine.py](./gmachine.py) file.

#Config
All config is stored in [config.py](./config.py) and contains hardware properties, limitations
and pin names for hardware control.

#Hardware
Currently, this project supports Raspberry Pi 1-3. But there is a way to add new boards.
See [hal.py](./hal.py) file.

#Performance notice
Pure Python interpreter wouldn't provide great performance for high speed machines.
Overspeeding setting causes motors mispulses and probably lose of trajectory. According
to my tests, Raspberry Pi 2 can handle axises with 400 pulses on mm with top velocity ~800 mm
per min. There is always way out! :) Use JIT Python implementation like PyPy. RPi2 can handle
up to 18000 mm per minute on the machine with 80 steps per millimeter motors with PyPy.
_Note: Raspbian has outdated PyPy version in repositories(v4.0). Moreover v4.0 has issue with
`mmap` module implementation. Use PyPy v5.0+, download it for your OS from
[here](https://pypy.org/download.html)._
PyPy installation:
```bash
wget wget https://bitbucket.org/pypy/pypy/downloads/pypy2-v5.7.1-linux-armhf-raspbian.tar.bz2
sudo mkdir /opt/pypy
sudo tar xvf pypy2-v5.7.1-linux-armhf-raspbian.tar.bz2 --directory /opt/pypy/ --strip-components=1
sudo ln -s /opt/pypy/bin/pypy /usr/local/bin/pypy
```

#Dependencies
Nothing. Just pure Python code.

#GCode simulation
Just a link to a nice web software for gcode files emulation (very helpful for manual creating of
gcode files): [https://nraynaud.github.io/webgcode/](https://nraynaud.github.io/webgcode/)

#License
see [LICENSE](./LICENSE) file.

#Author
Nikolay Khabarov

35 changes: 35 additions & 0 deletions config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#!/usr/bin/env python

# Hardware limitations config
STEPPER_PULSE_LINGTH_US = 2
STEPPER_MAX_VELOCITY_MM_PER_MIN = 1800 # mm per min
STEPPER_MAX_ACCELERATION_MM_PER_S2 = 200 # mm per sec^2
STEPPER_PULSES_PER_MM = 400

TABLE_SIZE_X_MM = 200
TABLE_SIZE_Y_MM = 300
TABLE_SIZE_Z_MM = 48

SPINDLE_MAX_RPM = 10000

# Pins config
STEPPER_STEP_PIN_X = 16
STEPPER_STEP_PIN_Y = 20
STEPPER_STEP_PIN_Z = 21

STEPPER_DIR_PIN_X = 13
STEPPER_DIR_PIN_Y = 19
STEPPER_DIR_PIN_Z = 26

SPINDLE_PWM_PIN = 7

ENDSTOP_PIN_X = 12
ENDSTOP_PIN_Y = 6
ENDSTOP_PIN_Z = 5

# Hardware behavior config
# Run command immediately after receiving and stream new pulses, otherwise
# buffer will be prepared firstly and then command will run.
# Before enabling this feature, please make sure that board performance is
# enough for streaming pulses(faster then real time).
INSTANT_RUN = True
86 changes: 86 additions & 0 deletions coordinates.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
#!/usr/bin/env python

import math


class Coordinates(object):
""" This object represent machine coordinates.
Machine supports 3 axis, so there are X, Y and Z.
"""
def __init__(self, x, y, z):
""" Create object.
:param x: x coordinated.
:param y: y coordinated.
:param z: z coordinated.
"""
self.x = round(x, 10)
self.y = round(y, 10)
self.z = round(z, 10)

def is_zero(self):
""" Check if all coordinates are zero.
:return: boolean value.
"""
return self.x == 0.0 and self.y == 0.0 and self.z == 0.0

def is_in_aabb(self, p1, p2):
""" Check coordinates are in aabb(Axis-Aligned Bounding Box).
aabb is specified with two points.
:param p1: First point in Coord object.
:param p2: Second point in Coord object.
:return: boolean value.
"""
minx, maxx = sorted((p1.x, p2.x))
miny, maxy = sorted((p1.y, p2.y))
minz, maxz = sorted((p1.z, p2.z))
if self.x < minx or self.y < miny or self.z < minz:
return False
if self.x > maxx or self.y > maxy or self.z > maxz:
return False
return True

def length(self):
""" Calculate the length of vector.
:return: Vector length.
"""
return math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z)

def round(self, base):
""" Round values to specified base, ie 0.49 with base 0.25 will be 0.5.
:param base: Base.
:return: New rounded object.
"""
return Coordinates(round(self.x / base) * base,
round(self.y / base) * base,
round(self.z / base) * base)

def find_max(self):
""" Find a maximum value of all values.
:return: maximum value.
"""
return max(self.x, self.y, self.z)

# build in function implementation
def __add__(self, other):
return Coordinates(self.x + other.x, self.y + other.y, self.z + other.z)

def __sub__(self, other):
return Coordinates(self.x - other.x, self.y - other.y, self.z - other.z)

def __mul__(self, v):
return Coordinates(self.x * v, self.y * v, self.z * v)

def __div__(self, v):
return Coordinates(self.x / v, self.y / v, self.z / v)

def __truediv__(self, v):
return Coordinates(self.x / v, self.y / v, self.z / v)

def __eq__(self, other):
return self.x == other.x and self.y == other.y and self.z == other.z

def __str__(self):
return '(' + str(self.x) + ', ' + str(self.y) + ', ' + str(self.z) + ')'

def __abs__(self):
return Coordinates(abs(self.x), abs(self.y), abs(self.z))
11 changes: 11 additions & 0 deletions deploy.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#!/bin/sh
set -e
PASS=raspberry
[email protected]
if [ ! -z $1 ]; then
ADDR=$1
fi
tar -cvjSf $(dirname "$0")/pycnc.tar.bz2 $(dirname "$0")/*.py > /dev/null
sshpass -p${PASS} scp $(dirname "$0")/pycnc.tar.bz2 "${ADDR}:~/pycnc"
sshpass -p${PASS} ssh -t ${ADDR} "(cd ~/pycnc && tar xvf pycnc.tar.bz2) > /dev/null" &> /dev/null
sshpass -p${PASS} ssh -t ${ADDR} "sudo pypy ~/pycnc/main.py"
87 changes: 87 additions & 0 deletions gcode.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
#!/usr/bin/env python

import re

from coordinates import Coordinates

gpattern = re.compile('([A-Z])([-+]?[0-9.]+)')
cleanpattern = re.compile('\s+|\(.*?\)|;.*') # white spaces and comments start with ';' and in '()'


class GCodeException(Exception):
""" Exceptions while parsing gcode.
"""
pass


class GCode(object):
""" This object represent single line of gcode.
Do not create it manually, use parse_line() instead.
"""
def __init__(self, params):
""" Create object.
:param params: dict with gcode key-values.
"""
self.params = params

def get(self, argname, default=None, multiply=1.0):
""" Get value from gcode line.
:param argname: Value name.
:param default: Default value if value doesn't exist.
:param multiply: if value exist, multiply it by this value.
:return: Value if exists or default otherwise.
"""
if argname not in self.params:
return default
return float(self.params[argname]) * multiply

def getXYZ(self, default, multiply):
""" Get X, Y and Z values as Coord object.
:param default: Default values, if any of coords is not specified.
:param multiply: If value exist, multiply it by this value.
:return: Coord object.
"""
x = self.get('X', default.x, multiply)
y = self.get('Y', default.y, multiply)
z = self.get('Z', default.z, multiply)
return Coordinates(x, y, z)

def isXYZ(self):
""" Check if at least one of the coordinates is present.
:return: Boolean value.
"""
return 'X' in self.params or 'Y' in self.params or 'Z' in self.params

def command(self):
""" Get value from gcode line.
:return: String with command or None if no command specified.
"""
if 'G' in self.params:
return 'G' + self.params['G']
if 'M' in self.params:
return 'M' + self.params['M']
return None

@staticmethod
def parse_line(line):
""" Parse line.
:param line: String with gcode line.
:return: gcode objects.
"""
line = line.upper()
line = re.sub(cleanpattern, '', line)
if len(line) == 0:
return None
if line[0] == '%':
return None
m = gpattern.findall(line)
if not m:
raise GCodeException('gcode not found')
if len(''.join(["%s%s" % i for i in m])) != len(line):
raise GCodeException('extra characters in line')
params = dict(m)
if len(params) != len(m):
raise GCodeException('duplicated gcode entries')
if 'G' in params and 'M' in params:
raise GCodeException('g and m command found')
return GCode(params)
Loading

0 comments on commit b70dd3c

Please sign in to comment.