ashio
September 13, 2023, 6:28pm
1
Hi !
I came here because I really need help for my code. So I have to make a program to make a push button a on/off switch. I found some code parts on internet and assembeld them into this code.
I want to convert the ternary condition to a classic if-else condition but all my atempts didn't work. So I ask if someon has the solution to my problem.
Thanks !
boolean lastButtonState = false;
boolean ledState = false;
void setup() {
pinMode(2, OUTPUT);
pinMode(7, INPUT);
}
void loop() {
int buttonState = digitalRead(7);
if (buttonState != lastButtonState) {
lastButtonState = buttonState;
if (buttonState == LOW) {
ledState = (ledState == true) ? LOW: HIGH;
digitalWrite(2, ledState);
}
}
}
blh64
September 13, 2023, 6:39pm
2
Why? Did your teacher ask you to do it that way?
What have you tried? Post your attempt at doing it and people will help. Writing code for others is not what this forum is about.
alto777
September 13, 2023, 6:58pm
3
Seems straightforward. Do you understand how the ternary operator functions?
See
https://codefinity.com/courses/v2/59a3e4eb-a3a1-49a4-ba70-da98e8fee510/5429077a-e308-4fb9-ba81-7305f195200b/d8948c9a-7af9-4839-ac86-5c191b240295
and read far enough to see how it might look as an if /else statement.
a7
awneil
September 13, 2023, 7:59pm
4
You mean this?
so something like this:
if( some_condition )
{
some_variable = this_value;
}
else
{
some_variable = that_value;
}
Note that the == true
is superfluous - you just need:
ledState = (ledState) ? LOW: HIGH;
Which actually just seems to be inverting the state:
ledState = !ledState;
kolaha
September 14, 2023, 11:46am
6
void setup() {
pinMode(2, OUTPUT);
pinMode(7, INPUT); // external signal? if button then pullup needed
}
void loop() {
static bool lastButtonState = false;
bool buttonState = digitalRead(7);
if (buttonState != lastButtonState) {
lastButtonState = buttonState;
if (buttonState == LOW) digitalWrite(2, ! digitalRead(2));
delay(20);
while (digitalRead(7) == buttonState);
}
}
system
Closed
March 12, 2024, 11:47am
7
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.