Input from serial monitor and push button - arduino

So I am doing a project. My task is to create a traffic light system that contains three modes that I can select from, by inputting the numbers 1,2 or 3 to the serial monitor. Everything was alright until I decided to add three push-buttons to the breadboard so I am also able to select any mode via the buttons. So far I have been unable to make the Arduino accept input from the serial monitor and the push buttons at the same time, I don't know if i'm in the right path or not to achieving my objective. I just need a small guidance to this, pls. Here is my current code:
//----------------------- Variables
#define ECHOPIN 3
#define TRIGPIN 2
char inVal;
String inString = "";
const int red_led = 11;
const int yellow_led = 12;
const int green_led = 13;
const int on_delay= 2000, off_delay= 1000; //led delays
const int min_distance = 10; // Distance sensor min distance
const int The_buzzer = 4;
float real_distance; // Distance obtained from function
int ldrPin = A0; // LDR pin
unsigned int sensorValue = 0;
float voltage;
float light_amount;
int brightness = 600; // amount of light treshhold
int button_one = 5;
String ButtonOne;
void setup() {
pinMode(red_led, OUTPUT);
pinMode(yellow_led, OUTPUT);
pinMode(green_led, OUTPUT);
pinMode(The_buzzer, OUTPUT);
Serial.begin(9600);
pinMode(ECHOPIN, INPUT);
pinMode(TRIGPIN, OUTPUT);
pinMode(button_one, INPUT);
}
void loop() {
if (Serial.available()>0)
distanceSensor(0); // distance sensor function
{
inVal=Serial.read();
switch((inVal) | (ButtonOne == "HIGH"))
{
case '1': // ------------------------- Regular Mode
while (true)
{
red_light();
yellow_light();
green_light();
yellow_light();
}
break;
case '2': // ------------------------ Pedestrian Mode
while (true)
{
real_distance = distanceSensor(0);
if (real_distance < min_distance)
{
for (int a= 0; a < 10; a++)
{
tone(The_buzzer,1000);
delay(1000);
noTone(The_buzzer);
delay(1000);
digitalWrite(yellow_led, HIGH);
delay(100);
digitalWrite(yellow_led,LOW);
}
}
real_distance = distanceSensor(0);
if (real_distance > min_distance)
{
red_light();
yellow_light();
green_light();
yellow_light();
}
}
break;
case '3': // --------------------------- NIGHT MODE
while (true)
{
light_amount = LDRSensor(0);
real_distance = distanceSensor(0);
if (light_amount > brightness)
{
red_light();
yellow_light();
green_light();
yellow_light();
red_light();
delay(100);
}
if (light_amount < brightness || real_distance < min_distance)
{
real_distance = distanceSensor(0); // distance sensor reading
if (real_distance > min_distance)
{
digitalWrite(green_led, LOW);
digitalWrite(red_led, HIGH);
}
if (real_distance < min_distance )
{
while(real_distance < min_distance && light_amount < brightness)
{ //maybe change this
digitalWrite(red_led, LOW);
digitalWrite(green_led, HIGH);
real_distance = distanceSensor(0);
}
digitalWrite(green_led, LOW);
}
}
}
break;
default:
standby_mode(); // blinks all leds until 1,2 or 3 is selected
}
}
}
//--------------------------------------- FUNCTIONS -----------------------
//----------------------------------- Red light function
void red_light()
{
digitalWrite(red_led, HIGH);
delay(on_delay);
digitalWrite(red_led,LOW);
}
//---------------------------------- Yellow light function
void yellow_light()
{
digitalWrite(yellow_led, HIGH);
delay(off_delay);
digitalWrite(yellow_led,LOW);
}
//--------------------------------- Green light function
void green_light()
{
digitalWrite(green_led, HIGH);
delay(on_delay);
digitalWrite(green_led,LOW);
}
//------------------------------ --- Distance sensor function
float distanceSensor(int x)
{
digitalWrite(TRIGPIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGPIN,HIGH);
delayMicroseconds(10);
digitalWrite(TRIGPIN,LOW);
float distance = pulseIn(ECHOPIN, HIGH);
distance = distance/58;
Serial.print(distance);
Serial.println("cm");
delay(200);
float distance_reading = distance;
return distance_reading;
}
//------------------------------------- LDR sensor function
float LDRSensor(int h)
{
sensorValue = analogRead(ldrPin);
voltage = sensorValue * (5000.0 / 1024.0);
Serial.print("Sensor Output: ");
Serial.println(sensorValue);
Serial.print("Voltage (mv): ");
Serial.println(voltage);
Serial.println();
delay(5000);
return sensorValue;
}
//------------------------------------- Buzzer Function
void buzzer(unsigned char delayms)
{
analogWrite(The_buzzer, 20);
delay(delayms);
analogWrite(The_buzzer, 0);
delay(delayms);
}
// ------------------------------------- Standby Mode
void standby_mode()
{
for ( int a= 10; a < 14; a++)
{
digitalWrite(a,HIGH);
}
delay(off_delay);
for (int b=10; b < 14; b++)
{
digitalWrite(b,LOW);
}
delay(off_delay);
}

