필터 지우기
필터 지우기

IF Statement Help?

조회 수: 2 (최근 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 CenterFile Exchange에서 Adding custom doc에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by