I am writing multithreading for Arduino, and for this you need to remove all delay(); . I replace these with millis(); , but this all works only once, although the cycle - the delay is correct, but it works once. Why is that?

Here is the code:

 unsigned long previousMillis = 0; const long interval = 1000; int main() { //init(); while (1) { led13_ne(); } } void led13_ne() { DDRB |= B10000000; init(); unsigned long currentMillis = millis(); byte port13read = 0; if (currentMillis - previousMillis >= interval) { previousMillis = currentMillis; port13read = bitRead(PORTB, 8); if (port13read == 0) { PORTB |= B10000000; //port13read = 1; } else { PORTB &= ~B10000000; //port13read = 0; } } } 
  • init(); in the cycle why ? - Fat-Zer
  • bitRead(PORTB, 8); - how do you read the ninth bit of a byte? - Fat-Zer
  • @ Fat-Zer init(); for millis(); . - Super_Puper_User
  • I'll ask differently, why is init () in a loop ? and bitRead(PORTB, 8); - trying to return the ninth bit of the eight-bit value, it is clear that it will always be zero ... - Fat-Zer

1 answer 1

bitRead () returns the value of the i-th bit of the byte transferred to it, counting from zero . Therefore, in order to get the value of the high-order bit, you must do the following:

 bitRead(PORTB, 7); 

In addition, this entry is exactly the same:

 (PORTB >> 7) & 0x01; 

Which I would recommend to use, since there is a course towards abandoning the arduino excesses. so A similar construction for 8-ki will always return zero.

In addition, init () should be called once i. it is worth uncommenting it in main () and removing it from led13_ne () . In this case, not so critical, but in principle - this is a bad practice.

  • Actually, I looked at Arduino for the first time, and here they write about PORTB - PORTB maps to Arduino digital pins 8 to 13 The two high bits (6 & 7) map to the crystal pins and are not usable . Are you sure that it makes sense to talk about the 7th bit? - avp
  • @avp, most likely he has Mega - there is the seventh bit of PORTB on the built-in LED goes ... - Fat-Zer
  • @ Fat-Zer Yeah, you guessed it, I torture Megu)) - Super_Puper_User