On/Off switch with button on arduino - arduino

I'm trying to create an Arduino circuit which runs this code. Basically, whith an ultrasonic sensor module, I set different distance ranges.
Within every range I chose to play a buzzer and light up a RGB led with different combinations.
Everything worked so far until I decided to add a button to act as a switch:
I can't think of a code that "turnes on/off" the circuit. To be more specific I want to light up a led (pin n.11) if the circuit is off, and to work normally when it's on, but now it works in the "on" state only if I keep pressed the button, and if I release it, the circuit "locks itself" on the last set of frequency (for the buzzer) and color (for the RGB led).
//pins for buzzer and ultrasonic sensor
int const trigPin = 10;
int const echoPin = 9;
int const buzzPin = 2;
//pins for rgb led(color changes as i get closer to an object)
const int VERDE = 3;
const int BLU = 5;
const int ROSSO = 6;
//pin for led representing main state of the circuit
const int accPin = 7;
// pins for button i want to use as an on/off switch
const int buttonPin = 11;
int stato=0;
int old = 0;
const int delayTime = 5;
void setup()
{
pinMode(VERDE, OUTPUT);
pinMode(BLU, OUTPUT);
pinMode(ROSSO, OUTPUT);
pinMode(accPin,OUTPUT);
digitalWrite(VERDE, LOW);
digitalWrite(BLU, LOW);
digitalWrite(ROSSO, LOW);
digitalWrite(accPin,LOW);
pinMode(buttonPin,INPUT);
pinMode(trigPin, OUTPUT); // trig pin will have pulses output
pinMode(echoPin, INPUT); // echo pin should be input to get pulse width
pinMode(buzzPin, OUTPUT); // buzz pin is output to control buzzering
}
void loop(){
stato=digitalRead(buttonPin);
//if the circuit is off and i turn it on by pressing the button, or if the circuit's already on, then do the things
if(((stato==1)&&(old==0))||((stato==0)&&(old==1))){
digitalWrite(accPin,LOW);
int duration, distance; // Duration will be the input pulse width and distance will be the distance to the obstacle in centimeters
digitalWrite(trigPin, HIGH); // Output pulse with 1ms width on trigPin
delay(1);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH); // Measure the pulse input in echo pin
// Distance is half the duration devided by 29.1 (from datasheet)
distance = (duration/2) / 29.1;
// the following code is just a test to see get a different frequency from the buzzer and a different color from the rgb led, while moving from the facing object
if (distance <= 10 && distance >= 0) {
// Buzz
tone(buzzPin, 2000);
digitalWrite(ROSSO, HIGH);
}
if (distance <= 20 && distance > 10) {
// Buzz
tone(buzzPin, 1750);
digitalWrite(BLU, HIGH);
digitalWrite(ROSSO, HIGH);
}
if (distance <= 30 && distance > 20) {
// Buzz
tone(buzzPin, 1250);
digitalWrite(BLU, HIGH);
}
if (distance <= 40 && distance > 30) {
// Buzz
tone(buzzPin, 1000);
digitalWrite(BLU, HIGH);
digitalWrite(VERDE, HIGH);
}
if (distance <= 80 && distance > 50) {
// Buzz
tone(buzzPin, 750);
digitalWrite(VERDE, HIGH);
}
if(distance>=81){
noTone(buzzPin);// if out of range then shut up
}
delay(60); // Waiting 60 ms won't hurt any one
digitalWrite(VERDE, LOW);
digitalWrite(BLU, LOW);
digitalWrite(ROSSO, LOW);
old=1;
}
//if the circuit is on and i press the button, turn it off
if((old==1)&&(stato=1)){old=0;}
//if the circuit is off and if i let it like this, don't do nothing, but turn on the a led to make it obvious(pin n.11)
if((old==0)&&(stato==0)){
digitalWrite(VERDE, LOW);
digitalWrite(BLU, LOW);
digitalWrite(ROSSO, LOW);
noTone(buzzPin);
digitalWrite(accPin,HIGH);
}
}

