grbl
plantimager.controller.scanner.grbl Link
GRBL-based CNC Controller for Plant Imaging Systems.
A concrete implementation of CNC machine control for 3D plant imaging systems using the GRBL firmware. This module enables precise XYZ positioning with millimeter accuracy for X/Y axes and degree accuracy for the rotational Z axis.
Key Features: - Serial communication with GRBL controller boards - Complete 3-axis (X, Y, Z) movement control with position tracking - Support for both synchronous and asynchronous operations - Safety features including position limits and homing procedures - Comprehensive access to GRBL firmware settings - Proper error handling and machine status reporting - Hardware abstraction layer compliant with AbstractCNC interface
Usage Examples:
>>> from plantimager.controller.scanner.grbl import CNC
>>> cnc = CNC("/dev/ttyUSB0") # Connect to GRBL controller
>>> cnc.home() # Perform a homing sequence
>>> cnc.moveto(100, 100, 45) # Move to position (100mm, 100mm, 45°)
>>> x, y, z = cnc.get_position() # Get the current position
>>> cnc.moveto_async(200, 200, 90) # Start asynchronous movement
>>> cnc.wait() # Wait for movement completion
CNC Link
CNC(port='/dev/ttyUSB0', baud_rate=115200)
Bases: AbstractCNC
A concrete implementation of CNC machine control using GRBL firmware.
This class provides functionality to control a CNC machine running GRBL firmware over a serial connection. It supports movement along X, Y, and Z axes, homing, position queries, and both synchronous and asynchronous operations.
Attributes:
Name | Type | Description |
---|---|---|
port |
str
|
Serial port used for communication |
baud_rate |
int
|
Communication baudrate (typically 115200 for Arduino UNO) |
x_lims |
tuple[float, float]
|
Allowed range for X-axis movement |
y_lims |
tuple[float, float]
|
Allowed range for Y-axis movement |
z_lims |
tuple[float, float]
|
Allowed range for Z-axis movement (rotationa axis) |
serial_port |
Serial
|
Serial connection instance |
invert_x |
bool
|
Whether to invert X-axis direction |
invert_y |
bool
|
Whether to invert Y-axis direction |
invert_z |
bool
|
Whether to invert Z-axis direction |
grbl_settings |
dict
|
Current GRBL configuration parameters |
Notes
- All movements are performed in absolute coordinates (G90 mode)
- Units are set to millimeters (G21 mode)
- Position limits are enforced for safety
- Homing is performed on startup
Examples:
>>> from plantimager.controller.scanner.grbl import CNC
>>> cnc = CNC("/dev/ttyACM0") # Initialize CNC connection
>>> cnc.home() # Perform homing sequence
>>> cnc.moveto(100, 100, 50) # Move to position synchronously
>>> x, y, z = cnc.get_position() # Get current position
>>> cnc.moveto_async(200, 200, 50) # Move asynchronously
>>> cnc.wait() # Wait for move to complete
Raises:
Type | Description |
---|---|
ValueError
|
If movement coordinates are outside allowed limits |
RuntimeError
|
If unable to read position from CNC |
SerialException
|
If serial communication fails |
References
- GRBL Commands: https://github.com/gnea/grbl/wiki/Grbl-v1.1-Commands
- G-Code Reference: http://linuxcnc.org/docs/html/gcode/g-code.html
Initializes the GRBL controller.
Source code in plantimager/controller/scanner/grbl.py
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 |
|
x
property
Link
x
Get the current X-axis position of the CNC machine.
Returns:
Type | Description |
---|---|
length_mm
|
The current X-axis position in millimeters. |
Raises:
Type | Description |
---|---|
RuntimeError
|
If unable to read position from CNC controller. |
SerialException
|
If serial communication with GRBL fails. |
See Also
- y : Y-axis position property
- z : Z-axis position property
- get_position : Method to get a complete X,Y,Z position tuple
y
property
Link
y
Get the current Y-axis position of the CNC machine.
Returns:
Type | Description |
---|---|
length_mm
|
The current Y-axis position in millimeters. |
Raises:
Type | Description |
---|---|
RuntimeError
|
If unable to read position from CNC controller. |
SerialException
|
If serial communication with GRBL fails. |
See Also
- x : X-axis position property
- z : Z-axis position property
- get_position : Method to get a complete X,Y,Z position tuple
z
property
Link
z
Get the current Z-axis position of the CNC machine.
Returns:
Type | Description |
---|---|
deg
|
The current Z-axis position in degrees. |
Raises:
Type | Description |
---|---|
RuntimeError
|
If unable to read position from CNC controller. |
SerialException
|
If serial communication with GRBL fails. |
See Also
- x : X-axis position property
- y : Y-axis position property
- get_position : Method to get a complete X,Y,Z position tuple
compute_move_time Link
compute_move_time(x, y, z)
Compute the estimated time required to move the CNC machine to the specified coordinates.
Source code in plantimager/controller/scanner/grbl.py
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 287 |
|
get_grbl_settings Link
get_grbl_settings()
Returns the GRBL firmware settings as a dictionary.
Returns:
Type | Description |
---|---|
dict
|
Dictionary containing GRBL settings in the format {'$param': value}, where: - Keys are parameter identifiers (strings) prefixed with '$' - Values are numeric settings (either int or float) |
Notes
- Clears the input buffer before sending the command to ensure clean communication
- All settings are converted to appropriate numeric types (int or float)
- Parameter identifiers in the returned dictionary include the '$' prefix
- Non-setting responses from GRBL are filtered out
Source code in plantimager/controller/scanner/grbl.py
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 |
|
get_position Link
get_position()
Get the current XYZ position of the CNC machine by querying GRBL controller.
Returns:
Type | Description |
---|---|
length_mm
|
Current X-axis position in millimeters |
length_mm
|
Current Y-axis position in millimeters |
deg
|
Current Z-axis position in degrees |
Raises:
Type | Description |
---|---|
RuntimeError
|
If unable to parse position data from the GRBL response |
SerialException
|
If communication with the serial port fails |
Notes
- Position values are returned in absolute coordinates (
G90
mode) - The method expects GRBL to be properly configured and responding to status queries
- Z-axis is treated as rotational, hence returned in degrees
- Response parsing uses regex to extract position values from a GRBL status message
Source code in plantimager/controller/scanner/grbl.py
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 |
|
get_status Link
get_status()
Query and parse the current status of the GRBL controller.
Returns:
Type | Description |
---|---|
dict or None
|
A dictionary containing the parsed status information with the following keys: - 'status' (str): Current state of the machine (e.g., 'Idle', 'Run') - 'position' (tuple of float): Current (x, y, z) position in mm, with configured axis inversions applied Returns |
Notes
- The response format from GRBL is typically '
', where additional fields may be present depending on GRBL configuration. - This method only extracts the status and machine position information.
- Axis inversions are applied according to the instance's configuration.
Source code in plantimager/controller/scanner/grbl.py
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 |
|
home Link
home()
Performs the GRBL homing cycle and sets machine coordinates.
Notes
The homing procedure consists of two steps:
1. Execute GRBL homing cycle ($H
)
2. Account for pull-off distance by setting machine coordinates (G92
)
The final position is affected by three GRBL settings:
- $27
: Homing pull-off distance
- $23
: Homing direction mask
- $3
: Direction port invert mask
Raises:
Type | Description |
---|---|
RuntimeError
|
If GRBL reports an error during homing or coordinate setting |
References
- GRBL Homing Cycle: https://github.com/gnea/grbl/wiki/Grbl-v1.1-Commands#h---run-homing-cycle
G92
Reference: http://linuxcnc.org/docs/html/gcode/g-code.html#gcode:g92
Source code in plantimager/controller/scanner/grbl.py
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 |
|
moveto Link
moveto(x, y, z)
Move the CNC machine to specified coordinates and wait until the target position is reached.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
length_mm
|
Target position along the X-axis in millimeters. Must be within the machine's x_lims range. |
required |
y
|
length_mm
|
Target position along the Y-axis in millimeters. Must be within the machine's y_lims range. |
required |
z
|
deg
|
Target position along the Z-axis in degrees. Must be within the machine's z_lims range. |
required |
Raises:
Type | Description |
---|---|
ValueError
|
If any of the target coordinates are outside the allowed limits defined in x_lims, y_lims, or z_lims. |
RuntimeError
|
If the movement cannot be completed or position verification fails. |
Notes
- The movement is performed in absolute coordinates (
G90
mode) - Units are in millimeters (
G21
mode) - The method will block until the movement is complete
Source code in plantimager/controller/scanner/grbl.py
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 |
|
moveto_async Link
moveto_async(x, y, z)
Asynchronously move the CNC machine to specified coordinates using G0 rapid positioning.
This method executes a rapid linear movement (G0) to the specified position without waiting for the movement to complete. The movement is executed at maximum speed. Axis inversions are applied based on the machine configuration.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
length_mm
|
Target position along the X-axis in millimeters. Must be within the machine's x_lims range. |
required |
y
|
length_mm
|
Target position along the Y-axis in millimeters. Must be within the machine's y_lims range. |
required |
z
|
deg
|
Target position along the Z-axis in degrees. Must be within the machine's z_lims range. |
required |
Returns:
Type | Description |
---|---|
bytes
|
Response from GRBL after sending the G0 command. b'ok' if successful. '' if still processing. |
Notes
- A small delay (0.1 s) is added after sending the command to prevent buffer overflow
- Movement is executed in absolute coordinates (
G90
mode) - Units are in millimeters (
G21
mode) - Position limits are checked before movement
- This method returns immediately without waiting for movement completion
- Multiple async moves may queue up in GRBL's motion planner
References
http://linuxcnc.org/docs/html/gcode/g-code.html#gcode:g0
Source code in plantimager/controller/scanner/grbl.py
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 |
|
print_grbl_settings Link
print_grbl_settings()
Print the GRBL firmware settings in a formatted, human-readable form.
Notes
The parameter names, units, and descriptions are defined in the GRBL_SETTINGS
constant dictionary in this module.
See Also
GRBL_SETTINGS : Dictionary containing parameter information get_grbl_settings : Method that retrieves current GRBL settings
References
https://github.com/gnea/grbl/wiki/Grbl-v1.1-Configuration#grbl-settings
Source code in plantimager/controller/scanner/grbl.py
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 |
|
send_cmd Link
send_cmd(cmd, wait=False, timeout=None)
Send a command to the GRBL controller and return its response.
Parameters
Parameters
cmd : str
A GRBL-compatible G-code command or system command.
Must be a valid command according to the GRBL command specification.
wait : bool, optional
If wait is True, the method will block until the command is completed or until timeout is reached.
timeout : int, optional
Specifies the maximum time in seconds to wait for the command to complete.
Returns
Returns
bytes
The raw response from the GRBL controller, including any trailing whitespace
and newline characters. Typically ends with 'ok
' for successful commands.
Examples
Examples
>>> from plantimager.controller.scanner.grbl import CNC
>>> cnc = CNC("/dev/ttyUSB0")
>>> response = cnc.send_cmd("G90") # Set absolute positioning mode
>>> print(response.strip())
b'ok'
>>> response = cnc.send_cmd("?") # Get status
>>> print(response.strip())
b'<Idle|MPos:0.000,0.000,0.000|FS:0,0|WCO:0.000,0.000,0.000>'
Notes
Notes
- Includes a 100ms delay after each command to prevent buffer overflow
- Always clears the input buffer before sending new commands
- Logs both sent commands and received responses at debug level
Raises
Raises
serial.SerialException
If there are communication errors with the serial port
serial.SerialTimeoutException
If reading the response times out
References
References
https://github.com/gnea/grbl/wiki/Grbl-v1.1-Commands
Source code in plantimager/controller/scanner/grbl.py
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 |
|
stop Link
stop()
Close the serial connection to the GRBL controller.
Notes
It's recommended to call this method in a try/finally block to ensure proper cleanup
Raises:
Type | Description |
---|---|
SerialException
|
If there's an error while closing the serial port |
Source code in plantimager/controller/scanner/grbl.py
246 247 248 249 250 251 252 253 254 255 256 257 258 259 |
|
wait Link
wait(timeout=60)
Wait for the CNC machine to complete any ongoing operations and returns the last response.
Notes
- This method blocks until a response is received from the device
- Uses a 10 ms delay between polling attempts to prevent CPU overload
- The status query command '?' is part of the GRBL protocol
- This method is typically used after async operations to ensure completion
Raises:
Type | Description |
---|---|
SerialException
|
If there are communication issues with the serial port |
RuntimeError
|
If the serial port is closed or not properly initialized |
TimeoutError
|
If the machine does not respond within the timeout period |
Source code in plantimager/controller/scanner/grbl.py
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 |
|
angle_min_travel Link
angle_min_travel(current_angle, desired_angle)
Calculate the postion of the machine to achieve a desired angle with minimal travel. Minimal travel means that machine_order-current_angle is in [-180, 180]
Source code in plantimager/controller/scanner/grbl.py
86 87 88 89 90 91 92 93 |
|
angle_min_travel_distance Link
angle_min_travel_distance(current_angle, desired_angle)
Calculate the minimal angle the machine has to turn to achieve a desired angle with minimal travel. Minimal travel means that machine_order-current_angle is in [-180, 180]
Source code in plantimager/controller/scanner/grbl.py
95 96 97 98 99 100 101 102 |
|