IF Statement Help?

3 ビュー (過去 30 日間)
Ravyn Schmidt
Ravyn Schmidt 2021 年 11 月 18 日
コメント済み: Ravyn Schmidt 2021 年 11 月 23 日
I have a setup with a Potentiometer setup to a servo.
I've now set up 4 LEDs and they are supposed to come on depending on the angle of the servo. I think I have everything right, EXCEPT the IF statemnt. I would really appricate some help. It's supposed to light up one LED from 0-45 degrees, 2 at 45-90, etc.
while(1) %infinite loop, use CTRL+C to end code execution
potPosition = readVoltage(a,potPin); %measure position of potentiometer
%use linear interpolation to scale the potentiomenter reading to be between 0 and 1.
servoPosition = interp1([0 5],[0 1],potPosition);
writePosition(s,servoPosition); %set position
CurrentPosition = readPosition(s)*180; %convert position to degrees
fprintf('Current servo position is %4.1f degrees\n', CurrentPosition);
pause(1) %pause for one second before checking the potentiometer again
%if angle of servo is X turn on 1 -4 LEDs
if CurrentPosition < 45
writeDigitalPin(a,gPin,1);
writeDigitalPin(a,rPin,0);
writeDigitalPin(a,bPin,0);
writeDigitalPin(a,yPin,0);
if CurrentPosition < 90
writeDigitalPin(a,gPin,1);
writeDigitalPin(a,rPin,1);
writeDigitalPin(a,bPin,0);
writeDigitalPin(a,yPin,0);
if CurrentPosition < 135
writeDigitalPin(a,gPin,1);
writeDigitalPin(a,rPin,1);
writeDigitalPin(a,bPin,1);
writeDigitalPin(a,yPin,0);
if CurrentPosition < 180
writeDigitalPin(a,gPin,1);
writeDigitalPin(a,rPin,1);
writeDigitalPin(a,bPin,1);
writeDigitalPin(a,yPin,1);
else
writeDigitalPin(a,gPin,0);
writeDigitalPin(a,rPin,0);
writeDigitalPin(a,bPin,0);
writeDigitalPin(a,yPin,0);

回答 (1 件)

Chris
Chris 2021 年 11 月 18 日
編集済み: Chris 2021 年 11 月 18 日
This statement would flow like this, for a 30-degree angle (in pseudocode):
if CurrentPosition < 45
% True, so...
write([1 0 0 0])
if CurrentPosition < 90
% Also true, so...
write([1 1 0 0])
if CurrentPosition < 180
% Still true...
write([1 1 1 0])
if etc
end
end
end
If CurrentPosiiton > 45, none of this ever triggers.
Try elseif
if CurrentPosition < 45
% [0-45) degrees?
write([1 0 0 0])
elseif CurrentPosition < 90
% if previous wasn't true, [45-90) degrees?
write([1 1 0 0])
elseif etc...
else
write([0 0 0 0])
end
  1 件のコメント
Ravyn Schmidt
Ravyn Schmidt 2021 年 11 月 23 日
Thank you so much ! :)

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeAdding custom doc についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by