Create a function with your whole code, or with piece that starts your process, than attach interrupt to the button pin (you'll have to replace the button pin). Use booleans to toggle button press.

Related

How do i make an ultrasonic sensor trigger an LED to stay on until reset?

So, I know it's probably SUPER simple, but I'm new to arduino and I'm just drawing a blank. I'm making a motion detector with an HC-SRO4 ultrasonic sensor. Right now I have it set so whenever it senses an object within 60 cm, it turns on an LED light, but when the object disappears, the LED turns off. What I would like to happen is that it would stay on until I press a button to reset it. Any help is really appreciated and i thank you in advance.
void setup() {
#define LED 8
#define trigPin 12
#define echoPin 13
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(LED, OUTPUT);
}
void loop() {
int duration, distance;
digitalWrite(trigPin, HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1
;if (distance >= 60 || distance <= 0){
Serial.println("no object detected");
digitalWrite(LED, LOW);}
else {
Serial.println("object detected");
digitalWrite(LED, HIGH);
}}
for this you have make low pushbutton pin while pressing.once the oobject came near the flag will set once the set it will move to while loop and run until the button pressed
#define LED 8
#define trigPin 12
#define echoPin 13
#define push_button 5
int flag=0;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(LED, OUTPUT);
pinMode(push_button,INPUT);
}
void loop() {
int duration, distance;
digitalWrite(trigPin, HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if(digitalRead()==0)
{
flag=0;
}
if (distance >= 60 || distance <= 0){
Serial.println("no object detected");
digitalWrite(LED, LOW);}
else {
Serial.println("object detected");
flag=1;
while(flag=1)
{
digitalWrite(LED, HIGH);}
}}

How to use millis on traffic light controller in Arduino

I'm doing a smart city project with my Arduino and I have a question. I have created 2 functions and one of them is the traffic light controller and I use the delay() to make them have the right delays between them. But I have a problem. I call both of the functions inside loop(), but one of them only runs when the other is finished. Is there any way to run them both? I've seen people using millis().
My code:
int smartled1 = 13;
int smartled2 = 12;
int smartled3 = 11;
int smartled4 = 10;
int smartled5 = 9;
int smartled6 = 8;
int smartled7 = 7;
int smartled8 = 6;
int smartled9 = 50;
int smartled10 = 51;
int smartled11 = 52;
int smartled12 = 53;// Pin para ligar o led
int sensorPin = A0; // Seleção do pin de entrada do LDR
int sensorValor = 0; // Variavel de armazenamento do LDR inicializada a 0
int semaforo1[]= {22, 24, 26};
int semaforo2[]= {5, 4, 3};
int semaforo3[]= {29, 31, 33};
int semaforo4[]= {28, 30, 32};
int Delayvermelho = 5000;
int Delayamarelo = 2000;
void setup() {
Serial.begin(9600); // Define a porta serie para comunicação
pinMode(smartled1, OUTPUT);
pinMode(smartled2, OUTPUT);
pinMode(smartled3, OUTPUT);
pinMode(smartled4, OUTPUT);
pinMode(smartled5, OUTPUT);
pinMode(smartled6, OUTPUT);
pinMode(smartled7, OUTPUT);
pinMode(smartled8, OUTPUT);
pinMode(smartled9, OUTPUT);
pinMode(smartled10, OUTPUT);
pinMode(smartled11, OUTPUT);
pinMode(smartled12, OUTPUT);// Define o pin do Led como saída
for (int i = 0; i < 3; i++) {
pinMode(semaforo1[i], OUTPUT);
pinMode(semaforo2[i], OUTPUT);
pinMode(semaforo3[i], OUTPUT);
pinMode(semaforo4[i], OUTPUT);
}
}
void loop() {
smart_lights();
semaforos_cruzamento();
}
void semaforos_cruzamento(){
// Making Green LED at signal 1 and red LED's at other signal HIGH
digitalWrite(semaforo1[2], HIGH);
digitalWrite(semaforo1[0], LOW);
digitalWrite(semaforo2[0], HIGH);
digitalWrite(semaforo3[0], HIGH);
digitalWrite(semaforo4[0], HIGH);
delay(Delayvermelho);
// Making Green LED at signal 1 LOW and making yellow LED at signal 1 HIGH for 2 seconds
digitalWrite(semaforo1[1], HIGH);
digitalWrite(semaforo1[2], LOW);
delay(Delayamarelo);
digitalWrite(semaforo1[1], LOW);
// Making Green LED at signal 2 and red LED's at other signal HIGH
digitalWrite(semaforo1[0], HIGH);
digitalWrite(semaforo2[2], HIGH);
digitalWrite(semaforo2[0], LOW);
digitalWrite(semaforo3[0], HIGH);
digitalWrite(semaforo4[0], HIGH);
delay(Delayvermelho);
// Making Green LED at signal 2 LOW and making yellow LED at signal 2 HIGH for 2 seconds
digitalWrite(semaforo2[1], HIGH);
digitalWrite(semaforo2[2], LOW);
delay(Delayamarelo);
digitalWrite(semaforo2[1], LOW);
// Making Green LED at signal 3 and red LED's at other signal HIGH
digitalWrite(semaforo1[0], HIGH);
digitalWrite(semaforo2[0], HIGH);
digitalWrite(semaforo3[2], HIGH);
digitalWrite(semaforo3[0], LOW);
digitalWrite(semaforo4[0], HIGH);
delay(Delayvermelho);
// Making Green LED at signal 3 LOW and making yellow LED at signal 3 HIGH for 2 seconds
digitalWrite(semaforo3[1], HIGH);
digitalWrite(semaforo3[2], LOW);
delay(Delayamarelo);
digitalWrite(semaforo3[1], LOW);
// Making Green LED at signal 4 and red LED's at other signal HIGH
digitalWrite(semaforo1[0], HIGH);
digitalWrite(semaforo2[0], HIGH);
digitalWrite(semaforo3[0], HIGH);
digitalWrite(semaforo4[2], HIGH);
digitalWrite(semaforo4[0], LOW);
delay(Delayvermelho);
// Making Green LED at signal 4 LOW and making yellow LED at signal 4 HIGH for 2 seconds
digitalWrite(semaforo4[1], HIGH);
digitalWrite(semaforo4[2], LOW);
delay(Delayamarelo);
digitalWrite(semaforo4[1], LOW);
}
void smart_lights(){
int sensorValor = analogRead(sensorPin);// Lê o valor fornecido pelo LDR
Serial.println(sensorValor);//Imprime os valores provenientes do sensor na ecrã
// Caso o valor lido na porta analógica A5 seja maior do que
// 800, acende o LED
// Ajuste o valor abaixo de acordo com o circuito
if (sensorValor < 400)
{
digitalWrite(smartled1, HIGH);
digitalWrite(smartled2, HIGH);
digitalWrite(smartled3, HIGH);
digitalWrite(smartled4, HIGH);
digitalWrite(smartled5, HIGH);
digitalWrite(smartled6, HIGH);
digitalWrite(smartled7, HIGH);
digitalWrite(smartled8, HIGH);
digitalWrite(smartled9, HIGH);
digitalWrite(smartled10, HIGH);
digitalWrite(smartled11, HIGH);
digitalWrite(smartled12, HIGH);
}
else //Caso contrário, apaga o led
{
digitalWrite(smartled1, LOW);
digitalWrite(smartled2, LOW);
digitalWrite(smartled3, LOW);
digitalWrite(smartled4, LOW);
digitalWrite(smartled5, LOW);
digitalWrite(smartled6, LOW);
digitalWrite(smartled7, LOW);
digitalWrite(smartled8, LOW);
digitalWrite(smartled9, LOW);
digitalWrite(smartled10, LOW);
digitalWrite(smartled11, LOW);
digitalWrite(smartled12, LOW);
}
}
Yes, you can use state machines.
Example:
// totally randon delays. Prime to each other.
static const unsigned char MY_EVENT_TIMEOUT = 100; // in milliseconds.
static const unsigned int HIS_EVENT_TIMEOUT = 2533; // in milliseconds.
// setup two sta=te machines. In this example both state machines will simply
// wait a bit before toggling between two states.
// state machines consist of different state values, a state variable, and some data
enum MyEventState {
my_event_state_initial, // we'll just start timing
my_event_state_1,
my_event_state_2,
/* and so on... */
};
MyEventState my_state = my_state_initial;
unsigned char my_event_timestamp; // largest my_event delay is less than 255 ms
// second state machine.
enum HisEventState {
his_event_state_iinitial, // we'll wait for some external event
his_event_state_1,
his_event_state_2,
/* more states if you need */
};
HisEventState his_state = his_state_initial;
unsigned int his_event_timestamp; // largest his_event delay is less than 65535 ms
void my_event_handler()
{
switch (my_state)
{
case my_event_state_initial:
// initialize our timestamp and go straight to state 1
my_event_timestamp = (unsigned char)millis();
my_state = my_event_state_1;
// passing though to execute next state handler immediately
case my_event_state_1:
// in real application, you'd likely CHECK for a triggering event first
// and check millis() for timeouts, etc. Using different states to
// check for time out... Note the use of subtraction of UNSIGNED
// values to avoid rollover issues altogether
// the extra cast is the correct way to to it. C++ subtraction MAY
// return an unsigned int, according to the standard. In practice, it
// does not happens for 8 and 16-bit MCUs.
// no matter what you do, do not wait, poll your input line, or
// check if there are bytes on the serial buffer, do not block.
if ((unsigned char)((unsigned char)millis() - my_event_timestamp) < MY_EVENT_TIMEOUT)
{
// not enough time has elapsed, nothing to do, so return
return;
}
my_event_timestamp = (unsigned char)millis(); // get a time stamp
my_state = my_event_state_2; // change state
// passing though to execute next state handler immediately
case my_event_state_2:
// it's always the same logic in this simple state machine,
// but you can put any logic you want here to turn one light on or off,
// check inputs, etc..
if ((unsigned char)millis() - my_event_timestamp < MY_EVENT_TIMEOUT)
{
// not enough time has elapsed, nothing to do, so return
return;
}
my_event_timestamp = (unsigned char)millis(); // get a time stamp
my_state = my_event_state_1; // change state
// we're done. the handler for state 1 will execute the next time
// loop() is called.
// This would be the place you could find an infamous goto within a
// switch blck, if timing needs to be suoer duper extra tight.
// It does happen sometimes, but rarely.
return;
}
}
void his_event_handler()
{
// this is the same logic, but with a different beat.
// since these handlers do not block for timers or events
// the handlers appear to run 'concurrently'
switch (his_state)
{
case his_event_state_initial:
// initialize our timestamp and go straight to state 1
his_event_timestamp = (unsigned int)millis();
his_state = his_event_state_1;
// passing though to execute next state handler immediately
case his_event_state_1:
if ((unsigned int)millis() - his_event_timestamp < HIS_EVENT_TIMEOUT)
{
// not enough time has elapsed, nothing to do, so return
return;
}
his_event_timestamp = (unsigned int)millis(); // get a time stamp
his_state = his_event_state_2; // change state
// passing though to execute next state handler immediately
case his_event_state_2:
if ((unsigned int)millis() - his_event_timestamp < HIS_EVENT_TIMEOUT)
{
// not enough time has elapsed, nothing to do, so return
return;
}
his_event_timestamp = (unsigned int)millis(); // get a time stamp
his_state = his_event_state_1; // change state
// we're done. the handler for state 1 will execute the next time
// loop() is called.
return;
}
}
void setup()
{
}
void loop() {
// call our concurrent state machines
my_event_handler();
his_event_handler();
/* some other non-blocking code... */
}

Ultrasonic program giving me an odd error

I created a program that is intended to turn a servo motor 180 degrees then back if an object is within 20cm of the ultrasonic sensor. This works fine except sometimes when the if condition is not met. In this case, the motor doesn't move at all and the distance is put into the serial monitor. This works fine sometimes, but in most cases the serial monitor just prints 0 repeatedly and I have to restart the program for it to work again. Even when I put an object within 20cm of the sensor it still prints 0. I am quite new to Arduino so this really just stumped me haha. Any tips or help would be greatly appreciated.
#include <Servo.h>
Servo servo1; // create servo object to control a servo
#define trigPin 13
#define echoPin 12
void setup()
{
Serial.begin(9600);
servo1.attach(9); // attaches the servo on pin 9 to the servo object
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop()
{
long duration = 0, distance = 0;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) / 29.1;
if(distance > 2 && distance < 20){
servo1.write(180);
Serial.println(distance);
delay(1000);
servo1.write(-180);
}
else{
servo1.write(0);
Serial.println(distance);
}
delay(2000);
}
See what happens when you try this code, as I cleaned it up a little bit:
#include <Servo.h>
#define trigPin 13
#define echoPin 12
Servo servo1; // create servo object to control a servo
void setup() {
Serial.begin (9600);
servo1.attach(9); // attaches the servo on pin 9 to the servo object
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
float duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) * 29.1;
if (duration) {
if (distance > 2 && distance < 20) {
servo1.write(180);
Serial.println(distance);
delay(1000);
servo1.write(-180);
}
else {
servo1.write(0);
Serial.println(distance);
}
}
delay(2000);
}
I think if you use a float it might work. However, if it doesn't work, try switching up the pin assignments to different pins on the Arduino and see if that works. If the distance measurment is off the best way to adjust it is with the multiplied value in the distance variable in the void loop ().This one works for me.

IR sensor with Arduino for restaurant parking

I have problem in the code logic, I did not find any solution.
My doubt is I'm using two IR sensor interface with Arduino, so when car is passing 1st sensor and 2nd sensor then I'm sending the data that car is passed. That is fine but whenever car1 is passing 1st sensor and another car, say car2 is in 2nd sensor, then also flag is becoming 1, that is true but I don't want that.
How to code this so that car should pass two sensors? If car 1 is in sensor 1 and car 2 is in sensor 2 than flag should not be 1.
Please find the code below:
#include<avr/wdt.h>
#define DISTANCE 100
const int trigPin1 = 7;
const int echoPin1 = 6;
const int trigPin2 = 5;
const int echoPin2 = 4;
int MOVE_FLAG = 0;
void setup() {
// initialize serial communication:
Serial.begin(9600);
MOVE_FLAG = 0;
wdt_enable(WDTO_8S);
}
void loop()
{
// establish variables for duration of the ping,
// and the distance result in inches and centimeters:
long duration1, duration2, inches1, inches2, cm1, cm2;
// The sensor is triggered by a HIGH pulse of 10 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
pinMode(trigPin1, OUTPUT);
digitalWrite(trigPin1, LOW);
delayMicroseconds(2);
digitalWrite(trigPin1, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin1, LOW);
// Read the signal from the sensor: a HIGH pulse whose
// duration is the time (in microseconds) from the sending
// of the ping to the reception of its echo off of an object.
pinMode(echoPin1, INPUT);
duration1 = pulseIn(echoPin1, HIGH);
inches1 = microsecondsToInches(duration1);
cm1 = microsecondsToCentimeters(duration1);
delay(10);
pinMode(trigPin2, OUTPUT);
digitalWrite(trigPin2, LOW);
delayMicroseconds(2);
digitalWrite(trigPin2, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin2, LOW);
pinMode(echoPin2, INPUT);
duration2 = pulseIn(echoPin2, HIGH);
// convert the time into a distance
inches2 = microsecondsToInches(duration2);
cm2 = microsecondsToCentimeters(duration2);
if(cm1 <= DISTANCE && cm2 <= DISTANCE && MOVE_FLAG == 0)
{
Serial.println("3");
MOVE_FLAG = 1;
}
if (cm1 > DISTANCE && cm2 > DISTANCE && MOVE_FLAG == 1)
{
MOVE_FLAG = 0;
delay(500);
}
delay(50);
wdt_reset();
}
long microsecondsToInches(long microseconds)
{
return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds)
{
return microseconds / 29 / 2;
}
Two motion sensors are inadequate to accomplish what you described. Without video or something similar, there's no way for you to know whether Car 1 triggered the sensor or Car 2 triggered the sensor.
I suggest you re-think your approach to solving the problem. You might want to look at other parking lot projects people have created and posted on the Internet. Do a Google search for "Arduino Parking Lot" or something similar.

LED stays on even when digitalRead is low

I am just creating a simple basic program, but I can't figure out what's going wrong.
I have set three pins as output and three pins as input. When those three pins digitalRead == HIGH they will set an LED to HIGH, but instead my LED is always staying high.
Here is my Arduino code:
int LED_Low = 4; // Red LED
int LED_Avg = 3; // Yellow LED
int LED_High = 2; // Green Led
int WaterLow = 7;
int WaterAvg = 8;
int WaterHigh = 9;
void setup() {
// Put your setup code here, to run once:
pinMode(LED_Low, OUTPUT);
pinMode(LED_Avg, OUTPUT);
pinMode(LED_High, OUTPUT);
pinMode(WaterLow, INPUT);
pinMode(WaterAvg, INPUT);
pinMode(WaterHigh, INPUT);
}
void check(){
if(digitalRead(WaterLow) == HIGH){ // If Water level is low
digitalWrite(ledLow, HIGH); // Turn on red LED indication water level is low
}
else{
digitalWrite(ledLow, LOW);
}
if(digitalRead(WaterAvg) == HIGH){ // If water level is medium
digitalWrite(ledAvg, HIGH); // Turn on yellow LED indicating water level is average
}
else{
digitalWrite(ledAvg, LOW);
}
if(digitalRead(WaterHigh) == HIGH){ //
digitalWrite(ledHigh, HIGH); //
}
else{
digitalWrite(ledHigh, LOW);
}
}
void loop() {
// Put your main code here, to run repeatedly:
check();
}
In the above image I have connected led on pin 2, 3, and 4 with 1.5 kilohm resistor and three wires in pin 7, 8, and 9 which will receive input from the 5 volt pin and turn on the LED. Accordingly, the 5 volt pin is connected to the positive terminal on the power bus and with 9.1 *2 resistors in series and then this wire connect with pin 2, 3, and 4.
I found the issue. My code was OK. It was my circuit.
The pins I declared to receive input were not connected to ground.
You can make that with the help of two cases
Define the delay
if (digitalRead(WaterLow) == HIGH) // If Water level is low
{
digitalWrite(ledLow, HIGH); // Turn red LED indication water level is low
delay(2000);
}
else
{
digitalWrite(ledLow, LOW);
}
Make a condition like this
int stateled = LOW;
int previous = LOW;
long time = 0;
long debounce = 200;
void loop()
{
stateButton = digitalRead(WaterLow);
if (stateButton == HIGH && previous == LOW && millis() - time > debounce)
{
if(stateLED == HIGH)
{
stateLED = LOW;
}
else
{
stateLED = HIGH;
}
time = millis();
}
digitalWrite(ledlow, stateLED);
previous == stateButton;
}

Resources