IR sensor with Arduino for restaurant parking - arduino

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.

Related

Pulsein() function blocks other tasks from running silmultaneously

I am using a zumo bot with a reflectance sensor used to follow a black line. I want to use an arduino to make the zumo bot stop once it gets a certain distance from an obstacle.
I have an ultrasonic sensor (HC-SR04) which ive connected to the bot.
Both of these tasks work independently but once i merge the code together(so it follows the line aswell as stoping when it detects an object using the ultrasonic sensor), it doesn't work properly.. (the zumo bot no longer follows the line)
I THINK it is to do with the pulsein() function blocking any other tasks but not sure.
My code is below. Can anyone help please?
#include <ZumoShield.h>
ZumoBuzzer buzzer;
ZumoReflectanceSensorArray reflectanceSensors;
ZumoMotors motors;
Pushbutton button(ZUMO_BUTTON);
int lastError = 0;
// This is the maximum speed the motors will be allowed to turn.
// (400 lets the motors go at top speed; decrease to impose a speed limit)
const int MAX_SPEED = 400;
#define echoPin A4
#define trigPin A5
// defines variables
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement
void setup()
{
reflectanceSensors.init();
pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
// Initialize the reflectance sensors module
// Wait for the user button to be pressed and released
button.waitForButton();
// Turn on LED to indicate we are in calibration mode
pinMode(13, OUTPUT);
digitalWrite(13, HIGH);
// Wait 1 second and then begin automatic sensor calibration
// by rotating in place to sweep the sensors over the line
delay(1000);
int i;
for(i = 0; i < 80; i++)
{
if ((i > 10 && i <= 30) || (i > 50 && i <= 70))
motors.setSpeeds(-200, 200);
else
motors.setSpeeds(200, -200);
reflectanceSensors.calibrate();
// Since our counter runs to 80, the total delay will be
// 80*20 = 1600 ms.
delay(20);
}
motors.setSpeeds(0,0);
// Turn off LED to indicate we are through with calibration
digitalWrite(13, LOW);
// Wait for the user button to be pressed and released
button.waitForButton();
Serial.begin(9600); // // Serial Communication is starting with 9600 of baudrate speed
Serial.println("Ultrasonic Sensor HC-SR04 Test"); // print some text in Serial Monitor
Serial.println("with Arduino UNO R3");
}
void loop()
{
unsigned int sensors[6];
// Get the position of the line. Note that we *must* provide the "sensors"
// argument to readLine() here, even though we are not interested in the
// individual sensor readings
int position = reflectanceSensors.readLine(sensors);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin HIGH (ACTIVE) for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Our "error" is how far we are away from the center of the line, which
// corresponds to position 2500.
int error = position - 2500;
// Get motor speed difference using proportional and derivative PID terms
// (the integral term is generally not very useful for line following).
// Here we are using a proportional constant of 1/4 and a derivative
// constant of 6, which should work decently for many Zumo motor choices.
int speedDifference = error / 4 + 6 * (error - lastError);
lastError = error;
// Get individual motor speeds. The sign of speedDifference
// determines if the robot turns left or right.
int m1Speed = MAX_SPEED + speedDifference;
int m2Speed = MAX_SPEED - speedDifference;
if (m1Speed < 0)
m1Speed = 0;
if (m2Speed < 0)
m2Speed = 0;
if (m1Speed > MAX_SPEED)
m1Speed = MAX_SPEED;
if (m2Speed > MAX_SPEED)
m2Speed = MAX_SPEED;
motors.setSpeeds(m1Speed, m2Speed);
//if (distance <20){
// motors.setSpeeds(0,0);
// }
////////////////////////////////////////////
// Calculating the distance
distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
// Displays the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
} ```
Of course pulseIn is blocking function. Arduino project is open source, you can easily check source code
Here is C equivalent countPulseASM function which does measurement.
unsigned long pulseInSimpl(volatile uint8_t *port, uint8_t bit, uint8_t stateMask, unsigned long maxloops)
{
unsigned long width = 0;
// wait for any previous pulse to end
while ((*port & bit) == stateMask)
if (--maxloops == 0)
return 0;
// wait for the pulse to start
while ((*port & bit) != stateMask)
if (--maxloops == 0)
return 0;
// wait for the pulse to stop
while ((*port & bit) == stateMask) {
if (++width == maxloops)
return 0;
}
return width;
}
If you need measure pulse length in non blocking way, use hw counters.

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 sensors

Now i am using 2 ultrasonic sensors but i found that they become unstable outdoors and give random readings .....although they act normally inside a room .....how can i solve this problem???
That is the code
it seems like the off Sensor always Reading and i checked the wiring and it is good so i don't really know where is the problem is ??
#define trig 2
#define echo 3
#define led 7
#define relay 4
#define trig2 10
#define echo2 9
#define led2 8
long duration,distance,OnSensor,OffSensor;
void setup() {
// put your setup code here, to run once:
pinMode(echo,INPUT);
pinMode(echo2,INPUT);
Serial.begin(9600);
pinMode(led,OUTPUT);
pinMode(led2,OUTPUT);
pinMode(relay,OUTPUT);
pinMode(trig,OUTPUT);
pinMode(trig2,OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(led,LOW);
digitalWrite(led2,LOW);
digitalWrite(relay,LOW);
SonarSensor(trig2, echo2);
OffSensor = distance;
delay(50);
SonarSensor(trig, echo);
OnSensor=distance;
if(OnSensor<80&&OffSensor>=80){//sensor 1 activated
digitalWrite(led,HIGH);
digitalWrite(relay,HIGH);
delay(150);
digitalWrite(led,LOW);
digitalWrite(relay,LOW);
delay(1000);
digitalWrite(led,HIGH);
digitalWrite(relay,HIGH);
delay(150);
digitalWrite(led,LOW);
digitalWrite(relay,LOW);
}
else if(OnSensor>80&&OffSensor>80){//No sensor activated
digitalWrite(led,LOW);
digitalWrite(relay,LOW);
}
else if(OnSensor>80&&OffSensor<80){//sensor2 activated
digitalWrite(led2,HIGH);
digitalWrite(relay,LOW);
delay(5000);
}
else if(OnSensor<80&&OffSensor<80){//Both sensors activated
digitalWrite(led2,HIGH);
digitalWrite(led,HIGH);
digitalWrite(relay,LOW);
delay(3000);
}
}
void SonarSensor(int trigPin,int echoPin)
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration*0.034/2;
}
I think there are 2 problem here
You use 2 sensor
List item
Use use it outdoor
From my experience the ultra sonic wave can bouncing around object many time. depend on your setup, second sensor might read echo form first sensor.
follow these step
1. Try to use 1 sensor per time to see if it error
2. If single sensor work you should add more delay after sensor reading
3. Plot the data to see how it look like you might need digital filter to improve reading
For step 3 if you use sensor as On Off by threshold you can see my example code.
This code work the same way as button de-bouncing so in need to trig continuously for 10 time to prevent false alarm (This code for single sensor)
#define ULTRASONIC_TRIG_PIN 8
#define ULTRASONIC_ECHO_PIN 7
#define RELAY_PIN 4
/**/
#define ULTRASONIC_INTERVAL_MS 100//50
#define ULTRASONIC_TRIG_COUNT_THRESH 10
#define ULTRASONIC_DISTACE_THRESH_CM 50
/**/
#define RELAY_TRIG__INTERVAL_MS 5000
#define RELAY_TRIG_LOGIC HIGH
void setup()
{
pinMode (RELAY_PIN, OUTPUT);
pinMode (ULTRASONIC_TRIG_PIN, OUTPUT);
pinMode (ULTRASONIC_ECHO_PIN, INPUT);
Serial.begin(115200);
}
void loop()
{
static unsigned long ultrasonic_timer = millis();
static unsigned long relay_trig_timer = millis();
static float us_distance_cm = 0;
static int us_trig_count = 0;
static byte relay_state = !RELAY_TRIG_LOGIC; // initial value as off;
if (millis() - ultrasonic_timer >= ULTRASONIC_INTERVAL_MS) {
ultrasonic_timer += ULTRASONIC_INTERVAL_MS;
us_distance_cm = getDistanceCM();
if (us_distance_cm <= ULTRASONIC_DISTACE_THRESH_CM) {
if (us_trig_count >= ULTRASONIC_TRIG_COUNT_THRESH) {
digitalWrite(RELAY_PIN, RELAY_TRIG_LOGIC);
relay_state = RELAY_TRIG_LOGIC;
relay_trig_timer = millis();
}
else {
us_trig_count++;
}
}
else {
us_trig_count = 0;
}
Serial.print("distance = ");
Serial.print(us_distance_cm);
Serial.print("cm, relay = ");
Serial.print(relay_state);
Serial.print(", count = ");
Serial.println(us_trig_count);
}
if (relay_state == RELAY_TRIG_LOGIC) {
if (millis() - relay_trig_timer > RELAY_TRIG__INTERVAL_MS) {
relay_state = !RELAY_TRIG_LOGIC;
digitalWrite(RELAY_PIN, !RELAY_TRIG_LOGIC);
}
}
}
float getDistanceCM() {
digitalWrite(ULTRASONIC_TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(ULTRASONIC_TRIG_PIN, LOW);
unsigned long duration = pulseIn(ULTRASONIC_ECHO_PIN, HIGH, 50000);
float distance = float(duration * 343) / 20000.0;
delay(5);
return distance;
}

Arduino: Pin time inactivity/activity

The purpose of the following Arduino code is to interface with the high and low signals sent from a Raspberry Pi; the full explanation is rather complex so I'll spare you the waste in time. The signals sent from the Pi (pins 10 and 11) turn a stepper motor connected to an A4988 driver clockwise or counterclockwise. The pins that dictate this out of the Arduino are the step and direction pins (9 and 8). What I am trying to accomplish is to enable the sleepPin after 60 seconds of pin 10 and 11 inactivity.
Likewise, in the same fashion, I want to stop accepting input from pin 10 and 11 if they both read the same input signal for more than 3 seconds. I've looked up methods on how to incorporate time into Arduino script but do not know how to incorporate it in this instance.
byte directionPin = 9;
byte stepPin = 8;
byte sleepPin = 12;
byte buttonCWpin = 10;
byte buttonCCWpin = 11;
boolean buttonCWpressed = false;
boolean buttonCCWpressed = false;
long previousMillis = 0;
long interval = 1000;
void setup() {
//determines length of stepper movement
pinMode(directionPin, OUTPUT);
pinMode(stepPin, OUTPUT);
//moves motors clockwise or counterclockwise
pinMode(buttonCWpin, INPUT_PULLUP);
pinMode(buttonCCWpin, INPUT_PULLUP);
}
void loop() {
readButtons();
actOnButtons();
}
void readButtons() {
buttonCCWpressed = false;
buttonCWpressed = false;
if (digitalRead(buttonCWpin) == LOW) {
buttonCWpressed = true;
}
if (digitalRead(buttonCCWpin) == LOW) {
buttonCCWpressed = true;
}
}
void actOnButtons() {
if (buttonCWpressed == true) {
digitalWrite(directionPin, LOW);
for(int x = 0; x < 1; x++) {
digitalWrite(stepPin,HIGH);
delayMicroseconds(515);
digitalWrite(stepPin,LOW);
delayMicroseconds(515);
}
}
if (buttonCCWpressed == true) {
digitalWrite(directionPin, HIGH);
for(int x = 0; x < 1; x++) {
digitalWrite(stepPin,HIGH);
delayMicroseconds(515);
digitalWrite(stepPin,LOW);
delayMicroseconds(515);
}
}
}
Any help would be greatly appreciated along with any tips or concerns.
Thank You.
If you have the luxury to use pins 2 and 3 rather than pins 10 and 11 (assuming you have an Arduino Uno for instance), it could be useful to work with external interrupts.
As a solution for your first problem, here's a minimal code that should put the sleep pin high after 60 seconds of inactivity on both direction pins 2 & 3:
volatile long int last_activity;
void setup(){
attachInterrupt(2, tstamp, CHANGE);
attachInterrupt(3, tstamp, CHANGE);
pinMode(2, INPUT); // your new CW pin
pinMode(3, INPUT); // your new CCW pin
pinMode(12, OUTPUT);
digitalWrite(12, LOW);
last_activity = millis();
}
void loop(){
if (millis() - last_activity > 60e3) {
digitalWrite(12, HIGH);
// do some other things...
}
}
void tstamp(){
last_activity = millis();
}
Now for your second problem, what exactly do you mean by "stop accepting input from pins 10 and 11"? If you only need to check that their state is the same, adding volatile long int last_common_state; in the preamble and checking for digitalRead(2) == digitalRead(3); in tstamp()'s body to update last_common_state should get you on the right track.

On/Off switch with button on 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.

Resources