As I mentioned in my top comments, once you enter a given case, you never leave it (i.e. things get "stuck")
So, as I said, have a single outer loop, and each case just does one iteration.
Also, note that, below, inVal only gets changed if the serial port has input data available. So, the single loop approach mimics the multiple loops but still responds to changes in input.
Here is something that I think gets you closer to your intent [please pardon the gratuitous style cleanup]:
//----------------------- Variables
#define ECHOPIN 3
#define TRIGPIN 2
char inVal;
String inString = "";
const int red_led = 11;
const int yellow_led = 12;
const int green_led = 13;
const int on_delay = 2000,
off_delay = 1000; // led delays
const int min_distance = 10; // Distance sensor min distance
const int The_buzzer = 4;
float real_distance; // Distance obtained from function
int ldrPin = A0; // LDR pin
unsigned int sensorValue = 0;
float voltage;
float light_amount;
int brightness = 600; // amount of light treshhold
int button_one = 5;
String ButtonOne;
void
setup()
{
pinMode(red_led, OUTPUT);
pinMode(yellow_led, OUTPUT);
pinMode(green_led, OUTPUT);
pinMode(The_buzzer, OUTPUT);
Serial.begin(9600);
pinMode(ECHOPIN, INPUT);
pinMode(TRIGPIN, OUTPUT);
pinMode(button_one, INPUT);
}
void
loop()
{
// distance sensor function
if (Serial.available() > 0)
distanceSensor(0);
while (1) {
if (Serial.available() > 0)
inVal = Serial.read();
switch ((inVal) | (ButtonOne == "HIGH")) {
case '1': // Regular Mode
red_light();
yellow_light();
green_light();
yellow_light();
break;
case '2': // Pedestrian Mode
real_distance = distanceSensor(0);
if (real_distance < min_distance) {
for (int a = 0; a < 10; a++) {
tone(The_buzzer, 1000);
delay(1000);
noTone(The_buzzer);
delay(1000);
digitalWrite(yellow_led, HIGH);
delay(100);
digitalWrite(yellow_led, LOW);
}
}
real_distance = distanceSensor(0);
if (real_distance > min_distance) {
red_light();
yellow_light();
green_light();
yellow_light();
}
break;
case '3': // NIGHT MODE
light_amount = LDRSensor(0);
real_distance = distanceSensor(0);
if (light_amount > brightness) {
red_light();
yellow_light();
green_light();
yellow_light();
red_light();
delay(100);
}
if (light_amount < brightness || real_distance < min_distance) {
real_distance = distanceSensor(0); // distance sensor reading
if (real_distance > min_distance) {
digitalWrite(green_led, LOW);
digitalWrite(red_led, HIGH);
}
if (real_distance < min_distance) {
while (real_distance < min_distance && light_amount < brightness) { // maybe change this
digitalWrite(red_led, LOW);
digitalWrite(green_led, HIGH);
real_distance = distanceSensor(0);
}
digitalWrite(green_led, LOW);
}
}
break;
default: // blinks all leds until 1,2 or 3 is selected
standby_mode();
break;
}
}
}
//--------------------------------------- FUNCTIONS -----------------------
//----------------------------------- Red light function
void
red_light()
{
digitalWrite(red_led, HIGH);
delay(on_delay);
digitalWrite(red_led, LOW);
}
//---------------------------------- Yellow light function
void
yellow_light()
{
digitalWrite(yellow_led, HIGH);
delay(off_delay);
digitalWrite(yellow_led, LOW);
}
//--------------------------------- Green light function
void
green_light()
{
digitalWrite(green_led, HIGH);
delay(on_delay);
digitalWrite(green_led, LOW);
}
//------------------------------ --- Distance sensor function
float
distanceSensor(int x)
{
digitalWrite(TRIGPIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGPIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGPIN, LOW);
float distance = pulseIn(ECHOPIN, HIGH);
distance = distance / 58;
Serial.print(distance);
Serial.println("cm");
delay(200);
float distance_reading = distance;
return distance_reading;
}
//------------------------------------- LDR sensor function
float
LDRSensor(int h)
{
sensorValue = analogRead(ldrPin);
voltage = sensorValue * (5000.0 / 1024.0);
Serial.print("Sensor Output: ");
Serial.println(sensorValue);
Serial.print("Voltage (mv): ");
Serial.println(voltage);
Serial.println();
delay(5000);
return sensorValue;
}
//------------------------------------- Buzzer Function
void
buzzer(unsigned char delayms)
{
analogWrite(The_buzzer, 20);
delay(delayms);
analogWrite(The_buzzer, 0);
delay(delayms);
}
// ------------------------------------- Standby Mode
void
standby_mode()
{
for (int a = 10; a < 14; a++) {
digitalWrite(a, HIGH);
}
delay(off_delay);
for (int b = 10; b < 14; b++) {
digitalWrite(b, LOW);
}
delay(off_delay);
}

