Shop OBEX P1 Docs P2 Docs Learn Events
BS2sx Loop optimizations? Different code behaviour. — Parallax Forums

BS2sx Loop optimizations? Different code behaviour.

DonivanDonivan Posts: 23
edited 2004-10-29 20:13 in BASIC Stamp
I was writing some BS2 code last night, and noticed some pronounced differences with seemingly identical code.· The code was to make an LED slowly dim and used the PWM command.· The first code snippet worked, but went too fast.· That is, you don't really see the LED dim, just dims quickly then turns off.· The second (longer, less efficient) code snippet worked OK.· If someone could explain why, that would be great. ·Here they are:

'eyes is defined as pin 4
'
'this does not work well:

FOR tempByte = 20 TO 0 STEP -5
·· FOR temp = 1 TO 20
····· PWM eyes,tempByte,10
·· NEXT
NEXT
'******************
'but moving things to separate
'loops works very well:

FOR temp = 1 TO·20
·· PWM eyes,20,10
NEXT

FOR temp = 1 TO·20
·· PWM eyes,15,10
NEXT

FOR temp = 1 TO·15
· PWM eyes,10,10
NEXT

FOR temp = 1 TO 15
·· PWM eyes,5,10
NEXT

FOR temp = 1 TO 15
·· PWM eyes,1,10
NEXT

'*****************

I realize the last loop won't get executed in the first example, but despite this the difference is very noticable.

Thanks,
Donivan

·

Comments

  • Jon WilliamsJon Williams Posts: 6,491
    edited 2004-10-29 18:25
    You don't need to the - when using the BS2; it determines step direction based on start and end values.

    FOR tempByte = 20 TO 0 STEP 5

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    Jon Williams
    Applications Engineer, Parallax
    Dallas Office
  • DonivanDonivan Posts: 23
    edited 2004-10-29 18:38
    So did the outer loop not execute correctly because of the "step -5" statement?· Is that why the code acted so differently?
  • Jon WilliamsJon Williams Posts: 6,491
    edited 2004-10-29 20:13
    Because negative numbers are stored in two's compliment form, so -5 works out to 65531.

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    Jon Williams
    Applications Engineer, Parallax
    Dallas Office
Sign In or Register to comment.