Can you give some examples of situations where a while loop and a if loop would be appropriate?
I am working on this project where an Arduino reads an analog input from a variable resistor.
This is how I have it read the raw input:
int intputValue = analogRead(A0);
Then I convert the raw input into a number between 0 and 100 for percentage:
double percentValue = inputValue * (1.0/10.23);
So then I use this percentValue to determine whether the Arduino needs to send signal(s) through several of its digital pins. I have signals going to a 4 channel relay module. Basically my idea is that if the percentValue is between 0-25, one of the relays would turn on, hence only one digital pin would need to be activated. Between 26-50, two pins, 51-75, three pins, and 76-100, four pins.
Here's my question: Should I use a if statement:
if(percentValue >=0 && percentValue <=25){
digitalWrite(pin1, HIGH); //turns on pin 1
}
Or use a while loop:
while(percentValue >= 0 && percentValue <=25){
digitalWrite(pin1, HIGH); //turns on pin 1
}
Then I'm going to do a similar thing for the rest of the percentValue ranges.
Is there a difference between using "if" and "while" in this case?
Thanks for any help.
There should be a setup and loop function in your code, you can put if in your loop function.
void setup() {
// put your setup code here, to run once:
int intputValue = analogRead(A0);
}
void loop() {
// put your main code here, to run repeatedly:
double percentValue = inputValue * (1.0/10.23);
if(percentValue >= 0 && percentValue <= 25){
digitalWrite(pin1, HIGH); //turns on pin 1
}
}
While loops are used to run a specific code block as long as certain parameters are met. An if statement is similar but it will only run the said code block once but a while statement will run until told otherwise.
So effectively:
while(1 == 1)
{
System.out.println("Hello World");
}
Will print Hello World indefinitely. On the other hand:
if(1 == 1)
{
System.out.println("Hello World");
}
Will print Hello World once.
Just for fun since your understanding of loops is shady; a for loop will run a specified number of times:
for(int i = 0; i < 3; i++)
{
System.out.println("Hello World");
}
Would print Hello World 3 times.
refer to:
While loop
For loop
If statement
General Java Tutorials
"Then I'm going to do a similar thing for the rest of the percentValue ranges."
This implies you should use an if statement, and not a while loop, especially if you want to do anything else with the device.
Presumably, this code will be placed in the Arduino loop() function, which is called repeatedly, giving you a loop. You don't want the Arduino to get stuck in a while loop of your own.
It appears that you want to light up different LEDs depending on the reading. You will want to turn off the other LEDs in the body of your if statements as well. Otherwise, the Arduino will just eventually have all 4 LEDs lit up.
if(percentValue >=0 && percentValue <=25){
digitalWrite(pin1, HIGH); //turns on pin 1
digitalWrite(pin2, LOW);
digitalWrite(pin3, LOW);
digitalWrite(pin4, LOW);
}
// etc.
Related
I wanted to execute a simple loop in Arduino UNO at the same time, but I don't know what statement/code use to able to execute it at the same time.
I've tried the while loop and having a time include starting. But since the function is separated from one another in the loop. The execution of the led is the 1st function and 2nd function in different direction. But I want them to be executed at the same time.
void loop() {
// loop from the highest pin to the lowest:
for (int thisPin = 2; thisPin >= 0; thisPin--) {
// turn the pin on:
digitalWrite(ledPins[thisPin], HIGH);
delay(timer);
// turn the pin off:
digitalWrite(ledPins[thisPin], LOW);
}
// loop from the lowest pin to the highest:
for (int thisPin = 0; thisPin < pinCount; thisPin++) {
// turn the pin on:
digitalWrite(ledPins[thisPin], HIGH);
delay(timer);
// turn the pin off:
digitalWrite(ledPins[thisPin], LOW);
}
}
It turns out that the execution is executed in function from the highest pin to lowest pin. Then, the lowest pin to the highest pin. Instead of executed at the same time.
Arduino doesn't have the usual capabilities to run tasks in parallel (it doesn't have multithreading). There are however some workarounds. See https://arduino.stackexchange.com/questions/286/how-can-i-create-multiple-running-threads for more details.
Fortunately in your case you don't need to run the loops in parallel. You can rethink your algorithm in one loop by turning at the same time the pins at opposite sides. Something like this:
for (int i = 0; i < pinCount; ++i) {
// turn the pins on:
digitalWrite(ledPins[i], HIGH);
digitalWrite(ledPins[pinCount - i - 1], HIGH);
delay(timer);
// turn the pins off:
digitalWrite(ledPins[i], HIGH);
digitalWrite(ledPins[pinCount - i - 1], LOW);
}
If you want to do multiple things at the same time, this example here is very useful https://forum.arduino.cc/index.php?topic=223286.0 while they may technically be out of sync it would be on a tiny scale
I am setting up a slot machine with 3 squares that blink alternatively using double buffering; the while loop is infinite and stops using kbhit() (Which I believe is the mistake), even though the loop stops the commands in the if condition is not executed.
rectangle()-A function I wrote to make three squares spaced out equally on the screen.
while(z!=1)
{
if(kbhit()!=0)
{ cleardevice();
delay(3000);
bar3d((150),(110),(230),(190),0,0);
z=1;
continue;}
setvisualpage(page);
setactivepage(1-page);
settextstyle(3,0,5);
rectangle((x-190),y,(x+190),(y+60));
outtextxy((x-120),(y+3),"Slot Machine");
if(page==0)
setfillstyle(SOLID_FILL,4);
else
setfillstyle(SOLID_FILL,GREEN);
rectanfle(x,y);
setfillstyle(SOLID_FILL,BLUE);
bar3d((x-90),(y+255),(x+90),(y+295),5,5);
floodfill((x-89),(y+264),WHITE);
settextstyle(0,0,2);
outtextxy((x-85),(y+265),"Press Enter");
page=1-page;
delay(100);
}
I am having trouble getting this loop to only run once. I have a flag set and my understanding is it will run through once, change flag = 1, then not run through again but when I execute it, the loop runs over and over again. Any help is appreciated.
EDIT: The issue I'm finding is even when my voltage satisfies the if statement, the loop continues to run.
voltage = analogRead(A0); //reads in voltage from pin A0
Serial.println(voltage);
//Calibration routine
do {
if ((voltage >= 1) && (voltage <= 10)) {
//while the voltage is between 4.88 and 48.8 mV the calibration light will flash once
//this ensures the voltage is above 0 and lower than the threshold for the max voltage routine
digitalWrite(calibrationLED, HIGH);
delay(2000);
digitalWrite(calibrationLED, LOW);
delay(1000);
digitalWrite(calibrationLED, HIGH);
delay(2000);
Serial.println("Calibrated");
delay(5000);
voltageInitial = analogRead(A0);
//stores the initial voltage to a separate variable, does not change over the course of the crimp
Serial.println("Initial Voltage: ");
Serial.println(voltageInitial);
flag = 1;
}
} while (flag == 0);
The flag variable will only get set to 1 if the if condition is true. This happens when voltage has a value from 1 to 10.
If the value of voltage is not in the range 1 - 10, flag will not be set. And since voltage is never modified inside of the loop, you have an infinite loop.
"the loop runs over and over again. "
It smells the loop never enter inside if ((voltage >= 1) && (voltage <= 10)) ,
thus never set flag = 1;
So naturally it keep running.
This is an infinite loop actually until the value of the voltage comes between 1 to 10. so flag=1 should be out of the if condition. Otherwise you can add a break after if condition is finished. It will execute exactly once after the condition.
You are waiting for the voltage variable to change, without actually changing it (reading from analog pin).
You need to add voltage = analogRead(A0); into your loop.
do
{
voltage = analogRead(A0);
if ((voltage >= 1) && (voltage <= 10)) //while the voltage is between 4.88 and 48.8 mV the calibration light will flash once
{ //this ensures the voltage is above 0 and lower than the threshold for the max voltage routine
...
flag = 1;
}
} while (flag == 0);
Really simple question but I'm not entirely sure how to incorporate a for loop in the if statement I have. Context: I have a humidifier I am trying to automate based on the humidity of the room. I'm using an ardiuno, dht11 humidity sensor and a servo. The humidifier knob has three settings (high low off) and so the servo has three positions. I have the code running so the servo turns appropriately according to the humidity level. The issue is that it fluctuates very easily. To correct that I'm looking to incorporate a for loop so that after let say 60 one second iterations of the humidity being greater than 55 the servo moves. I tried to add a for loop but it doesn't seem to be working.
But this is only my solution based on the little programming I know. If there is a better solution or even an equally viable alternative I'd love to know. I'm currently studying mechanical engineering but I'm finding that to really make something one needs a background in electronics and code. I'm trying to learn both independently through a series of projects and so I'm quite eager to learn. Hopefully this helps explain why I'm asking such a simple questions to begin with.
#include <dht.h>
#include <Servo.h>
Servo myservo;//create servo object to control a servo
dht DHT;
#define DHT11_PIN 7 // pin for humidity sensor ( also measure temp)
void setup() {
myservo.attach(9);//attachs the servo on pin 9 to servo object
myservo.write(0);//statting off position at 0 degrees
delay(1000);//wait for a second
Serial.begin(9600);
}
void loop() {
int chk = DHT.read11(DHT11_PIN); // the follow is just so that I can see the readings come out properly
Serial.print("Temperature = ");
Serial.println(DHT.temperature);
Serial.print("Humidity = ");
Serial.println(DHT.humidity);
delay(500);
if (DHT.humidity > 55) // here is where my code really begins
{
for (int i=0; i>60; i++); // my goal is to execute the follow code after the statement above has been true for 60 one second iterations
{
myservo.write(0);//goes to off position
delay(1000);//wait for a second
}
} else if (DHT.humidity > 40 ) {
for (int i=0; i>60; i++); // same thing here
myservo.write(90);//goes to low position
delay(1000);//wait for a second
}
else
{
for (int i=0; i>60; i++);
myservo.write(180);//goes to high position
delay(1000);
}
} // end of void loop()
Just addressing your question, the following line is incorrect:
for (int i=0; i>60; i++);
Two things:
1) The second statement in the for loop describes the conditions on which it executes. The way it is written, it will only execute when i>60 (not what you want according to the comments).
2) The semicolon after the for statement makes the next block unassociated.
Correct that line to the following:
for (int i=0; i<60; i++)
See the following for more information:
https://www.tutorialspoint.com/cprogramming/c_for_loop.htm
It would probably be helpful to examine your compiler warnings, and/or set a higher warning level, to catch these type of things early (this is, of course, somewhat compiler dependent).
I guess you trying kind of de-bouncing at you need humid level stay in same range for some period.
First, I define conversion function to map humid level to state
#define HUMID_OFF 1
#define HUMID_LOW 2
#define HUMID_HIGH 3
byte state_conv (float humid_level){
if (humid_level > 55) return HUMID_OFF ;
else if (humid_level > 40 ) return HUMID_LOW ;
else return HUMID_HIGH ;
}
Second I will check changing of state and use millis() to count time while current state is steady. if counting time are longer than threshold then change the actual state.
/*Global variable*/
byte actual_state;
byte flag_state;
void setup (){
// Do things that necessary
float humid = dht.readHumidity();
/*Initialize value*/
actual_state = state_conv(humid);
flag_state= state_conv(humid);
}
void loop(){
static unsigned long timer = millis();
float humid = dht.readHumidity();
byte crr_state = state_conv(humid);
if (crr_state != actual_state ){// if state is changing
if (flag_state != crr_state){
/if crr_state change form last iteration then reset timer
flag_state = crr_state;/
timer = millis();
}
else if (millis() - timer > 10000){
//if crr_state not change for 10000 ms (10 second)
actual_state = crr_state; // update actual state to crr_state
}
}
// After this use actual_state to control servo
if (actual_state == HUMID_OFF ){
myservo.write(0);//goes to off position
}
else if (actual_state == HUMID_LOW ){
myservo.write(90);//goes to low position
}
else if (actual_state == HUMID_HIGH ){
myservo.write(180);//goes to high position
}
}
DHT.humidity returns a float, so if you want to compare, then first store this in an int, and then compare.
the best way to explain my problem is in codeform.
const int ringerPin = A0;
const int offhook = A4;
const int onhook = A5;
void setup(){
pinMode(ringerPin, OUTPUT);
pinMode(offhook, INPUT);
pinMode(onhook, INPUT);
randomSeed(analogRead(0));
}
int randCall = random(60000, 3600000); // generate a random number between 1 min and 60 min
//ring every 1 to 60 minutes if the phone is down (hookon) and dont ring if the phone is picked up (no hookon)
void loop()
{
if (digitalRead(hookon) == HIGH)
void loop(){
delay(randCall);
//i dont know how to let this loop below here run for 30 seconds.
void loop()
{
//turn audio off - i dont know how to.
for(int x = 0; x < 15; x++){
digitalWrite(ringerPin, HIGH);
delay(50);
digitalWrite(ringerPin, LOW);
delay(80);
}
delay(2500);
}
else
//play one randomly choosen audiofile out of 10 - i dont know how to
}
}
I would be greatful if there is anybody who can give me some suggestions to my coding problems.?
I wrote them inside the code descriptions.
loop() is not a way to create a loop. loop() is the function that Arduino calls over and over when it can.
To create loops, use while or for. You can think of the loop() function as being the body of a while(true) loop.
That said, you should probably not use loops for what you are trying to do. There is a useful function called millis() that returns the number of milliseconds since the device was turned on. The value overflows every 50 days. You will need to handle that, but I suggest you write the loop() function to check if enough time has passed, and then do what it is supposed to. See this for an example.