Arduino Random Number Generator with pushbutton - random

I'm new to Arduino, trying to make a random number generator with pushbutton.
My questions are:
How can I do that,if I press the pushbutton once, then I will get one random number between 0 and 1024. After that, I want to loop from 0 to the random number and then back to 0.
How can I debounce the pushbutton
Sample code:
void setup(){
Serial.begin(57600);
pinMode(2,INPUT_PULLUP);
attachInterrupt(0,randomnumber,FALLING);
}
void randomnumber(){
int number=random(0,1024);
for(int x=0;x<=number; x++){
Serial.println(x);
delay(1000);
}
for(int y=number;y>=0; y--){
Serial.println(y);
delay(1000);
}
}
void loop(){
}
Any good suggestion?

Ok, what you are looking for is "signal debouncing".
When you press the button, the signal does not go right from low to high value, but is noisy on onset(that's a general property of mechanical contacts), creating multiple "button presses". Common and working approach is:
1) button press detected(transition from 0 to 1 on your input pin)
2) delay(10) // wait for a few milliseconds
3) check the button again to see if it's still pressed; if true, the button was really pressed, if not then it was just some noise and can be ignored
This will reject any pulse shorter than 10 ms
Here is a short video describing what actually happens when you press the button: https://youtu.be/jYOYgU2vlSE
And an article along with code: https://programmingelectronics.com/tutorial-19-debouncing-a-button-with-arduino-old-version/

Related

How can I randomize a video to play after another by pressing a key on Processing?

