| PIC Forth Control Structures | ||
| Links PIC Forth manual |
Like all programming languages, PIC Forth has conditional execution and looping. Consider this code: x @ 5 = if led high else led low then This gets the value in variable x (x @) compares it to 5 and if the result is true, turns the led pin high. Otherwise, it turns the led low. Note the odd use of then. In Forth, then ends an if block, which is not intuitive if you've used any other programming language. Some versions of Forth let you replace then with endif and you could certainly write that definition using some Forth trickery. But you might as well get used to seeing it this way so when you read other Forth programs you won't be confused. Of course, the else is optional and you can put as much code as you like in each part of the if statement. PIC Forth supports looping words like: begin, again, while, until, and repeat. Loops generally start with begin and end with repeat, again, while, or until. So: begin work 1 counter @ + dup ! $10 > until This calls the work word and then increments the counter (but leaves a copy of the incremented counter on the stack. Next, it compares the new counter with 10 (hex) and if it is less than or equal to 10, the until word will go back to the top of the loop. Look at the generated code (this requires libstore.fs to be included): ; name: test ; max return-stack depth: 1 0x0040 2012 call 0x012 ; work 0x0041 3001 movlw 0x01 Add 1 to counter 0x0042 0384 decf 0x04,f 0x0043 0080 movwf 0x00 0x0044 0823 movf 0x23,w Counter is at 0x23 0x0045 0780 addwf 0x00,f 0x0046 0800 movf 0x00,w 0x0047 0384 decf 0x04,f 0x0048 0080 movwf 0x00 0x0049 2003 call 0x003 ; any-! 0x004A 0800 movf 0x00,w 0x004B 0A84 incf 0x04,f 0x004C 3800 iorlw 0x00 0x004D 1903 btfsc 0x03,2 Optimized test for >10 0x004E 2840 goto 0x040 ; test (rs depth: 1) . . . The while word can occur inside the loop to exit the loop early if desired. Here is a shortcut loop that starts with counter=$10 and works down to zero $10 counter v-for work v-next PIC Forth optimizes loops pretty well. It even detects tail end recursion and converts it to a goto. You can also add assembly language to your programs...
|