I want to make a device like Knocki(https://knocki.com), which essentially is a relay control using a vibration sensor. i can detect vibrations rn but the problem is, once i knock the relay blinks on and then turns off. i understand this is a lack of programming that is causing this. could someone help me write code which makes it so that when i knock the relay is turned on indefinitely; until I knock again to turn relay off.
And yes u can probably tell that this code is copied from somewhere(https://wiki.keyestudio.com/Ks0068_keyestudio_37_in_1_Sensor_Kit_for_Arduino_Starters#Project_21:_Vibration_Sensor).I took it from the home page of the vibration sensor. the code was initially so that every time i knocked, the onboard Arduino led lit up. Also, right now the relay is blinking faintly every time i knock(Although correctly,in sync with my knocks)
#define SensorLED 13
#define SensorINPUT 3 //Connect the sensor to digital Pin 3 which is Interrupts 1.
unsigned char state = 0;
int Relay = 5;
void setup()
{
pinMode(SensorLED, OUTPUT);
pinMode(SensorINPUT, INPUT);
attachInterrupt(1, blink, FALLING);// Trigger the blink function when the falling edge is detected
}
void loop()
{ if(state!=0)
{
state = 0;
digitalWrite(SensorLED,HIGH);
delay(500);
digitalWrite(Relay,HIGH);
}
else
digitalWrite(SensorLED,LOW);
digitalWrite(Relay,lOW);
}
void blink()//Interrupts function
{ state++;
Yes its in your code: The (bad) example works only because there is a
digitalWrite(SensorLED,HIGH);
->>> delay(500);
a delay for 1/2 sec to keep the led on.So as a check put an other delay after the relay line and it should go on for 1/2 sec too (so the led is lit 1 sec in total)
digitalWrite(SensorLED,HIGH);
delay(500);
digitalWrite(Relay,HIGH);
delay(500);
Thats just for checking -> NEXT STEP:
Get rid of the delays (see blinkwithoutdelay example in
Arduino->File->Examples->2.Digital -> blinkwithoutdelay
and introduce a second state variable e.g.
bool relayStateOn = false;
to get an independent on/off of the relay and the led.(If thats - what I understand -what you want to do)
If you feed your relay from the board, that is not the problem. Please, check the voltage in your relay when you try to set it on, if your voltage falls down, it means that this output to your relay does not supply the necessary current.
Related
I would like your help to solve the following problem.
I'm using an ESP32 Dev Kit V1 connected as follows:
Pin 4 (input) is connected to a 20kHz and 3.3V signal and to channel 1 of the oscilloscope; and
Pin 2 (output) is connected to channel 2 of the oscilloscope.
My goal is to use interrupts and generate a signal on pin 2 (output) that follows the variations of the signal on pin 4 (input).
The image below illustrates two behaviors. The most frequent and the other one that happens occasionally.
In the first behavior, the latency is around 3 us, but sometimes there is a variation (jitter) and the rise of the output signal takes 15 us or even more to keep up with the input.
I would like to know how to remove this occasional behavior and keep the system stable.
The code that I'm using is below. To compile and upload I am using the latest Arduino IDE version 1.8.13.
I'm using GPIO.out_w1ts and GPIO.out_w1tc because I believe it will be faster than using digitalWrite(pin, state).
Also notice that I'm not reading the state of pin 4 (input) to be faster, because of this, sometimes the output signal gets inverted, but that's not a problem at this point.
#define OUTPUT_PIN 2
#define INPUT_PIN 4
volatile bool state = false;
void IRAM_ATTR interruptFunction() {
if (state)
GPIO.out_w1ts = 0b100;
else
GPIO.out_w1tc = 0b100;
state = !state;
}
void setup() {
pinMode(INPUT_PIN, INPUT);
attachInterrupt(digitalPinToInterrupt(INPUT_PIN), interruptFunction, CHANGE);
gpio_config_t io_conf;
io_conf.mode = GPIO_MODE_OUTPUT;
io_conf.pin_bit_mask = 0b100;
gpio_config(&io_conf);
}
void loop() {
}
The settings used in the Arduino IDE are illustrated in the next image.
Thanks in advance for all the help!
Code is suppose to Light the inbuit-LED at Pin 13 whenever Pin 5 is High, however i have encountered couple of problem.
While measuring Voltage though Digital Meter - one pin at arduino GND and other at 1,2,3,4. They are showing some non-zero values. Earlier triggering Pin was 4 and light was staying on all the time.
When Pin 5 is high (by connecting 5V Pin from Arduino to Pin 5) it lights the LED as it should, but if Pin 5 stays high for more than 1/2 second, light stays high for more than 0.5 second even after the Pin 5 is disconnected from 5V Pin.
int buttonState = LOW;
int light = 13;
void setup() {
// put your setup code here, to run once:
pinMode(gateopen,INPUT);
pinMode(light, OUTPUT);
}
void loop()
{
// put your main code here, to run repeatedly:
buttonState = digitalRead(gateopen);
if (buttonState == HIGH)
{
digitalWrite(light, HIGH);
}
else
{
digitalWrite(light, LOW);
}
//delayMicroseconds(500);
}
As suggested earlier, use a pull down resistor. Or change your circuit to active low and use INPUT_PULLUP.
I believe you're using delayMicroSeconds, which means the led is just blinking waaay too fast for your eyes. If you want 'half a second' as you hinted on your query, you would be using delay(500) instead.
You are experiencing electrical noise, just like Juraj said, just put a 220 Ohm pull down resistor
I am trying to create a working physical simulation of a traffic light intersection. I want to listen for button readings (pedestrian buttons to turn pedestrian lights green) continuously throughout the program and want to run a different function that will handle pedestrian lights if the buttons are ever pressed during the program.
I have tried it with while loops and if conditions but it just won't work because then it would read the button input at a specific point in time when I want it to read the readings constantly throughout the program and break the loop if the condition is ever untrue (while and do-while loops only check the condition at the end of the loop when I want it to check the condition throughout the loop). I also need to get which button was pressed if that possible. Then depending on which button was pressed, I want to run a function called pedes() or pedes2().
Feel free to ask if you need any clarifications.
I have posted my original code below that I want to run constantly until a button will be pressed.
Thanks!
// If at any point in time during this code, a button is pushed, I want to run a function called
pedes() or pedes2() depending on which button is pressed.
// First set of Trafiic Lights
int redT = 13 ;
int yellowT = 12;
int greenT = 11;
// First set of Pedestrian Lights
int redP = 10;
int greenP = 9;
// Second set of Traffic Lights
int redT2 = 8;
int yellowT2 = 7;
int greenT2 = 6;
// Second set of Pedestrian Lights
int redP2 = 5;
int greenP2 = 4;
// Pedestrian Buttons
int buttonT = 3;
int buttonT2 = 2;
int buttonT3 = 1;
int buttonT4 = 0;
int buttonStateT = 0;
int buttonStateT2 = 0;
int buttonStateT3 = 0;
int buttonStateT4 = 0;
// Booleans which will handle which button was pressed
void setup() {
// First set of Trafiic Lights
pinMode(redT, OUTPUT);
pinMode(yellowT, OUTPUT);
pinMode(greenT, OUTPUT);
// First set of Pedestrian Lights
pinMode(redP, OUTPUT);
pinMode(greenP, OUTPUT);
// Second set of Traffic Lights
pinMode(redT2, OUTPUT);
pinMode(yellowT2, OUTPUT);
pinMode(greenT2, OUTPUT);
// Second set of Pedestrian Lights
pinMode(redP2, OUTPUT);
pinMode(greenP2, OUTPUT);
// Pedestrian Buttons
pinMode(buttonT, INPUT);
pinMode(buttonT2, INPUT);
pinMode(buttonT3, INPUT);
pinMode(buttonP4, INPUT);
}
void loop() {
// Resetting all the traffic lights
digitalWrite(redP, HIGH); // Turns on red pedestrian LED from 1st bunch
digitalWrite(redP2, HIGH); // Turns on red pedestrian LED from 2nd bunch
digitalWrite(yellowT, LOW); // Turns off yellow traffic LED from 1st bunch
digitalWrite(yellowT2, LOW); // Turns off yellow traffic LED from 1st bunch
digitalWrite(redT, HIGH); // Turns on red traffic LED from 1st bunch
digitalWrite(redT2, HIGH); // Turns on red traffic LED from 2nd bunch
delay(2000);
digitalWrite(redT, LOW); // Turns off red traffic LED from 1st bunch
digitalWrite(redT2, HIGH); // Turns on red traffic LED from 2nd bunch
digitalWrite(greenT, HIGH); // Turns on green traffic LED from 1st bunch
digitalWrite(greenT2, LOW); // Turns off green traffic LED from 2nd bunch
delay(10000); // Pauses program for 8 seconds
digitalWrite(greenT, LOW); // Turns off green traffic LED from 1st bunch
digitalWrite(yellowT, HIGH); // Turns on yellow traffic LED from 1st bunch
delay(3000); // Pauses program for 3 seconds
digitalWrite(yellowT, LOW); // Turns off yellow traffic LED from 1st bunch
digitalWrite(redT, HIGH); // Turns on red traffic LED from 1st bunch
delay(2000); // Pauses program for 3 seconds
digitalWrite(redT2, LOW); // Turns off red traffic LED from 2nd bunch
digitalWrite(greenT2, HIGH); // Turns on green traffic LED from 2nd bunch
delay(6000); // Pauses program for 8 seconds
digitalWrite(greenT2, LOW); // Turns off green traffic LED from 2nd bunch
digitalWrite(yellowT2, HIGH); // Turns on yellow traffic LED from 2nd bunch
delay(3000); // Pauses program for 3 seconds
digitalWrite(yellowT2, LOW); // Turns off yellow traffic LED from 2nd bunch
digitalWrite(redT2, HIGH); // Turns on red traffic LED from 2nd bunch
delay(2000); // Pauses program for 3 seconds
}
Instead of constantly polling you could use an interrupt on the button pin and set a flag or call a function from within the interrupt routine.
Also make sure to debounce the button in hardware or software.
Since you seem to be learning, here are some extra improvements you could add as an exercise:
To switch the lights you could use timer interrupts instead of delays (you could even put the mcu in sleep mode in between).
Another improvement would be to create a TrafficLight class which contains all the logic. Here is an interesting tutorial. This way you could easily create multiple objects: TrafficLight tl1(..), tl2(..); or even arrays of traffic lights (for example with the same timings).
You could then even create a class Intersection which contains all the traffic lights and the logic for that intersection.
Well if you delay for 10 seconds you cannot react to something in the meantime.
You can use millis() to implement a non-blocking delay.
https://www.arduino.cc/en/tutorial/BlinkWithoutDelay
Instead of being idle and unable to respond you spend your time with checking and responding to your button states and/or time conditions.
Avoid using delays. Delays will pause everything until the time is up, which makes everything less responsive. Delays are useful when learning how to code, but they can hinder usability if you need to react to an external sensor or button.
A better habit to get into is using timers instead of delays. This lets your code keep looping without pausing, and you can add code to check for user input more frequently.
Here is an example of what you should NOT do:
void loop() {
digitalWrite(MY_LED,HIGH);
delay(1000);
digitalWrite(MY_LED,LOW);
delay(1000);
//This code only gets reached every 2 seconds
//This means you may need to hold the button for up to
//2 seconds before it will print a message
if (digitalRead(MY_BUTTON) == LOW) {
Serial.println("You pressed the button");
}
}
You can use millis() to return the number of milliseconds since the arduino started running. Here is a basic example of a timer:
bool ledState = false;
unsigned long toggledTime = 0; //The last time we toggled the led
void loop() {
//Calculate how much time has passed since the last time
//we turned the LED on or off
unsigned long timeElapsedSinceLastToggle = millis() - toggledTime;
//If 1000ms (1s) has passed, we'll toggle the LED
if (timeElapsedSinceLastToggle > 1000) {
ledState = !ledState; //Invert the state
digitalWrite(MY_LED,ledState); //Perform the action
toggledTime = millis(); //Reset our timer to the current time
}
//This code now checks very frequently since the code above
//never uses delay()
if (digitalRead(MY_BUTTON) == LOW) {
Serial.println("You pressed the button");
}
}
I would recommend using a different timer for each LED that you want to toggle. This will make your code much more responsive, and your buttons will respond (nearly) instantly.
There is one thing you will want to be careful with regarding timers. millis() is how many milliseconds since boot, but what happens when your code runs for a very long time? millis() resets (starts over at 0) after about 50 days. For lots of people, this doesn't matter much, but it is worth keeping in mind if your code will be running indefinitely for long periods of time.
I have an arduino nano. I want to connect MX Cherry switches and detect pressing throught the serial port. What pins should i use on arduino and what code should be uploaded to the plate?
I understand that i have to power the switches so there has to be 5v pin and input pin. But i'm new to electronics so i didn't manage to figure it out.
//that's just basic code for sending a number every second via 13 pin
int i=0;
void setup() {
Serial.begin(57600);
pinMode(13, OUTPUT);
}
void loop() {
i = i + 1;
Serial.println(i);
delay(1000);
}
Basically, i need a way of sending '1' if button is pressed and '0' if it's not.
Perhaps I've misunderstood your question. Why not just read the button and send a '1' if pressed and '0' if not?
void loop(){
int buttonState = digitalRead(buttonPin);
// Assumes active low button
if (buttonState == LOW){
Serial.print('1');
}
else {
Serial.print('0');
}
delay(500);
}
Of course you probably want to add some sort of timing to that so it doesn't send thousands of 0's and 1's per second. I added a delay, but that might not be the best answer for the application you have (and chose not to share). I've also assumed that your button is wired active-LOW with a pull-up since you didn't share that either.
I'm having a bit of trouble with my Arduino when I try and use long wires to a switch.
If I use a shorter wire I have no problems, but as soon as they are extended, things start playing up.
What I'm trying to do is, when I press a button I would like it to output to a pin, stay on for 2 seconds, then turn off regardless whether the button is still pressed or not.
The code I use at the moment that does work with short wires is:
// constants won't change. They're used here
// to set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 10; // the number of the LED pin
// variables will change:
int buttonState = 0; // variable for reading the pushbutton status
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
delay(2000); // wait for a second
digitalWrite(ledPin, LOW);
}
}
I've been reading on forums that using debounce may solve this problem. However I'm new to Arduino and not sure how to implement this.
I used the Arduino button tutorial and used a 10k pull down resistor as stated. Is there any way I can allow, either with code or with a resistor / cap, to trigger via a switch that has a wire length of <2m?
Any help appreciated.
Wire length is not going to be an issue here. You either have a wiring fault or your code doesn't match your expected behaviour. (You didn't mention what the actual behaviour is right now.)
Additional debouncing of the switch won't be necessary since after you detect a button press, you are ignoring its state for some time. That is what software debouncing typically is.
stay on for 2 seconds, then turn off regardless whether the button is still pressed or not.
Right now the output will not turn off until you release the button. The reason for this is that after you write it low, you immediately check the button again and write the output high if it's still pressed. You either need to put a delay below
digitalWrite(ledPin, LOW);
or be a little fancier and make sure the button is released before you allow another press.