Hi,
I'm trying to get arduino read mach3 usb stepper board pulses for every 10ms and send pwm signal to laser based on the current speed.
Problem is that my values are ranging from 80 to 160 with solid feedrate, I quess it would be that interrupts are running constantly and not giving time to main loop to execute its tasks..
here is code
int PWM_out = 11; //Pwm ulos
int x = 0; // X-akselin pulssit
int y = 0; // Y-akselin pulssit
float PWM = 0; // PWM signaalin voimakkuus
float juuri = 0;
int PWM_in = 4;// lähtökohtainen pwm teho input 4
void setup() {
pinMode(2, INPUT_PULLUP);
pinMode(3, INPUT_PULLUP);
pinMode(PWM_in, INPUT); //PWM sisään, lähtökohtainen teho
pinMode(PWM_out, OUTPUT); // pwm ulostulo pinni 13
attachInterrupt(0, XA, FALLING); // X akseli pinni 2 kun menee high->low
attachInterrupt(1, YA, FALLING); // Y akseli pinni 3
Serial.begin(9600); //
}
//
void loop() {
PWM = sqrt(sq((x*2))+sq(y));
analogWrite(PWM_out, PWM);
Serial.println(y, DEC); // matka kuljettu
//x = 0; //nollaa pulssit
//y = 0;
delay(20); //Päivittää pwm signaalin 30ms välein
}
// Interrupti rutiinit
void YA() {
y++;
}
void XA() {
x++;
}
Start by declaring x and y as volatile to warn the compiler that their values might change at any time.
What range of values do you expect ? If between 0 and 255 then declare x and y as byte instead of int. If they need to be int then in loop, before you use them you need to turn off interrupts, copy the value to another int and turn on interrupts again to avoid the possibility of the ISR being triggered part way through the program dealing with a multi byte variable
Thanks for help, that speed up my code, but biggest improve was to set microstepping resolution to same as Y-axis, now it runs smooth and perfect.
Here is final code for those who are interested, note: there is not all pwm output things set up yet, only inputting pulses and counting them.
byte PWM_out = 11; //Pwm ulos
volatile byte x = 0; // X-akselin pulssit
volatile byte y = 0; // Y-akselin pulssit
float PWM = 0; // PWM signaalin voimakkuus
int PWM_in = 4;// lähtökohtainen pwm teho input 4
void setup() {
pinMode(2, INPUT_PULLUP);
pinMode(3, INPUT_PULLUP);
pinMode(PWM_in, INPUT); //PWM sisään, lähtökohtainen teho
pinMode(PWM_out, OUTPUT); // pwm ulostulo pinni 13
attachInterrupt(0, XA, FALLING); // X akseli pinni 2 kun menee high->low
attachInterrupt(1, YA, FALLING); // Y akseli pinni 3
Serial.begin(9600); //
}
//
void loop() {
PWM = sqrt(sq((x))+sq(y));
Serial.println(PWM, DEC); // matka kuljettu
x = 0; //nollaa pulssit
y = 0;
delay(5); //Päivittää pwm signaalin 30ms välein
}
// Interrupti rutiinit
void YA() {
y++;
}
void XA() {
x++;
}