I think you didn't get the way arduino sketches works. The loop() function is called every time in a continuous loop (like a while(true)), so you should make your logic take advantage of this fact.
You use infinite loops inside the loop() function (which is already an infinite loop) so your code gets stuck in one of these loops and never get out, so it will never read the serial buffer or the GPIO pins.

Related

AttachIntrerrupt stops NRF24L01+ from working - ARDUINO

If I remove attachInterrupt(digitalPinToInterrupt(encoder1),readEncoder,RISING); The code works. But once its added, the radio.available doesnt let anything under it run.
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(7, 8); // CE, CSN
const byte address[6] = "00001";
struct InputData // define stuct
{
int x;
int y;
};
InputData data;
// Motor A connections
int motor_enA = 9;
int motor_in1 = 10;
int motor_in2 = 6;
int encoder1 = 2;
int encoder2 = 3;
int counter = 0;
int angle = 0;
void setup() {
Serial.begin(9600);
radio.begin();
radio.openReadingPipe(1, address);
radio.setPALevel(RF24_PA_MIN);
radio.startListening();
// Set all the motor control pins to outputs
pinMode(motor_enA, OUTPUT);
pinMode(motor_in1, OUTPUT);
pinMode(motor_in2, OUTPUT);
// Turn off motors - Initial state
digitalWrite(motor_in1, LOW);
digitalWrite(motor_in2, LOW);
analogWrite(motor_enA, 255);
pinMode (encoder1, INPUT);
pinMode (encoder2, INPUT);
attachInterrupt(digitalPinToInterrupt(encoder1),readEncoder,RISING);
}
void loop() {
readEncoder();
if (radio.available()) {
radio.read(&data, sizeof(data));
// Serial.println(data.y);
if (data.y > 5) {
digitalWrite(motor_in1, HIGH);
digitalWrite(motor_in2, LOW);
}
else if (data.y < -5) {
digitalWrite(motor_in1, LOW);
digitalWrite(motor_in2, HIGH);
}
else {
digitalWrite(motor_in1, LOW);
digitalWrite(motor_in2, LOW);
}
}
if(counter>1){
counter=0;
angle+=2;
}else if(counter<-1){
counter=0;
angle-=2;
}
Serial.print("Position: ");
Serial.println(angle);
}
void readEncoder()
{
if(digitalRead(encoder1)==HIGH){
int b = digitalRead(encoder2);
if(b>0){
counter++;
}
else{
counter--;
}
}
}
I have tried removing and adding the line, as described above^^
as mentioned by Hcheung, make counter volatile and remove readEncoder(); from loop.
I simplify a bit ISR readEncoder();
volatile int counter = 0;
[....]
void readEncoder() {
//if(digitalRead(encoder1)==HIGH){ //we are precisely here because digitalRead(encoder1) = HIGH !
if(digitalRead(encoder2)) counter++;
else counter--;
}

Arduino Anti-Theft System