I'm quite new to Processing.
I'm trying to make Processing randomly play a video after I clear the screen by mouseclick, so I create an array that contain 3 videos and play one at a time.
Holding 'Spacebar' will play a video and release it will stop the video. Mouseclick will clear the screen to an image. The question is how can it randomize to another video if I press spacebar again after clear the screen.
I've been searching all over the internet but couldn't find any solution for my coding or if my logic is wrong, please help me.
Here's my code.
int value = 0;
PImage photo;
import processing.video.*;
int n = 3; //number of videos
float vidN = random(0, n+1);
int x = int (vidN);
Movie[] video = new Movie[3];
//int rand = 0;
int index = 0;
void setup() {
size(800, 500);
frameRate(30);
video = new Movie[3];
video[0] = new Movie (this, "01.mp4");
video[1] = new Movie (this, "02.mp4");
video[2] = new Movie (this, "03.mp4");
photo = loadImage("1.jpg");
}
void draw() {
}
void movieEvent(Movie video) {
video.read();
}
void keyPressed() {
if (key == ' ') {
image(video[x], 0, 0);
video[x].play();
}
}
void mouseClicked() {
if (value == 0) {
video[x].jump(0);
video[x].stop();
background(0);
image(photo, 0, 0);
}
}
You have this bit of logic in your code which picks a random integer:
float vidN = random(0, n+1);
int x = int (vidN);
In theory, if you want to randomise to another video when the spacebar is pressed again you can re-use this bit of logic:
void keyPressed() {
if (key == ' ') {
x = int(random(n+1));
image(video[x], 0, 0);
video[x].play();
}
}
(Above I've used shorthand of the two lines declaring vidN and x, but the logic is the same. If the logic is harder to follow since two operations on the same line (picking a random float between 0,n+1 and rounding down to an integer value), feel free to expand back to two lines: readability is more important).
As side notes, these bit of logic look a bit off:
the if (value == 0) condition will always be true since value never changes, making both value and the condition redundant. (Perhaps you plan to use for something else later ? If so, you could save separate sketches, but start with the simplest version and exclude anything you don't need, otherwise, in general, remove any bit of code you don't need. It will be easier to read, follow and change.)
Currently your logic says that whenever you click current video resets to the start and stops playing and when you hit the spacebar. Once you add the logic to randomise the video that the most recent frame of the current video (just randomised) will display (image(video[x], 0, 0);), then that video will play. Unless you click to stop the current video, previously started videos (via play()) will play in the background (e.g. if they have audio you'll hear them in the background even if you only see one static frame from the last time space was pressed).
Maybe this is the behaviour you want ? You've explained a localised section of what you want to achieve, but not overall what the whole of the program you posted should do. That would help others provide suggestions regarding logic.
In general, try to break the problem down to simple steps that you can test in isolation. Once you've found a solid solution for each part, you can add each part into a main sketch one at a time, testing each time you add something. (This way if something goes wrong it's easy to isolate/fix).
Kevin Workman's How To Program is a great article on this.
As a mental excercise it will help to read through the code line by line and imagine what it might do. Then run it and see if the code behaves as you predicted/intended. Slowly and surely this will get better and better. Have fun learning!

Arduino mills() overflow

I have motor programmed with arduino, the hardware is already setup so i don't want to change the micro controller. I need to give the motor 1 second to move from each point to the other and if its too much stay until "one second" is done and then go the rest of the code.
the bellow code this is part of the whole code. it freezes and not working after about 40 hour. please advise how can i prevent that. I know that the mills() function is the problem but don't know whats the best option to replace or prevent that?
unsigned long firsttime = 0;
unsigned long secondtime = 0;
void loop(){
...
firsttime= millis();
myStepper.step(RNum);
secondtime = 1000-millis()+firsttime;
delay (secondtime);
...
}
Thanks

Arduino PWM program to generate a frequency in a loop

I am new to Arduino, and right now I am trying to generate a frequency that gradually decreases (without using the tone library) in a program that gradually increases the delay between the switching of the high and low. I have the arduino connected to an audio amp and a speaker.
For some reason, the speaker only outputs a single tone and I dont know why. Here is the code:
void setup()
{
pinMode(3, OUTPUT);
}
void loop()
{
for (int i=100; i <= 25500; i+100){
digitalWrite(3, HIGH);
delayMicroseconds(i);
digitalWrite(3, LOW);
delayMicroseconds(i);
}
}
Any help would be appreciated. I would prefer to try and do this the way I am doing, as opposed to using a completly different method or the tone library.
There is an error in the for statement: the increment statement is actually not a statement. You need to assign i to the new value, i.e. write i = i + 100 instead of just i + 100.

Arduino push Button

I need a help in arduino uno r3 with push button. By using the registers without using the pinMode, digitalWrite, digitalRead if-else, and switch-case.
int led1=2, led2=3, led3=4, led4=5;
int led5=8, led6=9, led7=10, led8=11;
int button=12;
int i,j,k;
void setup() {
DDRB=DDRB|B00001111;
DDRD=DDRD|B00111100;
Serial.begin (9600);
}
void loop() {
int f=0;
for(int s=0;s<16;s++){
int k=0;
int i=0b00001;
int j=0b0011;
PORTB=f;
f +=1;
if (f==64){f=0;}
PORTD=0;
for(k=0;k<7;k++){
delay(250);
PORTD=i;
delay(250);
PORTD=j;
i=(i<<1);
j=(j<<1);
}
j=(j>>1);
for(int d=0; d<9; d++){
delay(250);
PORTD=i;
delay(250);
PORTD=j;
i=(i>>1);
j=(j>>1);
}
}
}
This is the code. That what I need is to make a while loop for the push button. When I will push the button the program will be start and when I push the button again program will stop.
Well, you can do this in 2 way.
First one
The simple one is writing and reading a byte directly into/fom eeprom. Everytime you press the push button, you need to read it first and validate this value. Lets supose your byte means 0 to turned off and 1 to turned on. So if you push the button and the already saved byte is 0, so you need to change this to 1.
You are going to write using this:
https://www.arduino.cc/en/Tutorial/EEPROMWrite
After this management, you will need to read this byte constantly inside your loop statement. If byte is 1, so your thread can be executed.
You are going to read using this: https://www.arduino.cc/en/Tutorial/EEPROMRead
Second
This is a cannon to kill a mosquito, but can be reused later to manage other kinds of informations. You are going to use the same logic, but saving more detailed or complex values. We are talking about some kind of database.
http://playground.arduino.cc/Code/DatabaseLibrary
I'm sorry but I can't write to you a sample code right now. Job first. If you can't do this untill the end of the day, maybe I can come later and comlete this post to help you out.

Arduino keypad matrix example? ( teensyduino )

I'm a beginner using Arduino with a Teensy 3.2 board and programming it as a usb keyboard.
I have two 4 button membrane switches. Their button contacts are on pins 1-8, and the 9th pin holds a soldered together wire of both membrane switches' "ground" line or whatever it's true name is; the line that completes the circuit.
Basically when you press the buttons they are supposed to simply type "a, b, c..." respectively. I've been told I need to use a matrix for this.
I'm looking for an example of how to code a keyboard matrix that effectively supports a one row/9 column line (or vice versa?) I've been unable to find that solution online.
All I have so far is this code which, when the button on the second pin is pressed, sends tons of "AAAAAAAAAAAAAAAA" keystrokes.
void setup() {
// make pin 2 an input and turn on the
// pullup resistor so it goes high unless
// connected to ground:
pinMode(2, INPUT_PULLUP);
Keyboard.begin();
}
void loop() {
//if the button is pressed
if(digitalRead(2)==LOW){
//Send an ASCII 'A',
Keyboard.write(65);
}
}
Would anyone be able to help?
First of all, a 1-row keypad is NOT a matrix. Or better, technically it can be considered a matrix but... A matrix keypad is something like this:
You see? In order to scan this you have to
Pull Row1 to ground, while leaving rows 2-4 floating
Read the values of Col1-4. These are the values of switches 1-4
Pull Row2 to ground, while leaving rows 1 and 3-4 floating
Read the values of Col1-4. These are the values of switches 5-8
And so on, for all the rows
As for the other problem, you are printing an A when the button is held low. What you want to achieve is to print A only on the falling edge of the pin (ideally once per pressure), so
char currValue = digitalRead(2);
if((currValue==LOW) && (oldValue==HIGH))
{
//Send an ASCII 'A',
Keyboard.write(65);
}
oldValue = currValue;
Of course you need to declare oldValue outside the loop function and initialize it to HIGH in the main.
With this code you won't receive tons of 'A's, but however you will see something like 5-10 'A's every time you press the button. Why? Because of the bouncing of the button. That's what debouncing techniques are for!
I suggest you to look at the class Bounce2 to get an easy to use class for your button. IF you prefer some code, I wrote this small code for another question:
#define CHECK_EVERY_MS 20
#define MIN_STABLE_VALS 5
unsigned long previousMillis;
char stableVals;
char buttonPressed;
...
void loop() {
if ((millis() - previousMillis) > CHECK_EVERY_MS)
{
previousMillis += CHECK_EVERY_MS;
if (digitalRead(2) != buttonPressed)
{
stableVals++;
if (stableVals >= MIN_STABLE_VALS)
{
buttonPressed = !buttonPressed;
stableVals = 0;
if (buttonPressed)
{
//Send an ASCII 'A',
Keyboard.write(65);
}
}
}
else
stableVals = 0;
}
}
In this case there is no need to check for the previous value, since the function already has a point reached only when the state changes.
If you have to use this for more buttons, however, you will have to duplicate the whole code (and also to use more stableVals variables). That's why I suggsted you to use the Bounce2 class (it does something like this but, since it is all wrapped inside a class, you won't need to bother about variables).

Resources