Помощь новичку

Тема в разделе "Arduino & Shields", создана пользователем s2dent6732, 23 дек 2016.

  1. wildofficer

    wildofficer Нуб

    почему цикл счетчика не (виснет) после +3 ?
     
  2. wildofficer

    wildofficer Нуб

    Я как то с main пока не разбираюсь. Тема то вроде как "Помощь новичку". Поясните код пожалуйста.
     
  3. wildofficer

    wildofficer Нуб

    И если сделать точно так, ругается что ( i ) не обьявили
     
  4. Unixon

    Unixon Оракул Модератор

    Потому, что он заканчивается.
     
  5. Unixon

    Unixon Оракул Модератор

    Что именно непонятно? Исполнение скетча всегда начинается с main(). Внутри main() крутится бесконечный цикл, в котором на каждой итерации один раз вызывается loop(), выхода из этого цикла нет, да и выходить то собственно некуда.

    Чего вы вообще пытаетесь от программы добиться?
     
  6. mcureenab

    mcureenab Гуру

    Потому что после значения 255 происходит переполнение переменной типа byte и переменная принимает значение 0.
    На частоте 16МГц это практически мгновенно происходит.
     
  7. wildofficer

    wildofficer Нуб

    хочу чтобы цикл отработал определенное количество раз и остановился или завис или while в бесконечном режиме было, без разницы.
    Вот так вот работает
    Код (C++):
    #define LED_PIN 9
    void setup()
    {
       pinMode(LED_PIN, OUTPUT);
       Serial.begin(9600);
    }
    void loop()
    {
       static byte counter = 0;
       while (counter < 3)
       {
         analogWrite(LED_PIN, 85);
         delay(250);
         analogWrite(LED_PIN, 170);
         delay(250);
         analogWrite(LED_PIN, 255);
         delay(250);
         counter++;  
         Serial.println(counter);
       }
    // сюда попадаем только после того, как counter стал равен трём.
    // тут код все равно выполняется бесконечное количество раз.
    // если кода здесь нет, то и выполняться нечему :)
    }
     
  8. wildofficer

    wildofficer Нуб

    Хотел и в этом скетче сделать тоже самое
    Код (C++):
    //LED Pin Variables
    int ledPins[] = {2,3,4,5,6,7,8,9}; //An array to hold the pin each LED is connected to
                                       //i.e. LED #0 is connected to pin 2, LED #1, 3 and so on
                                       //to address an array use ledPins[0] this would equal 2
                                       //and ledPins[7] would equal 9
    /*
    * setup() - this function runs once when you turn your Arduino on
    * We the three control pins to outputs
    */

    void setup()
    {
     
      //Set each pin connected to an LED to output mode (pulling high (on) or low (off)
      for(int i = 0; i < 8; i++){         //this is a loop and will repeat eight times
          pinMode(ledPins[i],OUTPUT); //we use this to set each LED pin to output
      }                                   //the code this replaces is below
      /* (commented code will not run)
       * these are the lines replaced by the for loop above they do exactly the
       * same thing the one above just uses less typing
      pinMode(ledPins[0],OUTPUT);
      pinMode(ledPins[1],OUTPUT);
      pinMode(ledPins[2],OUTPUT);
      pinMode(ledPins[3],OUTPUT);
      pinMode(ledPins[4],OUTPUT);
      pinMode(ledPins[5],OUTPUT);
      pinMode(ledPins[6],OUTPUT);
      pinMode(ledPins[7],OUTPUT);
      (end of commented code)*/

    }
    /*
    * loop() - this function will start after setup finishes and then repeat
    * we call a function called oneAfterAnother(). if you would like a different behaviour
    * uncomment (delete the two slashes) one of the other lines
    */

    void loop()                     // run over and over again
    {
      oneAfterAnotherNoLoop();   //this will turn on each LED one by one then turn each off
      //oneAfterAnotherLoop();   //does the same as oneAfterAnotherNoLoop but with
                                 //much less typing
      //oneOnAtATime();          //this will turn one LED on then turn the next one
                                 //on turning the
                                 //former off (one LED will look like it is scrolling
                                 //along the line
      //inAndOut();              //lights the two middle LEDs then moves them out then back
                                 //in again
    }
    /*
    * oneAfterAnotherNoLoop() - Will light one LED then delay for delayTime then light
    * the next LED until all LEDs are on it will then turn them off one after another
    *
    * this does it without using a loop which makes for a lot of typing.
    * oneOnAtATimeLoop() does exactly the same thing with less typing
    */

    void oneAfterAnotherNoLoop(){
      int delayTime = 100; //the time (in milliseconds) to pause between LEDs
                           //make smaller for quicker switching and larger for slower
      digitalWrite(ledPins[0], HIGH);  //Turns on LED #0 (connected to pin 2 )
      delay(delayTime);                //waits delayTime milliseconds
      digitalWrite(ledPins[1], HIGH);  //Turns on LED #1 (connected to pin 3 )
      delay(delayTime);                //waits delayTime milliseconds
      digitalWrite(ledPins[2], HIGH);  //Turns on LED #2 (connected to pin 4 )
      delay(delayTime);                //waits delayTime milliseconds
      digitalWrite(ledPins[3], HIGH);  //Turns on LED #3 (connected to pin 5 )
      delay(delayTime);                //waits delayTime milliseconds
      digitalWrite(ledPins[4], HIGH);  //Turns on LED #4 (connected to pin 6 )
      delay(delayTime);                //waits delayTime milliseconds
      digitalWrite(ledPins[5], HIGH);  //Turns on LED #5 (connected to pin 7 )
      delay(delayTime);                //waits delayTime milliseconds
      digitalWrite(ledPins[6], HIGH);  //Turns on LED #6 (connected to pin 8 )
      delay(delayTime);                //waits delayTime milliseconds
      digitalWrite(ledPins[7], HIGH);  //Turns on LED #7 (connected to pin 9 )
      delay(delayTime);                //waits delayTime milliseconds
    //Turns Each LED Off
      digitalWrite(ledPins[7], LOW);  //Turns on LED #0 (connected to pin 2 )
      delay(delayTime);                //waits delayTime milliseconds
      digitalWrite(ledPins[6], LOW);  //Turns on LED #1 (connected to pin 3 )
      delay(delayTime);                //waits delayTime milliseconds
      digitalWrite(ledPins[5], LOW);  //Turns on LED #2 (connected to pin 4 )
      delay(delayTime);                //waits delayTime milliseconds
      digitalWrite(ledPins[4], LOW);  //Turns on LED #3 (connected to pin 5 )
      delay(delayTime);                //waits delayTime milliseconds
      digitalWrite(ledPins[3], LOW);  //Turns on LED #4 (connected to pin 6 )
      delay(delayTime);                //waits delayTime milliseconds
      digitalWrite(ledPins[2], LOW);  //Turns on LED #5 (connected to pin 7 )
      delay(delayTime);                //waits delayTime milliseconds
      digitalWrite(ledPins[1], LOW);  //Turns on LED #6 (connected to pin 8 )
      delay(delayTime);                //waits delayTime milliseconds
      digitalWrite(ledPins[0], LOW);  //Turns on LED #7 (connected to pin 9 )
      delay(delayTime);                //waits delayTime milliseconds
    }
    /*
    * oneAfterAnotherLoop() - Will light one LED then delay for delayTime then light
    * the next LED until all LEDs are on it will then turn them off one after another
    *
    * this does it using a loop which makes for a lot less typing.
    * than oneOnAtATimeNoLoop() does exactly the same thing with less typing
    */

    void oneAfterAnotherLoop(){
      int delayTime = 100; //the time (in milliseconds) to pause between LEDs
                           //make smaller for quicker switching and larger for slower
    //Turn Each LED on one after another
      for(int i = 0; i <= 7; i++){
        digitalWrite(ledPins[i], HIGH);  //Turns on LED #i each time this runs i
        delay(delayTime);                //gets one added to it so this will repeat
      }                                  //8 times the first time i will = 0 the final
                                         //time i will equal 7;
    //Turn Each LED off one after another
      for(int i = 7; i >= 0; i--){  //same as above but rather than starting at 0 and counting up
                                    //we start at seven and count down
        digitalWrite(ledPins[i], LOW);  //Turns off LED #i each time this runs i
        delay(delayTime);                //gets one subtracted from it so this will repeat
      }                                  //8 times the first time i will = 7 the final
                                         //time it will equal 0
                                       
                                       
    }
    /*
    * oneOnAtATime() - Will light one LED then the next turning off all the others
    */

    void oneOnAtATime(){
      int delayTime = 100; //the time (in milliseconds) to pause between LEDs
                           //make smaller for quicker switching and larger for slower
     
      for(int i = 0; i <= 7; i++){
        int offLED = i - 1;  //Calculate which LED was turned on last time through
        if(i == 0) {         //for i = 1 to 7 this is i minus 1 (i.e. if i = 2 we will
          offLED = 7;        //turn on LED 2 and off LED 1)
        }                    //however if i = 0 we don't want to turn of led -1 (doesn't exist)
                             //instead we turn off LED 7, (looping around)
        digitalWrite(ledPins[i], HIGH);     //turn on LED #i
        digitalWrite(ledPins[offLED], LOW); //turn off the LED we turned on last time
        delay(delayTime);
      }
    }
    /*
    * inAndOut() - This will turn on the two middle LEDs then the next two out
    * making an in and out look
    */

    void inAndOut(){
      int delayTime = 100; //the time (in milliseconds) to pause between LEDs
                           //make smaller for quicker switching and larger for slower
     
      //runs the LEDs out from the middle
      for(int i = 0; i <= 3; i++){
        int offLED = i - 1;  //Calculate which LED was turned on last time through
        if(i == 0) {         //for i = 1 to 7 this is i minus 1 (i.e. if i = 2 we will
          offLED = 3;        //turn on LED 2 and off LED 1)
        }                    //however if i = 0 we don't want to turn of led -1 (doesn't exist)
                             //instead we turn off LED 7, (looping around)
        int onLED1 = 3 - i;       //this is the first LED to go on ie. LED #3 when i = 0 and LED
                                 //#0 when i = 3
        int onLED2 = 4 + i;       //this is the first LED to go on ie. LED #4 when i = 0 and LED
                                 //#7 when i = 3
        int offLED1 = 3 - offLED; //turns off the LED we turned on last time
        int offLED2 = 4 + offLED; //turns off the LED we turned on last time
       
        digitalWrite(ledPins[onLED1], HIGH);
        digitalWrite(ledPins[onLED2], HIGH);  
        digitalWrite(ledPins[offLED1], LOW);  
        digitalWrite(ledPins[offLED2], LOW);      
        delay(delayTime);
      }
      //runs the LEDs into the middle
      for(int i = 3; i >= 0; i--){
        int offLED = i + 1;  //Calculate which LED was turned on last time through
        if(i == 3) {         //for i = 1 to 7 this is i minus 1 (i.e. if i = 2 we will
          offLED = 0;        //turn on LED 2 and off LED 1)
        }                    //however if i = 0 we don't want to turn of led -1 (doesn't exist)
                             //instead we turn off LED 7, (looping around)
        int onLED1 = 3 - i;       //this is the first LED to go on ie. LED #3 when i = 0 and LED
                                 //#0 when i = 3
        int onLED2 = 4 + i;       //this is the first LED to go on ie. LED #4 when i = 0 and LED
                                 //#7 when i = 3
        int offLED1 = 3 - offLED; //turns off the LED we turned on last time
        int offLED2 = 4 + offLED; //turns off the LED we turned on last time
       
        digitalWrite(ledPins[onLED1], HIGH);
        digitalWrite(ledPins[onLED2], HIGH);  
        digitalWrite(ledPins[offLED1], LOW);  
        digitalWrite(ledPins[offLED2], LOW);      
        delay(delayTime);
      }
    }
     
     
  9. Unixon

    Unixon Оракул Модератор

    Вы слишком усложняете.
    Берете примитив
    Код (C++):

    const int N = 3;
    for (int i=0; i<N; i++)
    {
      // do something
    }
    while (true); // halt
     
    и ставите его хоть в loop() хоть в setup()...
     
    wildofficer нравится это.
  10. wildofficer

    wildofficer Нуб

    В setup() не пробовал. В loop() все работает. Спасибо!!!
    Где я не в ту сторону думал? Действительно ли byte сразу заполняется как "mcureenab" писал? (хотя для меня пока байты тоже непонятны)
    Можно хоть чуток смысл происходящего пояснить, почему с do не работало?
     
  11. Jedi

    Jedi Гик

    Потому что do (выполнять то, что в фигурных скобках) { counter++; (то есть увеличивать значение ячейки памяти на 1 каждую 1/16 микросекунды) } while(counter<3) (пока значение ячейки памяти меньше трех);

    Что просили, то и сделал процессор. Просили до трех досчитать и больше ничего, он это и выполнил. А то, что моргнуть глазом не успели, так это не вина процессора
     
    wildofficer нравится это.
  12. wildofficer

    wildofficer Нуб

    Добрый день форумчане! Опять прошу помощи в моем обучении. В скетче диод загорается от 0 до 7 и 7 до 0. Помогите пожалуйста, как сделать чтобы оба цикла for в loop выполнялись одновременно ?
    Спасибо!

    Код (C++):

    int ledPins[] = {2,3,4,5,6,7,8,9};

    void setup()
    {
      int index;

        for(index = 0; index <= 7; index++)
      {
        pinMode(ledPins[index],OUTPUT);
      }
    }


    void loop()
    {
      pingPong();
    }


    void pingPong()
    {
      int index;
      int delayTime = 100;
     

     
      for(index = 0; index <= 7; index++)
      {
        digitalWrite(ledPins[index], HIGH);
        delay(delayTime);                  
        digitalWrite(ledPins[index], LOW);  
      }

      for(index = 7; index >= 0; index--)
      {
        digitalWrite(ledPins[index], HIGH);
        delay(delayTime);                  
        digitalWrite(ledPins[index], LOW);  
      }
    }
     
     
  13. Tomasina

    Tomasina Сушитель лампочек Модератор

    Код (C++):
    const byte ledCols = 8;
    const byte ledPins[ledCols] = {2, 3, 4, 5, 6, 7, 8, 9};

    void setup()
    {
      byte index;
      for (index = 0; index < ledCols; index++)
      {
        pinMode(ledPins[index], OUTPUT);
      }
    }


    void loop()
    {
      pingPong();
    }


    void pingPong()
    {
      static const unsigned int delayTime = 100;

      for (byte index = 0; index < ledCols; index++)
      {
        digitalWrite(ledPins[index], HIGH);
        digitalWrite(ledPins[ledCols -1 - index], HIGH);
        delay(delayTime);
        digitalWrite(ledPins[index], LOW);
        digitalWrite(ledPins[ledCols -1 - index], LOW);
        //delay(delayTime);
      }
    }
     
    Последнее редактирование: 13 май 2017
    wildofficer нравится это.
  14. mcureenab

    mcureenab Гуру

    Тело второго цикла поместить в первый. Чтобы сохранить порядок включения index заменить на 7 - index.
     
    wildofficer нравится это.
  15. wildofficer

    wildofficer Нуб

    Tomasina, вы как всегда выручаете! Хотя я ожидал, что будет попроще..
    Спасибо! Буду разбираться.
     
  16. Tomasina

    Tomasina Сушитель лампочек Модератор

    гм, а что тут сложного?
    Обратное движение - это всего лишь из максимального номера вычесть текущий. Обычная математика ;)
     
  17. wildofficer

    wildofficer Нуб

    Спасибо, mcureenab! Так что ли?
    Код (C++):


    int ledPins[] = {2,3,4,5,6,7,8,9};

    void setup()
    {
       int index;

         for(index = 0; index <= 7; index++)
       {
         pinMode(ledPins[index],OUTPUT);
       }
    }


    void loop()
    {
       pingPong();
    }


    void pingPong()
    {
       int index;
       int delayTime = 100;



       for(index = 0; index <= 7; index++)
       {
         digitalWrite(ledPins[index], HIGH);
         delay(delayTime);                
         digitalWrite(ledPins[index], LOW);
         digitalWrite(ledPins[7-index], HIGH);
         delay(delayTime);                
         digitalWrite(ledPins[7-index], LOW);
       }

      /* for(index = 7; index >= 0; index--)
       {
         digitalWrite(ledPins[index], HIGH);
         delay(delayTime);                
         digitalWrite(ledPins[index], LOW);
       }
       */

    }
     
     
  18. qwone

    qwone Гик

    Новички такие ... блин "новички". В общем код
    Код (C++):
    //pingPong.ino
    const byte Led_pin[] = {2, 3, 4, 5, 6, 7, 8, 9};
    const int time = 100;
    int pos = 0; // позиция 0..7
    int dir = 1; // направление движения +1 вправо -1 влево
    void pingPong_setup() {
      for (int i = 0; i <= 7; i++) {
        pinMode(Led_pin[i], OUTPUT);
        digitalWrite(Led_pin[i], LOW);
      }
    }
    void pingPong() {
      static uint32_t past = 0;
      if (millis() - past >= time) {
        past = millis();
        digitalWrite(Led_pin[pos], LOW);
        if (pos + dir > 7) dir = -1;
        if (pos + dir < 0) dir = 1;
        pos += dir;
        digitalWrite(Led_pin[pos], HIGH);
      }
    }
    void setup() {
      pingPong_setup();
    }

    void loop() {
      pingPong();
    }
     
  19. mcureenab

    mcureenab Гуру

    Как бы так. Пины будут срабатывать поочередно. 0,7,1,6,2,5...
    У Томасины порядок тот же но одновременно срабатывает два противоположных пина.
    Как вам надо я не знаю.
     
  20. wildofficer

    wildofficer Нуб

    :);):D Спасибо!