In line 59 and 70, When I press the buttons the serial doesnt always write
sometiemes it does sometimes it is random. Although When i remove mode--; and mode++; it seams to work fine... Please help!
#include <Arduino.h>
#include <LiquidCrystal.h>
#include <Wire.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
//Pinouts
int l298n_enable = 6;
int l298n_in1 = 7;
int ledr;
int ledg;
int pot = A0;
int mode_up_pin = 9;
int mode_down_pin = 13;
//Variables
int l298n_pwm = 0;
int mode = 0;
bool l298n_active = true;
int mode_up_state = 0;
int mode_down_state = 0;
int last_up_state = 0;
int last_down_state = 0;
void setup() {
//Pinmodes
pinMode(l298n_enable, OUTPUT);
pinMode(l298n_in1, OUTPUT);
// pinMode(ledr, OUTPUT);
// pinMode(ledg, OUTPUT);
pinMode(pot, INPUT);
pinMode(mode_up_pin, INPUT);
pinMode(mode_down_pin, INPUT);
//set motor direction
digitalWrite(l298n_in1, HIGH);
lcd.begin(16, 2);
Serial.begin(9600);
lcd.print("hello, world!");
}
void loop() {
//Write Pot value to motor
l298n_pwm = analogRead(pot);
l298n_pwm = map(l298n_pwm, 0, 1023, 0, 255);
if (l298n_active == true) { //Only write if it is ment to be active
analogWrite(l298n_enable, l298n_pwm);
}
//mode up logic
mode_up_state = digitalRead(mode_up_pin);
if (mode_up_state != last_up_state && mode_up_state == HIGH) {
mode++;
delay(50);
Serial.write("up");
}
last_up_state = mode_up_state;
//mode doqn logic
mode_down_state = digitalRead(mode_down_pin);
if (mode_down_state != last_down_state && mode_down_state == HIGH) {
mode--;
delay(50);
Serial.write("down");
}
last_down_state = mode_down_state;
//Stops mode from going below 0
if (mode < 0) {
mode = 0;
}
//Stops mode from going above 1
if (mode > 1) {
mode = 1;
}
if (mode == 0) {
l298n_active = true;
}
if (mode == 1) {
l298n_active = true;
delay(2000);
l298n_active = false;
delay(2000);
}
}```
if (mode_up_state != last_up_state) {
if ( mode_up_state == HIGH) {
mode++;
Serial.write("up");
}
last_up_state = mode_up_state;
delay(50);
}
You are constantly assigning the present state to the last state. You are recording the last state change, therefore you should only do it when the state does change.
working on a projct that has a jet of water and it kindof dances / goes up and down. The LCd shows the mode it is in and the modes are different settings for the bouncy water thing