Whats is wrong with my code / how can I make it work?

Good day friends, I am a bit op a coding noob but with some research I put this code together. I cant seem to find out why it doesn't work though. Could someone help me? I would be very grateful :slight_smile:

//buttonbounce introduction
#include <Bounce2.h>
#define BUTTON_PIN 2
Bounce b = Bounce(); // Instantiate a Bounce object
int state = 0;

//accelstepper introduction
#include <AccelStepper.h>
    // Motor pin definitions:
#define motorPin1  8      // IN1 on the ULN2003 driver
#define motorPin2  9      // IN2 on the ULN2003 driver
#define motorPin3  10     // IN3 on the ULN2003 driver
#define motorPin4  11     // IN4 on the ULN2003 driver
    // Define the AccelStepper interface type; 4 wire motor in half step mode:
#define MotorInterfaceType 8
    // Initialize with pin sequence IN1-IN3-IN2-IN4 for using the AccelStepper library with 28BYJ-48 stepper motor:
AccelStepper stepper = AccelStepper(MotorInterfaceType, motorPin1, motorPin3, motorPin2, motorPin4);

//introduce light
#include <Adafruit_NeoPixel.h>
#define LED_PIN 3   // input pin Neopixel is attached to
#define LED_COUNT      15 // number of neopixels in strip
Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);uint32_t white = strip.Color(255, 255, 255);
uint32_t bright = strip.Color(255, 255, 255);
uint32_t red = strip.Color(255, 0, 0);
uint32_t green = strip.Color(0, 255, 0);
uint32_t blue = strip.Color(0, 0, 255);

//introduce light sensor
const int LIGHT_SENSOR_PIN = A0; // pin connected to light sensor's
int sensorValue;
const int inputPin= 4;

//introduce motionsensor
const int motionSensorPin = 3;

void setup() {
  // buttonbounce
  b.attach(BUTTON_PIN,INPUT_PULLUP); // Attach the debouncer to a pin with INPUT_PULLUP mode
  b.interval(25); // Use a debounce interval of 25 milliseconds

  //stepperspeed
  stepper.setMaxSpeed(1250);

  //light strip
  strip.begin();
  strip.show();

  //light sensor
  Serial.begin(9600); //initialize communication sensor

  pinMode(LED_PIN, OUTPUT); 
  pinMode(LIGHT_SENSOR_PIN, INPUT);
}

void loop() {
  //motion sensor pin reading
  int motionValue= digitalRead(motionSensorPin);


  //light sensor reading
  int value= digitalRead(inputPin); //is this logical??
  sensorValue = analogRead(LIGHT_SENSOR_PIN); 
  Serial.print("Sensor reading: ");
  Serial.print(sensorValue);

  
  // buttonbounce
  b.update(); // Update the Bounce instance
   if(b.fell()){
   state = (state + 1) % 4;
                    }
switch(state){
   case 0:
     // stepper
     stepper.stop();
     //led strip
     strip.setBrightness(0);
     strip.show();
     break;
    
   case 1:
     // code for state 1 here
    {
    stepper.setSpeed(1200);
    stepper.runSpeed();

                if(sensorValue < 200)
                {
                    strip.fill(bright);
                    strip.setBrightness(255);
                    strip.show();
                    break;
                else
                    strip.setBrightness(100);
                    strip.show();
                    break;
                }
    
    }
     break;

   case 2:
     // code for state 2 here
     {
      //stepper
     stepper.setSpeed(250);
     stepper.runSpeed();
     //led light
                if(sensorValue < 200)
                {
                    strip.fill(red);
                    strip.setBrightness(255);
                    strip.show();
                    break;

                }   
                else{
                    strip.setBrightness(100);
                    strip.show();
                    break;
                }
                }
     }
     
     
   case 3:
     // code for state 3 here
     {
   if (motionValue == HIGH)
   {
      
     stepper.setSpeed(750);
     stepper.runSpeed();

                if(sensorValue < 200)
                {
                    strip.fill(green);
                    strip.setBrightness(255);
                    strip.show();
                }                
                else
                    strip.setBrightness(100);
                    strip.show();
                }
    else
     // stepper
     stepper.stop();
     //led strip
     strip.setBrightness(0);
     strip.show();          
   }           
     }
     break;
 }

 
}

What does that mean?

What is the code supposed to do?

What does the code do?

1 Like

What should it do and what does it do ?

Use Auto format to help you find the code formatting errors.

Each one of these { is supposed to have a } and these {} do matter where they are. After you fix the {} issues post your code in a new post so the other errors can be found.

Whats the code supposed to do:
my code if I break it down is supposed to do a few stuff and it's supposed to work with a few modes:

