How to code a servomotor with two buttons in arduino? - arduino-uno

I wanted to make a servomotor oscilate between 0-90 degrees when i push a button, but when i push another one, it stops oscillating and then remains in its latest position.
i started with this:
#include <Servo.h>
Servo myservo;
int pos = 0;
const int button1 = 5;
const int button2 = 6;
int lastpos = pos;
void setup() {
myservo.attach(3);
pinMode(button1, INPUT);
pinMode(button2, INPUT);
}
void loop() {
if(digitalRead(button1) == HIGH)
{for(pos = 0; pos <= 90; pos += 1)
{myservo.write(pos);
for(pos = 90; pos >= 0; pos -= 1)
{myservo.write(pos);
delay(36);
} } if(digitalRead(button2) == HIGH){ myservo.write(lastpos);}}}

To start, take a look at how to format code inside a question. It makes it a lot easier to read and help you out. See below for how I formatted for the site, but also readability.
Servo myservo;
int pos = 0;
const int button1 = 5;
const int button2 = 6;
int lastpos = pos;
void setup() {
myservo.attach(3);
pinMode(button1, INPUT);
pinMode(button2, INPUT);
}
void loop() {
if(digitalRead(button1) == HIGH) {
for(pos = 0; pos <= 90; pos += 1) {
myservo.write(pos);
for(pos = 90; pos >= 0; pos -= 1) {
myservo.write(pos);
delay(36);
}
}
if(digitalRead(button2) == HIGH) {
myservo.write(lastpos);
}
}
}
There are several issues with your code based on your description of what you are trying to achieve. First, let's start with the button presses. You are ready the button state, but your code will only detect the button if it is pressed at the exact moment you are doing the digital read. Here's a good resource for reading up on how to properly implement buttons on Arduino: https://www.logiqbit.com/perfect-arduino-button-presses
The second objective is to have the servo sweep back and forth, but stop when you press a button. Your for loops won't let that happen. As currently written, you will always do a sweep to one end and back and then check the next button.
You should update the position of the servo once each time through the loop so you can check on the status of the buttons. In pseudo-code, what I suggest you do is:
void loop() {
//Check button statuses
if(button1), start sweep
if(button2), stop sweep
//Update sweep position
if(ascending && pos < 90) {
//You should be increasing in angle and you haven't reached 90 yet
ascending = TRUE;
pos += 1
myservo.write(pos);
delay(36); //Or whatever delay you need for the servo
} else if(pos > 0) {
//You already reached 90 and are coming back down to 0
ascending = FALSE;
pos -= 1;
delay(36);
}

Related

How can I modify the program so that the delay for every interval the led turns On and Off increases by 1 seconds Everytime the loop restarts

It's my first time learning arduino uno and I do not know what to do
const int ledPin = LED_BUILTIN;
int ledState = LOW;
unsigned long previousMillis = 0;
const long interval = 1000;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
for(int interval = 500; interval >= 20; interval++)
previousMillis = currentMillis;
if (ledState == LOW) {
ledState = HIGH;
} else {
ledState = LOW;
}
digitalWrite(ledPin, ledState);
}
}
The delay for every interval the led turns On and Off increases by 1 seconds everytime the loop restarts.
Please make sure you ask your question in the question itself, not the title and also give us some more information about what you're trying to accomplish, what's working and what isn't working so we can help.
If I understand correctly, you want the LED to stay on longer and longer each time it blinks. First cycle 1 second, second cycle 2 seconds, third cycle 3 seconds, etc. You are pretty close, just need some tweaking of your logic.
void loop() {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) { //Check if LED duration has expired
//Toggle LED
if (ledState == LOW) {
ledState = HIGH;
} else {
ledState = LOW;
}
interval += 1000; //Increase the interval by 1 second
digitalWrite(ledPin, ledState); //Set the LED
previousMillis = currentMillis; //Set the time of the last transition to now
}
}

First led of WS2812B starts to light when the code enters the for loop

