2 Leds, 3 Pusbuttons Arduino UNO and breadboard - arduino-uno

So when i press button3 it's supposed to make led3 blink and button1 led1 blink
But when i press button2 it's supposed to make them turn off but it wont
Any ideas what might be wrong with my code?
// C++ code
//
const byte button3 = 4;
const byte button1 = 2;
const byte button2 = 3;
const int led1 = 9;
const int led2 = 8;
const int led3 = 7;
int buttonPushCounterRight = 0;
int buttonPushCounterDominant = 0;
int buttonPushCounterLeft = 0;
boolean buttonState = 0;
boolean lastButtonStateRight = 0;
boolean lastButtonStateDominant = 0;
boolean lastButtonStateLeft = 0;
void setup()
{
pinMode(button1, INPUT_PULLUP);
pinMode(button2, INPUT_PULLUP);
pinMode(button3, INPUT_PULLUP);
pinMode(led3, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led1, OUTPUT);
pinMode(A0, INPUT);
Serial.begin(9600);
}
void loop()
{
Serial.println (A0);
int potValue = analogRead (A0);
buttonState = digitalRead(button1);
if (buttonState != lastButtonStateLeft)
{
if (buttonState == LOW)
{
buttonPushCounterLeft++;
Serial.println("on");
Serial.print("button pushes: ");
Serial.println(buttonPushCounterLeft);
}
else
{
Serial.println("off");
}
lastButtonStateLeft = buttonState;
}
buttonState = digitalRead(button3);
if (buttonState != lastButtonStateRight)
{
if (buttonState == LOW)
{
buttonPushCounterRight++;
Serial.println("on");
Serial.print("button pushes: ");
Serial.println(buttonPushCounterRight);
}
else
{
Serial.println("off");
}
lastButtonStateRight = buttonState;
}
buttonState = digitalRead(button2);
if (buttonState != lastButtonStateDominant)
{
if (buttonState == LOW)
{
buttonPushCounterDominant++;
Serial.println("on");
Serial.print("button pushes: ");
Serial.println(buttonPushCounterDominant);
}
else
{
Serial.println("off");
}
lastButtonStateDominant = buttonState;
}
Serial.println(digitalRead(button1));
if (buttonPushCounterLeft == 1)
{
digitalWrite(led3, HIGH);
delay (potValue);
digitalWrite(led3, LOW);
delay (potValue);
}
Serial.println(digitalRead(button2));
if (buttonPushCounterDominant == 1)
{
digitalWrite(led3, LOW);
digitalWrite(led1, LOW);
}
Serial.println(digitalRead(button3));
if (buttonPushCounterRight == 1)
{
digitalWrite(led1, HIGH);
delay (potValue);
digitalWrite(led1, LOW);
delay (potValue);
}
}
When i press button2 once it will turn off the 2 leds but it doesn't
Other than that i don't know what to do.
Please guide me through my code and or possible solutions would be nice

Related

How do I turn off my void loop function after a certain IF condition is met? (arduino)