I have an arduino anti-theft sistem.
The problem is the function void disarm()
//define Variables
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
#include <RTClib.h>
//LCD
#define I2C_ADDR 0x27
#define LCD_COLUMNS 20
#define LCD_LINES 4
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES);
RTC_DS1307 rtc;
// Definire PINI
const int ledPin4 = 4;
const int ledPin5 = 5;
int lastButtonstate = LOW;
int lastState;
int button = 3;
// PIR
int pir = 2; // choose the input pin (for PIR sensor)
int pirState = LOW; // we start, assuming no motion detected
int val = 0;
//Senzor dist
#define trigerPin 9
#define echoPin 10
long duration, distance;
// Arm/Disarm
bool isArmed = false;
//tastatura si parola
char password[5] ="1234"; //create a password
int pozisyon = 0; //keypad position
const byte rows = 4; //number of the keypad's rows and columns
const byte cols = 4;
char keyMap [rows] [cols] = { //define the cymbols on the buttons of the keypad
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte rowPins [rows] = {14, 15, 16, 17}; //pins of the keypad
byte colPins [cols] = {18, 19, 20, 21};
Keypad myKeypad = Keypad( makeKeymap(keyMap), rowPins, colPins, rows, cols);
void setup() {
Serial.begin(9600);
rtc.begin();
pinMode(trigerPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(pir, INPUT);
//Setup for LEDs
pinMode(ledPin4, OUTPUT);
pinMode(ledPin5, OUTPUT);
// Pin Mode Buton
lastState = digitalRead(button);
//Setup for LCD
lcd.init();
lcd.backlight();
lcd.setCursor(5,0);
lcd.print(" Sistem ");
lcd.setCursor(2,1);
lcd.print(" anti-efractie ");
delay(1000);
lcd.clear();
}
void loop() {
int currState = digitalRead(button);
if(currState != lastState && currState == HIGH) {
if(!isArmed) {
arm();
}
else if(isArmed) {
disarm();
}
}
lastState = currState;
pirsenzor();
distsenzor();
delay(100);
}
//=================================FUNCTII & SENZORI=================================
void arm() {
if(!isArmed) {
// Armare si cerere parola
lcd.clear();
lcd.print("Armare sistem");
delay(1000);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Introduceti codul:");
delay(50);
int attempts = 0;
do {
char whichKey = myKeypad.getKey();
if (whichKey != NO_KEY) {
lcd.setCursor(pozisyon, 1);
lcd.print("*");
password[pozisyon] = whichKey;
pozisyon++;
}
if (pozisyon == 4) {
// Verificare parola corecta
if(strcmp(password, "1234") == 0) {
digitalWrite(ledPin5, HIGH);
delay(300);
digitalWrite(ledPin5, LOW);
delay(300);
digitalWrite(ledPin5, HIGH);
delay(300);
digitalWrite(ledPin5, LOW);
delay(300);
digitalWrite(ledPin5, HIGH);
delay(300);
digitalWrite(ledPin5, LOW);
lcd.clear();
lcd.setCursor(5, 0);
lcd.print("Sistem armat");
delay(3000);
lcd.clear();
isArmed = true;
break;
}
else {
// Verificare parola incorecta
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Parola Incorecta!");
delay(1000);
lcd.clear();
pozisyon = 0;
attempts++;
if(attempts == 1)
{
lcd.clear();
break;
}
continue;
}
}
} while (!isArmed);
}
}
void disarm() {
if(isArmed) {
// Dezarmare si cerere parola
lcd.clear();
lcd.print("Dezarmare sistem");
Serial.println("Sunt aici");
delay(1000);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Introduceti codul:");
delay(50);
int attempts = 0;
do {
char whichKey = myKeypad.getKey();
if (whichKey != NO_KEY) {
lcd.setCursor(pozisyon, 1);
lcd.print("*");
password[pozisyon] = whichKey;
pozisyon++;
}
if (pozisyon == 4) {
// Verificare parola corecta
if(strcmp(password, "1234") == 0) {
Serial.println("Am trecut de asta");
digitalWrite(ledPin4, HIGH);
delay(300);
digitalWrite(ledPin4, LOW);
delay(300);
digitalWrite(ledPin4, HIGH);
delay(300);
digitalWrite(ledPin4, LOW);
delay(300);
digitalWrite(ledPin4, HIGH);
delay(300);
digitalWrite(ledPin4, LOW);
lcd.clear();
lcd.setCursor(5, 0);
lcd.print("Sistem dezarmat");
Serial.println("Am facut asta");
delay(3000);
isArmed = false;
lcd.clear();
break;
}
else {
// Verificare parola incorecta
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Parola Incorecta!");
delay(1000);
lcd.clear();
pozisyon = 0;
attempts++;
if(attempts == 3)
{
lcd.clear();
break;
}
}
}
} while (isArmed);
}
}
// Senzor PIR
void pirsenzor() {
distsenzor();
val = digitalRead(pir); // read input value
if (val == HIGH && !isArmed && distance <= 250) {
digitalWrite(ledPin4, HIGH);
delay(300);
digitalWrite(ledPin4, LOW);
delay(300);
digitalWrite(ledPin4, HIGH);
delay(300);
digitalWrite(ledPin4, LOW); // turn LED ON
if (pirState == LOW) {
lcd.setCursor(0, 0);
lcd.print("Motion detected at");
lcd.setCursor(0, 1);
lcd.print(distance);
lcd.print(" m ");
pirState = HIGH;
}
} else {
digitalWrite(ledPin4, LOW); // turn LED OFF
if (pirState == HIGH) {
lcd.clear();
pirState = LOW;
}
}
}
//Senzor distanta
void distsenzor() {
digitalWrite(trigerPin, LOW); // ensure trigger is low
delayMicroseconds(2);
digitalWrite(trigerPin, HIGH); // send a 10us high to trigger
delayMicroseconds(10);
digitalWrite(trigerPin, LOW);
duration = pulseIn(echoPin, HIGH); //Measure the duration of the echo pulse
distance = (duration / 2) / 29.1; //Calculate the distance using the speed of sound
if (distance >= 400 || distance <= 2) { //Check if the distance is out of range
}
}
Everything is good I push the button to arm the system, the system ask to introduce the password everything is ok but when disarm function is called the function bypass password verification step.
A mention I have a pushbutton with a double function (arm/disarm system).
Sorry for my bad english :).
a suggestion or a solution please.
When you arm the system with
isArmed = true;
you should also reset
pozisyon = 0;
because pozisyon == 4 is used as an indicator that a password has been entered

Can you help me fix the error message I am getting on my code?

I have these two sets of code and they both run fine on their own, but when I am trying to merge them together I am getting a ton of error messages. I'm new to coding and don't really know a whole lot so I was wondering if someone could just quickly look it over and see what's wrong. The compiler is saying that there is an expected unqualified id before the '{' token at the bottom where I have the code for the pushbutton. However I have tried and removed this and then I get the same message but instead of '{' it says 'if'
Thank you very much
EDIT: I don't know what properly formatting an error message looks like but here is my attempt:
Complete_Code:69:1: error: expected unqualified-id before '{' token
{
^
exit status 1
expected unqualified-id before '{' token
Here is the code in question
int pinButton = 5;
#include <Servo.h>
int servo1Pin = 8;
Servo servo1;
#include <Servo.h>
#define mainArm 0
#define jib 1
#define bucket 2
#define slew 3
Servo servo[2]; //code used for attaching upto 4 servos
byte angle[2] = {90, 90}; // middle point for servo angle
byte potPin[2] = {A1, A2}; // input pins to attach your potentiometers
byte servoPin[2] = {7, 6};
void setup() {
Serial.begin(9600);
Serial.println("Starting DiggerCode.ino");
for (byte n = 0; n < 4; n++) {
servo[n].attach(servoPin[n]);
}
pinMode(pinButton, INPUT);
pinMode(12, OUTPUT); //red LED
pinMode(11, OUTPUT); // yellow LED
pinMode(10, OUTPUT); // green LED
servo1.attach(servo1Pin);
}
void loop() {
readPotentiometers();
moveServos();
delay(10);
}
void readPotentiometers() {
int potVal;
for (byte n = 0; n < 4; n++) {
potVal = analogRead(potPin[n]);
if (potVal < 200) { // dead zone for the joystick I used is 200 to 550.
angle[n] += 1;
if (angle[n] > 170) {
angle[n] = 170;
}
}
if (potVal > 550) { // deadzone upper value
angle[n] -= 1;
if (angle[n] < 10) {
angle[n] = 10;
}
}
}
}
void moveServos() {
for (byte n = 0; n < 4; n++) {
servo[n].write(angle[n]);
}
}
{
int stateButton = digitalRead(pinButton); //read the state of the button
if (stateButton == HIGH) { //if is pressed
Serial.println("Switch = High");
digitalWrite(12, HIGH);
delay(1000);
digitalWrite(12, LOW);
digitalWrite(11, HIGH);
delay(1000);
digitalWrite(11, LOW);
digitalWrite(10, HIGH);
delay(1000);
digitalWrite(10, LOW);
delay(500);
servo1.write(180);
delay(1000);
// Make servo go to 180 degrees
servo1.write(90);
delay(1000);
servo1.write(180);
}
}
It seems you dropped the first things of function definition for some reason.
Add function return type, name and arguments for example
void anImportedFunction()
Before the part starting from
{
int stateButton = digitalRead(pinButton); //read the state of the button
You may also need to call the added function from somewhere.
I looked through your code and edited, some unnecessary and missing parts.
I checked it, no more syntax errors. I think it must work.
#include <Servo.h>
#define mainArm 0
#define jib 1
#define bucket 2
#define slew 3
Servo servo1;
Servo servo[4]; //code used for attaching upto 4 servos
int pinButton = 5;
int servo1Pin = 8;
byte angle[2] = {90, 90}; // middle point for servo angle
byte potPin[2] = {A1, A2}; // input pins to attach your potentiometers
byte servoPin[2] = {7, 6};
void setup() {
Serial.begin(9600);
Serial.println("Starting DiggerCode.ino");
for (byte n = 0; n <= 4; n++) {
servo[n].attach(servoPin[n]);
}
pinMode(pinButton, INPUT);
pinMode(12, OUTPUT); //red LED
pinMode(11, OUTPUT); // yellow LED
pinMode(10, OUTPUT); // green LED
servo1.attach(servo1Pin);
}
void loop() {
readPotentiometers();
moveServos();
delay(10);
}
void readPotentiometers() {
int potVal;
for (byte n = 0; n <= 4; n++) {
potVal = analogRead(potPin[n]);
if (potVal < 200) { // dead zone for the joystick I used is 200 to 550.
angle[n] += 1;
if (angle[n] > 170) {
angle[n] = 170;
}
}
if (potVal > 550) { // deadzone upper value
angle[n] -= 1;
if (angle[n] < 10) {
angle[n] = 10;
}
}
}
}
void moveServos() {
for (byte n = 0; n <= 4; n++) {
servo[n].write(angle[n]);
}
}
void Switch() //here instead of "Switch" you can use any function name you want
{
int stateButton = digitalRead(pinButton); //read the state of the button
if (stateButton == HIGH) { //if is pressed
Serial.println("Switch = High");
digitalWrite(12, HIGH);
delay(1000);
digitalWrite(12, LOW);
digitalWrite(11, HIGH);
delay(1000);
digitalWrite(11, LOW);
digitalWrite(10, HIGH);
delay(1000);
digitalWrite(10, LOW);
delay(500);
servo1.write(180);
delay(1000);
// Make servo go to 180 degrees
servo1.write(90);
delay(1000);
servo1.write(180);
}
}

Implementing the function interrupt with if statements

I want to implement the function interrupt () but I don't know exactly how..In this case there is 2 for loops which can be seen in the code:I want whenever one of the 2 buttons is pressed the process inside the loop to be interrupted immediately:
void loop() {
int brightButton = digitalRead(K1);
int ldrStatus = analogRead(ldrPin);
if (brightButton == LOW && ldrStatus >= 200)
{
for (int i = 0; i < 10; i++)
{
digitalWrite(greenLed, HIGH);
tone(buzzer,400);
delay(500);
noTone(buzzer);
delay(500);
}
}
else {
digitalWrite(greenLed, LOW);
}
int tempButton = digitalRead(K2);
int valNTC = analogRead(NTC);
if (tempButton == LOW && valNTC > 512)
{
for (int i = 0; i <10; i++)
{
digitalWrite(redLed, HIGH);
tone(buzzer,450);
delay(300);
noTone(buzzer);
delay(1000);
}
}
else {
digitalWrite(redLed, LOW);
}
}
Example code from the Arduino manual:
https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/
const byte ledPin = 13;
const byte interruptPin = 2;
volatile byte state = LOW;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(interruptPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(interruptPin), blink, CHANGE);
}
void loop() {
digitalWrite(ledPin, state);
}
void blink() {
state = !state;
}
Note that this will interrupt the for loop and return to it once the interrupt service routine is finished.
If you want to abort the for loop check the pin state in every loop cycle and break if you want to leave the for loop or return if you want to leave loop().
Of course this is not "immediately".

LED pins on Arduino aren't being initialized when using classes

I'm trying to implement classes in my traffic lights program. The issues I'm facing are that the lights do not blink and the inherited class does not seem to work. How can I fix them?
class Sensors {
public:
Sensors(int echopin, int trigpin);
Sensors();
void init();
double light();
double sensor();
// protected:
int ECHOPIN;
int TRIGPIN;
};
class Mode: public Sensors
//Add the VARIABLES into the CLASSES from the FUNCTIONS
{
public: Mode(int gled, int yled, int rled, int Delay1);
void init();
void mode1();
void mode2();
void mode3();
double sensor() {
Sensors::sensor();
}
private: int Gled;
int Yled;
int Rled;
int Delay;
};
Sensors sense(3, 2);
Mode mode(13, 12, 11, 2000);
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
sense.init();
mode.init();
}
void loop() {
double measure;
double lightValue;
double MAXDISTANCE = 10;
double MAXLIGHT = 140;
measure = sense.sensor();
lightValue = sense.light();
if (measure < MAXDISTANCE) {
mode.mode2();
} else if (lightValue < MAXLIGHT) {
while (lightValue < MAXLIGHT) {
mode.mode3();
lightValue = sense.light();
}
} else {
mode.mode1();
}
}
Sensors::Sensors(int echopin, int trigpin) {
ECHOPIN = echopin;
TRIGPIN = trigpin;
}
Sensors::Sensors() {
ECHOPIN;
TRIGPIN;
}
double Sensors::light() {
//LIGHT SENSOR
int sensorPin = A0;
unsigned int value = 0;
value = analogRead(sensorPin);
Serial.print("Light value is: ");
Serial.println(value);
return value;
}
double Sensors::sensor() {
//Measure the distance for the RANGE FINDER
double distance;
double Time;
digitalWrite(TRIGPIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGPIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGPIN, LOW);
Time = pulseIn(ECHOPIN, HIGH);
distance = (Time * 340) / 20000;
Serial.print("Distance: ");
Serial.print(distance);
Serial.print(" cm \n");
return distance;
}
void Sensors::init() {
pinMode(ECHOPIN, INPUT);
pinMode(TRIGPIN, OUTPUT);
}
Mode::Mode(int gled, int yled, int rled, int Delay1) {
int Gled = gled;
int Yled = yled;
int Rled = rled;
int Delay = Delay1;
}
void Mode::init() {
pinMode(Gled, OUTPUT);
pinMode(Yled, OUTPUT);
pinMode(Rled, OUTPUT);
}
void Mode::mode1() {
//First Mode
digitalWrite(Gled, LOW);
digitalWrite(Rled, HIGH); //RED ON
delay(Delay);
digitalWrite(Rled, LOW);
digitalWrite(Yled, HIGH); //YELLOW ON
Delay -= 1000;
delay(Delay);
digitalWrite(Yled, LOW);
digitalWrite(Gled, HIGH); //GREEN ON
Delay += 1000;
delay(Delay);
digitalWrite(Yled, HIGH); //YELLOW ON
digitalWrite(Gled, LOW);
Delay -= 1000;
delay(Delay);
}
void Mode::mode2() {
int DELAY = 100;
int Y_LOOP = 10;
int buzz = 4;
pinMode(buzz, OUTPUT);
for (int i = 0; i < Y_LOOP; i++) {
tone(buzz, 20);
digitalWrite(Yled, HIGH);
delay(DELAY);
digitalWrite(Yled, LOW);
delay(DELAY);
}
noTone(buzz);
}
void Mode::mode3() {
double measure;
delay(1000);
measure = sensor();
if (measure < 10) {
digitalWrite(Rled, LOW);
digitalWrite(Gled, HIGH);
} else {
digitalWrite(Rled, HIGH);
digitalWrite(Gled, LOW);
}
delay(1000);
}
I expect the sensor method to return a distance, but it only does so the first time. When it is called as an inherited method it returns 0.
This code can be simplified to
struct foo
{
int myX;
foo(int x)
{
int myX = x;
}
};
int main()
{
foo f(42);
// f.myX is still garbage because in constuctor you initialize
// a local variable myX instead of object field
return 0;
}
So you should initialize class field in member initializer list instead:
foo(int x): myX{x}
{
// empty
}

Resources