a button gets pressed which changed the mode
mode 0: turn everything off and stop everything
mode 1:
motor turns in speed 1200,
led strip is burning bright if ldr picks up little light from outside.
led strip burns lower if ldr picks up high light

mode 2:
motor turns in speed 250,
led strip does the same as mode 1

mode 3:
if motionsensor detects motion then for 5 minutes
motor turns in speed 750,
led strip does the same as mode 1

if motionsensor detects no motion it does nothing

What does it do right now
Individually I tested the motor, the lights and the modes working with correct speeds and brightnesses. What happened now though is while combining all codes it's giving me code formatting errors and I am also unsure if the sensor is communicating correctly. For example I am unsure in my void loop if it's logical to have

 //light sensor reading
  int value= digitalRead(inputPin); //is this logical??

Also here's the formatting errors I am getting, I am such a noob that even though it literally says add a { before this when I start adding the { he starts saying theres something else wrong and then something else.

Codev5:87:17: error: expected '}' before 'else'
                 else
                 ^~~~
Codev5:93:6: error: break statement not within loop or switch
      break;
      ^~~~~
Codev5:95:4: error: case label '2' not within a switch statement
    case 2:
    ^~~~
D:\Gebruiker\Jottacloud\Sinan folder\SCHOOL\IPO HBO\Jaar 3\KVA65\Codev5\Codev5.ino: At global scope:
Codev5:114:6: error: expected unqualified-id before 'break'
      break;
      ^~~~~
Codev5:116:4: error: expected unqualified-id before 'case'
    case 3:
    ^~~~
Codev5:142:6: error: expected declaration before '}' token
      }
      ^
exit status 1
expected '}' before 'else'

Hey UKHeliBob, thankyou for your reply, I sent a reply to Idahowalker with all missing information, I'd be very grateful if you could give me a helping hand

Look at case two where you got the if else brackets squared away. Apply what you see to case one.

The IDE can give you a helping hand. Auto format the code using ctrl-T or the menu option for it, and the misplaced brackets will be visible.

Also, you have superfluous brackets in every case block. Remove them, they just add dross. Look at some switch-case examples to see how it's done.

Your state transition logic is dubious... I can see that you set the servo speed repeatedly in some of the cases. Initializing a servo condition should be performed in a previous state, prior to transitioning to a repeating state. If you don't have a previous state, you have to create one.

That is because, at the moment, you are executing the selected case every time through the loop() function execution.

For example, you have two states that just run the servo at different speeds. But setting the servo speed is supposed to be done only once. So you should have only one state, RUNNING, and the speed setting should be done either in another state, SETTING_SERVO_SPEED_TO_250, or in some code outside of the state machine entirely.

If you have a state SETTING_SERVO_SPEED_TO_250, it can precede RUNNING by coding as the last line,

state = RUNNING;

It would be better if you posted, "all missing information" here and kept us all in the loop, it sounds like the members here are no closer to all the information needed to help with your problem.

Tom.... :smiley: :+1: :coffee: :australia:

That was post #5 I think - basically a number of syntax errors due to missing/misplaced braces.

@Svop
Your if-else and {-} imbalances are removed. One thing could not be resolved and it is the stepper.stop() method. Check the .cpp file of the Library and get the correct method name.

//buttonbounce introduction
#include <Bounce2.h>
#define BUTTON_PIN 2
Bounce b = Bounce(); // Instantiate a Bounce object
int state = 0;

#include <AccelStepper.h>
// Motor pin definitions:
#define motorPin1  8      // IN1 on the ULN2003 driver
#define motorPin2  9      // IN2 on the ULN2003 driver
#define motorPin3  10     // IN3 on the ULN2003 driver
#define motorPin4  11     // IN4 on the ULN2003 driver
// Define the AccelStepper interface type; 4 wire motor in half step mode:
#define MotorInterfaceType 8
// Initialize with pin sequence IN1-IN3-IN2-IN4 for using the AccelStepper library with 28BYJ-48 stepper motor:
AccelStepper stepper = AccelStepper(MotorInterfaceType, motorPin1, motorPin3, motorPin2, motorPin4);

//introduce light
#include <Adafruit_NeoPixel.h>
#define LED_PIN 3   // input pin Neopixel is attached to
#define LED_COUNT      15 // number of neopixels in strip
Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800); uint32_t white = strip.Color(255, 255, 255);
uint32_t bright = strip.Color(255, 255, 255);
uint32_t red = strip.Color(255, 0, 0);
uint32_t green = strip.Color(0, 255, 0);
uint32_t blue = strip.Color(0, 0, 255);

//introduce light sensor
const int LIGHT_SENSOR_PIN = A0; // pin connected to light sensor's
int sensorValue;
const int inputPin = 4;

//introduce motionsensor
const int motionSensorPin = 3;

