MATLAB Answers

Arduino ... a lamp

2 views (last 30 days)
clear all
3 a = arduino()
4 configurePin(a,'D6','DigitalInput');
5 configurePin(a,'D9','DigitalOutput');
6 configurePin(a,'A0','DigitalInput');
7 k1 = 0;
8 LED = 0;
9 while(true)
10 while(k1)
11 k1 = readDigitalPin(a,'D6');
12 end
13 while(k1 == 0)
14 k1 = readDigitalPin(a,'D6');
15 end
16 if readVoltage(a,'A0') > 2
17 LED = ~LED;
18 else
19 LED = LED;
20 end
21 writeDigitalPin(a, 'D9', LED);
22 end
why cant i change line 10 and 13 with
while(k1 || (K1 == 0))
k1 = readDigitalPin(a,'D6');
end

  0 Comments

Sign in to comment.

Accepted Answer

Geoff Hayes
Geoff Hayes on 23 Mar 2020
Edited: Geoff Hayes on 23 Mar 2020
duaa - not quite sure what the error message is but I suspect it has to do with your second condition in
while(k1 || (K1 == 0))
Please note how you are using a capital K instead of a lower case k. The conditions should be
while k1 || (k1 == 0)

  5 Comments

Show 2 older comments
duaa Abdulzahra
duaa Abdulzahra on 23 Mar 2020
This way:
while(k1)
11 k1 = readDigitalPin(a,'D6');
12 end
13 while(k1 == 0)
14 k1 = readDigitalPin(a,'D6');
15 end
Or this way:
while k1 || (k1 == 0)
k1 = readDigitalPin(a,'D6');
Both work? OR only the first ont? its just for understanding. Im trying to use a button for turning off and on a LED.
Geoff Hayes
Geoff Hayes on 23 Mar 2020
I would think that both could work but...there may be reason why this was coded the way it was coded. Here is the original code
while(k1)
k1 = readDigitalPin(a,'D6');
end
while(k1 == 0)
k1 = readDigitalPin(a,'D6');
end
So there are two while loops where the first one exits if k1 is zero (or negative, if this is possible). Then the second loop exits only if k1 is non-zero.
If we put the two conditions together as
while k1 || (k1 == 0)
then the loop only exits if k1 is negative. And this is the "danger" - if k1 is never negative and so only takes on values of zero or greater, then we could get stuck in this loop and the remainder of the code will never be executed.
Without knowing the pattern of data (via readDigitalPin) from the Arduino, I would recommend leaving the code as is and NOT combining the two loops.
duaa Abdulzahra
duaa Abdulzahra on 23 Mar 2020
Super thank you! realy an appreciated answer. Tanks again!

Sign in to comment.

More Answers (0)

Sign in to answer this question.

Tags