Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
8 years, 2 months ago.
Knight Rider using For loops; LPC1768
Hello,
I need to make a Knight Rider program with mbed LPC1768. I have managed to code the part where it goes Right to Left, but can't seem to make it go back Left to Right. Need to use 2 For loops. This is what I've got so far.
BusOut myleds(LED4, LED3, LED2, LED1); BusOut myleds2(LED1, LED2, LED3, LED4); not sure if I need that
int main() { while(1) {
to LED4 after LED1 is lit. for(int i = 1; i < 16 ; i = i*2) { myleds = i; wait(0.5); } for(int i == 16 ; i == 1 ;i == i/2) { myleds2 = i; same here wait(0.5); } }
1 Answer
8 years, 2 months ago.
Firstly please use <<code>> and <</code>>
to format your code correctly, the preview button is your friend.
Here's a revised version of your code that should work. See the comments for the changes. Just about every setting in your for loop was wrong.
BusOut myleds(LED4, LED3, LED2, LED1); // BusOut myleds2(LED1, LED2, LED3, LED4); BAD idea, two things trying to control the same LED is not good. int main() { while(1) { for(int i = 1; i < 16 ; i = i*2) { myleds = i; wait(0.5); } for(int i = 8 ; i > 0 ;i = i/2) { // changed == to =, changed continue condition from == 1 to > 0. Changed start to 8 (the first LED) myleds = i; // changed from myleds2 wait(0.5); } } }
One tidy up you can do is to replace the *2 and /2 with bitwise shifts. Shifting left by one bit is the same as multiplying by 2. It may not look as intuitive to a beginner but once you get the hang of it it's a lot cleaner.
The code would become:
for(int i = 0; i < 4 ; i++) { myleds = 1<<i; wait(0.5); } for(int i = 3; i >= 0 ; i--) { myleds = 1<<i; wait(0.5); }
If you prefer to use multiply/divide then consider using hex for constants. e.g. 0x10 rather than 16. When dealing with binary patterns it's a lot easier to convert from hex than from decimal when reading the code.