lost in programming - cant bend my head around it

hi

i am trying to wright a code, but it just wont retur to start as i want it to.

i want to push the button, then it does something, then push it again, and it returns to zero, and so on.

here is my code so far:

#include "U8glib.h"
U8GLIB_LD7032_60x32 u8g(9, 8, 11, 10, 12);


#include <Servo.h> 

Servo myservo;  // create servo object to control a servo 
               // twelve servo objects can be created on most boards

int pos = 3;    // variable to store the servo position 
const int led1Pin = 4;
const int led2Pin = 5;
int flag1 = 0;
int switchPin = 2;              // switch is connected to pin 2
int val;                        // variable for reading the pin status
int buttonState;                // variable to hold the button state
int lightMode = 0;              // Is the light on or off?

unsigned long previousMillis1 = 0;
long LEDTime = 500;


void setup() {

  myservo.attach(3);  // attaches the servo on pin 9 to the servo object 
 pinMode(switchPin, INPUT);    // Set the switch pin as input

 pinMode(led1Pin, OUTPUT);
 pinMode(led2Pin, OUTPUT);

 
 Serial.begin(9600);           // Set up serial communication at 9600bps
 buttonState = digitalRead(switchPin);   // read the initial state
}

const uint8_t rook_bitmap[] PROGMEM = {
 0x00,         // 00000000
 0x55,         // 01010101
 0x7f,          // 01111111
 0x3e,         // 00111110
 0x3e,         // 00111110
 0x3e,         // 00111110
 0x3e,         // 00111110
 0x7f           // 01111111
};


void loop(){
Serial.print("Read switch input: ");
 Serial.println(digitalRead(switchPin));    // Read the pin and display the value
 delay(100);

unsigned long currentMillis = millis();


 
 val = digitalRead(switchPin);      // read input value and store it in val

 if (val != buttonState) {          // the button state has changed!
   if (val == HIGH) {                // check if the button is pressed
     if (flag1 == 0) {          // light is off
       flag1 = 1;                    // light is on!
     

if (flag1 == 1) {


 // picture loop
 u8g.firstPage();
 do {
   u8g.setFont(u8g_font_unifont);
   //       u8g.setFont(u8g_font_osb21);
   u8g.drawStr( 5, 20, "KILL");
 } while ( u8g.nextPage() );
 delay(1500);

  u8g.firstPage();
 do {
   u8g.setFont(u8g_font_unifont);
   //       u8g.setFont(u8g_font_osb21);
   u8g.drawStr( 5, 20, "RASMUS");
 } while ( u8g.nextPage() );
 delay(1500);
 
 u8g.firstPage();
 do {
   u8g.drawCircle(30, 20, 18);
   u8g.drawEllipse(26, 12, 7, 5,U8G_DRAW_UPPER_LEFT );
   u8g.drawEllipse(34, 12, 7, 5, U8G_DRAW_UPPER_RIGHT);
   u8g.drawTriangle(30,14, 27, 18, 33, 18);
   u8g.drawFilledEllipse( 30, 25, 10,5, U8G_DRAW_LOWER_LEFT);
   u8g.drawFilledEllipse( 30, 25, 10,5, U8G_DRAW_LOWER_RIGHT);
   u8g.drawLine(30, 13, 30, 16);
    
    
   u8g.drawFrame(0, 0,60 ,32);
    
 } while ( u8g.nextPage() );
 delay(2000);

 u8g.firstPage();
 do {
   u8g.drawBitmapP(30, 16,1, 8, rook_bitmap);
 } while ( u8g.nextPage() );
 delay(1000);
 u8g.firstPage();
 do {

 } while ( u8g.nextPage() );
 delay(1000);

flag1 = 2;


     }
     
   

       
else if (val != buttonState) {          // the button state has changed!
   if (val == HIGH) {                // check if the button is pressed
     if (flag1 == 2) {          // light is off
       flag1 = 0;                    // light is on!

       }}}

   
    
 buttonState = val;                 // save the new state in our variable

}
}}}