void setup()
{
  // buttonbounce
  b.attach(BUTTON_PIN, INPUT_PULLUP); // Attach the debouncer to a pin with INPUT_PULLUP mode
  b.interval(25); // Use a debounce interval of 25 milliseconds

  //stepperspeed
  stepper.setMaxSpeed(1250);

  //light strip
  strip.begin();
  strip.show();

  //light sensor
  Serial.begin(9600); //initialize communication sensor

  pinMode(LED_PIN, OUTPUT);
  pinMode(LIGHT_SENSOR_PIN, INPUT);
}

void loop()
{
  //motion sensor pin reading
  int motionValue = digitalRead(motionSensorPin);
  int value = digitalRead(inputPin); //is this logical??
  sensorValue = analogRead(LIGHT_SENSOR_PIN);
  Serial.print("Sensor reading: ");
  Serial.print(sensorValue);

  b.update(); // Update the Bounce instance
  if (b.fell())
  {
    state = (state + 1) % 4;
  }

  switch (state)
  {
    case 0:
      // stepper
      stepper.stop();
      //led strip
      strip.setBrightness(0);
      strip.show();
      break;
    case 1:
      // code for state 1 here
      {
        stepper.setSpeed(1200);
        stepper.runSpeed();

        if (sensorValue < 200)
        {
          strip.fill(bright);
          strip.setBrightness(255);
          strip.show();
          break;
        }
        else
        {
          strip.setBrightness(100);
          strip.show();
          break;
        }
      }
    case 2:
      {
        //stepper
        stepper.setSpeed(250);
        stepper.runSpeed();
        //led light
        if (sensorValue < 200)
        {
          strip.fill(red);
          strip.setBrightness(255);
          strip.show();
          break;
        }
        else
        {
          strip.setBrightness(100);
          strip.show();
          break;
        }
      }
    case 3:
      {
        if (motionValue == HIGH)
        {
          stepper.setSpeed(750);
          stepper.runSpeed();
          if (sensorValue < 200)
          {
            strip.fill(green);
            strip.setBrightness(255);
            strip.show();
          }
          else
          {
            strip.setBrightness(100);
            strip.show();
          }
        }
        break;
      }
  }
}

Fait quelque chose de simple : utilise des fonctions pour chaque mode, qui se répète jusqu'à que le mode change. Comme déjà dit, simplifie aussi ton code en faisant ctrl-t et bonne chance !

okay so i tried both ctrl+t and then following the instructions untill there were no more errors and also your code. Both seem to not give me errors so thanks everyone in this thread for helping.

Now I still do not know if my code actually works. I tried testing it on a tinkercad model I made with all the correct parts in it but it doesn't have bounce2.h and accelstepper.h library in it. So i will have to try tomorrow with the actual parts if the sensors communicate properly and my code actually works.

No! There is a compilation error regarding stepper.stop() method.

exit status 1
'class AccelStepper' has no member named 'stop'; did you mean 'step'?

What does the library documentation say?

huh strange, I do not seem to get that error nor have I gotten it in earlier testing. If I look into accelsteppers example library we have this code that uses stepper.stop(); in the same way:

// Quickstop.pde
// -*- mode: C++ -*-
//
// Check stop handling.
// Calls stop() while the stepper is travelling at full speed, causing
// the stepper to stop as quickly as possible, within the constraints of the
// current acceleration.
//
// Copyright (C) 2012 Mike McCauley
// $Id:  $

#include <AccelStepper.h>

// Define a stepper and the pins it will use
AccelStepper stepper; // Defaults to AccelStepper::FULL4WIRE (4 pins) on 2, 3, 4, 5

void setup()
{  
  stepper.setMaxSpeed(150);
  stepper.setAcceleration(100);
}

void loop()
{    
  stepper.moveTo(500);
  while (stepper.currentPosition() != 300) // Full speed up to 300
    stepper.run();
  stepper.stop(); // Stop as fast as possible: sets new target
  stepper.runToPosition(); 
  // Now stopped after quickstop

  // Now go backwards
  stepper.moveTo(-500);
  while (stepper.currentPosition() != 0) // Full speed basck to 0
    stepper.run();
  stepper.stop(); // Stop as fast as possible: sets new target
  stepper.runToPosition(); 
  // Now stopped after quickstop

It's in the documentation too. Likely a library version issue - you can ignore it.

In my .cpp file, there is no stop() method; instead, there are few step() methods.
AccelStepper-master.zip (62.0 KB)

Once you get the code to compile and upload, You may need to post a diagram of your wiring and power supplies.
Arduino can’t ’power’ a stepper motor directly, so there might be an issue there, along with the choice of battery etc.

its probably a new update of accelstepper library then