Forum Rule: Always post complete source code & details to reproduce any issue!
Results 1 to 16 of 16

Thread: Teensy 4.0 FOR statement not working

  1. #1

    Teensy 4.0 FOR statement not working

    I hate C. It gives me nothing but problems. Where is a nice straightforward command such as FOR X= 1 to 3 (BASIC).
    I have tried many variations of this program and nothing works PLUS the error description means nothing to me!

    So here is a description of how to use the FOR loop in Arduino C:
    https://startingelectronics.org/soft...e/07-for-loop/
    Look at the first example program:

    Code:
    void setup() {
      int i;
      
      Serial.begin(9600);
      
      for (i = 0; i < 10; i++) {
        Serial.print("i = ");
        Serial.println(i);
      }
    }
    
    void loop() {
    }
    I tried to duplicate this just to blink the on-board LED (on pin 13) three times and then stop.

    Code:
    // For Loop test lighting the LED
    const int ledPin = 13;
    const int x;
    
    void setup() {
      pinMode(ledPin, OUTPUT);
      
    }
    
    
      for (x = 1; x<4; x = x + 1 ) { 
     
      
      digitalWriteFast(ledPin, HIGH); // LED on
      delayMicroseconds(500 * 1000); // Pulse length half second 
      digitalWriteFast(ledPin, LOW); // LED off
      delayMicroseconds(500 * 1000); // Pulse every half second 
      }
    void loop() {
      }
    And so I get a ton of errors:
    Arduino: 1.8.9 (Windows 10), TD: 1.50, Board: "Teensy 4.0, Serial, 600 MHz, Faster, US English"

    C:\Users\DW\Documents\Arduino\Programs\For_loop_te st\For_loop_test.ino:3:11: warning: uninitialized const 'x' [-fpermissive]

    const int x;

    ^

    For_loop_test:11: error: expected unqualified-id before 'for'
    for (x = 1; x<4; x = x + 1 ) {

    ^

    For_loop_test:11: error: 'x' does not name a type
    for (x = 1; x<4; x = x + 1 ) {

    ^

    For_loop_test:11: error: 'x' does not name a type
    for (x = 1; x<4; x = x + 1 ) {

    ^

    expected unqualified-id before 'for'
    So why does it show the 2nd error twice and what is the meaning of a type. The type is identified in the declaration at the top?
    And what is an Unqualified ID?



    (Just so you know how easy this is to do in BASIC here it is.)

    10 FOR X=1 to 3
    20 OUTPUT Led, 1
    30 WAIT 500
    40 OUTPUT Led, 0
    50 WAIT 500
    60 NEXT X
    70 END

    Variables do not have to be defined, no little braces everywhere, case does not matter, easy and it works.

  2. #2
    Senior Member+ Frank B's Avatar
    Join Date
    Apr 2014
    Location
    Germany
    Posts
    8,692
    LOL, of course, the Teensy is the problem...

    Nope

    Think twice: why is x a constant in your program?
    Then, a bracket "}" is on the wrong position.

    (No worry, just yesterday I did not think too and posted a similar simple "problem" here.. <g> I learned it's called PICNIC: Problem In Chair Not In Computer
    Sometimes we need more than 2 eyes to see that.)

  3. #3
    Member KD0RC's Avatar
    Join Date
    May 2019
    Location
    Colorado, USA
    Posts
    81
    Not a C fan either... I grew up on a mainframe using PL/I, Fortran and COBOL...
    The main working components of your program need to be either within the braces of setup, or within the braces of loop. In this case putting it in loop is appropriate so that it continues to blink. Constants are not variables, so you can't use x the way you did. A suggestion would be to define x as a local variable right in the for statement: for (int x = 1; x<4; x = x + 1 )
    Shorthand for incrementing a value can also be used: for (x = 1; x<4; x++)

    With x defined this way, its scope is just within the for loop. If you took the const off the declaration in the beginning, it would work because it would then be a variable not a constant. It would be a global variable and would then be available to any routines that you subsequently write. In a simple example like this, it can be hard to see the value in using a local vs a global variable.

    Len

  4. #4
    Senior Member+ Frank B's Avatar
    Join Date
    Apr 2014
    Location
    Germany
    Posts
    8,692
    Yup,

    the working program looks like this:
    Code:
    // For Loop test lighting the LED
    const int ledPin = 13;
    int x;
    
    void setup() {
      pinMode(ledPin, OUTPUT);
    
      for (x = 1; x < 4; x = x + 1 ) {
    
    
        digitalWriteFast(ledPin, HIGH); // LED on
        delayMicroseconds(500 * 1000); // Pulse length half second
        digitalWriteFast(ledPin, LOW); // LED off
        delayMicroseconds(500 * 1000); // Pulse every half second
      }
      
    }
    
    void loop() {
    }
    For the first programs it's ok to use x as a global variable.
    The old BASIC has no such concept ("local" variables) , so if you're used to it and if it makes easier for you..

    But it's not a good habit and can lead to problems, later.

  5. #5
    Senior Member+ defragster's Avatar
    Join Date
    Feb 2015
    Posts
    14,492
    In this case the "const int x;" was a problem as noted in the compiler output - it is an unchanging constant value with no initial value.

    It shows twice perhaps because the line has two assignments to a const value - but the compiler is confused by the 'for()' being out of place with regard to the braces - noted below it was on function level - not used within a function() {}

    As far as the bad braces that was also indicated in the compiler output as the first problem after the const issue.

    Things like braces and syntax errors can often be identified with a 'Code Format'.

    In the Arduino IDE it has a Tool : Auto Format that has is activated easily with "Ctrl + t"
    Doing that on the code would quickly show that the for() loop was not contained within with setup() or loop() function due to the misplaced brace - and when compiled it was trying to make a function out of it and thus the complaint :: expected unqualified-id before 'for'


    'c' has complex syntax that will let you do anything within the rules. When the rules of syntax are broken the resulting errors as reported are often confusing because it was looking at the provided source and can only report the side effect of the confusion it caused.

    Doing the "Ctrl + t" reformat will also confuse the Auto Format parser and usually leaves a visual trace where the problem starts so that indenting will suddenly not appear as intended.

  6. #6
    I know the Teensy is not the problem, it is the software.
    If X is an integer constant does that mean I cannot assign a new value to it?
    I have already tried removing x from the CONST assignment and putting it under void SETUP.
    That did not fix it but moving the bracket around to make it look like the example fixed it.
    The code blinks the LED 3 times now.
    However the code has a box around one of the brackets. No where does it say what this means. Is there something wrong about it but
    that does not show up in the compiler ?
    Also, if I just ask the code to Verify, it compiles the code and then tries to load it when I did not ask it to load.
    Click image for larger version. 

Name:	Bracket.jpg 
Views:	30 
Size:	78.8 KB 
ID:	23433

  7. #7
    I also noticed that the "void loop()" is not even used in the example. Does that mean I can just eliminate it from the code or is it always required even if not used?
    Also, in the example code there is no ending bracket to close the starting bracket in the "void loop () {" line.
    So I put it in. Shouldn't that be required by the compiler syntax checker?
    These brackets are confusing. In other languages each starting bracket must have a corresponding closing bracket.

  8. #8
    Senior Member+ KurtE's Avatar
    Join Date
    Jan 2014
    Posts
    9,219
    It is showing you where the matching brace is to the brace next to text curser

  9. #9
    Senior Member+ defragster's Avatar
    Join Date
    Feb 2015
    Posts
    14,492
    Use of loop() is optional, but including it is required because 'Arduino' rules say so - it will be called and as empty do nothing - except return and then be called again ... some Millions of times per second on a Teensy 4.0.

    Go ahead and remove it and the compiler will run and the linker will give an error that loop() was not found.

    Verify won't generally try to upload - maybe if the Teensy is in bootloader mode - all it does it confirm the device existence and wake up Teensy Loader. Teensy Loader gets excited by ANY Teensy in bootloader mode and tried to program it.

    On a T_4.x the Button is Program - and will turn on the RED LED and halt execution waiting to have code uploaded. But TeensyLoader doesn't accept that when it is in AUTO mode ( GUI button on the app ) as noted it acts to program it.

    <edit?> : Yes EVERY OPEN brace or parenthesis MUST have a matching closing brace or parenthesis - same with the " double quote on strings or ' single quote on characters. If it was not found it somehow got deleted in the process.

  10. #10
    @KurtE OK, glad to know that the box does not mean something is wrong.
    Thank you everyone for helping me figure this out. It is so frustrating learning C. It is such a clumsy old language. I suppose Arduino used it because it is open sourced.
    It has way too many rules and punctuation requirements.
    What if a Google search was that specific? No one would be using Google. Programmers just put up with it and soldier on.

  11. #11
    Senior Member+ defragster's Avatar
    Join Date
    Feb 2015
    Posts
    14,492
    Actually search engines have a very specific set of syntax for advanced searches that return MUCH better results ... but nobody knows or uses them.

    C is simple the bestest most awesomest language ever is why Arduino picked it. With just a bit of ASM ground work 'c' was used to write 'c' - super efficient and able do anything but jump tall buildings since GOTO is frowned upon, okay so it can do that too. Other languages are probably written in 'c' too as are operating systems.

  12. #12
    "C" will always suck.

    @defragster -- I removed loop to see what would happen and it gives a long hash of words ending in "undefined reference to loop" even though the word loop does not appear in my code.
    So I put "void loop() {" above the LED blink FOR statement and here is what happened:

    Code:
    // For Loop test lighting the LED
    const int ledPin = 13;
    
    
    void setup() {
      pinMode(ledPin, OUTPUT);
      int x;
    
    void loop()  {
      for (x = 1; x < 4; x = x + 1 ) {
        digitalWriteFast(ledPin, HIGH); // LED on
        delayMicroseconds(500 * 1000); // Pulse length half second
        digitalWriteFast(ledPin, LOW); // LED off
        delayMicroseconds(500 * 1000); // Pulse every half second
      }
    }
    }
    And oh the errors: I have no idea why!! The code looks logical to me, and such an easy tiny program! All 3 curly brackets have corresponding brackets. What is going on?

    ERRORS:

    Arduino: 1.8.9 (Windows 10), TD: 1.50, Board: "Teensy 4.0, Serial, 600 MHz, Fastest, US English"

    C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Arduino\libraries -fqbn=teensy:avr:teensy40:usb=serial,speed=600,opt= o3std,keys=en-us -vid-pid=0000_0000 -ide-version=10809 -build-path C:\Users\DW\AppData\Local\Temp\arduino_build_90118 -warnings=default -build-cache C:\Users\DW\AppData\Local\Temp\arduino_cache_70593 3 -verbose C:\Arduino\For_loop_test\For_loop_test.ino
    C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Arduino\libraries -fqbn=teensy:avr:teensy40:usb=serial,speed=600,opt= o3std,keys=en-us -vid-pid=0000_0000 -ide-version=10809 -build-path C:\Users\DW\AppData\Local\Temp\arduino_build_90118 -warnings=default -build-cache C:\Users\DW\AppData\Local\Temp\arduino_cache_70593 3 -verbose C:\Arduino\For_loop_test\For_loop_test.ino
    Using board 'teensy40' from platform in folder: C:\Program Files (x86)\Arduino\hardware\teensy\avr
    Using core 'teensy4' from platform in folder: C:\Program Files (x86)\Arduino\hardware\teensy\avr
    Detecting libraries used...
    "C:\\Program Files (x86)\\Arduino\\hardware\\teensy/../tools/arm/bin/arm-none-eabi-g++" -E -CC -x c++ -w -g -Wall -ffunction-sections -fdata-sections -nostdlib -std=gnu++14 -fno-exceptions -fpermissive -fno-rtti -fno-threadsafe-statics -felide-constructors -Wno-error=narrowing -mthumb -mcpu=cortex-m7 -mfloat-abi=hard -mfpu=fpv5-d16 -D__IMXRT1062__ -DTEENSYDUINO=150 -DARDUINO=10809 -DARDUINO_TEENSY40 -DF_CPU=600000000 -DUSB_SERIAL -DLAYOUT_US_ENGLISH "-IC:\\Program Files (x86)\\Arduino\\hardware\\teensy\\avr\\cores\\teen sy4" "C:\\Users\\DW\\AppData\\Local\\Temp\\arduino_buil d_90118\\sketch\\For_loop_test.ino.cpp" -o nul
    Generating function prototypes...
    "C:\\Program Files (x86)\\Arduino\\hardware\\teensy/../tools/arm/bin/arm-none-eabi-g++" -E -CC -x c++ -w -g -Wall -ffunction-sections -fdata-sections -nostdlib -std=gnu++14 -fno-exceptions -fpermissive -fno-rtti -fno-threadsafe-statics -felide-constructors -Wno-error=narrowing -mthumb -mcpu=cortex-m7 -mfloat-abi=hard -mfpu=fpv5-d16 -D__IMXRT1062__ -DTEENSYDUINO=150 -DARDUINO=10809 -DARDUINO_TEENSY40 -DF_CPU=600000000 -DUSB_SERIAL -DLAYOUT_US_ENGLISH "-IC:\\Program Files (x86)\\Arduino\\hardware\\teensy\\avr\\cores\\teen sy4" "C:\\Users\\DW\\AppData\\Local\\Temp\\arduino_buil d_90118\\sketch\\For_loop_test.ino.cpp" -o "C:\\Users\\DW\\AppData\\Local\\Temp\\arduino_buil d_90118\\preproc\\ctags_target_for_gcc_minus_e.cpp "
    "C:\\Program Files (x86)\\Arduino\\tools-builder\\ctags\\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\\Users\\DW\\AppData\\Local\\Temp\\arduino_buil d_90118\\preproc\\ctags_target_for_gcc_minus_e.cpp "
    Compiling sketch...
    "C:\\Program Files (x86)\\Arduino\\hardware\\teensy/../tools/precompile_helper" "C:\\Program Files (x86)\\Arduino\\hardware\\teensy\\avr/cores/teensy4" "C:\\Users\\DW\\AppData\\Local\\Temp\\arduino_buil d_90118" "C:\\Program Files (x86)\\Arduino\\hardware\\teensy/../tools/arm/bin/arm-none-eabi-g++" -x c++-header -O3 -g -Wall -ffunction-sections -fdata-sections -nostdlib -MMD -std=gnu++14 -fno-exceptions -fpermissive -fno-rtti -fno-threadsafe-statics -felide-constructors -Wno-error=narrowing -mthumb -mcpu=cortex-m7 -mfloat-abi=hard -mfpu=fpv5-d16 -D__IMXRT1062__ -DTEENSYDUINO=150 -DARDUINO=10809 -DARDUINO_TEENSY40 -DF_CPU=600000000 -DUSB_SERIAL -DLAYOUT_US_ENGLISH "-IC:\\Program Files (x86)\\Arduino\\hardware\\teensy\\avr/cores/teensy4" "C:\\Users\\DW\\AppData\\Local\\Temp\\arduino_buil d_90118/pch/Arduino.h" -o "C:\\Users\\DW\\AppData\\Local\\Temp\\arduino_buil d_90118/pch/Arduino.h.gch"
    Using previously compiled file: C:\Users\DW\AppData\Local\Temp\arduino_build_90118 \pch\Arduino.h.gch

    "C:\\Program Files (x86)\\Arduino\\hardware\\teensy/../tools/arm/bin/arm-none-eabi-g++" -c -O3 -g -Wall -ffunction-sections -fdata-sections -nostdlib -MMD -std=gnu++14 -fno-exceptions -fpermissive -fno-rtti -fno-threadsafe-statics -felide-constructors -Wno-error=narrowing -mthumb -mcpu=cortex-m7 -mfloat-abi=hard -mfpu=fpv5-d16 -D__IMXRT1062__ -DTEENSYDUINO=150 -DARDUINO=10809 -DARDUINO_TEENSY40 -DF_CPU=600000000 -DUSB_SERIAL -DLAYOUT_US_ENGLISH "-IC:\\Users\\DW\\AppData\\Local\\Temp\\arduino_buil d_90118/pch" "-IC:\\Program Files (x86)\\Arduino\\hardware\\teensy\\avr\\cores\\teen sy4" "C:\\Users\\DW\\AppData\\Local\\Temp\\arduino_buil d_90118\\sketch\\For_loop_test.ino.cpp" -o "C:\\Users\\DW\\AppData\\Local\\Temp\\arduino_buil d_90118\\sketch\\For_loop_test.ino.cpp.o"
    For_loop_test: In function 'void setup()':
    For_loop_test:9: error: a function-definition is not allowed here before '{' token
    void loop() {

    ^

    For_loop_test:7: warning: unused variable 'x'
    int x;

    ^

    For_loop_test:19: error: expected '}' at end of input
    }

    ^

    a function-definition is not allowed here before '{' token

  13. #13
    Member
    Join Date
    Aug 2018
    Location
    Brisbane, Australia
    Posts
    59
    The errors are a result of you defining loop() within setup()

    Code:
    void setup() {
      pinMode(ledPin, OUTPUT);
      int x;
    
    void loop()  {
      for (x = 1; x < 4; x = x + 1 ) {
        digitalWriteFast(ledPin, HIGH); // LED on
        delayMicroseconds(500 * 1000); // Pulse length half second
        digitalWriteFast(ledPin, LOW); // LED off
        delayMicroseconds(500 * 1000); // Pulse every half second
      }
    }
    }
    Try this instead
    Code:
    void setup() {
      pinMode(ledPin, OUTPUT);
    }
      int x;
    
    void loop()  {
      for (x = 1; x < 4; x = x + 1 ) {
        digitalWriteFast(ledPin, HIGH); // LED on
        delayMicroseconds(500 * 1000); // Pulse length half second
        digitalWriteFast(ledPin, LOW); // LED off
        delayMicroseconds(500 * 1000); // Pulse every half second
      }
    }

  14. #14
    Senior Member+ defragster's Avatar
    Join Date
    Feb 2015
    Posts
    14,492
    Yes as noted by @thebigg - the closing brace wasn't respected on setup() and you can't put a loop() function inside of another function and have it work.

    If "Ctrl+T" had been done it would have shown that by indenting it off the left edge - rather than leaving it on the left edge. Maybe the IDE isn't in use? If so - hit Ctrl+t - to get uniform formatting and then glance at the code for odd spacing/indenting. I don't use the IDE - but in SublimeText I found its FORMAT and tied it to an open key sequence just so I'd have that.

    Also the Brace Matching pictured in post #6 is there to help with things like that. Feel free to click one on either end and then look for the highlight on the other end.

    'c' is as noted most awesome, no line numbers - semi colons still get me on edits - but it hasn't been quite 40 years yet so some day now ...

    c just has a few simple rules: do the syntax right, and enjoy the rope it gives you ... but don't hang yourself with it, and put a semi colon on the end of each line.

    The best thing is to find a book or website perhaps for reference and play with examples ... that's why my post count is what it is ... puzzling things out and and trying not to forget everything I should remember.

    My schooling was on stupid kraap like "PL/I, Fortran and COBOL" - luckily I found the C book by K&R and got into a minicomputer lab on campus ... funny a T_4.1 would blow those fancy mid 80's machines away and doesn't need to be locked in an air conditioned lab.

  15. #15
    @defragster Yes I learned all those older languages too. No semicolons required.
    So I did use that little trick about matching the start and ending brackets and all 3 showed up but I did not realize, but should have, that the setup() should be complete (with end bracket) before starting the loop. Simple stuff. Thanks @the bigg, all the way from Australia, for pointing that out. Just one little out of place curly bracket can screw up the whole blasted thing.

  16. #16
    Senior Member
    Join Date
    Jul 2020
    Posts
    1,121
    Quote Originally Posted by Deane View Post
    @KurtE OK, glad to know that the box does not mean something is wrong.
    Thank you everyone for helping me figure this out. It is so frustrating learning C. It is such a clumsy old language. I suppose Arduino used it because it is open sourced.
    It has way too many rules and punctuation requirements.
    What if a Google search was that specific? No one would be using Google. Programmers just put up with it and soldier on.
    Programmers learn to be precise and methodical. C++ was chosen I suspect because it uses very little runtime resources,
    and allows bare-metal control which is important for a microcontroller. Not sure any other language would fit on the original
    ATmega168 Arduino with 1k of RAM, other than assembler and that's really hard-going!

    Yes, if you use sharp tools you can cut yourself

    My recommendation on learning a new programming language is this:

    Find a tutorial with good coverage of the language and read it 3 times back to back. Each time you'll
    be able to realize the significance of more parts of the language. This may feel tedious, but it will
    make a solid foundation to speed up the learn-by-doing phase, as you'll have fewer misconceptions,
    and understand any technical terms specific to that language.

    Then start working on examples, and writing your own stuff.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •