Regarding your constant of “40”, this needs to be recorded somewhere, but it is different for different machines. I’m not sure if it should be in Ground Control or the Arduino. Probably the Arduino.

What you could do is store the max rpm of your spindle. Then the maths becomes:

Speed = argument of S command

pwm = speed*255/max

If pwm > 255 then pwm = 255

Analog Write(pwm)

So, if your max speed is 4000rpm and you get S4000:

pwm = 1020000/4000 = 255

If you get S2000

pwm = 510000/4000 = 127.5 -> 127

If you get S6000

pwm = 1530000/4000 = 382.5 -> 255

Having written that I realise your max rpm is 10000, but the calculation is the same.

You could also do the maths by ‘rpm per unit of pwm’, in your case it’s 40. So, get the argument of the S command and divide by 40, capping the result at 255.

But… where to store the max speed for the spindle, or the ‘rpm per unit of pwm’? And how to view it or change it?