Please help, i can't figure out what's wrong with my code [solved]

For my school project, I need to make a useless box using Arduino.
it is meant to work every case from 0 to 5 separately.
But I keep messing up the cases and basically everything else. I really can't figure this kind of difficult problem out since I just recently started coding.
Any help would be greatly appreciated!

Here's my code:

#include <Wire.h>

#include <LiquidCrystal_I2C.h>

#include <Servo.h>

int ldr = A3;                //ldr definieeren en koppelen aan pin
int vibrSensor = 11;               //Vibratie Sensor definieeren en koppelen aan pin
int toggleSwitch = 3;              //Toggle switch definieeren en koppelen aan pin
int vingerBev = 4;                 //Vinger Beveiliging definieeren en koppelen aan pin
int microSwitch = 5;               //Microswitch definieeren en koppelen aan pin
int buzzer = 6;                    //Buzzer definieeren en koppelen aan pin
int programCount = 0;
int val = 0;

int ldrStatus = analogRead(ldr);

Servo vinger;                            // vinger servo definieeren
Servo deksel;                            //deksel servo definieeren

LiquidCrystal_I2C lcd(0x3f, 16, 2);      // LCD definieeren

int pos = 180;
void setup() {
  pinMode(vibrSensor, INPUT);         //Input toewijzen
  pinMode(ldr, INPUT);                //Input toewijzen
  pinMode(toggleSwitch, INPUT);       //Input toewijzen
  pinMode(vingerBev, INPUT);          //Input toewijzen
  pinMode(microSwitch, INPUT);        //Input toewijzen
  pinMode(buzzer, OUTPUT);            //Output toewijzen


  vinger.attach(9);                   // Vinger Koppelen aan pin 9
  deksel.attach(10);                  //Deksel koppelen aan pin 10
  vinger.write(145);                  //Start Positie Vinger
  deksel.write(0);                  //Start Positie deksel

  lcd.init();                         //Lcd initialiseren/starten
  lcd.backlight();
  Serial.begin(9600);
  Serial.print("My Sketch has started");
  Serial.println("setup");
  programCount =  0;



}


