Я новичок в C++, пишу код для управления шаговыми двигателями с помощью функции micros() в Arduino IDE. Когда я запускаю код как есть, шаговый двигатель не вращается. Хотя двигатель работает ожидаемо, когда я назначаю переменные вне класса, а не в классе.
НЕРАБОТАЮЩИЙ КОД:
const int DIR_PIN = 5; // direction
const int STEP_PIN = 2; // step
class steppercontrol {
private:
unsigned long currenttime;
unsigned long prevtime;
int pulsecount;
int stepcount;
int delaytime;
bool pulse;
public:
void setspeed(int speed){
delaytime = speed;
}
void run(int targetstep){
while (stepcount < targetstep){
currenttime = micros();
if (currenttime - prevtime > delaytime){ // compare time passed to desired delay
pulsecount ++;
if(pulsecount % 2 == 0){stepcount++;} // 2 pulses in 1 step
pulse = pulse == LOW ? HIGH : LOW;
digitalWrite(STEP_PIN, pulse);
prevtime = currenttime;
}
}
}
};
void setup() {
pinMode(STEP_PIN, OUTPUT);
pinMode(DIR_PIN, OUTPUT);
digitalWrite(DIR_PIN, HIGH);
steppercontrol stepper;
stepper.setspeed(1000);
stepper.run(1600);
}
void loop() {
}
КОД С ПЕРЕМЕННЫМИ ВНЕ КЛАССА, РАБОТАЮЩИЙ:
const int DIR_PIN = 5; // direction
const int STEP_PIN = 2; // step
unsigned long currenttime;
unsigned long prevtime;
int pulsecount;
int stepcount;
int delaytime;
bool pulse;
class steppercontrol {
public:
void setspeed(int speed){
delaytime = speed;
}
void run(int targetstep){
while (stepcount < targetstep){
currenttime = micros();
if (currenttime - prevtime > delaytime){ // compare time passed to desired delay
pulsecount ++;
if(pulsecount % 2 == 0){stepcount++;} // 2 pulses in 1 step
pulse = pulse == LOW ? HIGH : LOW;
digitalWrite(STEP_PIN, pulse);
prevtime = currenttime;
}
}
}
};
void setup() {
pinMode(STEP_PIN, OUTPUT);
pinMode(DIR_PIN, OUTPUT);
digitalWrite(DIR_PIN, HIGH);
steppercontrol stepper;
stepper.setspeed(1000);
stepper.run(1600);
}
void loop() {
}
Подробнее здесь: https://stackoverflow.com/questions/781 ... -arduino-i
Код работает правильно только тогда, когда переменные определены вне класса в Arduino IDE. ⇐ C++
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение