Chat freely about anything...

User avatar
By eduperez
#34448
Barnabybear wrote:
Mmiscool wrote:
eduperez wrote:I would also consider using a switch / case statement: https://www.arduino.cc/en/Reference/SwitchCase

Hi, thanks. As it sets a variable for the number of times a for loop circles (its a lighting effet that 50% of the time runs the full effect, 34% and 14% runs a shortened effect). Is there an advantage to switch case over "if and else if"? Or generaly a better way to do this?
Code: Select allrLen = (random(6));
if  (rLen == 0 || rLen ==  1 || rLen ==  2 ){
nZone = 17;
}
else if  (rLen == 3 || rLen ==  4){
nZone = 16;
}
else {
nZone = 15;
{

for (int Zone = 12; Zone <= nZone; Zone++) {


Well, there is a semantic difference: "switch" is more suited when you have to choose an action based on the many values of a variable. For example, I would have done something similar to this (bear in mind that this is untested code):
Code: Select allswitch (random(6)) {
    case 0:
    case 1:
    case 2:
        nZone = 17;
        break;
    case 3:
    case 4:
        nZone = 16;
        break;
    default:
        nZone = 15;
}
User avatar
By Barnabybear
#34462 Hi guys, every days a school day.

@eduperez
Yep your code works:
Code: Select allint nZone;
switch (random(6)) {
    case 0:
    case 1:
    case 2:
        nZone = 17;
        break;
    case 3:
    case 4:
        nZone = 16;
        break;
    default:
        nZone = 15;
}

@igrr
Yep code from your link works:
Code: Select allint nZone;
switch (random(6)) {
    case 0 ... 2:
        nZone = 17;
        break;
    case 3 ... 4:
        nZone = 16;
        break;
    default:
        nZone = 15;
}

Thanks, another tool in the box.

Edit: still playing, this works too:
Code: Select allchar test;
test = 'a';
switch (test) {
    case 'a' ... 'f':
    case 'A' ... 'F':
        test = 17;
        break;
    case 'g' ... 'y':
    case 'G' ... 'Y':
        test = 16;
        break;
    default:
        test = 15;
}


Tested with Arduino 1.6.5 & ESP8266-01.
User avatar
By eduperez
#34491
Barnabybear wrote:Hi guys, every days a school day.
Edit: still playing, this works too:
Code: Select allchar test;
test = 'a';
switch (test) {
    case 'a' ... 'f':
    case 'A' ... 'F':
        test = 17;
        break;
    case 'g' ... 'y':
    case 'G' ... 'Y':
        test = 16;
        break;
    default:
        test = 15;
}


Tested with Arduino 1.6.5 & ESP8266-01.


In C, the expression "'a'" is equivalent to using the ASCII code for the 'a' character: "'a'" is exactly the same constant as "91" or "0x61", the compiler does the conversion for you.