While() being broken by a false result?

hey, i'm looking for support to figure out in what case the 'false' result can break the while loop, or any other mistake i made;

in the code, the 'x' was a const int e.g. 2000; in principle, the serial print result to be exactly '2000';
but in my practice, if run this code in a loop, i'll get something like 2000,1890,2000,2000,1890,2000,1890..... and this sequence it was not repeatable, the'1890' seems to be randomly appreared, but each time the 'tolerence' was the same(always 1890);
i can hardly understand why 'step_count=1890' can break the while loop, and below is part of my code:

while(step_count<x)
{
if (loaded==0)
{if(digitalRead(outer)==0)
{digitalWrite(motora1, HIGH); //loaded and stop rolling
loaded=1;shooted=0;
//timerecord();//loaded time
}
else{}}
}
Serial.println(step_count);
step_count=0;

//and 'step_count' was designed in below ISR to record the stepper

ISR(TIMER1_COMPA_vect)
{
//accel mode, index_acc = x; twice_coe=1; index_acc +1 and steps + 1 every two PB0 inverse
if (ticks) //
{
PORTB^=(1<<0);
twice_coe=!twice_coe;
if (twice_coe)
{
step_count++;
switch(flag)
{
case SLIP:
break;
case ACCEL:
if (index_acc==accel_step){flag=SLIP;} //set the accel_step as the limitation of max speed
else{
index_acc++;
OCR1A = pgm_read_word_near(speed_table+index_acc);
}
break;
case DECEL:
if (index_acc==0){flag=STOP;}
else{
index_acc--;
OCR1A = pgm_read_word_near(speed_table+index_acc);
}
break;
case STOP:
TIMSK1 &=(~(1 << OCIE1A));
digitalWrite(steperEN,1);
step_count=0;
break;
}
}
ticks=!ticks;
}
else {
ticks=!ticks;
}
}
```````````````

What protects accesses to step_count?

(If you'd posted your code, I wouldn't have had to ask)

The biggest one you made is that is only posted a snippet of your code... that's kinda useless to be honest. Post the entire sketch and you might get some help.

not clear what you're trying to say and what the problem is

Is step_count declared as volatile?
Obviously step_count is larger than a single byte, you can get unpredictable results by accessing step_count while interrupts are active, because an interrupt can occur between the individual bytes.

exactly, thanks!
looks it's not a proper way to control a stepper by frequently accessing counting in an ISR, i need to deep dive Marlin code.

rather complicated ISR. What is it expected to do?

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.