I am trying to make a simple burglar alarm using magnet value as my door. After pressing button1 it goes into countdown and then the user should be able to press button1 again to insert a 3 digit code with the help of pmeter. Except that after button1 is clicked it calls toggleOnOff() again. How do I block my void toggleOnOff() function after the conditions of the first IF statement are met? Thank you in advance.
int startMagnetValue;
int Code[3] = {1, 2, 3};
int userCode[3] = {0, 0, 0};
int secondsLimit = 20;
int countDown;
int pMeter = 0;
int pMin = 14;
int pMax = 948;
unsigned long time_now = 0;
unsigned long time_then = 0;
unsigned long seconds = 0;
unsigned long secondsbefore = 1;
unsigned long interval = 1000;
void setup() {
initializeBreadboard();
startMagnetValue = analogRead(MAGNETSENSOR);
}
//turns off leds
void turnOffLEDS() {
digitalWrite(LED_RED, LOW);
digitalWrite(LED_BLUE, LOW);
digitalWrite(LED_YELLOW, LOW);
digitalWrite(LED_GREEN, LOW);
}
// returns true when the difference is bigger than 50, returns false when it's less than 50. True meaning door is open and False meaning it is closed
bool isOpen(int magnetValue) {
int magnetValueDifference = abs(startMagnetValue - magnetValue);
if (magnetValueDifference <= 50) {
return true;
} else {
return false;
}
}
//Toggles the alarm On or Off
void toggleOnOff() {
isAlarmOn = !isAlarmOn;
delay(200);
}
//registers if the alarm is on or off, also prints current magnet value to the oled
void loop() {
pMeter = analogRead(POTENTIOMETER);
int currentMagnetValue = analogRead(MAGNETSENSOR);
pMeter = map(pMeter, pMin, pMax, 0, 9); //translates pmeter to simple digits
OLED.printBottom(pMeter);
Serial.println(userCode[1]);
//On Off
if (digitalRead(BUTTON1)) {
toggleOnOff();
}
// Door Open, Alarm On
if(isOpen(currentMagnetValue) && isAlarmOn) {
turnOffLEDS();
digitalWrite(LED_RED, HIGH);
OLED.printTop(secondsLimit);
time_now = millis();
while((time_now - time_then) >= 1000)
{ secondsLimit--;
time_then = time_now;
Serial.println(secondsLimit);
}
if (userCode[1] = 0) {
if (digitalRead(BUTTON1)) {
userCode[1] = pMeter;
}
}
if (userCode[2] = 0) {
if (digitalRead(BUTTON1)) {
userCode[2] = pMeter;
}
}
if (userCode[3] = 0) {
if (digitalRead(BUTTON1)) {
userCode[3] = pMeter;
}
}
if (Code == userCode) {
isAlarmOn = false;
}
if (secondsLimit <= 0) {
digitalWrite(BUZZER, HIGH);
turnOffLEDS();
while (secondsLimit <= 0) {
OLED.print("INTRUDER");
turnOffLEDS();
digitalWrite(LED_RED, HIGH);
delay(100);
turnOffLEDS();
digitalWrite(LED_BLUE, HIGH);
delay(100);
turnOffLEDS();
digitalWrite(LED_YELLOW, HIGH);
delay(100);
turnOffLEDS();
digitalWrite(LED_GREEN, HIGH);
}
}
} else if (isOpen(currentMagnetValue) && !isAlarmOn) {
turnOffLEDS();
digitalWrite(LED_BLUE, HIGH);
//Door closed, Alarm On
} else if (!isOpen(currentMagnetValue) && isAlarmOn) {
turnOffLEDS();
digitalWrite(LED_GREEN, HIGH);
//Door closed, Alarm Off
} else if (!isOpen(currentMagnetValue) && !isAlarmOn) {
turnOffLEDS();
digitalWrite(LED_YELLOW, HIGH);
}
}```

How to exit or break from 'for loop' on Arduino C Program

I'm not new to the programming world, but for last 2 weeks I'm working with Arduino C++. I have a strange problem. In general, I have a 7-segment display that will act as an up counter when the condition is 01, down counter when the condition is 10, 00 for reset to zero, and 11 for stop (pause in that number).
The problem is, when the up or down counter is still counting and I've change the state, the 7-segment is still counting! Besides that, I've printed the status of state when state is changed, but nothing happens. I think maybe there's mistakes in my code, I need some advice from you guys. Here is my code:
*FYI, I've try to use break, return, also call loop(), but nothing happens
*saklar1 = switch1
*saklar2 = switch2
#include <SevSeg.h>
SevSeg sevseg;
const int saklar1 = 2;
const int saklar2 = 3;
void setup() {
byte sevenSegments = 1;
byte commonPins[] = {};
byte sevenPins[] = {11, 10, 9, 8, 7, 6, 5, 4};
bool resistor = true;
sevseg.begin(COMMON_CATHODE, sevenSegments, commonPins, sevenPins, resistor);
sevseg.setBrightness(90);
pinMode(saklar1, INPUT);
pinMode(saklar2, INPUT);
Serial.begin(9600);
}
void loop() {
checking(digitalRead(saklar1), digitalRead(saklar2));
}
void checking(bool saklar1, bool saklar2){
if (saklar1 == LOW && saklar2 == LOW) {
setSevSeg(0);
} else if (saklar1 == LOW && saklar2 == HIGH) {
for (int i=0; i<=9; i++) {
setSevSeg(i);
if (saklar1 != LOW || saklar2 != HIGH) {
Serial.println("STATE CHANGED"); //THIS LINE IS NOT EXECUTED OR PRINTED
checking(digitalRead(saklar1), digitalRead(saklar2));
}
}
} else if (saklar1 == HIGH && saklar2 == LOW) {
for (int i=9; i>=0; i--) {
setSevSeg(i);
if (saklar1 != HIGH || saklar2 != LOW) {
checking(digitalRead(saklar1), digitalRead(saklar2));
}
}
} else if (saklar1 == HIGH && saklar2 == HIGH) {
delay(100); //Stop
}
}
void setSevSeg(int num) {
sevseg.setNumber(num);
sevseg.refreshDisplay();
delay(500); //1 detik
}
In the following code, the control exits the for loop when the sensor value exceeds the threshold.
Reference: [https://www.arduino.cc/reference/en/language/structure/control-structure/break]
int threshold = 40;
for (int x = 0; x < 255; x++) {
analogWrite(PWMpin, x);
sens = analogRead(sensorPin);
if (sens > threshold) { // bail out on sensor detect
x = 0;
break;
}
delay(50);
}

Holding a push button for 3 second in a for loop

I have a button that basically has two functions. The aim is:
First push will blink a LED 15 times.
If someone holds the button longer than 3 seconds while the LED is blinking, it should stop and go back to the initial.
So I checked the Arduino's hold a button page and came up with this code. The problem is that I can not properly stop the blinking. The line Serial.println("DONE!!"); never works.
Where should I check if the button is held or not and should I use interrupt to end the for loop?
Here is my code:
int inPin = 2; // the pin number for input (for me a push button)
int ledPin = 9;
int current; // Current state of the button
// (LOW is pressed b/c I'm using the pullup resistors)
long millis_held; // How long the button was held (milliseconds)
long secs_held; // How long the button was held (seconds)
long prev_secs_held; // How long the button was held in the previous check
byte previous = LOW;
unsigned long firstTime; // how long since the button was first pressed
long millis_held2; // How long the button was held (milliseconds)
long secs_held2; // How long the button was held (seconds)
long prev_secs_held2; // How long the button was held in the previous check
byte previous2 = LOW;
unsigned long firstTime2; // how long since the button was first pressed
void setup() {
Serial.begin(9600); // Use serial for debugging
pinMode(ledPin, OUTPUT);
digitalWrite(inPin, INPUT); // Turn on 20k pullup resistors to simplify switch input
}
void loop() {
current = digitalRead(inPin);
// if the button state changes to pressed, remember the start time
if (current == HIGH && previous == LOW && (millis() - firstTime) > 200) {
firstTime = millis();
}
millis_held = (millis() - firstTime);
secs_held = millis_held / 1000;
// This if statement is a basic debouncing tool, the button must be pushed for at least
// 100 milliseconds in a row for it to be considered as a push.
if (millis_held > 50) {
// check if the button was released since we last checked
if (current == LOW && previous == HIGH) {
// HERE YOU WOULD ADD VARIOUS ACTIONS AND TIMES FOR YOUR OWN CODE
// ===============================================================================
//////////////////////////////////////////////////////// Button pressed Blink 15 times.
if (secs_held <= 0) {
for (int i = 0; i < 15; i++) {
ledblink(1, 750, ledPin);
current = digitalRead(inPin);
if (current == HIGH && previous == LOW && (millis() - firstTime2) > 200) {
firstTime2 = millis();
}
millis_held2 = (millis() - firstTime2);
secs_held2 = millis_held2 / 1000;
if (millis_held2 > 50) {
Serial.print("previousA ");
Serial.print(previous);
Serial.print(" currentA ");
Serial.println(current);
current = digitalRead(inPin);
if (current == HIGH && previous2 == HIGH) {
Serial.println("ALMOST! ");
Serial.println(secs_held2);
if (secs_held2 >= 2 && secs_held2 < 6) {
Serial.println("DONE!!");
}
}
}
previous2 = current;
prev_secs_held2 = secs_held2;
}
}
}
}
previous = current;
prev_secs_held = secs_held;
}
void ledblink(int times, int lengthms, int pinnum) {
for (int x = 0; x < times; x++) {
digitalWrite(pinnum, HIGH);
delay (lengthms);
digitalWrite(pinnum, LOW);
delay(lengthms);
}
}
This is how it would be done without using delay():
int inPin = 2;
int ledPin = 9;
long pressTimer;
long blinkTimer;
long blinkHalfDelay = 500; //milliseconds
int blinkCount = 0;
int blinkLimit = 15;
bool blinkFlag = false;
bool blinkLatch = true;
bool currentBtnState = false;
bool lastBtnState = false;
void setup() {
}
void loop() {
lastBtnState = currentBtnState;
currentBtnState = digitalRead(inPin);
//on rising edge, start timers
if(currentBtnState==true && lastBtnState==false)
{
pressTimer = millis();
}
//debounce activation
if(currentBtnState==true && !blinkFlag && millis()-pressTimer > 50)
{
blinkTimer = millis();
blinkCount = 0;
blinkLatch = true;
blinkFlag = true;
//functional execution would go here
}
if(currentBtnState = false || (millis()-pressTimer>3000 && currentBtnState == true))
{
blinkCount=blinkLimit;
blinkLatch = false;
}
if(blinkFlag == true)
{
if(millis()-blinkTimer > blinkHalfDelay)
{
blinkTimer = millis();
if(blinkLatch)
{
digitalWrite(pinnum, HIGH);
}
else
{
digitalWrite(pinnum, LOW);
blinkCount+=1;
}
}
if(blinkCount>blinkLimit)
{
blinkFlag = false;
digitalWrite(pinnum, LOW);
}
}
}
ps: sorry for not correcting your code directly, but it was kinda hard to read...

SG90 MIcro Servo Motor Push Button Arduino for Vending Machie Prototype

I have made my new code for my prototype again and my problems are:
When the arduino started running, the three SG90 Micro servo motors rotated 360 degrees at the same time and didn't stop. When I pushed the round push button it slowed the speed of rotation of the servo motor.
When I tried to simulate my program to 123d.circuits.io, it worked. I used the momentary push button since there is no round push button there.
What I wanted to achieve is that:
When push button A/B/C is pushed, the servo Motor A/B/C will rotate 360 deg to dispense an item for my vending machine prototype.
Here's my code. Hope you can help me.
#include <Servo.h>
const int pushButtonA = 2;
const int pushButtonB = 4;
const int pushButtonC = 7;
Servo myservoA;
Servo myservoB;
Servo myservoC;
int pos = 0;
int buttonStateA = 0;
int buttonStateB = 0;
int buttonStateC = 0;
void setup() {
Serial.begin(9600);
pinMode(pushButtonA, INPUT);
pinMode(pushButtonB, INPUT);
pinMode(pushButtonC, INPUT);
myservoA.attach(3);
myservoB.attach(5);
myservoC.attach(9);
}
void loop() {
buttonStateA = digitalRead (pushButtonA);
buttonStateB = digitalRead (pushButtonB);
buttonStateC = digitalRead (pushButtonC);
if((buttonStateA == LOW) && (buttonStateB == HIGH) && (buttonStateC == HIGH)){
digitalWrite(3, HIGH);
for(pos = 0; pos <=360; pos++);
myservoA.write(pos);
delay(15);
digitalWrite(3, HIGH);
}
if((buttonStateB == LOW) && (buttonStateA == HIGH) && (buttonStateC == HIGH)){
digitalWrite(5, HIGH);
for(pos = 0; pos <=360; pos++);
myservoB.write(pos);
delay(15);
digitalWrite(5, HIGH);
}
if((buttonStateC == LOW) && (buttonStateB == HIGH) && (buttonStateA == HIGH)){
digitalWrite(9, HIGH);
for(pos = 0; pos <=360; pos++);
myservoC.write(pos);
delay(15);
digitalWrite(9, HIGH);
};
}
There are two problems with your code.
As mentioned by #MikeCAT, the for loops in the code are empty because you added a semi-colon after them. See Effect of semicolon after 'for' loop for further clarification.
There is no need to perform digitalWrite in servo pins. For controlling them just use the method write from the Servo class.
Corrected code:
#include <Servo.h>
const int pushButtonA = 2;
const int pushButtonB = 4;
const int pushButtonC = 7;
Servo myservoA;
Servo myservoB;
Servo myservoC;
int pos = 0;
int buttonStateA = 0;
int buttonStateB = 0;
int buttonStateC = 0;
void setup() {
Serial.begin(9600);
pinMode(pushButtonA, INPUT);
pinMode(pushButtonB, INPUT);
pinMode(pushButtonC, INPUT);
myservoA.attach(3);
myservoB.attach(5);
myservoC.attach(9);
}
void loop() {
buttonStateA = digitalRead (pushButtonA);
buttonStateB = digitalRead (pushButtonB);
buttonStateC = digitalRead (pushButtonC);
if((buttonStateA == LOW) && (buttonStateB == HIGH) && (buttonStateC == HIGH)){
for(pos = 0; pos <=360; pos++) {
myservoA.write(pos);
delay(15);
}
}
if((buttonStateB == LOW) && (buttonStateA == HIGH) && (buttonStateC == HIGH)){
for(pos = 0; pos <=360; pos++) {
myservoB.write(pos);
delay(15);
}
}
if((buttonStateC == LOW) && (buttonStateB == HIGH) && (buttonStateA == HIGH)){
for(pos = 0; pos <=360; pos++) {
myservoC.write(pos);
delay(15);
}
}
}

Read byte from Serial

I´ve made this program that reads info from serial and writes the value binary to 6 LEDs. I don´t feel that it´s the easiest or the fastest way though and that is what I´m really looking for. My code looks like this:
boolean enable = false;
void setup()
{
for (int i = 2; i < 8; i++)
{
pinMode(i, OUTPUT);
}
}
void loop()
{
if (Serial.available() > 0)
{
enable = true;
}
if (enable)
{
while (Serial.available() > 0)
{
byte b = Serial.parseInt();
b = constrain(b, 0, 63);
byte val = b;
for (int i = 7; i >= 2; i--)
{
if (pow(2, (i-2)) <= val)
{
digitalWrite(i, HIGH);
val -= pow(2, (i-2));
}
else
{
digitalWrite(i, LOW);
}
}
}
enable = false;
}
delay(100);
}
A valid code example would be nice. I´ve tried using PORTD but it does not work.
Use binary operations
for(int i = 0 ; i < 8 ; i++ ) {
val = ( b >> i ) & 0x1;
digitalWrite(i, val == 1 ? HIGH : LOW );
}
If you plan some serious serial communication have a look into library I created https://github.com/lukaszkujawa/arduino-serial-helper

Resources