Please modify your post and use the code button </> so your code looks like this and is easy to copy to a text editor. Then I will study it. See How to use the Forum

…R

i want to push the button, then it does something, then push it again, and it returns to zero, and so on.

Few suggestions.
Add Serial prints liberally to your code so you can see what it actually does.
Use AutoFormat so your code is easier to read.( For YOU , not for the forum "benefits".)
Instead of physically pushing the button set the val , for test purposes only, and than trace your code flow.
Does it do what you expected?
....
val =digitalRead(switchPin) ; // read input value and store it in val
val = 0; // force val in test run
...
It is better to always initialize variables.

And most of all - you have a simple task - monitor button - code just that and when it works add the "meat and potatoes " ( display or whatever) later.

When you suspect the code flow is not getting into correct line, just stop the processing, temporary with

Serial.println(func); // prints the current function
Serial.println(LINE); // prints current line - you MAY have to set the "use lines" option in Prefernces.
for(semicolon semicolon ) semicolon // halt processing in infinite loop here

.....
if( val) // test button
{ // button pushed main code block start
// button pushed
Serial.print("button pushed ");
// turn LED on
// display , play etc.
}// button pushed main code block end

{// "automatic" else - binary condition 0 or 1 only - button not pushed main code block start
// button not pushed
Serial.print("button not pushed ");
// ...
}// button not pushed main code block end

delay(....); // so you can observe the code if it is in loop()
....
BTW you probably do not need flag, but that is too early / irrelevant at this point.
Make it work first, than you can tune it up later.

Good luck.

@Topholm, thank you for using the code tags.

As @Vaclav says you code is almost impossible to read due to the poor formatting.

I notice that you have some long delay()s in your code. They always interfere with buttons because the Arduino cannot do anything during a delay(). You should use millis() to manage timing as illustrated in Several Things at a Time

It would also a good idea to organize your code into single-purpose functions that can each be tested on their own. This is illustrated in Planning and Implementing a Program

...R