I'am working on this project, it should be a light for a carport. There are two ways to turn the light on, via motion sensor or via a switch. The Led strip starts to turn on one led after another. It will stay on for a period of time and then a reversed animation starts and turns all LEDs to black. I'am using a for loop for this animation (it's the same one FastLed uses in the first light example). The error is only when the motion sensor is activate and while the for loop is running. I'am sorry for the bad integer names, could be confusing.
Thanks a lot!
Here is the Code:
(If you can't understand German,
- Bewegungsmelder = Motion sensor
- Schalter = Switch
// für die Leds
#define NUMfront_LEDS 150 //150 Leds
#define NUMinner_LEDS 35 //35 Leds
#define rightPIN 6 //Pin 6
#define leftPIN 5
#define innerrightPIN 8
#define innerleftPIN 7
#define CLOCK_PIN 13
// für die Schalter
#define schalter 2 //Pin 2
#define Bewegungsmelder 4 //Pin 4
int schalterval = 0;
int Bewegungsval = 0;
long Time = 0;
long Wait = 900000;
int On = 0;
CRGB leftLeds[NUMfront_LEDS];
CRGB rightLeds[NUMfront_LEDS];
CRGB innerleftLeds[NUMinner_LEDS];
CRGB innerrightLeds[NUMinner_LEDS];
void setup() {
// sanity check delay - allows reprogramming if accidently blowing power w/leds
Serial.begin(115200);
delay(2000);
FastLED.addLeds<WS2812B, rightPIN, RGB>(rightLeds, NUMfront_LEDS); // GRB ordering is typical
FastLED.addLeds<WS2812B, leftPIN, RGB>(leftLeds, NUMfront_LEDS);
FastLED.addLeds<WS2812B, innerrightPIN, RGB>(innerrightLeds, NUMinner_LEDS);
FastLED.addLeds<WS2812B, innerleftPIN, RGB>(innerleftLeds, NUMinner_LEDS);
Time = millis();
}
void loop() {
Serial.println("----------------------------------------------");
Serial.print(Wait);
Serial.print("----");
Serial.print(millis());
Bewegungsval = digitalRead(Bewegungsmelder);
schalterval = digitalRead(schalter);
Serial.println(Bewegungsval);
Serial.println(schalterval);
Serial.println("Space");
Schalter:
if (digitalRead(schalter) == 1) {
On = 0;
for (int blackLed = NUMfront_LEDS; blackLed > -1; blackLed = blackLed - 1) {
leftLeds[blackLed] = CRGB::White;
rightLeds[blackLed] = CRGB::White;
delay(19);
FastLED.show();
}
// Carport innen
fill_solid( innerrightLeds, NUMinner_LEDS, CRGB::White);
fill_solid( innerleftLeds, NUMinner_LEDS, CRGB::White);
//Leds aus
//Carport aussen
while (digitalRead(schalter) == 1) {
}
for (int whiteLed = 0; whiteLed < NUMfront_LEDS; whiteLed = whiteLed + 1) {
leftLeds[whiteLed] = CRGB::Black;
rightLeds[whiteLed] = CRGB::Black;
delay(19);
FastLED.show();
}
// Carport innen
fill_solid( innerrightLeds, NUMinner_LEDS, CRGB::Black);
fill_solid( innerleftLeds, NUMinner_LEDS, CRGB::Black);
FastLED.show();
}
else if (Bewegungsval == 1) {
//Carport aussen
if (On == 1) {
goto Skip;
}
for (int blackLed = NUMfront_LEDS; blackLed > -1; blackLed = blackLed - 1) {
leftLeds[blackLed] = CRGB::White;
rightLeds[blackLed] = CRGB::White;
delay(19);
FastLED.show();
}
// Carport innen
fill_solid( innerrightLeds, NUMinner_LEDS, CRGB::White);
fill_solid( innerleftLeds, NUMinner_LEDS, CRGB::White);
FastLED.show();
//Leds aus
On = 1;
Skip:
Time = millis();
Wait = Time + 10000; // + 5min. 300000
Bewegungsval = digitalRead(Bewegungsmelder);
goto Schalter;
}
Time = millis();
if (Time >= Wait) {
On = 0;
for (int whiteLed = 0; whiteLed < NUMfront_LEDS; whiteLed = whiteLed + 1) {
leftLeds[whiteLed] = CRGB::Black;
rightLeds[whiteLed] = CRGB::Black;
delay(19);
FastLED.show();
}
// Carport innen
fill_solid( innerrightLeds, NUMinner_LEDS, CRGB::Black);
fill_solid( innerleftLeds, NUMinner_LEDS, CRGB::Black);
}
}```
Although fluent in German the program structure is alittle chaotic. Since we are in C++
you should not use goto
Since to my understanding the light routines for switch and IR are the same this code should only exist once
Your routine for measuring time is not rollover safe see blinkwithoutdelay example how todo
So clean the code up by using the following structure:
unsigned long startTime = 0;
unsigned long myTimer = 10000;// 10 sec
bool lightIsOn = false;
setup(){....}
loop(){
....
// We check wether switch or IR are triggerd AND we are not already in a light sequence
if ((digitalRead(schalter) == 1 || Bewegungsval == 1) && lightIsOn == false) {
lightIsOn = true; // change state so we know that a light sequence is running
startTime = millis(); // reset the timer
}
// this part runs as long lighIsOn == true and time is not up
if(millis() - startTime <= myTimer && lighIsOn == true){
// Carport aussen
your light sequence .....
}
// Here we run the time is up sequence
if(millis() - startTime > myTimer && lighIsOn == true) { // rollover safe
light sequence for time is up
........
lightIsOn = false; // change state so we know that a light sequence is over
}
}
This technique is called finite state machine there is no "jumping around" via goto.
If you need more states you just expand the sequence - there is no else because eg in the last two combined if statements we check for lightIsON == true ==> else would mean lightIsON == false in the second which makes no sense here as we only differentiate these to states by time.
Please never use goto in object oriented programming it makes your code unreadable and untraceable. Rewrite the program and if there are "new" problems edit here or open a new question

Stopwatch fails to reset

I am working on an Arduino stopwatch, where it needs a start, stop, and reset button. To reset it, I am using a variable called starttime that is updated to equal to millis(), and then take the difference to display time. However, past thirty seconds, the starttime does not update correctly, and the resulting difference between starttime and millis() is equivalent to 65 seconds. Can someone explain why this is happening?
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
const int start = 8;
const int stp = 9;
const int reset = 10;
int seconds;
int minutes;
int timedif;
int starttime = -1;
int timestall = 0;
bool onoff = true;
void setup()
{
pinMode(start, INPUT);
pinMode(stp, INPUT);
pinMode(reset, INPUT);
lcd.begin(16, 2); //Initialize the 16x2 LCD
lcd.clear(); //Clear any old data displayed on the LCD
Serial.begin(9600);
}
void loop()
{
int bsta = digitalRead(start);//sees if start switch is pressed
int bstp = digitalRead(stp);//records if stop switch is pressed
int bres = digitalRead(reset);//records if reset switch is pressed
lcd.setCursor(0,0);
lcd.print("Stopwatch");//prints stopwatch top row
lcd.setCursor(0,1);
if (starttime == -1) { //if running first time, time dif is initiated
starttime = millis();
}
timedif = (millis() - starttime )/1000 + timestall; //will get difference in terms of seconds
minutes = floor(timedif/60); // divides by sixty, drops decimal
seconds = timedif%60; //gets remainder of divided by 60
lcd.print(minutes);
lcd.print(":");
lcd.print(seconds);
if (seconds < 10) {
lcd.setCursor(3,1);
lcd.print(' ');
}
if (bstp == HIGH) {
onoff = false;
while(onoff == false) {
if (digitalRead(start) == HIGH) {
onoff = true;
}
}
timestall = timedif;
starttime = millis();
}
if (bres == HIGH) {
delay(100);
timestall = 0;
starttime = millis();
timedif = 0;
lcd.clear();
Serial.println("stall:");
Serial.println(timestall);
Serial.println("dif");
Serial.println(timedif);
Serial.println("start");
Serial.println(millis() - starttime);
}
}
You should use long or unsigned long instead if int to declare variables that hold time values.
A int variable can only hold 32,767 millisecond hence the 32 sec. where a long variable can hold 2,147,483,647 millisecond which is something like 48 days. A unsigned long can hold double of that but can not hold a negative value.

How to add settings to snake game(Processing)?

Im trying to add settings to a snake game made in processing. I want to have something like easy, normal and hard or something along the lines of that and change the speed and maybe size of the grid. If anyone coudl explain how to id greatly appreciate it!
ArrayList<Integer> x = new ArrayList<Integer>(), y = new ArrayList<Integer>();
int w = 30, h = 30, bs = 20, dir = 2, applex = 12, appley = 10;
int[] dx = {0,0,1,-1}, dy = {1,-1,0,0};
boolean gameover = false;
void setup() {
size(600,600);
x.add(5);
y.add(5);
}
void draw() {
background(255);
for(int i = 0 ; i < w; i++) line(i*bs, 0, i*bs, height); //Vertical line for grid
for(int i = 0 ; i < h; i++) line(0, i*bs, width, i*bs); //Horizontal line for grid
for(int i = 0 ; i < x.size(); i++) {
fill (0,255,0);
rect(x.get(i)*bs, y.get(i)*bs, bs, bs);
}
if(!gameover) {
fill(255,0,0);
rect(applex*bs, appley*bs, bs, bs);
if(frameCount%5==0) {
x.add(0,x.get(0) + dx[dir]);
y.add(0,y.get(0) + dy[dir]);
if(x.get(0) < 0 || y.get(0) < 0 || x.get(0) >= w || y.get(0) >= h) gameover = true;
for(int i = 1; i < x.size(); i++) if(x.get(0) == x.get(i) && y.get(0) == y.get(i)) gameover = true;
if(x.get(0)==applex && y.get(0)==appley) {
applex = (int)random(0,w);
appley = (int)random(0,h);
}else {
x.remove(x.size()-1);
y.remove(y.size()-1);
}
}
} else {
fill(0);
textSize(30);
text("GAME OVER. Press Space to Play Again", 20, height/2);
if(keyPressed && key == ' ') {
x.clear(); //Clear array list
y.clear(); //Clear array list
x.add(5);
y.add(5);
gameover = false;
}
}
if (keyPressed == true) {
int newdir = key=='s' ? 0 : (key=='w' ? 1 : (key=='d' ? 2 : (key=='a' ? 3 : -1)));
if(newdir != -1 && (x.size() <= 1 || !(x.get(1) ==x.get(0) + dx[newdir] && y.get (1) == y.get(0) + dy[newdir]))) dir = newdir;
}
}
You need to break your problem down into smaller steps:
Step one: Can you store the difficulty in a variable? This might be an int that keeps track of a level, or a boolean that switches between easy and hard. Just hardcode the value of that variable for now.
Step two: Can you write your code so it changes behavior based on the difficulty level? Use the variable you created in step one. You might use an if statement to check the difficulty level, or maybe the speed increases over time. It's completely up to you. Start out with a hard-coded value. Change the value to see different behaviors.
Step three: Can you programatically change that value? Maybe this requires a settings screen where the user chooses the difficulty, or maybe it gets more difficult over time. But you have to do the first two steps before you can start this step.
If you get stuck on a specific step, then post an MCVE and we'll go from there.

How to set up if statements so that loop goes forward and then in reverse? Processing

int x = 31;
int y = 31;
int x_dir = 4;
int y_dir = 0;
void setup ()
{
size (800, 800);
}
void draw ()
{
background (150);
ellipse (x,y,60, 60);
if (x+30>=width)
{
x_dir =-4;
y_dir = 4;
}
if (y+30>=height)
{
x_dir=4;
y_dir = 0;
}
if (x+30>=width)
{
x_dir = -4;
}
x+=x_dir;
y+=y_dir;
println(x,y);
}
Hi,
I have to create this program in processing which produces an animation of a ball going in a Z pattern (top left to top right, diagonal top right to bottom left, and then straight from bottom left to bottom right) which then goes backwards along the same path it came.
While I have the code written out for the forward direction, I don't know what 2 if or else statements I need to write for the program so that based on one condition it goes forwards, and based on another condition it will go backwards, and it will continue doing so until it terminates.
If I am able to figure out which two if statements I need to write, all I need to do is copy and reverse the x_dir and y_dir signs on the forward loop.
There are a ton of different ways you can do this.
One approach is to keep track of which "mode" you're in. You could do this using an int variable that's 0 when you're on the first part of the path, 1 when you're on the second part of the path, etc. Then just use an if statement to decide what to do, how to move the ball, etc.
Here's an example:
int x = 31;
int y = 31;
int mode = 0;
void setup ()
{
size (800, 800);
}
void draw ()
{
background (150);
ellipse (x, y, 60, 60);
if (mode == 0) {
x = x + 4;
if (x+30>=width) {
mode = 1;
}
} else if (mode == 1) {
x = x - 4;
y = y + 4;
if (y+30>=height) {
mode = 2;
}
} else if (mode == 2) {
x = x + 4;
if (x+30>=width) {
mode = 3;
}
} else if (mode == 3) {
x = x - 4;
y = y - 4;
if (y-30 < 0) {
mode = 2;
}
}
}
Like I said, this is only one way to approach the problem, and there are some obvious improvements you could make. For example, you could store the movement speeds and the conditions that change the mode in an array (or better yet, in objects) and get rid of all of the if statements.

Resources