void loop() {
  val = digitalRead(toggleSwitch);
  Serial.println("Toggleswitch =");
  Serial.println(val);
  Serial.println(" ");
  Serial.println("Loop");
  delay(1000);
  Serial.println(" ");
  Serial.println("Current program");
  Serial.println(programCount);

  switch (programCount)


  {


    case 0:

      while (programCount = 0) {

        Serial.println("Case 0 Start");
        if (val == 1) {

          Serial.println("Funct 0");
          Serial.println("closeSim");
          lcd.setCursor(2, 0);                                                      // Zet Cursor op de derde kolom eerste rij.
          lcd.print(" Hi i'm Chucky!");                                             // Print "Til de doos op!"
          lcd.setCursor(2, 1);                                                      //Zet Cursor op de derde kolom tweede rij.
          lcd.print("Wanna play?");
          servo_ac();
          Serial.println(toggleSwitch);
          programCount = 1;
          Serial.println("Case 0 End");

          break;
        }
      }

    case 1:

      while (programCount = 1) {

        Serial.println("Case 1 Start");
        Serial.println("ldrStatus = ");
        Serial.println(ldr);
        delay(1000);

        if (ldr >= 15) {
          for (pos = 0; pos <= 50; pos += 2) { // goes from 0 degrees to 180 degrees in steps of 1 degree
            deksel.write(pos);              // tell servo to go to position in variable 'pos'
            delay(15);                       // waits 15ms for the servo to reach the position

            delay(1000);
            if (val == 1) {
              Serial.println("Case 1");
              Serial.println("Lichtmetinguitvoeren");
              lcd.setCursor(2, 0);                                                      // Zet Cursor op de derde kolom eerste rij.
              lcd.print("Don't Touch me!");                                             // Print "Til de doos op!"
              lcd.setCursor(2, 1);                                                      //Zet Cursor op de derde kolom tweede rij.
              lcd.print("STOP!");
              //deksel omhoog

              if (ldr >= 15) {
                servo_ac();

                programCount = 2;
              }
            }
          }
          Serial.println("Case 1 End");
          break;

        }
      }



    case 2:

      while (programCount = 2) {
        Serial.println("Case 2 Start");
        delay(100);
        if (val == 1 && programCount == 2) {
          delay(1000);
          Serial.println("Case 2");
          lcd.setCursor(2, 0);                                                      // Zet Cursor op de derde kolom eerste rij.
          lcd.print("Lift me up!");                                             // Print "Til de doos op!"
          lcd.setCursor(2, 1);                                                      //Zet Cursor op de derde kolom tweede rij.
          lcd.print("Now!");                                                         // Print "NU!"
          Serial.println("MSG 2 Printed");
          if (microSwitch == 1) {                                                  //microswitch uitlezen op High signaal
            Serial.println("microSwitch == 1");
            servo_ac();                                                        //verwijzing naar Servo deelprogramma
            programCount = (3);
          }
          Serial.println("Case 2 End");
          break;
        }
      }

    case 3:

      while (programCount = 3) {
        Serial.println("Case 3 Start");
        if (val == 1) {
          delay(1000);
          Serial.println("Case 3");
          lcd.setCursor(2, 0);                                                      // Zet Cursor op de derde kolom eerste rij.
          lcd.print("Press the red");                                               // Print "Press the red"
          lcd.setCursor(2, 1);                                                      //Zet Cursor op de derde kolom tweede rij.
          lcd.print("Buttons NOW!!");                                               // Print "Buttons NOW!!"
          Serial.println("MSG 3 Printed");
          delay(1000);
          if (vingerBev == 1) {                                                    //vingerbeveiliging uitlezen op High signaal
            Serial.println("Vingerbev = HIGH");
            servo_ac();                                                             //verwijzing naar Servo deelprogramma
            programCount = 4;
          }
          Serial.println("Case 3 End");
          break;
        }
      }

    case 4:

      while (programCount = 4) {
        Serial.println("Case 4 Start");
        if (val == 1) {
          Serial.println("Case 4");
          lcd.setCursor(2, 0);                                                      // Zet Cursor op de derde kolom eerste rij.
          lcd.print("Shake The boxx");                                              // Print "Shake The boxx"
          lcd.setCursor(2, 1);                                                      //Zet Cursor op de derde kolom tweede rij.
          lcd.print("Shake it NOW!!");                                              // Print "Shake it NOW!!"
          Serial.println("MSG 4 Printed");


          delay(1000);
          if (digitalRead(vibrSensor) == 1) {                                                //vibratiesensor uitlezen op signaal waarde
            Serial.println("vibrSensor = HIGH");

            servo_ac();                                                             //verwijzing naar Servo deelprogramma
            programCount = 5;
          }

          Serial.println("Case 4 End");
          break;
        }
      }


    case 5:

      while (programCount = 5) {
        Serial.println("Case 5 Start");
        if (programCount = 5) {
          if (digitalRead(toggleSwitch) == 1) {
            Serial.println("Case 5");
            lcd.setCursor(2, 0);                                                       // Zet Cursor op de derde kolom eerste rij.
            lcd.print("I give up!");                                                   // Print "I give up!"
            lcd.setCursor(2, 1);                                                       //Zet Cursor op de derde kolom tweede rij.
            lcd.print("GAME OVER");                                                    // Print "GAME OVER"
            servo_ac();
            programCount = 0;
          }
          Serial.println("Case 5 End");
          break;
        }

      default:
        Serial.println("default");
        digitalWrite(6, HIGH);
        delay(1000);
        digitalWrite(6, LOW);



      }
  }
}



void servo_ac()                                                               //Standaard programma voor herhaalde servo bewegingen.
{
  Serial.println("ServoOnOff");
  for (pos = 0; pos <= 50; pos += 1) { // goes from 0 degrees to 180 degrees in steps of 1 degree
    deksel.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }

  for (pos = 145; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    vinger.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 0; pos <= 145; pos += 1) { // goes from 0 degrees to 180 degrees in steps of 1 degree
    vinger.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }

  for (pos = 50; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    deksel.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
    Serial.println("Servo Finished");
    break;

  }

}

Because of its layout some of your code has had code tags added to it by the forum software

Please follow the advice given in the link below and post **all **of it in code tags

Thanks, I've done that now.

Stop assuming - start analysing in detail.

You should add debug-output to your code that prints all and everything that might be of interest to the serial monitor

print the values of variables and
when an if-condition becomes true print to the serial monitor

seeing what values your variables have wil guide you to the places where your logic needs correction.

best regards Stefan

developers can often find the problem with their code by describing it in detail. explain what each part of the code is intended to do and what it actually does

while describing it out loud can work, writing a description is even better.

Just saying "useless box" and "work every case separately" doesn't tell us much. Describe IN DETAIL what should happen and when. Since your switch works on programCount and values for that are only set in a previous case I can't see how they can be separate, particularly since you set a value like 3 then do a break which takes you out of the switch, round to the top of loop where you print programCount 3 then instantly set it back to 0 before calling the switch again.

You have a lot of Serial.prints in your code. What do they tell you is happening?

You have this in multiple locations, remove the ';' at the end as this ends the 'if'

Sorry for my unclear description.

What the useless box is meant to do:

  • Begin with case 0
  • Wait for the toggle switch to go to 1
  • The toggle switch is switched to 1
  • The LCD needs to display a message
  • Activate a void (servo_ac) to switch the toggle switch back to 0 using the 4 movements in the servo_ac void.
  • The program count needs to go to 1 so that the program count is now 1. this is meant to get to case 1

  • Case 1 first waits for the LDR to reach a certain value and it actuates one servo to open a lid.
  • After it opens the lid the program needs to wait for the LDR value to go back down again.
  • Then the lid needs to close.
  • Then the program needs to wait for the toggle switch to switch to 1.
  • Then it activates servo_ac again to switch it back to 0.
  • Program count to 2 so it can go to case 2.

  • Case 2 needs to wait for the toggle switch to go to 1
  • the lcd needs to display a message saying 'lift me up , now'
  • wait for the microswitch to go to 1
  • microswitch switch to 1
  • servo_ac
  • program count to 3

  • open case 3
  • wait for the toggle switch to go to 1
  • toggle switch to 1
  • the LCD needs to display a message saying 'press the red buttons, now'
  • wait for the 'vingerBev' to go to 1
  • vingerbev to 1
  • servo_ac
  • program count to 4

  • open case 4
  • wait for the toggle switch to go to 1
  • toggle switch to 1
  • the LCD needs to display a message saying 'shake the box, now'
  • wait for the 'vibrSensor' to go to 1
  • vibrSensor to 1
  • servo_ac
  • program count to 5

  • open case 5
  • wait for the toggle switch to go to 1
  • toggle switch to 1
  • the LCD needs to display a message saying 'i give up, game over'
  • servo_ac
  • program count reset to 0 (to loop the whole procces.

thanks for the description (not too bad)

is "messing up" a technical term?

how about a description of what it does?

Messing up isn't a technical term indeed.
What i meant by this is shown in the screenshot. it immediatly goes to case 1 and when this case is finnished it walks through all the cases without waiting for the if statement etc.

I updated the code show on top.

@borisvd Please do not post pictures of Serial monitor output. They are generally a waste of time

Using the mosue, select the text in the Serial monitor that you want to post then use Ctrl+C to copy it to the clipboard and paste it here in code tags

you can also copy and paste output from the serial monitor using </> instead of an image

more or less your code waits for val == 1 to advance to the next state, your programCount

there are a couple issues:

presumably you have a button switch connected to the pin, vingerBev. it is conventional that the switch is connected between the pin and ground and pulls the pin LOW.

for this to work reliably, something needs to pull the pin HIGH by default, and to do this, it can be configure INPUT_PULLUP. when done the way, pressing the button makes the pin LOW.

the code is checking for it to be HIGH (1). so if the pin is HIGH, the code races thru each case.

if the pin were configure INPUT_PULLUP and the logic reversed to check for LOW (0), there would still be a problem because the code can execute faster than your finger can press and release a button.

so logic is need to recognize a change in state of the pin and that when it does change it goes LOW. this is a "press" event and won't re-occur until after another change in state

you should also enable enable compiler warnings to see other errors in your code (File->Preferences Compiler Warnings set to "More"

Hi,
We need know your hardware.
Can you please post a circuit diagram?
Draw a pen(cil) and paper circuit and post an image please.

Tom... :grinning: :+1: :coffee: :australia:

image

All the switches have a resistor soldered on. And when i use the same setup with a seperate program led on /off when switch(x) = 1 command all the switches work.

Thank all of you for the helpfull comments, unfortunatly i don't know how to do most of the suggested stuff. maybe someone can write an example for this code or something.

Hi,
I'm sorry that does not show the actual pin connections and pin and component labels.

How are your switches connected, do they switch input to 5V or gnd?
Do you have pullup or pulldown resistors with them?

Please show all your wiring including power supplies.

I know it may be a labor to do, but this will help to troubleshoot your code.

Tom.... :grinning: :+1: :coffee: :australia:

The = here (and in other places) should be ==

while (programCount = 1)

a resistor has 2 ends, so onto what 2 things is it soldered to. (presumably not between the switch and pin)

DON'T do this, EVER!!!!!!!!!!

You are just making me look like an idiot, asking you to fix stuff htat no longer appears broken.

When you make changes, reply with the amended code. NEVER edit code you have already posted!

2 Likes