{// "automatic"  else - binary condition 0 or 1 only

Gibberish.
An else clause is executed only if the “if” expression evaluates to false.
@vaclav’s “automatic” else is executed whether or not the “if” expression is false.

Groove:

{// "automatic"  else - binary condition 0 or 1 only

Gibberish.
An else clause is executed only if the "if" expression evaluates to false.
@vaclav's "automatic" else is executed whether or not the "if" expression is false.

Yes, you are correct. And this is not the first time I done that!
It was inappropriate anyway. It did not help much , just confused things.
But OP is gone so who cares, right?

Vaclav:
It was inappropriate anyway. It did not help much , just confused things.
But OP is gone so who cares, right?

Am I alone in being unimpressed by that attitude.

People other than the OP may get value (or NOT) from any Reply in any Thread.

I make mistakes, but I hope I always apologize and try to put them right when they are pointed out.

...R

Robin2:
Am I alone in being unimpressed by that attitude.

Nope.

Though I think you've pointed out what's likely the issue - the chain of delays means it's only checking for a button press once per 5 seconds. And the formatting is atrocious, of course... but that's just because he didn't know about the autoformat.

thanks for all the input, despite the intention behind.

i have been struggling for at least the last 4 hours with this, trying to use all of the input i have gotten. but sadly with no luck. it just wont do as i want i to.

its pretty simple: push the button, then move the servo from 0 to 90 degrees. and stop, while in the 90 degrees position blink 2 LED’s in random while showing “symbols” on the screen. and continue to do that until i push the button again, and it should move from 90 to 0 degrees and do nothing until next time i push it and then from the top.

i have tried making my own code, tried copy/paste a code, tried stealing other codes that had almost similar movement. but with no luck.

Topholm:
i have been struggling for at least the last 4 hours with this, trying to use all of the input i have gotten. but sadly with no luck.

Truthfully, 4 hours is not very long. I spent at least 4 hours a couple of days ago trying to figure why something wasn’t working when in fact it was working perfectly all the time but the message it was printing looked like an error. (I was trying to figure out some code I had written 12 months ago)

Presumably you have made some changes to your code taking acccount of the replies here. Post the latest version of your code and describe carefully what it actually does and what you want it to do.

And please use the code button </> so your code looks like this and is easy to copy to a text editor

…R

sorry, i know 4 hours isn’t a lot, but i didn’t only use 4 hours, just after 4 hours without progress i needed some outburst, :stuck_out_tongue:

the is my code so far:

#include "U8glib.h"
U8GLIB_LD7032_60x32 u8g(9, 8, 11, 10, 12);


#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 5;    // variable to store the servo position
const int led1Pin = 4;
const int led2Pin = 5;




int switchPin = 2;              // switch is connected to pin 2


int val;                        // variable for reading the pin status
int buttonState;                // variable to hold the button state
int lightMode = 0;              // Is the light on or off?
int blinkmode = 0;

void setup(void) {

  myservo.attach(3);  // attaches the servo on pin 9 to the servo object
  pinMode(switchPin, INPUT);    // Set the switch pin as input

  pinMode(led1Pin, OUTPUT);
  pinMode(led2Pin, OUTPUT);


  Serial.begin(9600);           // Set up serial communication at 9600bps
  buttonState = digitalRead(switchPin);   // read the initial state
}

const uint8_t rook_bitmap[] PROGMEM = {
  0x00,         // 00000000
  0x55,         // 01010101
  0x7f,          // 01111111
  0x3e,         // 00111110
  0x3e,         // 00111110
  0x3e,         // 00111110
  0x3e,         // 00111110
  0x7f           // 01111111
};


void loop(void) {

 val = digitalRead(switchPin);      // read input value and store it in val

  if (val != buttonState) {          // the button state has changed!
    if (val == HIGH) {                // check if the button is pressed
      if (lightMode == 0) {          // light is off
        lightMode = 1;               // light is on!


        for (pos = 1; pos <= 90; pos += 1) // goes from 0 degrees to 180 degrees


        { // in steps of 1 degree
          myservo.write(pos);              // tell servo to go to position in variable 'pos'
          // waits 15ms for the servo to reach the position
          blinkmode = 1;
        }

      } else {
        lightMode = 0;               // light is on!

        for (pos = 90; pos >= 1; pos -= 1) // goes from 180 degrees to 0 degrees
        {
          myservo.write(pos);              // tell servo to go to position in variable 'pos'
          // waits 15ms for the servo to reach the position
          blinkmode = 0;
        }
        if (blinkmode == 1);

      }
    }
  }

  digitalWrite(led1Pin, HIGH);

  if (blinkmode == 0);

  digitalWrite(led1Pin, LOW);

  buttonState = val;                 // save the new state in our variable
}

when i push the button the servo does move, and then push it again it goes back. but the LED state is always high. i did what was sugested at took all the meat out until the “master” code was done, so this is just a try to get the servo to move, the light on, servo move back, light off.

and this time i did use the Auto Format button. :smiley:

 if (blinkmode == 1);

Lose the semicolons on these lines.
With them in place the only code that will be executed if the condition is true is the semicolon.

Look at the if clauses in general

       if (blinkmode == 1);

      }

What commands should be executed if the condition is true ?

 if (blinkmode == 0);

  digitalWrite(led1Pin, LOW);

  buttonState = val;                 // save the new state in our variable

and again.

Suggestion. Always use opening and closing braces to define the command(s) to be executed when the condition in the if is true even if there is only one command.

Topholm:
sorry, i know 4 hours isn’t a lot, but i didn’t only use 4 hours, just after 4 hours without progress i needed some outburst, :stuck_out_tongue:

the is my code so far:

#include "U8glib.h"

U8GLIB_LD7032_60x32 u8g(9, 8, 11, 10, 12);

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 5;    // variable to store the servo position
const int led1Pin = 4;
const int led2Pin = 5;

int switchPin = 2;              // switch is connected to pin 2

int val;                        // variable for reading the pin status
int buttonState;                // variable to hold the button state
int lightMode = 0;              // Is the light on or off?
int blinkmode = 0;

void setup(void) {

myservo.attach(3);  // attaches the servo on pin 9 to the servo object
  pinMode(switchPin, INPUT);    // Set the switch pin as input

pinMode(led1Pin, OUTPUT);
  pinMode(led2Pin, OUTPUT);

Serial.begin(9600);          // Set up serial communication at 9600bps
  buttonState = digitalRead(switchPin);  // read the initial state
}

const uint8_t rook_bitmap PROGMEM = {
  0x00,        // 00000000
  0x55,        // 01010101
  0x7f,          // 01111111
  0x3e,        // 00111110
  0x3e,        // 00111110
  0x3e,        // 00111110
  0x3e,        // 00111110
  0x7f          // 01111111
};

void loop(void) {

val = digitalRead(switchPin);      // read input value and store it in val

if (val != buttonState) {          // the button state has changed!
    if (val == HIGH) {                // check if the button is pressed
      if (lightMode == 0) {          // light is off
        lightMode = 1;              // light is on!

for (pos = 1; pos <= 90; pos += 1) // goes from 0 degrees to 180 degrees

{ // in steps of 1 degree
          myservo.write(pos);              // tell servo to go to position in variable ‘pos’
          // waits 15ms for the servo to reach the position
          blinkmode = 1;
        }

} else {
        lightMode = 0;              // light is on!

for (pos = 90; pos >= 1; pos -= 1) // goes from 180 degrees to 0 degrees
        {
          myservo.write(pos);              // tell servo to go to position in variable ‘pos’
          // waits 15ms for the servo to reach the position
          blinkmode = 0;
        }
        if (blinkmode == 1);

}
    }
  }

digitalWrite(led1Pin, HIGH);

if (blinkmode == 0);

digitalWrite(led1Pin, LOW);

buttonState = val;                // save the new state in our variable
}





when i push the button the servo does move, and then push it again it goes back. but the LED state is always high. i did what was sugested at took all the meat out until the "master" code was done, so this is just a try to get the servo to move, the light on, servo move back, light off. 

and this time i did use the Auto Format button. :D

You are doing OK.
Read your code line by line , include “wait” ( you have comments to wait by no instructions to do that ) and remember that the function "loop() " gets executed over and over.
Also check what the code is doing when “if” is false.
To see the LED light changing you need to wait in each state,
servo is mechanical device and takes few ms to move.
At this point just put “delay(xxx)” where appropriate, you can do "blink without delay " later.

It may be too early to tune things up, but in general always use “smallest” variable size.
Digital read of a button returns 0 or 1 so using int is not necessary , boolean will do.

so i lost the semicolons and that did make it work with just turning the LED on and of in between the servo set positions. i then tried to incorporate the blink without delay code. but that just made it a bit more unstable.

now sometimes when i “reset” and the servo goes back the LED is still on and sometimes it turns off. also sometimes the servo just makes a small twitch and then does nothing.

i guess my problem now is that the difference comes from “where” in the loop i hit the switch and that is why both the LED and the Servo does some weird stuff once in awhile?

#include "U8glib.h"
U8GLIB_LD7032_60x32 u8g(9, 8, 11, 10, 12);


#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 5;    // variable to store the servo position
const int led1Pin = 4;
const int led2Pin = 5;

int ledState = LOW;             // ledState used to set the LED
long previousMillis = 0;        // will store last time LED was updated
long interval = 1000;           // interval at which to blink (milliseconds

int switchPin = 2;              // switch is connected to pin 2


int val;                        // variable for reading the pin status
int buttonState;                // variable to hold the button state
int lightMode = 0;              // Is the light on or off?
int blinkmode = 0;

void setup(void) {

  myservo.attach(3);  // attaches the servo on pin 9 to the servo object
  pinMode(switchPin, INPUT);    // Set the switch pin as input

  pinMode(led1Pin, OUTPUT);
  pinMode(led2Pin, OUTPUT);


  Serial.begin(9600);           // Set up serial communication at 9600bps
  buttonState = digitalRead(switchPin);   // read the initial state
}

const uint8_t rook_bitmap[] PROGMEM = {
  0x00,         // 00000000
  0x55,         // 01010101
  0x7f,          // 01111111
  0x3e,         // 00111110
  0x3e,         // 00111110
  0x3e,         // 00111110
  0x3e,         // 00111110
  0x7f           // 01111111
};


void loop(void) {

  unsigned long currentMillis = millis();

  val = digitalRead(switchPin);      // read input value and store it in val

  if (val != buttonState) {          // the button state has changed!
    if (val == HIGH) {                // check if the button is pressed
      if (lightMode == 0) {          // light is off
        lightMode = 1;               // light is on!


        for (pos = 1; pos <= 90; pos += 1) // goes from 0 degrees to 180 degrees


        { // in steps of 1 degree
          myservo.write(pos);              // tell servo to go to position in variable 'pos'
          // waits 15ms for the servo to reach the position
          blinkmode = 1;
        }

      } else {
        lightMode = 0;               // light is on!

        for (pos = 90; pos >= 1; pos -= 1) // goes from 180 degrees to 0 degrees
        {
          myservo.write(pos);              // tell servo to go to position in variable 'pos'
          // waits 15ms for the servo to reach the position
          blinkmode = 0;
        }

      }
    }
  }
  if (blinkmode == 1)



    if (currentMillis - previousMillis > interval) {
      // save the last time you blinked the LED
      previousMillis = currentMillis;

      // if the LED is off turn it on and vice-versa:
      if (ledState == LOW)
        ledState = HIGH;
      else
        ledState = LOW;

      // set the LED with the ledState of the variable:
      digitalWrite(led1Pin, ledState);

 if (blinkmode == 0)

        if (currentMillis - previousMillis > interval) {
          // save the last time you blinked the LED
          previousMillis = currentMillis;

          // if the LED is off turn it on and vice-versa:
          if (ledState == LOW)
            ledState = LOW;
          else
            ledState = LOW;

          // set the LED with the ledState of the variable:
          digitalWrite(led1Pin, ledState);

          buttonState = val;                 // save the new state in our variable
        }
    }
}

It is not causing the problem that you are having but why use a for loop to move the servo when a single servo.write() would do the same thing and you only need to set blinkmode once, not inside a for loop.

i guess my problem now is that the difference comes from "where" in the loop i hit the switch and that is why both the LED and the Servo does some weird stuff once in awhile?

So, when you detect the button press explicitly write to the LED pin to put the LED into the state you require and move the servo to its required position.

yeah that is a good question. im am kind of new in the coding world, and this is literally my first code that didn't come from the arduino starter pack. so when you say why not use a servo.write() thats because i don't know about servo.write()

But i will definitely check it out.

I have taken the liberty to reformat your code - remove most of the empty lines.
( I have an option to let AutoFormat to do that and I can show you later how to do that if you are interested.)
Also I have added some comments.

I’ll have to take a look at sample code “blink without delay” , I am pressed for time to analyze yours.
My guess is you want to check the interval and if it expired just complement the LED state
You do not need to check the LED state, you have defined it initially, just change it.

But there is nothing wrong in checking the actual LED state if you are more comfortable have all the code visible for you.

[code]

#include "U8glib.h"
U8GLIB_LD7032_60x32 u8g(9, 8, 11, 10, 12);


#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 5;    // variable to store the servo position
const int led1Pin = 4;
const int led2Pin = 5;

int ledState = LOW;             // ledState used to set the LED
long previousMillis = 0;        // will store last time LED was updated
long interval = 1000;           // interval at which to blink (milliseconds

int switchPin = 2;              // switch is connected to pin 2


int val;                        // variable for reading the pin status
int buttonState;                // variable to hold the button state
int lightMode = 0;              // Is the light on or off?
int blinkmode = 0;

void setup(void) {
  myservo.attach(3);  // attaches the servo on pin 9 to the servo object
  pinMode(switchPin, INPUT);    // Set the switch pin as input
  pinMode(led1Pin, OUTPUT);
  pinMode(led2Pin, OUTPUT);
  Serial.begin(9600);           // Set up serial communication at 9600bps
  buttonState = digitalRead(switchPin);   // read the initial state
}

const uint8_t rook_bitmap[] PROGMEM = {
  0x00,         // 00000000
  0x55,         // 01010101
  0x7f,          // 01111111
  0x3e,         // 00111110
  0x3e,         // 00111110
  0x3e,         // 00111110
  0x3e,         // 00111110
  0x7f           // 01111111
};


void loop(void) {
  unsigned long currentMillis = millis();
  val = digitalRead(switchPin);      // read input value and store it in val
  if (val != buttonState) {          // the button state has changed!
    if (val == HIGH) {                // check if the button is pressed
      if (lightMode == 0) {          // light is off
        lightMode = 1;               // light is on!

this "for" loop runs the servo ins steps of 1 all at once 
add short delay  ( few ms) to allow servo to settle at step and than add 
another delay , perhaps 1 second, so you can observe the servo movement 
do same / similar for both direction 

keep in mind that you run the servo code THAN  do the LED 

later you can add "blink without delay to do both relatively same time 

        for (pos = 1; pos <= 90; pos += 1) // goes from 0 degrees to 180 degrees
        { // in steps of 1 degree
          myservo.write(pos);              // tell servo to go to position in variable 'pos'
          // waits 15ms for the servo to reach the position
          delay(15); 
      
          // test delay so it can be observed , to be removed later 
          delay (1000); 
          blinkmode = 1;
        }
      } else {
        lightMode = 0;               // light is on!
        for (pos = 90; pos >= 1; pos -= 1) // goes from 180 degrees to 0 degrees
        {
          myservo.write(pos);              // tell servo to go to position in variable 'pos'
          // waits 15ms for the servo to reach the position
          blinkmode = 0;
        }
      }
    }
  }

now checking LED see comment above 

  if (blinkmode == 1)
    if (currentMillis - previousMillis > interval) {
      // save the last time you blinked the LED
      previousMillis = currentMillis;
      // if the LED is off turn it on and vice-versa:
      if (ledState == LOW)
        ledState = HIGH;
      else
        ledState = LOW;
      // set the LED with the ledState of the variable:
      digitalWrite(led1Pin, ledState);
      if (blinkmode == 0)
        if (currentMillis - previousMillis > interval) {
          // save the last time you blinked the LED
          previousMillis = currentMillis;
          // if the LED is off turn it on and vice-versa:
          if (ledState == LOW)
            ledState = LOW;
          else
            ledState = LOW;
          // set the LED with the ledState of the variable:
          digitalWrite(led1Pin, ledState);
          buttonState = val;                 // save the new state in our variable
        }
    }
}

[/code]

Topholm:
yeah that is a good question. im am kind of new in the coding world, and this is literally my first code that didn’t come from the arduino starter pack. so when you say why not use a servo.write() thats because i don’t know about servo.write()

But i will definitely check it out.

What I had in mind was

      myservo.write(90);              // tell servo to go to position 90
      blinkmode = 1;

instead of

        for (pos = 1; pos <= 90; pos += 1) // goes from 0 degrees to 180 degrees THE COMMENT DOES NOT MATCH THE CODE
        { // in steps of 1 degree
          myservo.write(pos);              // tell servo to go to position in variable 'pos'
          // waits 15ms for the servo to reach the position OH NO IT DOESN'T
          blinkmode = 1;
        }

Note the extra comments that I have added to your code.

#Vaclav i just checked out your code and thanks for the help.

but when i upload your code, the servo moves at the first push, and that's it.

i would like to learn your Auto format, because even do this is my first project, i am definetly hooked and have a lot of projects planned for the future.

but i do appreciate your help! BIG THANKS!!!

#UKHeliBob that does indeed look a lot more simple that the thing i have done. :smiley: