IF Statement Help?
4 views (last 30 days)
Show older comments
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);
0 Comments
Answers (1)
Chris
on 18 Nov 2021
Edited: Chris
on 18 Nov 2021
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
See Also
Categories
Find more on Software Development Tools in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!