Merge branch 'main' into dev

This commit is contained in:
Alexander Richter 2023-05-02 13:53:00 +02:00
commit da66118131
6 changed files with 1387 additions and 76 deletions

2
.gitignore vendored
View File

@ -1,2 +1,2 @@
.vscode
.vscode/arduino.json

1162
ArduinoChip.svg Normal file

File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 46 KiB

View File

@ -20,9 +20,7 @@
To begin Transmitting Ready is send out and expects to receive E: to establish connection. Afterwards Data is exchanged.
Data is only send everythime it changes once.
LinuxCNC HAL Pins:
Inputs = 'I' -write only -Pin State: 0,1
Inputs & Toggle Inputs = 'I' -write only -Pin State: 0,1
Outputs = 'O' -read only -Pin State: 0,1
PWM Outputs = 'P' -read only -Pin State: 0-255
Digital LED Outputs = 'D' -read only -Pin State: 0,1
@ -61,14 +59,20 @@ Communication Status = 'E' -read/Write -Pin State: 0:0
//###################################################IO's###################################################
//#define INPUTS //Use Arduino IO's as Inputs. Define how many Inputs you want in total and then which Pins you want to be Inputs.
#define INPUTS //Use Arduino IO's as Inputs. Define how many Inputs you want in total and then which Pins you want to be Inputs.
#ifdef INPUTS
const int Inputs = 16; //number of inputs using internal Pullup resistor. (short to ground to trigger)
int InPinmap[] = {32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47};
const int Inputs = 5; //number of inputs using internal Pullup resistor. (short to ground to trigger)
int InPinmap[] = {37,38,39,40,41};
#endif
//Use Arduino IO's as Toggle Inputs, which means Inputs (Buttons for example) keep HIGH State after Release and Send LOW only after beeing Pressed again.
#define SINPUTS //Define how many Toggle Inputs you want in total and then which Pins you want to be Toggle Inputs.
#ifdef SINPUTS
const int sInputs = 5; //number of inputs using internal Pullup resistor. (short to ground to trigger)
int sInPinmap[] = {32,33,34,35,36};
#endif
//#define OUTPUTS //Use Arduino IO's as Outputs. Define how many Outputs you want in total and then which Pins you want to be Outputs.
#define OUTPUTS //Use Arduino IO's as Outputs. Define how many Outputs you want in total and then which Pins you want to be Outputs.
#ifdef OUTPUTS
const int Outputs = 9; //number of outputs
int OutPinmap[] = {10,9,8,7,6,5,4,3,2,21};
@ -166,8 +170,8 @@ If you use STATUSLED, it will also take the colors of your definition here.
const int DLEDBrightness = 70; //Brightness of the LED's 0-100%
int DledOnColors[DLEDcount][3] = {
{0,0,255},
{255,0,0},
{0,255,255},
{0,255,0},
{0,255,0},
{0,255,0},
@ -178,7 +182,7 @@ If you use STATUSLED, it will also take the colors of your definition here.
int DledOffColors[DLEDcount][3] = {
{0,0,0},
{0,255,0},
{0,0,0},
{255,0,0},
{255,0,0},
{255,0,0},
@ -205,6 +209,7 @@ const int numCols = 4; // Define the number of columns in the matrix
const int rowPins[numRows] = {2, 3, 4, 5};
const int colPins[numCols] = {6, 7, 8, 9};
//####################################### END OF CONFIG ###########################
int keys[numRows][numCols] = {
{1,2,3,4},
@ -217,15 +222,24 @@ int lastKey= 0;
#endif
//#define DEBUG
//###Misc Settings###
const int timeout = 10000; // timeout after 10 sec not receiving Stuff
const int debounceDelay = 50;
//#define DEBUG
//Variables for Saving States
#ifdef INPUTS
int InState[Inputs];
int oldInState[Inputs];
unsigned long lastInputDebounce[Inputs];
#endif
#ifdef SINPUTS
int sInState[sInputs];
int soldInState[sInputs];
int togglesinputs[sInputs];
unsigned long lastsInputDebounce[sInputs];
#endif
#ifdef OUTPUTS
int OutState[Outputs];
@ -279,6 +293,16 @@ void setup() {
oldInState[i] = -1;
}
#endif
#ifdef SINPUTS
//setting Inputs with internal Pullup Resistors
for(int i= 0; i<sInputs;i++){
pinMode(sInPinmap[i], INPUT_PULLUP);
soldInState[i] = -1;
togglesinputs[i] = 0;
}
#endif
#ifdef AINPUTS
for(int i= 0; i<AInputs;i++){
@ -346,6 +370,9 @@ void loop() {
#ifdef INPUTS
readInputs(); //read Inputs & send data
#endif
#ifdef SINPUTS
readsInputs(); //read Inputs & send data
#endif
#ifdef AINPUTS
readAInputs(); //read Analog Inputs & send data
#endif
@ -499,13 +526,39 @@ int readAInputs(){
void readInputs(){
for(int i= 0;i<Inputs; i++){
int State = digitalRead(InPinmap[i]);
if(InState[i]!= State){
if(InState[i]!= State && millis()- lastInputDebounce[i] > debounceDelay){
InState[i] = State;
sendData('I',InPinmap[i],InState[i]);
lastInputDebounce[i] = millis();
}
}
}
#endif
#ifdef SINPUTS
void readsInputs(){
for(int i= 0;i<sInputs; i++){
sInState[i] = digitalRead(sInPinmap[i]);
if (sInState[i] != soldInState[i] && millis()- lastsInputDebounce[i] > debounceDelay){
// Button state has changed and debounce delay has passed
if (sInState[i] == LOW || soldInState[i]== -1) { // Stuff after || is only there to send States at Startup
// Button has been pressed
togglesinputs[i] = !togglesinputs[i]; // Toggle the LED state
if (togglesinputs[i]) {
sendData('I',sInPinmap[i],togglesinputs[i]); // Turn the LED on
}
else {
sendData('I',sInPinmap[i],togglesinputs[i]); // Turn the LED off
}
}
soldInState[i] = sInState[i];
lastsInputDebounce[i] = millis();
}
}
}
#endif
#ifdef ABSENCODER
int readAbsKnob(){
@ -584,7 +637,6 @@ void commandReceived(char cmd, uint16_t io, uint16_t value){
controlDLED(io,value);
}
#endif
if(cmd == 'E'){
lastcom=millis();
}

156
README.md
View File

@ -1,53 +1,79 @@
# LinuxCNC_ArduinoConnector
By Alexander Richter, info@theartoftinkering.com 2022
please consider supporting me on Patreon: https://www.patreon.com/theartoftinkering
For my CNC Machine i wanted to include more IO's than my Mesa card was offering. This Projekt enables to connect Arduino to LinuxCNC to include as many IO's as you wish.
<img src="/ArduinoChip.svg" width="250" align="right">
This Software is used as IO Expansion for LinuxCNC. Here i am using a Mega 2560.
By Alexander Richter, info@theartoftinkering.com 2022
please consider supporting me on Patreon:
https://www.patreon.com/theartoftinkering
Website: https://theartoftinkering.com
Youtube: https://youtube.com/@theartoftinkering
This Projekt enables you to connect an Arduino to LinuxCNC and provides as many IO's as you could ever wish for.
This Software is used as IO Expansion for LinuxCNC.
## It is NOT intended for timing and security relevant IO's. Don't use it for Emergency Stops or Endstop switches! ##
+++It is NOT intended for timing and security relevant IO's. Don't use it for Emergency Stops or Endstop switches!+++
You can create as many digital & analog Inputs, Outputs and PWM Outputs as your Arduino can handle.
You can also generate "virtual Pins" by using latching Potentiometers, which are connected to one analog Pin, but are read in Hal as individual Pins.
It also supports Digital LEDs such as WS2812 or PL9823. This way you can have as many LEDs as you want and you can also define the color of them with just one Pin.
In LinuxCNC each LED is listed as one Output that can be set to HIGH and LOW. For both States you can define a color per LED.
This way, you can make them turn on or shut off or have them Change color, from Green to Red for example.
Currently the Software provides:
- analog Inputs
- digital Inputs
- digital Outputs
- support of Digital RGB LEDs like WS2812 or PL9823
- latching Potentiometers
- 1 absolute encoder input
Currently the Software Supports:
- Analog Inputs
- Digital Inputs
- Digital Outputs
- PWM Outputs
- Digital RGB LEDs like WS2812 or PL9823
- latching Potentiometers / Selector Switches
- 1 absolute encoder Selector Switch
TODO
- Matrix Keyboard Support
- Rotary Encoder Input
# compatiblity
Should this be supported?
- RC Servo Support
# Compatiblity
This software works with LinuxCNC 2.8, 2.9 and 2.10.
For 2.8 however you have to change #!/usr/bin/python3.9 in the first line of arduino.py to #!/usr/bin/python2.7.
# Configuration
To Install LinuxCNC_ArduinoConnector.ino on your Arduino first work through the settings in the beginning of the file.
The Settings are commented in the file.
To test you Arduino you can connect to it after flashing with the Arduino IDE. Set your Baudrate to 115200.
In the Beginning the ARduino will Spam ```E0:0``` to the console. This is used to establish connection.
Just return ```E0:0``` to it. You can now communicate with the Arduino. Further info is in the Chapter [Serial Communication](#serial-communication-over-usb)
# Installation
- configure the Firmware file to your demands and flash it to your arduino
- connect the arduino to your LinuxCNC Computer via USB
- install python-serial
sudo apt-get install python-serial
- edit arduino.py to match your arduino settings.
- also check if the Serial adress is correct for your Arduino. I found it easyest to run "sudo dmesg | grep tty" in Terminal.
- move arduino.py to /usr/bin and make it executable with chmod +x
sudo chmod +x arduino.py
sudo cp arduino.py /usr/bin/arduino
1. configure the Firmware file to your demands and flash it to your arduino
2. connect the arduino to your LinuxCNC Computer via USB
3. install python-serial
```sudo apt-get install python-serial```
4. edit arduino.py to match your arduino settings. If you're running 2.8 change
#!/usr/bin/python3.9 in the first line of arduino.py to #!/usr/bin/python2.7.
5. also check if the Serial adress is correct for your Arduino. I found it easyest to run
```sudo dmesg | grep tty``` in Terminal while plugging and unplugging the arduino a couple of times and whatch which entry is changing.
6. make arduino.py executable with chmod +x, delete the suffix .py and copy
it to /usr/bin
```sudo chmod +x arduino.py ```
```sudo cp arduino.py /usr/bin/arduino ```
7. add this entry to the end of your hal file: ```loadusr arduino```
- add to your hal file: loadusr arduino
# Testing
To test your Setup, you can run "halrun" in Terminal.
To test your Setup, you can run ```halrun``` in Terminal.
Then you will see halcmd:
Enter "loadusr arduino" and then "show pin"
Enter ```loadusr arduino``` and then ```show pin```
All the Arduino generated Pins should now be listed and the State they are in.
You can click buttons now and if you run show pin again the state should've changed.
@ -60,22 +86,78 @@ You can now use arduino pins in your hal file.
Pin Names are named arduino.[Pin Type]-[Pin Number]. Example:
arduino.digital-in-32 for Pin 32 on an Arduino Mega2560
# Analog Inputs
These are used for example to connect Potentiometers. You can add as many as your Arduino has Analog Pins.
The Software has a smoothing parameter, which will remove jitter.
# Digital Inputs
Digital Inputs use internal Pullup Resistors. So to trigger them you just short the Pin to Ground. There are two Digital Input Types implemented.
Don't use them for Timing or Safety relevant Stuff like Endstops or Emergency Switches.
1. INPUTS uses the spezified Pins as Inputs. The Value is parsed to LinuxCNC dirketly. There is also a inverted Parameter per Pin.
2. Trigger INPUTS (SINPUTS) are handled like INPUTS, but simulate Latching Buttons. So when you press once, the Pin goes HIGH and stays HIGH, until you press the Button again.
# Digital Outputs
Digital Outputs drive the spezified Arduinos IO's as Output Pins. You can use it however you want, but don't use it for Timing or Safety relevant Stuff like Stepper Motors.
# support of Digital RGB LEDs like WS2812 or PL9823
Digital LED's do skale very easily, you only need one Pin to drive an infinite amount of them.
To make implementation in LinuxCNC easy you can set predefined LED RGB colors.
You can set a color for "on" and "off" State for each LED.
LED colors are set with values 0-255 for Red, Green and Blue. 0 beeing off and 255 beeing full on.
Here are two examples:
1. This LED should be glowing Red when "on" and just turn off when "off".
The Setting in Arduino is:
```int DledOnColors[DLEDcount][3] = {{255,0,0}};```
```int DledOffColors[DLEDcount][3] = {{0,0,0}};```
2. This LED should glow Green when "on" and Red when "off".
```int DledOnColors[DLEDcount][3] = {{0,255,0}};```
```int DledOffColors[DLEDcount][3] = {{255,0,0}};```
Depending on the used LED Chipset, Color sequence can vary. Please try, which value correspons to which color with your LED's.
Typically it should be R G B for WS2812 and G R B for PL9823.
You can mix both in one chain, just modify the color values accordingly.
# Latching Potentiometers / Selector Switches
This is a special Feature for rotary Selector Switches. Instead of loosing one Pin per Selection you can turn your Switch in a Potentiometer by soldering 10K resistors between the Pins and connecting the Selector Pin to an Analog Input.
The Software will divide the Measured Value and create Hal Pins from it. This way you can have Selector Switches with many positions while only needing one Pin for it.
# 1 binary encoded Selector Switch input / absolute encoder
Some rotary Selector Switches work with Binary Encoded Positions. The Software Supports Encoders with 32 Positions. (this could be more if requested)
For each Bit one Pin is needed. So for all 32 Positions 5 Pins are needed = 1,2,4,8,16
If this feature is enabled, 32 Hal Pins will be created in LinuxCNC.
# Status LED
The Arduino only works, if LinuxCNC is running and an USB Connection is established.
To give optical Feedback of the State of the connection a Status LED setting is provided.
This can be either an LED connected to an Output Pin or you can select one LED in your Digital LED Chain.
- It will flash slowly after startup, when it waits for communication setup by LinuxCNC.
- It will glow constantly when everything works.
- it Will flash short when Connection was lost.
# Serial communication over USB
The Send and receive Protocol is <Signal><PinNumber>:<Pin State>
To begin Transmitting Ready is send out and expects to receive E: to establish connection. Afterwards Data is exchanged.
Data is only send everythime it changes once.
After Bootup the Arduino will continuously print E0:0 to Serial. Once the Host Python skript runs and connects, it will answer and hence the Arduino knows, the connection is established.
Inputs = 'I' -write only -Pin State: 0,1
Outputs = 'O' -read only -Pin State: 0,1
PWM Outputs = 'P' -read only -Pin State: 0-255
Digital LED Outputs = 'D' -read only -Pin State: 0,1
Analog Inputs = 'A' -write only -Pin State: 0-1024
Latching Potentiometers = 'L' -write only -Pin State: 0-max Position
Absolute Encoder input = 'K' -write only -Pin State: 0-32
For testing you can still connect to it with your Serial terminal. Send ```E0:0```, afterwards it will listen to your commands and post Input Changes.
Command 'E0:0' is used for connectivity checks and is send every 5 seconds as keep alive signal. If connection is lost the arduino begins flashing an LED to alarm the User.
Data is always only send once, everytime it changes.
| Signal | Header |direction |Values |
| ------------- | ------------- |------------- |------------- |
| Inputs & Toggle Inputs | I | write only |0,1 |
| Outputs | O | read only |0,1 |
| PWM Outputs | P | read only |0-255 |
| Digital LED Outputs | D | read only |0,1 |
| Analog Inputs | A | write only |0-1024 |
| Latching Potentiometers | L | write only |0-max Position|
| Absolute Encoder input | K | write only |0-32 |
| Connection established | E | read/ write |0:0 |
Command 'E0:0' is used for connectivity checks and is send every 5 seconds as keep alive signal. If it is not received in Time, the connection is lost and the arduino begins flashing an LED to alarm the User. It will however work the same and try to send it's Data to the Host.
# License
This program is free software; you can redistribute it and/or modify
@ -88,4 +170,4 @@ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

67
arduino.py Executable file → Normal file
View File

@ -21,7 +21,7 @@ import serial, time, hal
# To begin Transmitting Ready is send out and expects to receive E: to establish connection. Afterwards Data is exchanged.
# Data is only send everythime it changes once.
# Inputs = 'I' -write only -Pin State: 0,1
# Inputs & Toggle Inputs = 'I' -write only -Pin State: 0,1
# Outputs = 'O' -read only -Pin State: 0,1
# PWM Outputs = 'P' -read only -Pin State: 0-255
# Digital LED Outputs = 'D' -read only -Pin State: 0,1
@ -46,34 +46,40 @@ import serial, time, hal
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
c = hal.component("arduino") #name that we will cal pins from in hal
connection = '/dev/ttyACM0'
c = hal.component("arduino") #name that we will cal pins from in hal
connection = '/dev/ttyACM0' #this is the port your Arduino is connected to. You can check with ""sudo dmesg | grep tty"" in Terminal
# Set how many Inputs you have programmed in Arduino and which pins are Inputs
Inputs = 16
InPinmap = [32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48]
# Set how many Inputs you have programmed in Arduino and which pins are Inputs, Set Inputs = 0 to disable
Inputs = 5
InPinmap = [37,38,39,40,41]
# Set how many Outputs you have programmed in Arduino and which pins are Outputs
Outputs = 9
OutPinmap = [10,9,8,7,6,5,4,3,2,21]
# Set how many PWM Outputs you have programmed in Arduino and which pins are PWM Outputs
PwmOutputs = 2
PwmOutPinmap = [11,12]
# Set how many Analog Inputs you have programmed in Arduino and which pins are Analog Inputs
AInputs = 1
AInPinmap = [1]
# Set how many Toggled ("sticky") Inputs you have programmed in Arduino and which pins are Toggled Inputs , Set SInputs = 0 to disable
SInputs = 5
sInPinmap = [32,33,34,35,36]
# Set how many Latching Analog Inputs you have programmed in Arduino and how many latches there are
LPoti = 2
LPotiLatches = [[2,9],
[3,4]]
# Set how many Outputs you have programmed in Arduino and which pins are Outputs, Set Outputs = 0 to disable
Outputs = 9 #9 Outputs, Set Outputs = 0 to disable
OutPinmap = [10,9,8,7,6,5,4,3,2,21]
# Set how many PWM Outputs you have programmed in Arduino and which pins are PWM Outputs, you can set as many as your Arduino has PWM pins. List the connected pins below.
PwmOutputs = 2 #number of PwmOutputs, Set PwmOutputs = 0 to disable
PwmOutPinmap = [11,12] #PwmPutput connected to Pin 11 & 12
# Set how many Analog Inputs you have programmed in Arduino and which pins are Analog Inputs, you can set as many as your Arduino has Analog pins. List the connected pins below.
AInputs = 1 #number of AInputs, Set AInputs = 0 to disable
AInPinmap = [1] #Potentiometer connected to Pin 1 (A0)
# Set how many Latching Analog Inputs you have programmed in Arduino and how many latches there are, you can set as many as your Arduino has Analog pins. List the connected pins below.
LPoti = 2 #number of LPotis, Set LPoti = 0 to disable
LPotiLatches = [[2,9], #Poti is connected to Pin 2 (A1) and has 9 positions
[3,4]] #Poti is connected to Pin 3 (A2) and has 4 positions
# Set if you have an Absolute Encoder Knob and how many positions it has (only one supported, as i don't think they are very common and propably nobody uses these anyway)
AbsKnob = 1
# Set AbsKnob = 0 to disable
AbsKnob = 0 #1 enable
AbsKnobPos = 32
# Set how many Digital LED's you have connected.
@ -120,6 +126,7 @@ Destination = [ #define, which Key should be inserted in LinuxCNC as Input or a
Debug = 0
Debug = 0 #only works when this script is run from halrun in Terminal. "halrun","loadusr arduino" now Debug info will be displayed.
######## End of Config! ########
olddOutStates= [0]*Outputs
oldPwmOutStates=[0]*PwmOutputs
@ -128,12 +135,18 @@ oldPwmOutStates=[0]*PwmOutputs
if LinuxKeyboardInput:
import subprocess
# Inputs and Toggled Inputs are handled the same.
# For DAU compatiblity we set them up seperately.
# Here we merge the arrays.
Inputs = Inputs+ SInputs
InPinmap += sInPinmap
######## SetUp of HalPins ########
# setup Input halpins
for port in range(Inputs):
c.newpin("dIn.{}".format(InPinmap[port]), hal.HAL_BIT, hal.HAL_OUT)
c.newparam("dIn.{}-invert".format(InPinmap[port]), hal.HAL_BIT, hal.HAL_OUT)
c.newparam("dIn.{}-invert".format(InPinmap[port]), hal.HAL_BIT, hal.HAL_RW)
# setup Output halpins
for port in range(Outputs):
@ -178,6 +191,8 @@ arduino = serial.Serial(connection, 115200, timeout=1, xonxoff=False, rtscts=Fal
firstcom = 0
event = time.time()
timeout = 9 #send something after max 9 seconds
######## Functions ########
def keepAlive(event):
@ -236,7 +251,7 @@ def managageOutputs():
while True:
try:
data = arduino.readline().decode('utf-8')
data = arduino.readline().decode('utf-8') #read Data received from Arduino and decode it
if (Debug):print ("I received:{}".format(data))
data = data.split(":",1)
@ -325,9 +340,9 @@ while True:
if (Debug):print ("I received garbage")
arduino.flush()
if firstcom == 1: managageOutputs()
if firstcom == 1: managageOutputs() #if ==1: E0:0 has been exchanged, which means Arduino knows that LinuxCNC is running and starts sending and receiving Data
if keepAlive(event):
if keepAlive(event): #keep com alive. This is send to help Arduino detect connection loss.
arduino.write(b"E:\n")
if (Debug):print("keepAlive")
event = time.time()

View File