- Configuring LinuxCNC
- Advanced Configuration
- [SOLVED] How to properly connect LASER and control its power?
[SOLVED] How to properly connect LASER and control its power?
- abs32
- Offline
- New Member
-
Less
More
- Posts: 19
- Thank you received: 0
15 Oct 2025 14:41 - 01 Nov 2025 09:05 #336503
by abs32
[SOLVED] How to properly connect LASER and control its power? was created by abs32
I read forum.linuxcnc.org/10-advanced-configura...pwm-output-for-laser, read Google + AI. The result is zero.
Let's keep it simple. Let's say my configuration doesn't mention anything about the spindle or the laser.
How exactly should I format the hal file?
The scenario is as follows: there is a laser, controlled by PWM via LPT. It has been proven that the laser itself works. It has been proven that PWM also works (because we control the spindle through it).
The documentation indicates that we must set several mandatory parameters. It would seem that this is sufficient.
linuxcnc.org/docs/2.8/html/man/man9/pwmgen.9.html
forum.linuxcnc.org/media/kunena/attachme...19092/FRANKENLAB.hal
forum.linuxcnc.org/media/kunena/attachme...-mill_2019-07-26.hal
#spindle section
loadrt pwmgen output_type=0
addf pwmgen.make-pulses base-thread #enabled PWM frequency signal generation
addf pwmgen.update servo-thread #enabled control synchronization with the servo cycle
net spindle-pwm <= pwmgen.0.pwm #set the name of the signal controlled by the pwmgen.0.pwm signal
net spindle-pwm => parport.0.pin-14-out #set the LPT port pin to which the signal is transmitted
setp pwmgen.0.dither-pwm true #enabled frequency regulation stepping
setp pwmgen.0.pwm-freq 100.0
setp pwmgen.0.scale 24000
The spindle can be controlled normally with these parameters. If you connect a laser PWM to pin 14 instead, the laser should work somehow, either via M68 or M3S24000.
But the laser does not turn on. Only with the forced activation button on the laser body, and immediately at 100% power.
What am I doing wrong?
=================================
Colleagues, English is not my language. Therefore, first I will formulate the idea in my own language and below there will be a translation into international English by a robot.
===============================
Перед нами стоит задача подключения лазера к станку, управляемому LinuxCNC. Не важно, lan or lpt, модель контроллера тоже не имеет значение. Чаще всего подключение необходимо выполнить к станку, у которого уже есть используемый шпиндель.
Самый простой вопрос - это именено работа LinuxCNC, он, зайка, работает без нареканий и легко настраивается. А вот сделать так, чтобы покупаемое в Китае оборудование адекватно работало, на много сложнее и поэтому нам придется затронуть вопросы электрики.
1. Сам лазер. Обычно покупаемый лазер имеет корпус лазера и плату управления мощности (2025г.) К
этой плате подключается3 провода - Плюс 12 (24)В, Минус 12 (24)В - он же GND, и PWM - управление мощностью лазера частотным сигналом. Главный вопрос - где взять этот сигнал? Такой сигнал идет от компьютера к плате управления станком (контроллеру), но ток этого сигнала слишком маленький, лазер его отказыватся понимать. Из этого следует необходимость покупки отдельной платы преобразования сигнала Напряжение-ШИМ. Она может стоит 1-10 долларов и точно будет посредственного качества. Эту плату необходимо подключить и у нее три группы контактов -
1.1. группа питания, Плюс 12 (24)В - его здесь назвали VCC, Минус 12 (24)В - он же GND
1.2. управляющий вход - это сигнальный провод, тот же, который управляет работой инвертора шпинделя, здесь его назвали VIN, и GNG. Но это уже другая Земля, это GND от контроллера станка - замечание важное. Да, все контакты GNG ШИМ генератора замкнуты между собой на плате, поэтому чисто электрически их можно соединить в любом месте "до", но если есть клеммы, почему бы их не использовать по назанчению?
1.3. управляющий выход - сигнальный провод PWM и GND. GND отсюда можено не использовать, а вот PWM покдключить к такому же разъему PWM на лазере.
2. Теперь надо решить вопросы электрики. У нас есть шпиндель и лазер. Если раньше у нас провод управления инвертором шпинделя шел от контроллера станка до инвертора, то теперь от контроллера и от того же контакта (или от этого же провода, но от входа в инвертор) мы тянем длинный провод VIN сигнала к самому лазеру. Отслюда следует несколько необходимых действий -
2.1. надо сделать отдельный выключатель питания инвертора - чтобы при использовании лазера шпиндель не крутился
2.2. надо предусмотреть отключения провода VIN, идущего от контроллера или инвертора к лазеру. Провод этот длинный и на него будут наводки. Если мы этот провод не отключим, то при включении шпинделя наводки будут искажать сигнал VIN и инвертор будет постоянно изменять частоту для шпинделя. Это могут быть такие сильные искажения, что шпиндель станет неуправляемым - вы ему даете сигнал s1000 или даже s0, а он то разгоняется, то тормозит - такие качели.
Важно - китайцы врут с характеристиками. На примере моего лазера якобы мощностью 10вт и током 3.8А реальный ток был 2.6А, т.е. примерно 75%. Вам тоже надо будет провести измерения. Для этого надо аккуратно отвинтить винты крепления платы к корпусу-радиатору лазера и разрезать один из проводов питания диодов, зачистить кончики, облудить и подключить амперметр. Надеть очки (мне повезно - купил много лет назад на барахолке еще кожанные очки сварщика со стеклянными стеклами) и включить лазер без управления мощностью, замерить ток. Выключить (кнопкой на плате) лазер. Подключить провод PWM - как только лазер почувствует подключенный сигнал PWM он перестанет включаться кнопкой на плате. теперь эта кнопка будет означать лишь включения режима готовности РЕАГИРОВАТЬ на сигнал PWM.
Итак, все настройки LinuxCNC у нас пока еще такие, какие были при работе со шпинделем, ничего не меняем. Командой M3 даем команду включить шпиндель. Затем командой s24000 включаем на "полную мощность" (согласно настройкам ini станка, о чем ниже) и измеряем ток. Затем даем другие команды S12000 и пробуем другие значения, записываем показания тока. Дело в том, что китайцы и здесь врут. Купленная плата ШИМ точно не даст 100% мощности (здесь мы имеем ввиду ту мощность, которую лазер выдает при включении кнопкой без сигнала ШИМ, т.е. про ток 2.6а = 100%). Никогда. Здесь тоже максимум будет %%75. И будут задержки исполнения команды Snnnn - с этим просто беда. Также надо найти минимальные значения сигнала Snnn, при которых плата управления будет устойчиво держать включенным реле управления включения шпинделя. В моем случае s200 его не включало, s250 было дрожание, а s300 держало реле включенным с такой мизерной мощностью луча, что его не было видно
Вы увидите, что зависимость, влияние цифр после S на ток сильно не линейная. Вот измеренные мною значения -
Обороты S ток, A 2,5 = 100%
24000 1,89 76%
23500 1,72 69%
23000 1,6 64%
22000 1,31 52%
21000 1,08 43%
20000 1,02 41%
19000 0,9 36%
17000 0,81 32%
15000 0,67 27%
12000 0,46 18%
Теперь приходится соглашаться, что "полная мощность" будет 1.89А, теперь она =100%. Тогда для управления лазером получается примерно такая таблица -
S процент мощности
24000 100
23400 90
22800 80
22100 70
21300 60
19500 50
16000 40
14000 30
3. конфигурация LinuxCNC - это самая простая часть. Следует иметь ввиду, что в любом случае она состоит из задания сигналов, ножек и т.п. Но задания сигналов требуют использования функций, которые перед этим следует объявить, прочитать и пр. Обычно в файлах ini объявление и ззапуск фукнций в самом начале файла, а использование - на много ниже, по месту требования. И обычно публикуются записи строк лишь "по месту использования", что приводит к ошибкам запуска (хрен найдешь, где и какая именно функция объявлена).
3.1. итак, базовая конфигурация, которая использовалась в работе со шпинделем -
#раздел шпинделя
loadrt pwmgen output_type=0 #(считали библиотеку, выбор типа сигнала управления, 0 или 1 - зависит от контроллера, можно менять и пробовать)
addf pwmgen.make-pulses base-thread #(активировали функцию)
addf pwmgen.update servo-thread #(активировали функцию)
net spindle-pwm => parport.0.pin-14-out #(указали используемую ножку LPT порта)
setp parport.0.pin-14-out-invert 1 # (инвертировали сигнлал - это капризы платы управления - )
#(если при запуска LinuxCNC шпиндель сразу включается, меняем значение 0\1)
#задание диапазаон значений
setp pwmgen.0.pwm-freq 100.0 #фиксированный щаг изменения значений
setp pwmgen.0.scale 24000.0 #максимальное значение. Разумно по число оборотов
setp pwmgen.0.offset 0 #минимальное значение. У инветора есть своя
#настройка рабочего минимума, потом можно ставить =0
#задание вцелом не нужных кнопочек управления шпинделем
net spindle-cmd-rpm => pwmgen.0.value
net spindle-on <= spindle.0.on => pwmgen.0.enable
net spindle-pwm <= pwmgen.0.pwm
setp pwmgen.0.dither-pwm true
net spindle-cmd-rpm <= spindle.0.speed-out
net spindle-cmd-rpm-abs <= spindle.0.speed-out-abs
net spindle-cmd-rps <= spindle.0.speed-out-rps
net spindle-cmd-rps-abs <= spindle.0.speed-out-rps-abs
net spindle-at-speed => spindle.0.at-speed
С этими настройками работа лазером будет управляться командами, у меня их три группы -
m3 s300 - в начале программы, как запуск шпинделя, просто активировали лазер
1. в каждой строке G1-3 можно предусмотреть команду S24000 (для условных 100% мощности), или
2. в каждой строке G1 движения вниз "головы" в начале радочего хода давать команду S24000
0. в каждой строке G0 добавить команду S300 . Не НОЛЬ!!! потому, что если добавим 0, то следующее включение только через M3 S24000, а это повлечет за собой задержку на включение релюшки.
В реальности приходится делать скрипт, который исходный g-code трансформирует в обработанный для работы с лазером. В моем случае все строки g-code пришлось разделить на три группы и для каждой вызывается подпрограмма, в которой указываю последовательность шагов.
Сама рабочая программа выглядит так, с реализацией нужной мне логики -
===========
o<r199> sub ([1- Х][2- У][3 - Параметр_1][4- Параметр_2]
G53 G0 Z180
#<_pb> = #3
#<_pm> = #3
#11 = #5 (масштаб Х)
#12 = #6 (масштаб У)
#<pwm> = 22100 (мощность )
G53 G0 Z180
(Pocket_Shape001)
G0
o<цель> call [#<_профиль>] [0] [0] [#11 * 0.060379] [#12 * -1.979806]
o<цель> call [#<_профиль>] [0] [0] [#11 * 0.060379] [#12 * -1.979806] [0.100000]
o<цель> call [#<_профиль>] [2] [#<pwm>] [#11 * 0.060379] [#12 * -1.979806] [0.000000]
o<цель> call [#<_профиль>] [1] [#<pwm>] [#11 * -0.115411] [#12 * -1.968975] [0.000000]
o<цель> call [#<_профиль>] [1] [#<pwm>] [#11 * -0.141985] [#12 * -2.119684] [0.000000]
===============
o<цель> sub (движение G1 к цели с учетом скорости и изменения высоты от координаты У)
/#1 = #1 (номер функции)
/#2 = #2 (G0 или G1)
/#3 = #3 (крокодилы мощности лазера)
/#4 = #4 (значение Х)
/#5 = #5 (значение У)
/#6 = #6 (значение Z - его не используем вовсе, чтобы не путаться и не бегать вверх-вниз)
o[#1] call [#5] (вызывается функция коррекции высоты, в результате от координаты У получаем корректируещее значение #<_dzfy>
o<g0> if [#2 eq 0] (если быстрая подача, то делаем так)
S3000
G4 P0.5
G0 X[#4] Y[#5]
o<g0> endif
o<g1> if [#2 eq 1] (если рабочая подача, то делаем так)
S#3
G1 F[#<_pb>] X[#4] Y[#5]
o<g1> endif
o<g2> if [#2 eq 3] (если начало рабочего хода, то делаем так)
G0 X[#4] Y[#5]
S#3
G4 P0.2
G1 F[#<_pb> ] X[#4] Y[#5] Z[ 0]
G4 P0.2
o<g2> endif
o<цель> endsub
================
Я не смог обнаружить необходимости использования кода M68. И использую Snnnnn. Но для желающих использовать M68 надо в ini файле активировать привязку сигнала движения -
net analogout motion.analog-out-00 => pwmgen.0.value #для использования кодов M68 надо генерацию связатьс движением
и, соответстенно, убрать другое упоминание о pwmgen.0.value в конфиге, где-то выше
=================
We are faced with the task of connecting a laser to a machine controlled by LinuxCNC. It doesn't matter, lan or lpt, the controller model doesn't matter either. Most often, the connection must be made to a machine that already has a spindle in use.
The simplest question is called LinuxCNC work, it, bunny, works without complaints and is easy to configure. But making the equipment purchased in China work adequately is much more difficult and therefore we will have to touch upon electrical issues.
1. The laser itself. Typically, the laser purchased has a laser housing and a power control board (2025) K
this board connects 3 wires - Plus 12 (24)V, Minus 12 (24)V - also known as GND, and PWM - control of laser power by a frequency signal. The main question is where to get this signal? Such a signal goes from the computer to the machine control board (controller), but the current of this signal is too small, and the laser refuses to understand it. This implies the need to purchase a separate Voltage-PWM signal conversion board. It can cost 1-10 dollars and will definitely be of mediocre quality. This board must be connected and it has three groups of contacts -
1.1. nutrition group, Plus 12 (24)B - it was called VCC here, Minus 12 (24)B - also known as GND
1.2. the control input is the signal wire, the same one that controls the operation of the spindle inverter, here it is called VIN, and GNG. But this is a different Earth, this is GND from the machine controller - an important note. Yes, all contacts of the GNG PWM generator are closed to each other on the board, so purely electrically they can be connected anywhere "before", but if there are terminals, why not use them as intended?
1.3. the control output is the PWM and GND signal wire. GND may not be used from here, but PWM is connected to the same PWM connector on the laser.
2. Now we need to resolve electrical issues. We have a spindle and a laser. If earlier our spindle inverter control wire went from the machine controller to the inverter, now from the controller and from the same contact (or from the same wire, but from the entrance to the inverter) we pull the long VIN signal wire to the laser itself. Several necessary actions follow from here -
2.1. It is necessary to make a separate inverter power switch so that the spindle does not spin when using a laser
2.2. it is necessary to provide for disconnection of the VIN wire going from the controller or inverter to the laser. This wire is long and there will be leads on it. If we do not turn off this wire, then when the spindle is turned on, the aiming will distort the VIN signal and the inverter will constantly change the frequency for the spindle. These can be such strong distortions that the spindle becomes uncontrollable - you give it a signal s1000 or even s0, and it either accelerates or brakes - such a swing.
It is important - the Chinese lie with characteristics. Using the example of my laser, supposedly with a power of 10 watts and a current of 3.8A, the real current was 2.6A, i.e. approximately 75%. You will also need to take measurements. To do this, you need to carefully unscrew the screws securing the board to the laser radiator housing and cut one of the diode power wires, clean the tips, irradiate and connect the ammeter. Put on glasses (I’m lucky - I bought a welder’s leather glasses with glass at a flea market many years ago) and turn on the laser without power control, measure the current. Turn off the laser (button on the board). Connect the PWM wire - as soon as the laser senses the connected PWM signal, it will no longer turn on with a button on the board. now this button will only mean turning on the ready mode to RESPOND to the PWM signal.
So, all the LinuxCNC settings we still have are the same as when working with the spindle, we don’t change anything. Using the M3 command, we give the command to turn on the spindle. Then, using the command s24000, turn on at "full power" (according to the ini settings of the machine, as discussed below) and measure the current. Then we give other commands to S12000 and try other values, recording the current readings. The fact is that the Chinese lie here too. The purchased PWM board will definitely not provide 100% power (here we mean the power that the laser produces when turned on with a button without a PWM signal, i.e. about a current of 2.6a = 100%). Never. Here, too, the maximum will be %%75. And there will be delays in executing the Snnnn command - that’s just a problem. It is also necessary to find the minimum values of the Snnn signal at which the control board will stably keep the spindle activation control relay on. In my case, the s200 didn't turn it on, the s250 was jittery, and the s300 kept the relay on with so little beam power that it couldn't be seen
You will see that the dependence, the effect of the digits after S on the current is not very linear. Here are the values I measured -
Revolutions S current, A 2.5 = 100%
24000 1.89 76%
23500 1.72 69%
23000 1.6 64%
22000 1.31 52%
21000 1.08 43%
20000 1.02 41%
19000 0.9 36%
17000 0.81 32%
15000 0.67 27%
12000 0.46 18%
Now we have to agree that "full power" will be 1.89A, now it is =100%. Then, to control the laser, you get something like this table -
S power percentage
24000 100
23400 90
22800 80
22100 70
21300 60
19500 50
16000 40
14000 30
3. The LinuxCNC configuration is the simplest part. It should be borne in mind that in any case it consists of setting signals, legs, etc. But setting signals requires the use of functions that must first be declared, read, etc. Typically, in ini files, announcement and launch functions are at the very beginning of the file, and use is much lower, at the place of requirement. And usually string entries are published only "at the place of use," which leads to startup errors (you’ll find where and which function is declared).
3.1. so, the basic configuration that was used in working with the spindle is
#spindle section
loadrt pwmgen output_type=0 #(considered library, choice of control signal type, 0 or 1 - depends on the controller, can be changed and tried)
addf pwmgen.make-pulses base-thread #(activated function)
addf pwmgen.update servo-thread #(activated function)
net spindle-pwm => parport.0.pin-14-out #(specify the LPT port leg used)
setp parport.0.pin-14-out-invert 1 # (inverted signallal - these are the vagaries of the control board - )
#(if the spindle turns on immediately when starting LinuxCNC, change the value to 0\1)
#set range of values
setp pwmgen.0.pwm-freq 100.0 #fixed step of changing values
setp pwmgen.0.scale 24000.0 #max value. Reasonably in terms of speed
setp pwmgen.0.offset 0 #minimum value. The inverter has its own
#setting the operating minimum, then you can set =0
#setting completely unnecessary spindle control buttons
net spindle-cmd-rpm => pwmgen.0.value
net spindle-on <= spindle.0.on => pwmgen.0.enable
net spindle-pwm <= pwmgen.0.pwm
setp pwmgen.0.dither-pwm true
net spindle-cmd-rpm <= spindle.0.speed-out
net spindle-cmd-rpm-abs <= spindle.0.speed-out-abs
net spindle-cmd-rps <= spindle.0.speed-out-rps
net spindle-cmd-rps-abs <= spindle.0.speed-out-rps-abs
net spindle-at-speed => spindle.0.at-speed
With these settings, laser operation will be controlled by commands, I have three groups of them -
m3 s300 - at the beginning of the program, as a spindle start, they simply activated the laser
1. in each line G1-3, the command S24000 can be provided (for a notional 100% power), or
2. in each line G1 of the downward movement of the "head" at the beginning of the joyful move, give the command S24000
0. in each line G0 add the command S300 -. Not ZERO!!! because if we add 0, then the next activation is only through the M3 S24000, and this will entail a delay in turning on the relay.
In reality, we have to create a script that transforms the original g-code into a processed one for working with a laser. In my case, all the g-code strings had to be divided into three groups, and for each one a subroutine is called in which I specify the sequence of steps.
The work program itself looks like this, with the implementation of the logic I need -
===========
o<r_199> sub ([1- X][2- Y][3 - Parameter_1][4- Parameter_2]
G53 G0 Z180
#<_pb> = #3
#<_pm> = #3
#11 = #5 (X scale)
#12 = #6 (scale Y)
#<pwm> = 22100 (power)
G53 G0 Z180
(Pocket_Shape001)
G0
o<purpose> call [#<_profile>] [0] [0] [#11 * 0.060379] [#12 * -1.979806]
o<purpose> call [#<_profile>] [0] [0] [#11 * 0.060379] [#12 * -1.979806] [0.100000]
o<purpose> call [#<_profile>] [2] [#<pwm>] [#11 * 0.060379] [#12 * -1.979806] [0.000000]
o<purpose> call [#<_profile>] [1] [#<pwm>] [#11 * -0.115411] [#12 * -1.968975] [0.000000]
o<purpose> call [#<_profile>] [1] [#<pwm>] [#11 * -0.141985] [#12 * -2.119684] [0.000000]
==============
o<target> sub (movement of G1 towards the target, taking into account speed and change in altitude from the Y coordinate)
/#1 = #1 (function number)
/#2 = #2 (G0 or G1)
/#3 = #3 (laser power crocodiles)
/#4 = #4 (X value)
/#5 = #5 (Y value)
/#6 = #6 (Z value - we don’t use it at all so as not to get confused and run up and down)
o[#1] call [#5] (the height correction function is called, as a result, from the Y coordinate we get the correction value #<_dzfy>
o<g0> if [#2 eq 0] (if fast serve, we do so)
S3000
G4 P0.5
G0 X[#4] Y[#5]
o<g0> endif
o<g1> if [#2 eq 1] (if working feed, then we do so)
S#3
G1 F[#<_pb>] X[#4] Y[#5]
o<g1> endif
o<g2> if [#2 eq 3] (if the working stroke begins, then we do so)
G0 X[#4] Y[#5]
S#3
G4 P0.2
G1 F[#<_pb> ] X[#4] Y[#5] Z[ 0]
G4 P0.2
o<g2> endif
o<purpose> endsub
==============
I couldn't detect the need to use the M68 code. And I use Snnnnn. But for those who want to use M68, they need to activate the motion signal binding in the ini file -
net analogout motion.analog-out-00 => pwmgen.0.value #to use M68 codes you need to generate by motion
and, accordingly, remove the other mention of pwmgen.0.value in the configuration somewhere above
Let's keep it simple. Let's say my configuration doesn't mention anything about the spindle or the laser.
How exactly should I format the hal file?
The scenario is as follows: there is a laser, controlled by PWM via LPT. It has been proven that the laser itself works. It has been proven that PWM also works (because we control the spindle through it).
The documentation indicates that we must set several mandatory parameters. It would seem that this is sufficient.
linuxcnc.org/docs/2.8/html/man/man9/pwmgen.9.html
forum.linuxcnc.org/media/kunena/attachme...19092/FRANKENLAB.hal
forum.linuxcnc.org/media/kunena/attachme...-mill_2019-07-26.hal
#spindle section
loadrt pwmgen output_type=0
addf pwmgen.make-pulses base-thread #enabled PWM frequency signal generation
addf pwmgen.update servo-thread #enabled control synchronization with the servo cycle
net spindle-pwm <= pwmgen.0.pwm #set the name of the signal controlled by the pwmgen.0.pwm signal
net spindle-pwm => parport.0.pin-14-out #set the LPT port pin to which the signal is transmitted
setp pwmgen.0.dither-pwm true #enabled frequency regulation stepping
setp pwmgen.0.pwm-freq 100.0
setp pwmgen.0.scale 24000
The spindle can be controlled normally with these parameters. If you connect a laser PWM to pin 14 instead, the laser should work somehow, either via M68 or M3S24000.
But the laser does not turn on. Only with the forced activation button on the laser body, and immediately at 100% power.
What am I doing wrong?
=================================
Colleagues, English is not my language. Therefore, first I will formulate the idea in my own language and below there will be a translation into international English by a robot.
===============================
Перед нами стоит задача подключения лазера к станку, управляемому LinuxCNC. Не важно, lan or lpt, модель контроллера тоже не имеет значение. Чаще всего подключение необходимо выполнить к станку, у которого уже есть используемый шпиндель.
Самый простой вопрос - это именено работа LinuxCNC, он, зайка, работает без нареканий и легко настраивается. А вот сделать так, чтобы покупаемое в Китае оборудование адекватно работало, на много сложнее и поэтому нам придется затронуть вопросы электрики.
1. Сам лазер. Обычно покупаемый лазер имеет корпус лазера и плату управления мощности (2025г.) К
этой плате подключается3 провода - Плюс 12 (24)В, Минус 12 (24)В - он же GND, и PWM - управление мощностью лазера частотным сигналом. Главный вопрос - где взять этот сигнал? Такой сигнал идет от компьютера к плате управления станком (контроллеру), но ток этого сигнала слишком маленький, лазер его отказыватся понимать. Из этого следует необходимость покупки отдельной платы преобразования сигнала Напряжение-ШИМ. Она может стоит 1-10 долларов и точно будет посредственного качества. Эту плату необходимо подключить и у нее три группы контактов -
1.1. группа питания, Плюс 12 (24)В - его здесь назвали VCC, Минус 12 (24)В - он же GND
1.2. управляющий вход - это сигнальный провод, тот же, который управляет работой инвертора шпинделя, здесь его назвали VIN, и GNG. Но это уже другая Земля, это GND от контроллера станка - замечание важное. Да, все контакты GNG ШИМ генератора замкнуты между собой на плате, поэтому чисто электрически их можно соединить в любом месте "до", но если есть клеммы, почему бы их не использовать по назанчению?
1.3. управляющий выход - сигнальный провод PWM и GND. GND отсюда можено не использовать, а вот PWM покдключить к такому же разъему PWM на лазере.
2. Теперь надо решить вопросы электрики. У нас есть шпиндель и лазер. Если раньше у нас провод управления инвертором шпинделя шел от контроллера станка до инвертора, то теперь от контроллера и от того же контакта (или от этого же провода, но от входа в инвертор) мы тянем длинный провод VIN сигнала к самому лазеру. Отслюда следует несколько необходимых действий -
2.1. надо сделать отдельный выключатель питания инвертора - чтобы при использовании лазера шпиндель не крутился
2.2. надо предусмотреть отключения провода VIN, идущего от контроллера или инвертора к лазеру. Провод этот длинный и на него будут наводки. Если мы этот провод не отключим, то при включении шпинделя наводки будут искажать сигнал VIN и инвертор будет постоянно изменять частоту для шпинделя. Это могут быть такие сильные искажения, что шпиндель станет неуправляемым - вы ему даете сигнал s1000 или даже s0, а он то разгоняется, то тормозит - такие качели.
Важно - китайцы врут с характеристиками. На примере моего лазера якобы мощностью 10вт и током 3.8А реальный ток был 2.6А, т.е. примерно 75%. Вам тоже надо будет провести измерения. Для этого надо аккуратно отвинтить винты крепления платы к корпусу-радиатору лазера и разрезать один из проводов питания диодов, зачистить кончики, облудить и подключить амперметр. Надеть очки (мне повезно - купил много лет назад на барахолке еще кожанные очки сварщика со стеклянными стеклами) и включить лазер без управления мощностью, замерить ток. Выключить (кнопкой на плате) лазер. Подключить провод PWM - как только лазер почувствует подключенный сигнал PWM он перестанет включаться кнопкой на плате. теперь эта кнопка будет означать лишь включения режима готовности РЕАГИРОВАТЬ на сигнал PWM.
Итак, все настройки LinuxCNC у нас пока еще такие, какие были при работе со шпинделем, ничего не меняем. Командой M3 даем команду включить шпиндель. Затем командой s24000 включаем на "полную мощность" (согласно настройкам ini станка, о чем ниже) и измеряем ток. Затем даем другие команды S12000 и пробуем другие значения, записываем показания тока. Дело в том, что китайцы и здесь врут. Купленная плата ШИМ точно не даст 100% мощности (здесь мы имеем ввиду ту мощность, которую лазер выдает при включении кнопкой без сигнала ШИМ, т.е. про ток 2.6а = 100%). Никогда. Здесь тоже максимум будет %%75. И будут задержки исполнения команды Snnnn - с этим просто беда. Также надо найти минимальные значения сигнала Snnn, при которых плата управления будет устойчиво держать включенным реле управления включения шпинделя. В моем случае s200 его не включало, s250 было дрожание, а s300 держало реле включенным с такой мизерной мощностью луча, что его не было видно
Вы увидите, что зависимость, влияние цифр после S на ток сильно не линейная. Вот измеренные мною значения -
Обороты S ток, A 2,5 = 100%
24000 1,89 76%
23500 1,72 69%
23000 1,6 64%
22000 1,31 52%
21000 1,08 43%
20000 1,02 41%
19000 0,9 36%
17000 0,81 32%
15000 0,67 27%
12000 0,46 18%
Теперь приходится соглашаться, что "полная мощность" будет 1.89А, теперь она =100%. Тогда для управления лазером получается примерно такая таблица -
S процент мощности
24000 100
23400 90
22800 80
22100 70
21300 60
19500 50
16000 40
14000 30
3. конфигурация LinuxCNC - это самая простая часть. Следует иметь ввиду, что в любом случае она состоит из задания сигналов, ножек и т.п. Но задания сигналов требуют использования функций, которые перед этим следует объявить, прочитать и пр. Обычно в файлах ini объявление и ззапуск фукнций в самом начале файла, а использование - на много ниже, по месту требования. И обычно публикуются записи строк лишь "по месту использования", что приводит к ошибкам запуска (хрен найдешь, где и какая именно функция объявлена).
3.1. итак, базовая конфигурация, которая использовалась в работе со шпинделем -
#раздел шпинделя
loadrt pwmgen output_type=0 #(считали библиотеку, выбор типа сигнала управления, 0 или 1 - зависит от контроллера, можно менять и пробовать)
addf pwmgen.make-pulses base-thread #(активировали функцию)
addf pwmgen.update servo-thread #(активировали функцию)
net spindle-pwm => parport.0.pin-14-out #(указали используемую ножку LPT порта)
setp parport.0.pin-14-out-invert 1 # (инвертировали сигнлал - это капризы платы управления - )
#(если при запуска LinuxCNC шпиндель сразу включается, меняем значение 0\1)
#задание диапазаон значений
setp pwmgen.0.pwm-freq 100.0 #фиксированный щаг изменения значений
setp pwmgen.0.scale 24000.0 #максимальное значение. Разумно по число оборотов
setp pwmgen.0.offset 0 #минимальное значение. У инветора есть своя
#настройка рабочего минимума, потом можно ставить =0
#задание вцелом не нужных кнопочек управления шпинделем
net spindle-cmd-rpm => pwmgen.0.value
net spindle-on <= spindle.0.on => pwmgen.0.enable
net spindle-pwm <= pwmgen.0.pwm
setp pwmgen.0.dither-pwm true
net spindle-cmd-rpm <= spindle.0.speed-out
net spindle-cmd-rpm-abs <= spindle.0.speed-out-abs
net spindle-cmd-rps <= spindle.0.speed-out-rps
net spindle-cmd-rps-abs <= spindle.0.speed-out-rps-abs
net spindle-at-speed => spindle.0.at-speed
С этими настройками работа лазером будет управляться командами, у меня их три группы -
m3 s300 - в начале программы, как запуск шпинделя, просто активировали лазер
1. в каждой строке G1-3 можно предусмотреть команду S24000 (для условных 100% мощности), или
2. в каждой строке G1 движения вниз "головы" в начале радочего хода давать команду S24000
0. в каждой строке G0 добавить команду S300 . Не НОЛЬ!!! потому, что если добавим 0, то следующее включение только через M3 S24000, а это повлечет за собой задержку на включение релюшки.
В реальности приходится делать скрипт, который исходный g-code трансформирует в обработанный для работы с лазером. В моем случае все строки g-code пришлось разделить на три группы и для каждой вызывается подпрограмма, в которой указываю последовательность шагов.
Сама рабочая программа выглядит так, с реализацией нужной мне логики -
===========
o<r199> sub ([1- Х][2- У][3 - Параметр_1][4- Параметр_2]
G53 G0 Z180
#<_pb> = #3
#<_pm> = #3
#11 = #5 (масштаб Х)
#12 = #6 (масштаб У)
#<pwm> = 22100 (мощность )
G53 G0 Z180
(Pocket_Shape001)
G0
o<цель> call [#<_профиль>] [0] [0] [#11 * 0.060379] [#12 * -1.979806]
o<цель> call [#<_профиль>] [0] [0] [#11 * 0.060379] [#12 * -1.979806] [0.100000]
o<цель> call [#<_профиль>] [2] [#<pwm>] [#11 * 0.060379] [#12 * -1.979806] [0.000000]
o<цель> call [#<_профиль>] [1] [#<pwm>] [#11 * -0.115411] [#12 * -1.968975] [0.000000]
o<цель> call [#<_профиль>] [1] [#<pwm>] [#11 * -0.141985] [#12 * -2.119684] [0.000000]
===============
o<цель> sub (движение G1 к цели с учетом скорости и изменения высоты от координаты У)
/#1 = #1 (номер функции)
/#2 = #2 (G0 или G1)
/#3 = #3 (крокодилы мощности лазера)
/#4 = #4 (значение Х)
/#5 = #5 (значение У)
/#6 = #6 (значение Z - его не используем вовсе, чтобы не путаться и не бегать вверх-вниз)
o[#1] call [#5] (вызывается функция коррекции высоты, в результате от координаты У получаем корректируещее значение #<_dzfy>
o<g0> if [#2 eq 0] (если быстрая подача, то делаем так)
S3000
G4 P0.5
G0 X[#4] Y[#5]
o<g0> endif
o<g1> if [#2 eq 1] (если рабочая подача, то делаем так)
S#3
G1 F[#<_pb>] X[#4] Y[#5]
o<g1> endif
o<g2> if [#2 eq 3] (если начало рабочего хода, то делаем так)
G0 X[#4] Y[#5]
S#3
G4 P0.2
G1 F[#<_pb> ] X[#4] Y[#5] Z[ 0]
G4 P0.2
o<g2> endif
o<цель> endsub
================
Я не смог обнаружить необходимости использования кода M68. И использую Snnnnn. Но для желающих использовать M68 надо в ini файле активировать привязку сигнала движения -
net analogout motion.analog-out-00 => pwmgen.0.value #для использования кодов M68 надо генерацию связатьс движением
и, соответстенно, убрать другое упоминание о pwmgen.0.value в конфиге, где-то выше
=================
We are faced with the task of connecting a laser to a machine controlled by LinuxCNC. It doesn't matter, lan or lpt, the controller model doesn't matter either. Most often, the connection must be made to a machine that already has a spindle in use.
The simplest question is called LinuxCNC work, it, bunny, works without complaints and is easy to configure. But making the equipment purchased in China work adequately is much more difficult and therefore we will have to touch upon electrical issues.
1. The laser itself. Typically, the laser purchased has a laser housing and a power control board (2025) K
this board connects 3 wires - Plus 12 (24)V, Minus 12 (24)V - also known as GND, and PWM - control of laser power by a frequency signal. The main question is where to get this signal? Such a signal goes from the computer to the machine control board (controller), but the current of this signal is too small, and the laser refuses to understand it. This implies the need to purchase a separate Voltage-PWM signal conversion board. It can cost 1-10 dollars and will definitely be of mediocre quality. This board must be connected and it has three groups of contacts -
1.1. nutrition group, Plus 12 (24)B - it was called VCC here, Minus 12 (24)B - also known as GND
1.2. the control input is the signal wire, the same one that controls the operation of the spindle inverter, here it is called VIN, and GNG. But this is a different Earth, this is GND from the machine controller - an important note. Yes, all contacts of the GNG PWM generator are closed to each other on the board, so purely electrically they can be connected anywhere "before", but if there are terminals, why not use them as intended?
1.3. the control output is the PWM and GND signal wire. GND may not be used from here, but PWM is connected to the same PWM connector on the laser.
2. Now we need to resolve electrical issues. We have a spindle and a laser. If earlier our spindle inverter control wire went from the machine controller to the inverter, now from the controller and from the same contact (or from the same wire, but from the entrance to the inverter) we pull the long VIN signal wire to the laser itself. Several necessary actions follow from here -
2.1. It is necessary to make a separate inverter power switch so that the spindle does not spin when using a laser
2.2. it is necessary to provide for disconnection of the VIN wire going from the controller or inverter to the laser. This wire is long and there will be leads on it. If we do not turn off this wire, then when the spindle is turned on, the aiming will distort the VIN signal and the inverter will constantly change the frequency for the spindle. These can be such strong distortions that the spindle becomes uncontrollable - you give it a signal s1000 or even s0, and it either accelerates or brakes - such a swing.
It is important - the Chinese lie with characteristics. Using the example of my laser, supposedly with a power of 10 watts and a current of 3.8A, the real current was 2.6A, i.e. approximately 75%. You will also need to take measurements. To do this, you need to carefully unscrew the screws securing the board to the laser radiator housing and cut one of the diode power wires, clean the tips, irradiate and connect the ammeter. Put on glasses (I’m lucky - I bought a welder’s leather glasses with glass at a flea market many years ago) and turn on the laser without power control, measure the current. Turn off the laser (button on the board). Connect the PWM wire - as soon as the laser senses the connected PWM signal, it will no longer turn on with a button on the board. now this button will only mean turning on the ready mode to RESPOND to the PWM signal.
So, all the LinuxCNC settings we still have are the same as when working with the spindle, we don’t change anything. Using the M3 command, we give the command to turn on the spindle. Then, using the command s24000, turn on at "full power" (according to the ini settings of the machine, as discussed below) and measure the current. Then we give other commands to S12000 and try other values, recording the current readings. The fact is that the Chinese lie here too. The purchased PWM board will definitely not provide 100% power (here we mean the power that the laser produces when turned on with a button without a PWM signal, i.e. about a current of 2.6a = 100%). Never. Here, too, the maximum will be %%75. And there will be delays in executing the Snnnn command - that’s just a problem. It is also necessary to find the minimum values of the Snnn signal at which the control board will stably keep the spindle activation control relay on. In my case, the s200 didn't turn it on, the s250 was jittery, and the s300 kept the relay on with so little beam power that it couldn't be seen
You will see that the dependence, the effect of the digits after S on the current is not very linear. Here are the values I measured -
Revolutions S current, A 2.5 = 100%
24000 1.89 76%
23500 1.72 69%
23000 1.6 64%
22000 1.31 52%
21000 1.08 43%
20000 1.02 41%
19000 0.9 36%
17000 0.81 32%
15000 0.67 27%
12000 0.46 18%
Now we have to agree that "full power" will be 1.89A, now it is =100%. Then, to control the laser, you get something like this table -
S power percentage
24000 100
23400 90
22800 80
22100 70
21300 60
19500 50
16000 40
14000 30
3. The LinuxCNC configuration is the simplest part. It should be borne in mind that in any case it consists of setting signals, legs, etc. But setting signals requires the use of functions that must first be declared, read, etc. Typically, in ini files, announcement and launch functions are at the very beginning of the file, and use is much lower, at the place of requirement. And usually string entries are published only "at the place of use," which leads to startup errors (you’ll find where and which function is declared).
3.1. so, the basic configuration that was used in working with the spindle is
#spindle section
loadrt pwmgen output_type=0 #(considered library, choice of control signal type, 0 or 1 - depends on the controller, can be changed and tried)
addf pwmgen.make-pulses base-thread #(activated function)
addf pwmgen.update servo-thread #(activated function)
net spindle-pwm => parport.0.pin-14-out #(specify the LPT port leg used)
setp parport.0.pin-14-out-invert 1 # (inverted signallal - these are the vagaries of the control board - )
#(if the spindle turns on immediately when starting LinuxCNC, change the value to 0\1)
#set range of values
setp pwmgen.0.pwm-freq 100.0 #fixed step of changing values
setp pwmgen.0.scale 24000.0 #max value. Reasonably in terms of speed
setp pwmgen.0.offset 0 #minimum value. The inverter has its own
#setting the operating minimum, then you can set =0
#setting completely unnecessary spindle control buttons
net spindle-cmd-rpm => pwmgen.0.value
net spindle-on <= spindle.0.on => pwmgen.0.enable
net spindle-pwm <= pwmgen.0.pwm
setp pwmgen.0.dither-pwm true
net spindle-cmd-rpm <= spindle.0.speed-out
net spindle-cmd-rpm-abs <= spindle.0.speed-out-abs
net spindle-cmd-rps <= spindle.0.speed-out-rps
net spindle-cmd-rps-abs <= spindle.0.speed-out-rps-abs
net spindle-at-speed => spindle.0.at-speed
With these settings, laser operation will be controlled by commands, I have three groups of them -
m3 s300 - at the beginning of the program, as a spindle start, they simply activated the laser
1. in each line G1-3, the command S24000 can be provided (for a notional 100% power), or
2. in each line G1 of the downward movement of the "head" at the beginning of the joyful move, give the command S24000
0. in each line G0 add the command S300 -. Not ZERO!!! because if we add 0, then the next activation is only through the M3 S24000, and this will entail a delay in turning on the relay.
In reality, we have to create a script that transforms the original g-code into a processed one for working with a laser. In my case, all the g-code strings had to be divided into three groups, and for each one a subroutine is called in which I specify the sequence of steps.
The work program itself looks like this, with the implementation of the logic I need -
===========
o<r_199> sub ([1- X][2- Y][3 - Parameter_1][4- Parameter_2]
G53 G0 Z180
#<_pb> = #3
#<_pm> = #3
#11 = #5 (X scale)
#12 = #6 (scale Y)
#<pwm> = 22100 (power)
G53 G0 Z180
(Pocket_Shape001)
G0
o<purpose> call [#<_profile>] [0] [0] [#11 * 0.060379] [#12 * -1.979806]
o<purpose> call [#<_profile>] [0] [0] [#11 * 0.060379] [#12 * -1.979806] [0.100000]
o<purpose> call [#<_profile>] [2] [#<pwm>] [#11 * 0.060379] [#12 * -1.979806] [0.000000]
o<purpose> call [#<_profile>] [1] [#<pwm>] [#11 * -0.115411] [#12 * -1.968975] [0.000000]
o<purpose> call [#<_profile>] [1] [#<pwm>] [#11 * -0.141985] [#12 * -2.119684] [0.000000]
==============
o<target> sub (movement of G1 towards the target, taking into account speed and change in altitude from the Y coordinate)
/#1 = #1 (function number)
/#2 = #2 (G0 or G1)
/#3 = #3 (laser power crocodiles)
/#4 = #4 (X value)
/#5 = #5 (Y value)
/#6 = #6 (Z value - we don’t use it at all so as not to get confused and run up and down)
o[#1] call [#5] (the height correction function is called, as a result, from the Y coordinate we get the correction value #<_dzfy>
o<g0> if [#2 eq 0] (if fast serve, we do so)
S3000
G4 P0.5
G0 X[#4] Y[#5]
o<g0> endif
o<g1> if [#2 eq 1] (if working feed, then we do so)
S#3
G1 F[#<_pb>] X[#4] Y[#5]
o<g1> endif
o<g2> if [#2 eq 3] (if the working stroke begins, then we do so)
G0 X[#4] Y[#5]
S#3
G4 P0.2
G1 F[#<_pb> ] X[#4] Y[#5] Z[ 0]
G4 P0.2
o<g2> endif
o<purpose> endsub
==============
I couldn't detect the need to use the M68 code. And I use Snnnnn. But for those who want to use M68, they need to activate the motion signal binding in the ini file -
net analogout motion.analog-out-00 => pwmgen.0.value #to use M68 codes you need to generate by motion
and, accordingly, remove the other mention of pwmgen.0.value in the configuration somewhere above
Last edit: 01 Nov 2025 09:05 by abs32.
Please Log in or Create an account to join the conversation.
- tommylight
-
- Away
- Moderator
-
Less
More
- Posts: 20854
- Thank you received: 7108
15 Oct 2025 15:06 #336505
by tommylight
Replied by tommylight on topic How to properly connect LASER and control its power?
This has been already answered and promptly ignored here
forum.linuxcnc.org/10-advanced-configura...aser?start=30#336428
-
How many inputs does it have?
forum.linuxcnc.org/10-advanced-configura...aser?start=30#336428
-
You should have started with this as it clearly shows the wiring is incorrect or there is a signal mismatch, so what does your laser input work with?The spindle can be controlled normally with these parameters. If you connect a laser PWM to pin 14 instead, the laser should work somehow, either via M68 or M3S24000.
But the laser does not turn on. Only with the forced activation button on the laser body, and immediately at 100% power.
How many inputs does it have?
Please Log in or Create an account to join the conversation.
- abs32
- Offline
- New Member
-
Less
More
- Posts: 19
- Thank you received: 0
15 Oct 2025 15:12 #336506
by abs32
Replied by abs32 on topic How to properly connect LASER and control its power?
The laser has 3 inputs. PWM, +12v and ground.
Please Log in or Create an account to join the conversation.
- tommylight
-
- Away
- Moderator
-
Less
More
- Posts: 20854
- Thank you received: 7108
15 Oct 2025 15:29 #336507
by tommylight
Replied by tommylight on topic How to properly connect LASER and control its power?
OK, 5V TTL, so should work as is, but did you wire the GND on BOB to GND on laser?
Please Log in or Create an account to join the conversation.
- abs32
- Offline
- New Member
-
Less
More
- Posts: 19
- Thank you received: 0
15 Oct 2025 15:41 - 15 Oct 2025 15:50 #336508
by abs32
Replied by abs32 on topic How to properly connect LASER and control its power?
Good question. The laser has three inputs:
1. PWM
2. +12V
3. Ground.
Is 3 ground or -12V?
The laser itself operates from the mechanical switch button on the laser. Logically, it needs a separate + and a separate -. I don't see a ground contact.
When attempting to connect pin 3 (ground) of the laser to the ground of the control board (instead of minus 12V), the laser does not flash and the fan does not spin.
1. PWM
2. +12V
3. Ground.
Is 3 ground or -12V?
The laser itself operates from the mechanical switch button on the laser. Logically, it needs a separate + and a separate -. I don't see a ground contact.
When attempting to connect pin 3 (ground) of the laser to the ground of the control board (instead of minus 12V), the laser does not flash and the fan does not spin.
Last edit: 15 Oct 2025 15:50 by abs32.
Please Log in or Create an account to join the conversation.
- abs32
- Offline
- New Member
-
Less
More
- Posts: 19
- Thank you received: 0
15 Oct 2025 16:00 - 15 Oct 2025 16:13 #336509
by abs32
Replied by abs32 on topic How to properly connect LASER and control its power?
Connected the laser mounting screw to the machine and the control board ground contact with a wire. No changes.
I connected a voltmeter directly to the wire at the laser input.
At m30, the voltage is 0.26, and at m3, the voltage is 4.7. The spindle frequency converter is connected here as well and is controlled normally.
The machine controller board indicator also responds appropriately—it turns on and off at m3 or m30.
I connected a voltmeter directly to the wire at the laser input.
At m30, the voltage is 0.26, and at m3, the voltage is 4.7. The spindle frequency converter is connected here as well and is controlled normally.
The machine controller board indicator also responds appropriately—it turns on and off at m3 or m30.
Last edit: 15 Oct 2025 16:13 by abs32.
Please Log in or Create an account to join the conversation.
- abs32
- Offline
- New Member
-
Less
More
- Posts: 19
- Thank you received: 0
01 Nov 2025 07:53 #337621
by abs32
Replied by abs32 on topic How to properly connect LASER and control its power?
Later I will summarize and correct the first message of the topic.
First, it turned out that it was pointless to consider the topic without taking into account the electrical component and connection diagram.
Then it turned out that neither the Snnnnn parameter nor the M68 Qnnn control the laser power as it should (the hypothesis from the message www.forum.linuxcnc.org/10-advanced-confi...-laser?start=0#92752 is not correct in part 50%).
First, it turned out that it was pointless to consider the topic without taking into account the electrical component and connection diagram.
Then it turned out that neither the Snnnnn parameter nor the M68 Qnnn control the laser power as it should (the hypothesis from the message www.forum.linuxcnc.org/10-advanced-confi...-laser?start=0#92752 is not correct in part 50%).
Please Log in or Create an account to join the conversation.
- Configuring LinuxCNC
- Advanced Configuration
- [SOLVED] How to properly connect LASER and control its power?
Time to create page: 0.093 seconds