text:
exit status 1 - expected primary-expression before '(' token
When I try to compile the following sketch, the compiler returns the error "exit status 1 - expected primary-expression before '(' token", and highlights "midi();" in my code.
Here is my sketch:
#include <Stepper.h>
#include <Servo.h>
#include <MIDI.h>

/*ARDUINO MOTOR SHIELD
 * The pin breakdown is as follows:
 * Function          Channel A   Channel B
 * Direction         Digital 12  Digital 13
 * Speed (PWM)       Digital 3   Digital 11
 * Brake             Digital 9   Digital 8
 * Current Sensing   Analog 0  Analog 1
 */

const int stepsPerRevolution = 200;  // 1.8 deg. step angle(200 steps/360 deg. rev)
const int dirChA = 12;     // assigning name "dirChA" to pin 12
const int dirChB = 13;     // assigning name "dirChB" to pin 13
const int pwmChA = 3;      // assigning name "pwmChA" to pin 3
const int pwmChB = 11;     // assigning name "pwmChB" to pin 11
const int brkChA = 9;      // assigning name "brkChA" to pin 9
const int brkChB = 8;      // assigning name "brkChB" to pin 8

const int srvoMtr = 10;    // assigning name "srvoMtr" to pin 10

const int pButton1 = 4;    // assigning name "pButton1" to pin 4
const int pButton2 = 5;    // assigning name "pButton2" to pin 5
const int pButton3 = 6;    // assigning name "pButton3" to pin 6
const int pButton4 = 7;    // assigning name "pButton4" to pin 7

const int ledLight = 2;    // assigning name "ledLight" to pin 2

const int tonePin = 1;     // assigning name "tonePin" to pin 1

Stepper myStepper(stepsPerRevolution, dirChA, dirChB);  // initialize the stepper library on pins 12 & 13
Servo myServo;  // initialize the servo library to logical name myServo

int pButton1State = 0;     // variable for reading the pButton1 state as LOW or HIGH
int pButton2State = 0;     // variable for reading the pButton2 state as LOW or HIGH
int pButton3State = 0;     // variable for reading the pButton3 state as LOW or HIGH
int pButton4State = 0;   // variable for reading the pButton4 state as LOW or HIGH

int pButtonFlag = 0;     // variable for when button 1 has been pressed and released

int myServoPos = 0;    // variable for when servo has reached it's position
int myServoFlag = 0;   // variable for servo when any of the 4 pButton are pressed

void setup() {
//Serial.begin(31250);   // initialize the serial port for messaging & troubleshooting
 //Serial.println("Running UNO Setup");

 // 1 Stepper Motor
// Serial.println("\nStepper Motor");
 pinMode(dirChA, OUTPUT);   // initialize pin 12 as an OUTPUT
 digitalWrite(dirChA, LOW);   //initialize pin 12 as LOW (pin voltage is 0 V)
// Serial.println("Channel A Dir - PIN 12 - set as Output & Low");
 pinMode(dirChB, OUTPUT);   // initialize pin 13 as an OUTPUT
 digitalWrite(dirChB, LOW);   //intialize pin 13 as LOW (pin voltage is 0 V)
// Serial.println("Channel B Dir - PIN 13 - set as Output & Low");
 pinMode(pwmChA, OUTPUT);   // initialize pin 3 as an OUTPUT
 digitalWrite(pwmChA, LOW);   //intialize pin 3 as LOW (pin voltage is 0 V)
// Serial.println("Channel A PWM - PIN 3 - set as Output & Low");
 pinMode(pwmChB, OUTPUT);   // initialize pin 11 as an OUTPUT
 digitalWrite(pwmChB, LOW);   //intialize pin 11 as LOW (pin voltage is 0 V)
// Serial.println("Channel B PWM - PIN 11 - set as Output & Low");
 pinMode(brkChA, OUTPUT);   // initialize pin 9 as an OUTPUT
 digitalWrite(brkChA, LOW);   //intialize pin 9 as LOW (pin voltage is 0 V)
// Serial.println("Channel A Brake - PIN 9 - set as Output & Low");
 pinMode(brkChB, OUTPUT);   // initialize pin 8 as an OUTPUT
 digitalWrite(brkChB, LOW);   //intialize pin 8 as LOW (pin voltage is 0 V)
// Serial.println("Channel B Brake - PIN 8 - set as Output & Low");

 myStepper.setSpeed(60);   // set the speed of the stepper motor to 60 RPM
// Serial.println("\nSet Stepper Speed to 60 RPM");

 // 4 Push Buttons
// Serial.println("\n4 Push Buttons");
 pinMode(pButton1, INPUT);   // initialize pin 4 as an INPUT
 digitalWrite(pButton1, LOW);   // initialize pin 4 as LOW (pin voltage less than 1.5V)
// Serial.println("Push Button 1 - PIN 4 - set a Input & Low");
 pinMode(pButton2, INPUT);   // initialize pin 5 as an INPUT
 digitalWrite(pButton2, LOW);   // initialize pin 5 as LOW (pin voltage less than 1.5V)
// Serial.println("Push Button 2 - PIN 5 - set a Input & Low");
 pinMode(pButton3, INPUT);   // initialize pin 6 as an INPUT
 digitalWrite(pButton3, LOW);   // initialize pin 6 as LOW (pin voltage less than 1.5V)
// Serial.println("Push Button 3 - PIN 6 - set a Input & Low");
 pinMode(pButton4, INPUT);   // initialize pin 7 as an INPUT
 digitalWrite(pButton4, LOW);   // initialize pin 7 as LOW (pin voltage less than 1.5V)
// Serial.println("Push Button 4 - PIN 7 - set a Input & Low");

 // 1 Led Light
// Serial.println("\nLED Light");
 pinMode(ledLight, OUTPUT);   // initialize pin 2 as an OUTPUT
 digitalWrite(ledLight, LOW);   // initialize pin 2 as LOW (pin voltage is 0 V)
// Serial.println("LED Light - PIN 2 - set to Output & Low");

 // 1 Piezo Speaker
midi();
// Serial.println("Piezo Speaker Inialized");
}

void loop() {
  //Read button state (pressed or not pressed?)
//  Serial.println("\nReading button 1 thru 4 states - high or low");
  pButton1State = digitalRead(pButton1);   // read the state of pButton1 as LOW or HIGH
  pButton2State = digitalRead(pButton2);   // read the state of pButton2 as LOW or HIGH
  pButton3State = digitalRead(pButton3);   // read the state of pButton3 as LOW or HIGH
  pButton4State = digitalRead(pButton4);   // read the state of pButton4 as LOW or HIGH

  // check if the pushbutton is pressed. If it is, the pbuttonState is HIGH:
  if (pButton1State == HIGH) {
 //    Serial.println("\nPush Button 1 Pressed");
     pButtonFlag=1;  // change pButton1Flag variable
 //    Serial.println("Button 1 flag = 1");
  }
     if (pButtonFlag == 1){
 //       Serial.println("Stepper Start - Forward 40 steps");
        digitalWrite(pwmChA, HIGH);   // enable power to stepper
        digitalWrite(pwmChB, HIGH);   // enable power to stepper
        myStepper.step(40);          // step forward 40 steps to position 1
        digitalWrite(pwmChA, LOW);    // disable power to stepper
        digitalWrite(pwmChB, LOW);    //disable power to stepper
 //       Serial.println("Stepper Stop");
        delay(2000);

        myServoFlag=1;             // change ServoFlag variable to dispense chocolate
 //       Serial.println("\nServo Flag = 1 - Dispense Chocolate");

        if (myServoFlag == 1){
 //          Serial.println("Servo Start");
           myServo.attach(srvoMtr);   // attaches the servo library to pin 10
 //          Serial.println("Attach Servo Library to PIN 10");

           for (myServoPos = 0; myServoPos <= 100; myServoPos += 1) { // goes from 0 degrees to 100 degrees in steps of 5 degrees
               myServo.write(myServoPos);    // tell servo to go to position in variable 'myServoPos'
               delay(15);                    // waits 3 sec for the servo to reach the position
           }
           myServo.detach();   // detaches the servo library from pin 10
 //          Serial.println("\nDetach Servo Library to PIN 10");
 //          Serial.println("Servo Stop");
 //          Serial.println("Hold position OPEN for 3 sec");
           delay(2000);

           myServo.attach(srvoMtr);   // attaches the servo library to pin 10
 //          Serial.println("Attach Servo Library to PIN 10");

           for (myServoPos = 100; myServoPos >= 0; myServoPos -= 1) { // goes from 100 degrees to 0 degrees in steps of 1 degree
               myServo.write(myServoPos);    // tell servo to go to position in variable 'pos
               delay(15);
           }
           myServo.detach();   // detaches the servo library from pin 10
 //          Serial.println("\nDetach Servo Library to PIN 10");
 //          Serial.println("Servo Stop - Awaiting next selection");
        }
        myServoFlag=0;                // changes myServoFlag value back to zero (0)
 //       Serial.println("Servo Flag = 0");

        digitalWrite(ledLight, HIGH);   // turn on light to indicate chocolate is dispensed
 //       Serial.println("\nLed Light ON");
 //       Serial.println("\nPlay Tones");

        void midi() {
                 tone(tonePin, 233, 203.992851562);
                 delay(226.658723958);
                 delay(4.82252604167);
                 tone(tonePin, 184, 412.325976562);
                 delay(458.139973958);
                 delay(4.82252604167);
                 tone(tonePin, 184, 99.8262890625);
                 delay(110.918098958);
                 delay(4.82252604167);
                 tone(tonePin, 155, 99.8262890625);
                 delay(110.918098958);
                 delay(4.82252604167);
                 tone(tonePin, 184, 203.992851562);
                 delay(226.658723958);
                 delay(4.82252604167);
                 tone(tonePin, 184, 203.992851562);
                 delay(226.658723958);
                 delay(236.303776042);
                 tone(tonePin, 184, 99.8262890625);
                 delay(110.918098958);
                 delay(4.82252604167);
                 tone(tonePin, 155, 99.8262890625);
                 delay(110.918098958);
                 delay(4.82252604167);
                 tone(tonePin, 184, 203.992851562);
                 delay(226.658723958);
                 delay(4.82252604167);
                 tone(tonePin, 184, 203.992851562);
                 delay(226.658723958);
                 delay(236.303776042);
                 tone(tonePin, 184, 203.992851562);
                 delay(226.658723958);
                 delay(236.303776042);
                 tone(tonePin, 233, 555.555);
                 }

        delay(3000);

//        Serial.println("Stepper Start - Return to position zero");
        digitalWrite(pwmChA, HIGH);   // enable power to stepper
        digitalWrite(pwmChB, HIGH);   // enable power to stepper
        myStepper.step(-40);          // step backward 40 steps to position 0
        digitalWrite(pwmChA, LOW);    // disable power to stepper
        digitalWrite(pwmChB, LOW);    //disable power to stepper
//        Serial.println("Stepper Stop");

        digitalWrite(pButton1, LOW);   // initialize pin 4 as LOW (pin voltage less than 1.5V)
//        Serial.println("\nReset Button 1 - PIN 4 - Low");
        digitalWrite(ledLight, LOW);   //turns off light to indicate the sequence is completed
//        Serial.println("\nLed Light OFF");

        pButtonFlag=0;                // changes pButtonFlat value back to zero (0)
//        Serial.println("\Button 1 Flag = 0");
        delay(2000);
     }

  // position 2
  if (pButton2State == HIGH) {
//     Serial.println("\nPush Button 2 Pressed");
     pButtonFlag=1;  // change pButtonFlag variable
//     Serial.println("Button 2 flag = 1");
  }
     if (pButtonFlag == 1){
//        Serial.println("Stepper Start - Forward 80 steps");
        digitalWrite(pwmChA, HIGH);   // enable power to stepper
        digitalWrite(pwmChB, HIGH);   // enable power to stepper
        myStepper.step(80);          // step forward 80 steps to position 2
        digitalWrite(pwmChA, LOW);    // disable power to stepper
        digitalWrite(pwmChB, LOW);    //disable power to stepper
//        Serial.println("Stepper Stop");
        delay(2000);

        myServoFlag=1;    // change ServoFlag variable to dispense chocolate
//        Serial.println("\nServo Flag = 1 - Dispense Chocolate");

        if (myServoFlag == 1){
//           Serial.println("Servo Start");
           myServo.attach(srvoMtr);   // attaches the servo library to pin 10
//           Serial.println("Attach Servo Library to PIN 10");

           for (myServoPos = 0; myServoPos <= 100; myServoPos += 1) { // goes from 0 degrees to 100 degrees in steps of 5 degrees
               myServo.write(myServoPos);    // tell servo to go to position in variable 'myServoPos'
               delay(15);                    // waits 3 sec for the servo to reach the position
           }
           myServo.detach();   // detaches the servo library from pin 10
//           Serial.println("\nDetach Servo Library to PIN 10");
//           Serial.println("Servo Stop");
//           Serial.println("Hold position OPEN for 2 sec");
           delay(2000);

           myServo.attach(srvoMtr);   // attaches the servo library to pin 10
//           Serial.println("Attach Servo Library to PIN 10");

           for (myServoPos = 100; myServoPos >= 0; myServoPos -= 1) { // goes from 100 degrees to 0 degrees in steps of 1 degree
               myServo.write(myServoPos);    // tell servo to go to position in variable 'pos
               delay(15);
           }
           myServo.detach();   // detaches the servo library from pin 10
//           Serial.println("\nDetach Servo Library to PIN 10");
//           Serial.println("Servo Stop - Awaiting next selection");
        }
        myServoFlag=0;                // changes myServoFlag value back to zero (0)
//        Serial.println("Servo Flag = 0");

        digitalWrite(ledLight, HIGH);    // turn on light to indicate chocolate is dispensed
//        Serial.println("\nLed Light ON");
        delay(3000);

//        Serial.println("Stepper Start - Return to position zero");
        digitalWrite(pwmChA, HIGH);   // enable power to stepper
        digitalWrite(pwmChB, HIGH);   // enable power to stepper
        myStepper.step(-80);          // step backward 80 steps to position 0
        digitalWrite(pwmChA, LOW);    // disable power to stepper
        digitalWrite(pwmChB, LOW);    //disable power to stepper
//        Serial.println("Stepper Stop");

        digitalWrite(pButton2, LOW);   // initialize pin 5 as LOW (pin voltage less than 1.5V)
//        Serial.println("\nReset Button 2 - PIN 5 - Low");
        digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed
//        Serial.println("\nLed Light OFF");

        pButtonFlag=0;   // changes pButton2Flag value back to zero (0)
//        Serial.println("\Button 2 Flag = 0");
        delay(2000);
    }

    // position 3
    if (pButton3State == HIGH) {
//       Serial.println("\nPush Button 3 Pressed");
       pButtonFlag=1;   // change pButtonFlag variable
//       Serial.println("Button 3 flag = 1");
    }
       if (pButtonFlag == 1){
//          Serial.println("Stepper Start - Forward 120 steps");
          digitalWrite(pwmChA, HIGH);   // enable power to stepper
          digitalWrite(pwmChB, HIGH);   // enable power to stepper
          myStepper.step(120);          // step forward 120 steps to position 3
          digitalWrite(pwmChA, LOW);    // disable power to stepper
          digitalWrite(pwmChB, LOW);    //disable power to stepper
//          Serial.println("Stepper Stop");
          delay(2000);

          myServoFlag=1;   // change ServoFlag variable to dispense chocolate
          Serial.println("\nServo Flag = 1 - Dispense Chocolate");

          if (myServoFlag == 1){
//            Serial.println("Servo Start");
             myServo.attach(srvoMtr);   // attaches the servo library to pin 10
//             Serial.println("Attach Servo Library to PIN 10");

             for (myServoPos = 0; myServoPos <= 100; myServoPos += 1) { // goes from 0 degrees to 100 degrees in steps of 5 degrees
                 myServo.write(myServoPos);    // tell servo to go to position in variable 'myServoPos'
                 delay(15);                    // waits 3 sec for the servo to reach the position
             }
             myServo.detach();   // detaches the servo library from pin 10
//             Serial.println("\nDetach Servo Library to PIN 10");
//             Serial.println("Servo Stop");
//             Serial.println("Hold position OPEN for 2 sec");
             delay(2000);

             myServo.attach(srvoMtr);   // attaches the servo library to pin 10
//             Serial.println("Attach Servo Library to PIN 10");

             for (myServoPos = 100; myServoPos >= 0; myServoPos -= 1) { // goes from 100 degrees to 0 degrees in steps of 1 degree
               myServo.write(myServoPos);    // tell servo to go to position in variable 'pos
               delay(15);
             }
             myServo.detach();   // detaches the servo library from pin 10
//             Serial.println("\nDetach Servo Library to PIN 10");
//             Serial.println("Servo Stop - Awaiting next selection");
          }
          myServoFlag=0;                // changes myServoFlag value back to zero (0)
//          Serial.println("Servo Flag = 0");

          digitalWrite(ledLight, HIGH);   // turn on light to indicate chocolate is dispensed
//          Serial.println("\nLed Light ON");
          delay(3000);

//          Serial.println("Stepper Start - Return to position zero");
          digitalWrite(pwmChA, HIGH);   // enable power to stepper
          digitalWrite(pwmChB, HIGH);   // enable power to stepper
          myStepper.step(-120);         // step backward 120 steps to position 0
          digitalWrite(pwmChA, LOW);    // disable power to stepper
          digitalWrite(pwmChB, LOW);    // disable power to stepper
//          Serial.println("Stepper Stop");

          digitalWrite(pButton3, LOW);   // initialize pin 6 as LOW (pin voltage less than 1.5V)
//          Serial.println("\nReset Button 3 - PIN 6 - Low");
          digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed
//          Serial.println("\nLed Light OFF");

          pButtonFlag=0;   // changes pButton3Flag value back to zero (0)
//          Serial.println("\Button 3 Flag = 0");
          delay(2000);
     }
    // position 4
    if (pButton4State == HIGH) {
//       Serial.println("\nPush Button 4 Pressed");
       pButtonFlag=1;   // change pButtonFlag variable
//       Serial.println("Button 3 flag = 1");
    }
       if (pButtonFlag == 1){
//          Serial.println("Stepper Start - Forward 160 steps");
          digitalWrite(pwmChA, HIGH);   // enable power to stepper
          digitalWrite(pwmChB, HIGH);   // enable power to stepper
          myStepper.step(160);          // step forward 160 steps to position 3
          digitalWrite(pwmChA, LOW);    // disable power to stepper
          digitalWrite(pwmChB, LOW);    //disable power to stepper
//          Serial.println("Stepper Stop");
          delay(2000);

          myServoFlag=1;   // change ServoFlag variable to dispense chocolate
//          Serial.println("\nServo Flag = 1 - Dispense Chocolate");

          if (myServoFlag == 1){
//             Serial.println("Servo Start");
             myServo.attach(srvoMtr);   // attaches the servo library to pin 10
//             Serial.println("Attach Servo Library to PIN 10");

             for (myServoPos = 0; myServoPos <= 100; myServoPos += 1) { // goes from 0 degrees to 100 degrees in steps of 5 degrees
                 myServo.write(myServoPos);    // tell servo to go to position in variable 'myServoPos'
                 delay(15);                    // waits 3 sec for the servo to reach the position
             }
             myServo.detach();   // detaches the servo library from pin 10
//             Serial.println("\nDetach Servo Library to PIN 10");
//             Serial.println("Servo Stop");
//             Serial.println("Hold position OPEN for 2 sec");
             delay(2000);

             myServo.attach(srvoMtr);   // attaches the servo library to pin 10
//             Serial.println("Attach Servo Library to PIN 10");

             for (myServoPos = 100; myServoPos >= 0; myServoPos -= 1) { // goes from 100 degrees to 0 degrees in steps of 1 degree
               myServo.write(myServoPos);    // tell servo to go to position in variable 'pos
               delay(15);
             }
             myServo.detach();   // detaches the servo library from pin 10
//             Serial.println("\nDetach Servo Library to PIN 10");
//             Serial.println("Servo Stop - Awaiting next selection");
          }
          myServoFlag=0;   // changes myServoFlag value back to zero (0)
//          Serial.println("Servo Flag = 0");

          digitalWrite(ledLight, HIGH);   // turn on light to indicate chocolate is dispensed
//          Serial.println("\nLed Light ON");
          delay(3000);

//          Serial.println("Stepper Start - Return to position zero");
          digitalWrite(pwmChA, HIGH);   // enable power to stepper
          digitalWrite(pwmChB, HIGH);   // enable power to stepper
          myStepper.step(-160);         // step backward 160 steps to position 0
          digitalWrite(pwmChA, LOW);    // disable power to stepper
          digitalWrite(pwmChB, LOW);    // disable power to stepper
//          Serial.println("Stepper Stop");

          digitalWrite(pButton3, LOW);   // initialize pin 6 as LOW (pin voltage less than 1.5V)
//          Serial.println("\nReset Button 3 - PIN 6 - Low");
          digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed
//          Serial.println("\nLed Light OFF");

          pButtonFlag=0;   // changes pButton3Flag value back to zero (0)
//          Serial.println("\Button 4 Flag = 0");
          delay(2000);
       }
}

I'm including the "midi();" function to play a short melody through an attached Piezo speaker (buzzer) once the led is activated.
When I compile the midi code on its own in a separate sketch it works (see below).
int tonePin = 1;
void setup() {
 midi ();
}

void midi() {
    tone(tonePin, 233, 203.992851562);
    delay(226.658723958);
    delay(4.82252604167);
    tone(tonePin, 184, 412.325976562);
    delay(458.139973958);
    delay(4.82252604167);
    tone(tonePin, 184, 99.8262890625);
    delay(110.918098958);
    delay(4.82252604167);
    tone(tonePin, 155, 99.8262890625);
    delay(110.918098958);
    delay(4.82252604167);
    tone(tonePin, 184, 203.992851562);
    delay(226.658723958);
    delay(4.82252604167);
    tone(tonePin, 184, 203.992851562);
    delay(226.658723958);
    delay(236.303776042);
    tone(tonePin, 184, 99.8262890625);
    delay(110.918098958);
    delay(4.82252604167);
    tone(tonePin, 155, 99.8262890625);
    delay(110.918098958);
    delay(4.82252604167);
    tone(tonePin, 184, 203.992851562);
    delay(226.658723958);
    delay(4.82252604167);
    tone(tonePin, 184, 203.992851562);
    delay(226.658723958);
    delay(236.303776042);
    tone(tonePin, 184, 203.992851562);
    delay(226.658723958);
    delay(236.303776042);
    tone(tonePin, 233, 555.555);

   }

void loop() {
  // put your main code here, to run repeatedly:

}

I've searched the Internet for an answer, but have found none that relate directly with what I'm attempting to make work. Can you help me, please?

You have tried to define void midi() {...} inside the loop() function. But you cannot nest function definitions. Your definition (implementation) of midi() should be outside any other function.
Like this:
#include <Stepper.h>
#include <Servo.h>
#include <MIDI.h>

/*ARDUINO MOTOR SHIELD
   The pin breakdown is as follows:
   Function          Channel A   Channel B
   Direction         Digital 12  Digital 13
   Speed (PWM)       Digital 3   Digital 11
   Brake             Digital 9   Digital 8
   Current Sensing   Analog 0  Analog 1
*/

const int stepsPerRevolution = 200;  // 1.8 deg. step angle(200 steps/360 deg. rev)
const int dirChA = 12;     // assigning name "dirChA" to pin 12
const int dirChB = 13;     // assigning name "dirChB" to pin 13
const int pwmChA = 3;      // assigning name "pwmChA" to pin 3
const int pwmChB = 11;     // assigning name "pwmChB" to pin 11
const int brkChA = 9;      // assigning name "brkChA" to pin 9
const int brkChB = 8;      // assigning name "brkChB" to pin 8

const int srvoMtr = 10;    // assigning name "srvoMtr" to pin 10

const int pButton1 = 4;    // assigning name "pButton1" to pin 4
const int pButton2 = 5;    // assigning name "pButton2" to pin 5
const int pButton3 = 6;    // assigning name "pButton3" to pin 6
const int pButton4 = 7;    // assigning name "pButton4" to pin 7

const int ledLight = 2;    // assigning name "ledLight" to pin 2

const int tonePin = 1;     // assigning name "tonePin" to pin 1

Stepper myStepper(stepsPerRevolution, dirChA, dirChB);  // initialize the stepper library on pins 12 & 13
Servo myServo;  // initialize the servo library to logical name myServo

int pButton1State = 0;     // variable for reading the pButton1 state as LOW or HIGH
int pButton2State = 0;     // variable for reading the pButton2 state as LOW or HIGH
int pButton3State = 0;     // variable for reading the pButton3 state as LOW or HIGH
int pButton4State = 0;   // variable for reading the pButton4 state as LOW or HIGH

int pButtonFlag = 0;     // variable for when button 1 has been pressed and released

int myServoPos = 0;    // variable for when servo has reached it's position
int myServoFlag = 0;   // variable for servo when any of the 4 pButton are pressed

void midiplay() {
  tone(tonePin, 233, 203.992851562);
  delay(226.658723958);
  delay(4.82252604167);
  tone(tonePin, 184, 412.325976562);
  delay(458.139973958);
  delay(4.82252604167);
  tone(tonePin, 184, 99.8262890625);
  delay(110.918098958);
  delay(4.82252604167);
  tone(tonePin, 155, 99.8262890625);
  delay(110.918098958);
  delay(4.82252604167);
  tone(tonePin, 184, 203.992851562);
  delay(226.658723958);
  delay(4.82252604167);
  tone(tonePin, 184, 203.992851562);
  delay(226.658723958);
  delay(236.303776042);
  tone(tonePin, 184, 99.8262890625);
  delay(110.918098958);
  delay(4.82252604167);
  tone(tonePin, 155, 99.8262890625);
  delay(110.918098958);
  delay(4.82252604167);
  tone(tonePin, 184, 203.992851562);
  delay(226.658723958);
  delay(4.82252604167);
  tone(tonePin, 184, 203.992851562);
  delay(226.658723958);
  delay(236.303776042);
  tone(tonePin, 184, 203.992851562);
  delay(226.658723958);
  delay(236.303776042);
  tone(tonePin, 233, 555.555);
}

void setup() {
  //Serial.begin(31250);   // initialize the serial port for messaging & troubleshooting
  //Serial.println("Running UNO Setup");

  // 1 Stepper Motor
  // Serial.println("\nStepper Motor");
  pinMode(dirChA, OUTPUT);   // initialize pin 12 as an OUTPUT
  digitalWrite(dirChA, LOW);   //initialize pin 12 as LOW (pin voltage is 0 V)
  // Serial.println("Channel A Dir - PIN 12 - set as Output & Low");
  pinMode(dirChB, OUTPUT);   // initialize pin 13 as an OUTPUT
  digitalWrite(dirChB, LOW);   //intialize pin 13 as LOW (pin voltage is 0 V)
  // Serial.println("Channel B Dir - PIN 13 - set as Output & Low");
  pinMode(pwmChA, OUTPUT);   // initialize pin 3 as an OUTPUT
  digitalWrite(pwmChA, LOW);   //intialize pin 3 as LOW (pin voltage is 0 V)
  // Serial.println("Channel A PWM - PIN 3 - set as Output & Low");
  pinMode(pwmChB, OUTPUT);   // initialize pin 11 as an OUTPUT
  digitalWrite(pwmChB, LOW);   //intialize pin 11 as LOW (pin voltage is 0 V)
  // Serial.println("Channel B PWM - PIN 11 - set as Output & Low");
  pinMode(brkChA, OUTPUT);   // initialize pin 9 as an OUTPUT
  digitalWrite(brkChA, LOW);   //intialize pin 9 as LOW (pin voltage is 0 V)
  // Serial.println("Channel A Brake - PIN 9 - set as Output & Low");
  pinMode(brkChB, OUTPUT);   // initialize pin 8 as an OUTPUT
  digitalWrite(brkChB, LOW);   //intialize pin 8 as LOW (pin voltage is 0 V)
  // Serial.println("Channel B Brake - PIN 8 - set as Output & Low");

  myStepper.setSpeed(60);   // set the speed of the stepper motor to 60 RPM
  // Serial.println("\nSet Stepper Speed to 60 RPM");

  // 4 Push Buttons
  // Serial.println("\n4 Push Buttons");
  pinMode(pButton1, INPUT);   // initialize pin 4 as an INPUT
  digitalWrite(pButton1, LOW);   // initialize pin 4 as LOW (pin voltage less than 1.5V)
  // Serial.println("Push Button 1 - PIN 4 - set a Input & Low");
  pinMode(pButton2, INPUT);   // initialize pin 5 as an INPUT
  digitalWrite(pButton2, LOW);   // initialize pin 5 as LOW (pin voltage less than 1.5V)
  // Serial.println("Push Button 2 - PIN 5 - set a Input & Low");
  pinMode(pButton3, INPUT);   // initialize pin 6 as an INPUT
  digitalWrite(pButton3, LOW);   // initialize pin 6 as LOW (pin voltage less than 1.5V)
  // Serial.println("Push Button 3 - PIN 6 - set a Input & Low");
  pinMode(pButton4, INPUT);   // initialize pin 7 as an INPUT
  digitalWrite(pButton4, LOW);   // initialize pin 7 as LOW (pin voltage less than 1.5V)
  // Serial.println("Push Button 4 - PIN 7 - set a Input & Low");

  // 1 Led Light
  // Serial.println("\nLED Light");
  pinMode(ledLight, OUTPUT);   // initialize pin 2 as an OUTPUT
  digitalWrite(ledLight, LOW);   // initialize pin 2 as LOW (pin voltage is 0 V)
  // Serial.println("LED Light - PIN 2 - set to Output & Low");

  // 1 Piezo Speaker
  midiplay();
  // Serial.println("Piezo Speaker Inialized");
}

void loop() {
  //Read button state (pressed or not pressed?)
  //  Serial.println("\nReading button 1 thru 4 states - high or low");
  pButton1State = digitalRead(pButton1);   // read the state of pButton1 as LOW or HIGH
  pButton2State = digitalRead(pButton2);   // read the state of pButton2 as LOW or HIGH
  pButton3State = digitalRead(pButton3);   // read the state of pButton3 as LOW or HIGH
  pButton4State = digitalRead(pButton4);   // read the state of pButton4 as LOW or HIGH

  // check if the pushbutton is pressed. If it is, the pbuttonState is HIGH:
  if (pButton1State == HIGH) {
    //    Serial.println("\nPush Button 1 Pressed");
    pButtonFlag = 1; // change pButton1Flag variable
    //    Serial.println("Button 1 flag = 1");
  }
  if (pButtonFlag == 1) {
    //       Serial.println("Stepper Start - Forward 40 steps");
    digitalWrite(pwmChA, HIGH);   // enable power to stepper
    digitalWrite(pwmChB, HIGH);   // enable power to stepper
    myStepper.step(40);          // step forward 40 steps to position 1
    digitalWrite(pwmChA, LOW);    // disable power to stepper
    digitalWrite(pwmChB, LOW);    //disable power to stepper
    //       Serial.println("Stepper Stop");
    delay(2000);

    myServoFlag = 1;           // change ServoFlag variable to dispense chocolate
    //       Serial.println("\nServo Flag = 1 - Dispense Chocolate");

    if (myServoFlag == 1) {
      //          Serial.println("Servo Start");
      myServo.attach(srvoMtr);   // attaches the servo library to pin 10
      //          Serial.println("Attach Servo Library to PIN 10");

      for (myServoPos = 0; myServoPos <= 100; myServoPos += 1) { // goes from 0 degrees to 100 degrees in steps of 5 degrees
        myServo.write(myServoPos);    // tell servo to go to position in variable 'myServoPos'
        delay(15);                    // waits 3 sec for the servo to reach the position
      }
      myServo.detach();   // detaches the servo library from pin 10
      //          Serial.println("\nDetach Servo Library to PIN 10");
      //          Serial.println("Servo Stop");
      //          Serial.println("Hold position OPEN for 3 sec");
      delay(2000);

      myServo.attach(srvoMtr);   // attaches the servo library to pin 10
      //          Serial.println("Attach Servo Library to PIN 10");

      for (myServoPos = 100; myServoPos >= 0; myServoPos -= 1) { // goes from 100 degrees to 0 degrees in steps of 1 degree
        myServo.write(myServoPos);    // tell servo to go to position in variable 'pos
        delay(15);
      }
      myServo.detach();   // detaches the servo library from pin 10
      //          Serial.println("\nDetach Servo Library to PIN 10");
      //          Serial.println("Servo Stop - Awaiting next selection");
    }
    myServoFlag = 0;              // changes myServoFlag value back to zero (0)
    //       Serial.println("Servo Flag = 0");

    digitalWrite(ledLight, HIGH);   // turn on light to indicate chocolate is dispensed
    //       Serial.println("\nLed Light ON");
    //       Serial.println("\nPlay Tones");

    midiplay();
    delay(3000);

    //        Serial.println("Stepper Start - Return to position zero");
    digitalWrite(pwmChA, HIGH);   // enable power to stepper
    digitalWrite(pwmChB, HIGH);   // enable power to stepper
    myStepper.step(-40);          // step backward 40 steps to position 0
    digitalWrite(pwmChA, LOW);    // disable power to stepper
    digitalWrite(pwmChB, LOW);    //disable power to stepper
    //        Serial.println("Stepper Stop");

    digitalWrite(pButton1, LOW);   // initialize pin 4 as LOW (pin voltage less than 1.5V)
    //        Serial.println("\nReset Button 1 - PIN 4 - Low");
    digitalWrite(ledLight, LOW);   //turns off light to indicate the sequence is completed
    //        Serial.println("\nLed Light OFF");

    pButtonFlag = 0;              // changes pButtonFlat value back to zero (0)
    //        Serial.println("\Button 1 Flag = 0");
    delay(2000);
  }

  // position 2
  if (pButton2State == HIGH) {
    //     Serial.println("\nPush Button 2 Pressed");
    pButtonFlag = 1; // change pButtonFlag variable
    //     Serial.println("Button 2 flag = 1");
  }
  if (pButtonFlag == 1) {
    //        Serial.println("Stepper Start - Forward 80 steps");
    digitalWrite(pwmChA, HIGH);   // enable power to stepper
    digitalWrite(pwmChB, HIGH);   // enable power to stepper
    myStepper.step(80);          // step forward 80 steps to position 2
    digitalWrite(pwmChA, LOW);    // disable power to stepper
    digitalWrite(pwmChB, LOW);    //disable power to stepper
    //        Serial.println("Stepper Stop");
    delay(2000);

    myServoFlag = 1;  // change ServoFlag variable to dispense chocolate
    //        Serial.println("\nServo Flag = 1 - Dispense Chocolate");

    if (myServoFlag == 1) {
      //           Serial.println("Servo Start");
      myServo.attach(srvoMtr);   // attaches the servo library to pin 10
      //           Serial.println("Attach Servo Library to PIN 10");

      for (myServoPos = 0; myServoPos <= 100; myServoPos += 1) { // goes from 0 degrees to 100 degrees in steps of 5 degrees
        myServo.write(myServoPos);    // tell servo to go to position in variable 'myServoPos'
        delay(15);                    // waits 3 sec for the servo to reach the position
      }
      myServo.detach();   // detaches the servo library from pin 10
      //           Serial.println("\nDetach Servo Library to PIN 10");
      //           Serial.println("Servo Stop");
      //           Serial.println("Hold position OPEN for 2 sec");
      delay(2000);

      myServo.attach(srvoMtr);   // attaches the servo library to pin 10
      //           Serial.println("Attach Servo Library to PIN 10");

      for (myServoPos = 100; myServoPos >= 0; myServoPos -= 1) { // goes from 100 degrees to 0 degrees in steps of 1 degree
        myServo.write(myServoPos);    // tell servo to go to position in variable 'pos
        delay(15);
      }
      myServo.detach();   // detaches the servo library from pin 10
      //           Serial.println("\nDetach Servo Library to PIN 10");
      //           Serial.println("Servo Stop - Awaiting next selection");
    }
    myServoFlag = 0;              // changes myServoFlag value back to zero (0)
    //        Serial.println("Servo Flag = 0");

    digitalWrite(ledLight, HIGH);    // turn on light to indicate chocolate is dispensed
    //        Serial.println("\nLed Light ON");
    delay(3000);

    //        Serial.println("Stepper Start - Return to position zero");
    digitalWrite(pwmChA, HIGH);   // enable power to stepper
    digitalWrite(pwmChB, HIGH);   // enable power to stepper
    myStepper.step(-80);          // step backward 80 steps to position 0
    digitalWrite(pwmChA, LOW);    // disable power to stepper
    digitalWrite(pwmChB, LOW);    //disable power to stepper
    //        Serial.println("Stepper Stop");

    digitalWrite(pButton2, LOW);   // initialize pin 5 as LOW (pin voltage less than 1.5V)
    //        Serial.println("\nReset Button 2 - PIN 5 - Low");
    digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed
    //        Serial.println("\nLed Light OFF");

    pButtonFlag = 0; // changes pButton2Flag value back to zero (0)
    //        Serial.println("\Button 2 Flag = 0");
    delay(2000);
  }

  // position 3
  if (pButton3State == HIGH) {
    //       Serial.println("\nPush Button 3 Pressed");
    pButtonFlag = 1; // change pButtonFlag variable
    //       Serial.println("Button 3 flag = 1");
  }
  if (pButtonFlag == 1) {
    //          Serial.println("Stepper Start - Forward 120 steps");
    digitalWrite(pwmChA, HIGH);   // enable power to stepper
    digitalWrite(pwmChB, HIGH);   // enable power to stepper
    myStepper.step(120);          // step forward 120 steps to position 3
    digitalWrite(pwmChA, LOW);    // disable power to stepper
    digitalWrite(pwmChB, LOW);    //disable power to stepper
    //          Serial.println("Stepper Stop");
    delay(2000);

    myServoFlag = 1; // change ServoFlag variable to dispense chocolate
    Serial.println("\nServo Flag = 1 - Dispense Chocolate");

    if (myServoFlag == 1) {
      //            Serial.println("Servo Start");
      myServo.attach(srvoMtr);   // attaches the servo library to pin 10
      //             Serial.println("Attach Servo Library to PIN 10");

      for (myServoPos = 0; myServoPos <= 100; myServoPos += 1) { // goes from 0 degrees to 100 degrees in steps of 5 degrees
        myServo.write(myServoPos);    // tell servo to go to position in variable 'myServoPos'
        delay(15);                    // waits 3 sec for the servo to reach the position
      }
      myServo.detach();   // detaches the servo library from pin 10
      //             Serial.println("\nDetach Servo Library to PIN 10");
      //             Serial.println("Servo Stop");
      //             Serial.println("Hold position OPEN for 2 sec");
      delay(2000);

      myServo.attach(srvoMtr);   // attaches the servo library to pin 10
      //             Serial.println("Attach Servo Library to PIN 10");

      for (myServoPos = 100; myServoPos >= 0; myServoPos -= 1) { // goes from 100 degrees to 0 degrees in steps of 1 degree
        myServo.write(myServoPos);    // tell servo to go to position in variable 'pos
        delay(15);
      }
      myServo.detach();   // detaches the servo library from pin 10
      //             Serial.println("\nDetach Servo Library to PIN 10");
      //             Serial.println("Servo Stop - Awaiting next selection");
    }
    myServoFlag = 0;              // changes myServoFlag value back to zero (0)
    //          Serial.println("Servo Flag = 0");

    digitalWrite(ledLight, HIGH);   // turn on light to indicate chocolate is dispensed
    //          Serial.println("\nLed Light ON");
    delay(3000);

    //          Serial.println("Stepper Start - Return to position zero");
    digitalWrite(pwmChA, HIGH);   // enable power to stepper
    digitalWrite(pwmChB, HIGH);   // enable power to stepper
    myStepper.step(-120);         // step backward 120 steps to position 0
    digitalWrite(pwmChA, LOW);    // disable power to stepper
    digitalWrite(pwmChB, LOW);    // disable power to stepper
    //          Serial.println("Stepper Stop");

    digitalWrite(pButton3, LOW);   // initialize pin 6 as LOW (pin voltage less than 1.5V)
    //          Serial.println("\nReset Button 3 - PIN 6 - Low");
    digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed
    //          Serial.println("\nLed Light OFF");

    pButtonFlag = 0; // changes pButton3Flag value back to zero (0)
    //          Serial.println("\Button 3 Flag = 0");
    delay(2000);
  }
  // position 4
  if (pButton4State == HIGH) {
    //       Serial.println("\nPush Button 4 Pressed");
    pButtonFlag = 1; // change pButtonFlag variable
    //       Serial.println("Button 3 flag = 1");
  }
  if (pButtonFlag == 1) {
    //          Serial.println("Stepper Start - Forward 160 steps");
    digitalWrite(pwmChA, HIGH);   // enable power to stepper
    digitalWrite(pwmChB, HIGH);   // enable power to stepper
    myStepper.step(160);          // step forward 160 steps to position 3
    digitalWrite(pwmChA, LOW);    // disable power to stepper
    digitalWrite(pwmChB, LOW);    //disable power to stepper
    //          Serial.println("Stepper Stop");
    delay(2000);

    myServoFlag = 1; // change ServoFlag variable to dispense chocolate
    //          Serial.println("\nServo Flag = 1 - Dispense Chocolate");

    if (myServoFlag == 1) {
      //             Serial.println("Servo Start");
      myServo.attach(srvoMtr);   // attaches the servo library to pin 10
      //             Serial.println("Attach Servo Library to PIN 10");

      for (myServoPos = 0; myServoPos <= 100; myServoPos += 1) { // goes from 0 degrees to 100 degrees in steps of 5 degrees
        myServo.write(myServoPos);    // tell servo to go to position in variable 'myServoPos'
        delay(15);                    // waits 3 sec for the servo to reach the position
      }
      myServo.detach();   // detaches the servo library from pin 10
      //             Serial.println("\nDetach Servo Library to PIN 10");
      //             Serial.println("Servo Stop");
      //             Serial.println("Hold position OPEN for 2 sec");
      delay(2000);

      myServo.attach(srvoMtr);   // attaches the servo library to pin 10
      //             Serial.println("Attach Servo Library to PIN 10");

      for (myServoPos = 100; myServoPos >= 0; myServoPos -= 1) { // goes from 100 degrees to 0 degrees in steps of 1 degree
        myServo.write(myServoPos);    // tell servo to go to position in variable 'pos
        delay(15);
      }
      myServo.detach();   // detaches the servo library from pin 10
      //             Serial.println("\nDetach Servo Library to PIN 10");
      //             Serial.println("Servo Stop - Awaiting next selection");
    }
    myServoFlag = 0; // changes myServoFlag value back to zero (0)
    //          Serial.println("Servo Flag = 0");

    digitalWrite(ledLight, HIGH);   // turn on light to indicate chocolate is dispensed
    //          Serial.println("\nLed Light ON");
    delay(3000);

    //          Serial.println("Stepper Start - Return to position zero");
    digitalWrite(pwmChA, HIGH);   // enable power to stepper
    digitalWrite(pwmChB, HIGH);   // enable power to stepper
    myStepper.step(-160);         // step backward 160 steps to position 0
    digitalWrite(pwmChA, LOW);    // disable power to stepper
    digitalWrite(pwmChB, LOW);    // disable power to stepper
    //          Serial.println("Stepper Stop");

    digitalWrite(pButton3, LOW);   // initialize pin 6 as LOW (pin voltage less than 1.5V)
    //          Serial.println("\nReset Button 3 - PIN 6 - Low");
    digitalWrite(ledLight, LOW);   // turns off light to indicate the sequence is completed
    //          Serial.println("\nLed Light OFF");

    pButtonFlag = 0; // changes pButton3Flag value back to zero (0)
    //          Serial.println("\Button 4 Flag = 0");
    delay(2000);
  }
}

Thank you Jose! I appreciate your quick reply. So can I make a call to run the program outside the loop function. If yes, how? I'm not an expert.

There is a difference between defining a function and calling a function. You must define it outside any other function. But you must call it from within setup() or loop() (or some other function that is called by those, etc.) To define the function, is where you say void midi() { blah blah code here}, and to call it you just write midi();.

Hi Jose, I'm a new-be to Arduino. I would need a detailed example in the form of a sketch, or if can, correct the sketch I've provided so that it will compile, please. Ok?

You have already done it... In your second code block that "does work" because midi() is alone, you have the block that defines what midi() does and it's not inside setup() or loop(). And you have called midi(); from the setup() function. So, just move the definition of midi() {...} to a place that is not inside any other function. In the place in loop() or setup() where you want the action to take place, just call the function with midi();

I'm sorry, Jose. I'm not getting it to work because I'm not following/understanding your explanation.

My hope is that you can give me a clear, step by step instructions, to get my code to work.

I updated my answer to include this very simple change, exactly as I had explained. Just MOVE the midi function OUTSIDE of loop().

Very helpful, Jose! Thanks for helping me out. I'm grateful to you.

The code is compiling and loading with mixed results. I've submitted the revised code under a new question - "Code causing Servo motor not to work!" Please have a look. Thx.

Sorry, I’m no longer interested in writing more code for your project. I suggest you learn more about fundamentals of C coding, as it would really help you solve these simple problems on your own.


text:
Arduino IDE gives error a1 is not declared
#include <LiquidCrystal.h>
LiquidCrystal lcd(A0,A1,A2,A3,A4,A5);

in this code the error given by IDE is 'A1' was not declared in this scope.
So whats the problem please help

Is that your whole code?

in Arduino IDE? with Nano selected in Tools menu?

Try using the GPIO numbers LiquidCrystal lcd(14,15,16,17,18,19); rather than the analog pin numbers. https://i2.wp.com/christianto.tjahyadi.com/wp-content/uploads/2014/11/nano.jpg has the pinout diagram.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Why Wire.write twice?
I'm checking an example for the MPU6050 and got to this part
Wire.beginTransmission(0x68);           //begin, Send the slave adress (in this case 68)
Wire.write(0x1B);                       //We want to write to the GYRO_CONFIG register (1B hex)
Wire.write(0x10);                       //Set the register bits as 00010000 (1000dps full scale)
Wire.endTransmission(true);             //End the transmission with the gyro

Serial.begin(9600);                     //Remember to set this same baud rate to the serial monitor
time = millis();                        //Start counting time in milliseconds

/*Here we calculate the gyro data error before we start the loop
 * I make the mean of 200 values, that should be enough*/
if(gyro_error==0)
{
  for(int i=0; i<200; i++)
  {
    Wire.beginTransmission(0x68);            //begin, Send the slave adress (in this case 68)
    Wire.write(0x43);                        //First adress of the Gyro data
    Wire.endTransmission(false);
    Wire.requestFrom(0x68,4,true);           //We ask for just 4 registers

Why is there two consecutive wire.write() in the begining and only one later? Is it different somehow?

it is write(byte). to write two bytes to TX buffer it must be called twice

The truth is, the Arduino Wire library sends the data only if endTransmission is called. Until then it collects the data in TX buffer. The version of the write function used in your snippet adds a byte to the TX buffer.
With I2C usually the first byte written is the address of the register to write. Then the data follow. In case of the first part in your snippet the data are only one byte long.
In the second part, first the register address is sent with write and then the data from this register and 3 following registers are requested.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Using a rotary switch
I don’t have a sketch for this project, just doing some thinking before I pullout the keyboard (this is my phone).  I was interested in writing a program that uses a predetermined time limit, for instance having a definition like...
#define RUNTIME 30000

So the game runs for 30 seconds.
By doing this it would be a simple matter of changing the 30000 to 60000 and uploading to the Arduino.
After thinking about that a while, I would prefer to be able to adjust the time using a selector switch.
So my question is....  if I use a 1p4t (on-on-on-on) rotary selector switch,  assign each position to a pin and run 5v to the common. Each pin would defined as RUNTIME and a different time limit, 30000, 60000, 90000, 120000, three pins would be LOW and one HIGH depending on position.
Then using IF and ELSE statements in the loop setup would I be able to switch the times?  I know once the Arduino is powered up the selector switch would need to be at the correct location and if you choose to change the “RUNTIME” a reset would need to be pressed.
Thank you for any assistance or ideas.

Better to use GND not +5V and use the INPUT_PULLUP mode for the pins. If you don't you then need to add a pulldown resistor to all 4 inputs.

You would not HAVE to reset when changing the switch position. you could periodically check the switch input and update the value while running.

you could use an analog pin and 4 voltages instead of many pins.

for a simpler keyswitch circuit look at the keypad schematic at the bottom of this page ... in the "More" section .... https://www.dfrobot.com/wiki/index.php/LCD_KeyPad_Shield_For_Arduino_SKU:_DFR0009    ......... use the code on the page for reference

If I understand you well, it's very easy.
Assuming the 4 outputs of the switch will be connected to 4 GPIO's you just can check for the state of each GPIO and act on it
// Pin numbers where switch 1 to 4 are attached to.
#define PIN_SWITCH_1  8
#define PIN_SWITCH_2  9
#define PIN_SWITCH_3 10
#define PIN_SWITCH_4 11

unsigned long timer_value = 1000; // No switch selected

void setup()
{
     // Set switch pins to input mode.
     pinMode(PIN_SWITCH_1, INPUT);
     pinMode(PIN_SWITCH_2, INPUT);
     pinMode(PIN_SWITCH_3, INPUT);
     pinMode(PIN_SWITCH_4, INPUT);

     // Check switches
     if (digitalRead(PIN_SWITCH_1) == HIGH)
     {
         timer_value = 30000;
     }
     else if (digitalRead(PIN_SWITCH_2) == HIGH)
     {
         timer_value = 60000;
     }
     else if (digitalRead(PIN_SWITCH_3) == HIGH)
     {
         timer_value = 90000;
     }
     else if (digitalRead(PIN_SWITCH_4) == HIGH)
     {
         timer_value = 120000;
     }
     else
     {
         // Keep default value
     }
 }

 void loop()
 {
     // Here you can use timer_value to check for the end of the game.
 }

Thank you everyone for your input.  I will be moving  ahead with this project.

pin 1 is a trap for the beginner?

@Juraj ... yes it's mean of me to use those pins ... I was not near an Arduino so I should check which are really free and obvious to use.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Management issues through Blynk
I wrote a sketch for controlling the stepper motor under the controls of the Blynk application, the sketch was compiled but there was a problem in that no control was taking place. Receipts and controls occur on virtual pins V1, V2, V3. (The problem is that nothing is controlled), please help solve the problem.

//#include <Stepper.h>
//#define BLYNK_WRITE
//#include <ESP8266WiFi.h>
//#include <BlynkSimpleEsp8266.h>

const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution
// for your motor
Stepper myStepper(stepsPerRevolution, 1, 2, 3, 4);

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "[private]";

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "S30mini";
char pass[] = "12345678";

int pinData;
int pinData1;
int pinData2;
BLYNK_WRITE(V3) //Button Widget is writing to pin V1
{
  int pinData = param.asInt();
 }
BLYNK_WRITE(V2) //Button Widget is writing to pin V1
{
  int pinData1 = param.asInt();
 }
BLYNK_WRITE(V1) //Button Widget is writing to pin V1
{
  int pinData2 = param.asInt();
 }

void setup()
{
  // Debug console
  Serial.begin(115200);
  Blynk.begin(auth, ssid, pass);
}

void loop()
{
    Blynk.run();

  // map it to a range from 0 to 100:
  int motorSpeed = map(pinData, 0, 1023, 0, 100);
  // set the motor speed:
  if (motorSpeed > 0) {
    myStepper.setSpeed(motorSpeed);
    // step 1/100 of a revolution:
    myStepper.step(stepsPerRevolution / 100);
  }

   if (pinData1 == 1){
      myStepper.step(stepsPerRevolution);
   }

   if (pinData2 == 1){
     myStepper.step(-stepsPerRevolution);
    }

}

By prefixing your pinData variables with int, you are declaring local variables in your BLYNK_WRITE() functions, whose scope is only in that function. The local version is written to, instead of the global.
To fix this, do not declare a new variable in BLYNK_WRITE():
BLYNK_WRITE(V3) //Button Widget is writing to pin V1
{
  pinData = param.asInt();
}
BLYNK_WRITE(V2) //Button Widget is writing to pin V1
{
  pinData1 = param.asInt();
}
BLYNK_WRITE(V1) //Button Widget is writing to pin V1
{
  pinData2 = param.asInt();
}


text:
Serial Comm. timing issue between Arduino and Pyserial
This is my first post to Stack Exchange so please forgive any formatting errors.
I am conducting an experiment that has 7 total sensors: 5 thermocouples, 2 humidity sensors and 1 pressure sensor. I am reading their signals via Arduino Mega analog input ports. I chose to use Python to save and compile the data in a nice csv file, therefore I am using Pyserial.
My problem is that I cannot go above 1 sample/second. As you can see in my code, I have a 1 second delay in Arduino and Python. I have ran successful calibration tests with my thermocouples, so I know at that rate Python and Arduino are communicating well. Anything faster than 1 sample/second (i.e. I change my delays to .5 or .25 seconds), a timing error occurs and my data is "cut up" and sent in odd chunks instead of the standard layout I programmed.
Additionally, I tried to increase the baud rate from 9600 and anything above that will send "garbage" ASCII characters (e.g. little blank blocks and odd characters) to the Serial Comm. I changed the baud rate in Arduino, Python and the COM port in my devices manager settings to no avail.
I would really like to increase my sampling rate to increase my signal-to-noise ratio and I believe it's good practice as a metrologist to have a higher sampling rate than 1 samp/sec. I am sending ~1072 bits each time I write to the Serial Comm (if I'm counting right??) so I should have enough room to increase the amount of bits to send per second (around 3 times what I am currently sending).
In summary, my two main issues are: if I increase the baud rate, I get garbage in my Serial Comm and if I try to increase my "sampling rate" by decreasing my delays, timing issues appear and my data is split up erroneously. Should I be using a different function, like Serial.flush()?
I greatly appreciate any feedback, thank you for your time!
// Data acquisition
// updated  March 30, 2017

//Note: This version is for TEMPERATURE, HUMIDITY and PRESSURE data
acquisition ALONE. No motor/conveyor control.

//***GLOBAL VARIABLES***//

float lfactor = 125.0;
float afactor = 1.15;

/////////////////////////

//Standard setup with analogReference to 5Volts.

void setup() {

Serial.begin(9600);
}

void loop() {

//******THERMOCOUPLES*******//

//get voltage reading
// [code]; TC # - Location

float tcv1 = analogRead(A4) * ( 5.0 / 1024.0 ); //TC 1
float tcv2 = analogRead(A7) * ( 5.0 / 1024.0 ); //TC 2
float tcv3 = analogRead(A8) * ( 5.0 / 1024.0 ); //TC 3
float tcv4 = analogRead(A9) * ( 5.0 / 1024.0 ); //TC 4
float tcv5 = analogRead(A10) * ( 5.0 / 1024.0 ); //TC 5

//convert to temperature using custom equation based on 5V reference
float tc1 = ( 188.7755 * tcv1 ) - 245.3959;
float tc2 = ( 188.7755 * tcv2 ) - 245.3959;
float tc3 = ( 188.7755 * tcv3 ) - 245.3959;
float tc4 = ( 188.7755 * tcv4 ) - 245.3959;
float tc5 = ( 188.7755 * tcv5 ) - 245.3959;

//******HUMIDITY SENSORS********//

float hs1 = ((( analogRead(A13) * ( 5.0 / 1024.0) ) / 5.0 ) * 100.0 ); //HS
1
float hs2 = ((( analogRead(A15) * ( 5.0 / 1024.0) ) / 5.0 ) * 100.0 ); //HS
2

//******PRESSURE SENSORS********//

//obtain voltage signal from Sensirion sensor
float pvolt = analogRead(A0) * (4.995 / 1024.0);

//convert to Pascals using equation from datasheet, including altitude
compensation
//P = lfactor * (voltage[V] - .250 ) / 3.750

float pressure =  lfactor * ( pvolt - .250 ) / 3.750;
float pascals = pressure * afactor;

Serial.print("TC1");
Serial.print(":");
Serial.print(tc1);
Serial.print(";");

Serial.print("TC2");
Serial.print(":");
Serial.print(tc2);
Serial.print(";");

Serial.print("TC3");
Serial.print(":");
Serial.print(tc3);
Serial.print(";");

Serial.print("TC4");
Serial.print(":");
Serial.print(tc4);
Serial.print(";");

Serial.print("TC5");
Serial.print(":");
Serial.print(tc5);
Serial.print(";");

Serial.print("RH 1");
Serial.print(":");
Serial.print(hs1);
Serial.print(";");

Serial.print("RH 2");
Serial.print(":");
Serial.print(hs2);
Serial.print(";");

Serial.print("Pressure");
Serial.print(":");
Serial.print(pascals);
Serial.print(";");

Serial.println("");
delay(1000);

  }

Python Code:
from threading import Thread
import time
import serial
import os
global datalist
global fileName

global motorspeed

motorspeed = 0

def serInitialization():
    #activate the serial port, if possible
    try:
        ser = serial.Serial('COM9', 9600) #initialize the serial port
        print "Serial connection successful."
        return ser
    except:
        print "Error: serial port cannot be initialized"
        while(1):
            voidholder = 1

def getDateTime():
  """Function grabs current time and date, then returns values in a 2-
 element list. """
   timeNow = time.strftime("%H:%M:%S")
   dateToday = time.strftime("%m/%d/%y")
  return [dateToday, timeNow]

def writetocsv(data):

    """ function writes datalist values to a csv file. If daily csv file
exists already,
    list values are simply appended to end of file. If it does not, function
creates the file,
    then appends values.
    """

    global csv_success

    header = ["date", "time", " ", "TC1", " ", "TC2", " ",
"TC3", " ", "TC4", " ", "TC5", " ", "HS1", " ", "HS2"," ",
"PRESSURE", " ", "PRESSURE(alt)", "\n"]

    fileName = str(time.strftime("%m_%d_%y_")+ "log.csv")

    if os.path.exists(fileName):
        f = open(fileName, "a")

    else:
        f = open(fileName, "a+")

        for element in header:
            f.write(element + ",")
        f.write("\n")

    for element in data:
        if type(element)==str:
            f.write(element + ",")
        if type(element) == list:
            for i in element:
                f.write(i + ",")

    f.write("\n")
    f.close()
    csv_success = True

def mainprogram():

    data = []

    if ser.inWaiting():
        datetimeData = getDateTime()

        for i in datetimeData:
            data.append(i)

        val = ser.readline().strip('\n\r').split(';')
        print "Current readings: "
        for i in range(0,len(val)):
            sensorData = val[i].split(':')
            data.append(sensorData)

            print sensorData

        writetocsv(data)

        time.sleep(1)

        print "\n" * 50

#Initializes the serial port with the arduino so now we can read what
Arduino is sending us!
print "*******************************"
print "DATA ACQUISITION PROGRAM       "
print "*******************************"
print "Data files are saved under "
print "C:\\Users\\lpaw\\Downloads\\python workspace"
print "*******************************"

ser = serInitialization()

while True:

   mainprogram()

Screenshots of errors:

I suspect I already know where your sampling-rate problem is, but can you post an example of a 'good' vs a 'bad' set of received data?

Your main problem is in erroneously having a delay in both the sender and the receiver.  While this sometimes works by lucky accident, it essentially never does what is hoped for by those who try it.
In a system such as this, you should have a delay in the sender only, in order to produce quasi-regular sample intervals, but no delay in the receiver.  Rather, the receiver should accept data whenever the transmitter produces it, or more specifically in your case, every time it completes a terminated line of data.
But you also seem to want to write the data in an organized way as sets of measurements.  To do that, you should reject data until you see the first "TC1", then collect lines to fill in a data block until and end of data condition is recognized (in your case a blank line), and write it out to disk in a timestamped file.  You may also want to include code that abandons a corrupted block unwritten if any of the intermediate reading headers aren't as expected, and goes back to looking for the next hopefully clean TC1, or marks it as erroneous, or whatever.
To use a different baud rate, you must apply a matching setting in both the Arduino and the python ends of the link.
Also note that while the Arduino serial monitor is indeed useful for debugging, you must not have it open while trying to collect data with python - this will either cause an error in that one program is disallowed, or the two programs to fight over the data and each get incomplete results.
Another technique which can be simple and useful, especially during development, is to write every received line of serial data out to a text file with a numeric timestamp at the start of each line.  You can then have a second process which reads this file, grabs complete multi-line records, and writes them out using either the timestamp of the first or last element of the record.  In particular this lets you get an intermediate view of the data to understand any oddities.  With various Unix style command line tricks you can even run the first program both saving the intermediate format and feeding the second record extraction program in real time.

Okay, I understand what you're saying. The reason why I have a delay is because I need to be able to observe the data in real time, and I wasn't able to run a GUI. So I have the program delayed so I have enough time to read the data in the Python Shell . I'll just bite the bullet and learn threading (I was struggling with that, thus I went with my current [crappy] setup). Thanks so much for your help!!

Threading is not the solution to this either.  What you should do is pipe the output through a pager, or capture it to a file and view that separately.

But isn't threading how I would be able to both continuously "capture" data and print it out to a user interface simultaneously?

I will look into that, thank you again @Chris Stratton

Does your Python code have any way of determining the start & end of a data set?
Does it 'assume' that when it reads a chunk of data from the serial port that the first byte it gets will always be the start of a "Cond.temp" and the last byte will be the ; at the end of Press(alt)?
After reading a chunk of data, do you have any check to see if it is complete or if you should wait a few 10's of milliseconds and go back to read some more?
I'm assuming the answers to these questions are No, Yes & No.
Your PC and your Arduino are running completely asynchronously - neither one really knows what the other is doing.
When your python code reads a chunk of data from the serial port (I'm making another assumption here - that you're not reading it byte-by-byte), you have no way of knowing that the beginning of that chunk is really the beginning of your data set.
Similarly, you also have no way of knowing that the end of that chunk is the end of your data set - maybe it's only a small piece - or maybe you're getting the beginning of the next set glued to the end of this on.
If you're using a USB-Serial adapter then your data is even more likely to arrive in bits & pieces which you'll need to reassemble - just by the nature of how these beasties often work - they could be buffering some number of serial bytes before packaging them together in a single USB packet.
You need some way of flagging the start and/or end of your data sets. Even something as simple as a \n newline character at the end of each one might work for you.
Then, you need to read in and buffer the data you're receiving until you know you've reached the end of a data set.
So, for the \n example:
 - read some stuff
 - add it to a buffer
 - do you have a \n anywhere in the buffer?
 -- yes - pull that section from the start of the buffer up to the \n & process it
 -- no - go back to the beginning and wait for more stuff
 - after you've pulled some stuff out of the buffer to process,
don't just forget the rest - it could be the start of your next data set!
 - move it to the start of your buffer
 - rinse & repeat
For your baud-rate issue I can't say much for sure. The garbage you're seeing is typical for a mismatched baud-rate situation.
Check that your particular Arduino supports the baud rates you're trying to use at whatever clock speed you're running it at.
Check that your USB-Serial adapter (if you're using one) works at those speeds (either loop pins 2&3 and type to yourself in a terminal or get another, preferably different one, and hook them together with a 3-wire link pin 2-3, pin 3-2, pin 5-5).

You certainly should use a single Serial.flush at the end of your loop()
Serial.println("");
Serial.flush()
delay(100);

Remember you have limited SRAM to store characters.
I'd suggest you should use the inbuilt serial monitor in the Arduino IDE with the above alteration, and increase your baud rate. There should be no problems sending data at 115k baud.
You should also consider sending a signal back from Python that you have received a valid reading string (ACK/NAK) that way you can remove delays altogether (you still need the flush).

This is not the issue

@ChrisStratton ...then please share you knowledge.

Serial output blocks until there is room in the buffer.  All your change would do is extend the sample interval beyond what is intended by the transmission time of whatever has not yet been sent, while without the flush() it is extended by only any portion that has not yet fit in the outgoing data buffer.

authors: Андрей Мячев

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Snake head in snake game always diagonal to rest of body
I am trying to create a basic snake game using the arduino UNO along with the MAX72XX module, the LCD module and the analog joystick module. I have made my program using object orientated programming. I have no experience with C++ so I have done really well to get this far in my program (This is the only thing left to help me complete the game!). The only problem that is holding me back is that the snake head is always diagonal to the rest of the body. Here are a few examples of what I mean:

Here is my code if the issue is in here (I have commented what part does what):
#include "LedControl.h"
#include <LiquidCrystal.h>
LedControl lc=LedControl(12,10,11,1);
LiquidCrystal lcd(8, 13, 3, 5, 6, 7);

/*lcd->setCursor(0, 1);
  // print the number of seconds since reset:
  lcd->print(millis() / 1000);*/

class Snake_body//class of each snake body part
{
  //private:

  public:

    int following_direction;
    int x;
    int y;
    int previous_x;
    int previous_y;
    bool enabled;
    /*Snake_body()
    {
      this->enabled = false;
    }*/
    /*Snake_body(int x_value, int y_value)
    {
      this->enabled = false;
      this->following_direction = 1;
      this->x = x_value;
      this->y = y_value;
      this->previous_y = y_value;
      this->previous_x = x_value;
    }*/
    void configure(int x_value, int y_value)
    {
      //this->enabled = true;
      this->following_direction = 1;
      this->x = x_value;
      this->y = y_value;
      this->previous_y = y_value;
      this->previous_x = x_value;
    }

};

class Power_up
{
  private:

  public:
    virtual void init()
    {
      this->x = 0;
      this->y = 0;
    }

    int x;
    int y;
};

Snake_body *snake[64];
int snakes_length;

//Snake_body *snake[0];
Power_up *power_up;

int score;

void setup() {

  Serial.begin(9600);

  lcd.begin(16, 2);

  snakes_length = 1;

  for(int z = 1; z < 64; z++)
  {
    snake[z] = NULL;//makes all snake body parts except head NULL
  }

  snake[0] = new Snake_body();//define snake head
  snake[0]->configure(0,0);//set it up
  power_up = new Power_up();//power up to increase in body size
  //Snake_body snake[0] = new Snake_body();
  // put your setup code here, to run once:
  lc.shutdown(0,false);
  /* Set the brightness to a medium values */
  lc.setIntensity(0,8);
  /* and clear the display */
  lc.clearDisplay(0);
  lcd.setCursor(0, 0);
  score = 0;
  lcd.print("score: ");
  lcd.setCursor(6, 0);
  lcd.print(score);
  pinMode(2, INPUT);
  digitalWrite(2, HIGH);
  power_up->x = random(0, 8);
  power_up->y = random(0, 8);
}

int snake_direction;

void loop()
{
  int x_axis = analogRead(A0);
  int y_axis = analogRead(A1);
  int switcher = digitalRead(2);

   if(x_axis <= 400)//the following 4 directions are for moving the snake
   {
     snake[0]->following_direction = 0;
     //x += 1;
     Serial.println("left");
   }

   else if(x_axis >= 600)
   {
     snake[0]->following_direction = 1;
     //x -= 1;
     Serial.println("right");
   }

   else if(y_axis <= 400)
   {
     snake[0]->following_direction = 2;
     //y -= 1;
     Serial.println("up");
   }

   else if(y_axis >= 600)
   {
     snake[0]->following_direction = 3;
     //y += 1;
     Serial.println("down");
   }

  if(snake[0]->following_direction == 0 && snake[0]->x < 7)//updates the snakes position
  {
    snake[0]->previous_x = snake[0]->x;
    snake[0]->x += 1;
  }

  else if(snake[0]->following_direction == 1 && snake[0]->x > 0)//updates the snakes position
  {
    snake[0]->previous_x = snake[0]->x;
    snake[0]->x -= 1;
  }

  else if(snake[0]->following_direction == 2 && snake[0]->y > 0)//updates the snakes position
  {
    snake[0]->previous_y = snake[0]->y;
    snake[0]->y -= 1;
  }

  else if(snake[0]->following_direction == 3 && snake[0]->y < 7)//updates the snakes position
  {
    snake[0]->previous_y = snake[0]->y;
    snake[0]->y += 1;
  }

  Serial.println("\n");//USED THESE PRINT STATEMENTS TO PRINT VALUES

  Serial.print("previous x: ");
  Serial.print(snake[0]->previous_x);
  Serial.println("");
  Serial.print("previous y: ");
  Serial.print(snake[0]->previous_y);
  Serial.println("");
  Serial.print("direction: ");
  Serial.print(snake[0]->following_direction);
  Serial.println("\n");

  if(snake[0]->x == power_up->x && snake[0]->y == power_up->y)//if the head collides with the power up
  {
    score += 1;
    lcd.setCursor(6,0);
    lcd.print(score);

    power_up->x = random(0, 8);
    power_up->y = random(0, 8);

    for(int j = 0; j < 64; j++)
    {
      if(snake[j] == NULL)//searches for empty snake body
      {

         snake[j] = new Snake_body();//creates new snake body part
         snake[j]->configure(snake[j-1]->previous_x, snake[j-1]->previous_y);//sets up the snake body part

         snake[j]->following_direction = NULL;
         snakes_length += 1;
         break;
      }
    }
  }

  for(int i = 1; i < 64; i++)
  {
    if(snake[i] != NULL)//updates the other body parts appart from the snake head (it was updated before this)
    {
      snake[i]->previous_x = snake[i]->x;
      snake[i]->previous_y = snake[i]->y;
      snake[i]->x = snake[i-1]->previous_x;
      snake[i]->y = snake[i-1]->previous_y;
    }
  }

  lc.setLed(0,power_up->x,power_up->y,true);
  for(int w = 0; w < 64; w++)//drawing body parts onto the screen
  {

    if(snake[w] != NULL)
    {
      lc.setLed(0,snake[w]->x,snake[w]->y,true);
    }
  }

  delay(100);

  lc.clearDisplay(0);
}

I'm not sure if I understand the problem well... in the first example the snake body has three straight dots. This means that before the head was straight compared to the body. Only in the screenshot you made it 'turned'  diagonal (?)

What you can do yourself to 'debug' is to RUN the sketch on a PC. You can do this by creating a class for all Arduino specific classes (like LiquidCrystal, Serial and LedControl) and program all functions (to do nothing or show a simple display, or write just some lines to mimic the output). This will let you easily add break points and step through your code, or see a (long) list of output including history.

And some OO improvements (you did already a good job): you don't have to use the 'new'/dynamic way of allocating in your case, just create elements directly. The normal naming for classes is PascalCasing thus PowerUp instead of Power_up, and make all variables in a class private (move the private  keyword before int x;  in the Power_up class. Instead of snake[0]->y += 1; you can use snake[0]-y++, similar with --.

When a new snake body part is added, let the sketch print out it's position. Check, if that position is correct. I see you are adding the new element at the previous position of the last one, but then you let every part (except for the head) move one step further. Please try to move the adding part to after the body updating part

@MichelKeijzers No the snake can only move vertically and horizontally. In the picture it is moving in a straight line. But for example if the snake's body was on x axis 5 and the snake head was on x axis 4 and if both of their y axis' get moved up by one then their x would be on the same x axis as before but the head would be one place higher than the body.

@chrisl tried putting the adding a new snake part after updating. No luck.

Then please print the position of the new added element. Show the complete Serial output

@chrisl I have had an idea! Could I use the previous direction of the snake head and use the current direction to determine which way the snake turned and then fix the head using the x and y axis' from there.

@chrisl does not matter I fixed the game myself. All that I did was move the previous_x and previous_y out of the if statements

@MichelKeijzers does not matter I fixed the game myself. All that I did was move the previous_x and previous_y out of the if statements

Then please write an answer yourself, so that others might profit from your learning and that this question can be marked as answered by yourself.

Glad you sorted it out yourself. If you have more complicated problems in the future, consider trying some non-Arduino specific parts on a PC, with full debugging capabilities.

when debugging a problem such as yours, it is important to identify the failure correctly .... you say that the head is diagonal from the body ... but that is not what the actual problem is ... the head is not offset at a diagonal, it is offset by one square to left or to right


text:
request for member 'attribute' in 'object', which is of non-class type 'int'
I am trying to create a basic snake game using the arduino UNO along with the MAX72XX module, the LCD module and the analog joystick module. I am wanting to program my program using object orientated programming. I have no experience with C++ so I am struggling quite a bit to understand what the following error is trying to say to me: request for member 'following_direction' in 'snake[0]', which is of non-class type 'int'.Here is the full code:
#include "LedControl.h"
#include <LiquidCrystal.h>
LedControl lc=LedControl(12,10,11,1);
LiquidCrystal lcd(8, 13, 3, 5, 6, 7);

/*lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(millis() / 1000);*/

class Snake_body
{
  //private:

  public:

    int following_direction;
    int body_length[64];
    int x;
    int y;
    int previous_x;
    int previous_y;

    Snake_body(int x_value, int y_value)
    {
      this->following_direction = 1;
      this->x = x_value;
      this->y = y_value;
      this->previous_y = y_value;
      this->previous_x = x_value;
    }
    /*void configure(int x_value, int y_value)
    {
      this->following_direction = 1;
      this->x = x_value;
      this->y = y_value;
      this->previous_y = y_value;
      this->previous_x = x_value;
    }*/

};

class Power_up
{
  private:

  public:
    virtual void init()
    {
      this->x = 0;
      this->y = 0;
    }

    int x;
    int y;
};

int snake[64];
int snakes_length;

Snake_body *snake_body;
Power_up *power_up;

void setup() {

  lcd.begin(16, 1);

  snakes_length = 1;

  for(int z = 1; z < 64; z++)
  {
  snake[z] = 0;
  }

  snake[0] = new Snake_body(0,0);
  //Snake_body snake[0] = new Snake_body();
  //snake[0].configure(0,0);
  // put your setup code here, to run once:
  lc.shutdown(0,false);
  /* Set the brightness to a medium values */
  lc.setIntensity(0,8);
  /* and clear the display */
  lc.clearDisplay(0);

  pinMode(2, INPUT);
  digitalWrite(2, HIGH);

  Serial.begin(9600);
  power_up->x = random(0, 8);
  power_up->y = random(0, 8);
}

int snake_direction;

void loop()
{
  int x_axis = analogRead(A0);
  int y_axis = analogRead(A1);
  int switcher = digitalRead(2);

   if(x_axis <= 400) //&& x < 7)
   {
     snake[0].following_direction = 0;
     //x += 1;
     //Serial.println("right");
   }

   else if(x_axis >= 600) //&& x > 0)
   {
     snake[0].following_direction = 1;
     //x -= 1;
     //Serial.println("left");
   }

   else if(y_axis <= 400) //&& y > 0)
   {
     snake[0].following_direction = 2;
     //y -= 1;
     //Serial.println("up");
   }

   else if(y_axis >= 600) //&& y < 7)
   {
     snake[0].following_direction = 3;
     //y += 1;
     //Serial.println("down");
   }

  if(snake[0].following_direction == 0 && snake[0].x < 7)
  {
    snake[0].previous_x = snake[0].x;
    snake[0].x += 1;
  }

  else if(snake[0].following_direction == 1 && snake[0].x > 0)
  {
    snake[0].previous_x = snake[0].x;
    snake[0].x -= 1;
  }

  else if(snake[0].following_direction == 2 && snake[0].y > 0)
  {
    snake[0].previous_y = snake[0].y;
    snake[0].y -= 1;
  }

  else if(snake[0].following_direction == 3 && snake[0].y < 7)
  {
    snake[0].previous_y = snake[0].y;
    snake[0].y += 1;
  }

  for(int a = 1; a < 64; a++)
  {
    if(snake[i] != 0)
    {

      snake[i].x = snake[i-1].previous_x;
      snake[i].y = snake[i-1].previous_y;
    }
  }

  lc.setLed(0,power_up->x,power_up->y,true);
  for(int w = 0; w < 64; w++)
  {
    if(snake[w] != 0)
    {
      lc.setLed(0,snake[w].x,snake[w].y,true);
    }
  }

  if(snake[0].x == power_up->x && snake[0].y == power_up->y)
  {
    power_up->x = random(0, 8);
    power_up->y = random(0, 8);

    for(int i = 0; i < 64; i++)
    {
      if(snake[i] == 0)
      {
         Snake_body *snake[i];

         //next_snake_body = new Snake_body();
         snake[i] = new Snake_body(snake[i-1].previous_x, snake[i-1].previous_y);
         //Snake_body next_snake_body;
         //snake[i].configure(snake[i-1].previous_x, snake[i-1].previous_y);
      }
    }
  }
  /*Serial.print("x: ");
  Serial.print(snake.x);
  Serial.println();

  Serial.print("y: ");
  Serial.print(snake.y);
  Serial.println();*/

  if(switcher == 0)
  {
    delay(50);
  }
  else
  {
    delay(100);
  }
  lc.clearDisplay(0);
}

the error is coming from this line here:
else if(snake[0].following_direction == 3 && snake[0].y < 7)

but I think it is also happening at all other lines of which are similar to this one.
I have tried replacing the . in snake[0].following_direction with a -> instead but that just caused the error: base operand of '-> ' is not a pointer. I have experience programming in java python and a few others but not arduino C++.

The problem is indeed in that line:
else if(snake[0].following_direction == 3 && snake[0].y < 7)

And specifically in:
snake[0].following_direction

snake is defined as
int snake[64];

Thus snake[0] is of type int.
And you cannot request the member following_direction from type.
Since you make new instances with:
snake[0] = new Snake_body(0,0)

I assume snake should be an array of Snake_body.
So I suggest (at least) change the type to:
Snake_body snake[64];

Just as a side note, I think one instance of Snake_body can take up like 16 bytes, and you make 64 of them, this results in 1,024 bytes which is half the memory of an Arduino Uno. Also, sometimes a library takes up some space, so keep this in mind if you are intending to add more libraries/global variables or stack space.
Update
Also the following line seems wrong:
snake[0] = new Snake_body(0,0);

You already created 64 instances of Snake_body (and assigned to snake) after you do my change. So you do not need to do this yourself; actually you cannot, unless you create an array of POINTERS to Snake_body.

That is now so obvious that I see that. This was a silly mistake I did not see. Also you are 100% right in thinking that snake is an array of snake_body. I probably did it because I am used to doing arrays of integers. You are such a legend! Cheers!

One problem though, when I have done the line Snake_body snake[64];, it thinks it is a function

Can you add the line and exact error you get (it thinks it is a function, that's not enough for me to see what isi wrong)

I added an update.

Isn't snake[64] just an array that takes in snake objects. How would I exactly define snake[0] as a new snake object. snake[0] is supposed to be the front of the snake.

Would the pointer point at each snake object in the array?

You can write snake[0] = new Snake_body(...), however, than you should declar the type as Snake_body* snakes[64]';, and keep a variable to show how many of the elements are filled/used.

I have already created a mechanism to see how many elements are in the list. That is where  int snakes_length; comes in.

Problem is now solved but the program is still having some work done on it. Its up to the point of what my question is about.

Yes that int variable is a good way to keep track (so it's like a stack object). If the solution helped you upvote it please, and if it solves your problem, also accept the answer (you can click next to the answer). Good luck with your game (I guess) and enjoy Arduino Stack Exchange.


text:
Do passive buzzers require a PWM pin?
This guide   Shows how to wire a passive buzzer to be used with tone(). I notice they have it wired to D9, which is a PWM pin. But is it required to use a PWM capable digital output pin to play tones from a passive buzzer?

No, it doesn't need to be a PWM pin. tone() uses a timer and an interrupt to generate the audio signal and can work with any IO pin.


text:
Setting Time Function With DS3232 Library
I am trying to set the time on my DS3231, then read that time on my arduino nano. This is for a digital clock project. I am using DS3232 library by JChristensen.
He has an example that can set the DS3231 time through the serial monitor, and it works great, but I don't understand how to implement it into my sketch.
I can confirm that once the external RTC is set using said example, I can then upload my code, and the clock holds time when unplugged. It's setting the time within my sketch that I can't figure out. I've been at it for about 8 hours today and read through the github resources.
Here's my code. Towards the top you can see my attempt to set the system time, then set it to the RTC.
 #include "SevSeg.h";
    #include <DS3232RTC.h>; //Jack Christensen
    https://github.com/JChristensen/DS3232RTC
    #include <Streaming.h>; //Mikal Hart https://github.com/janelia-
     arduino/Streaming
    //Also requires time library https://github.com/PaulStoffregen/Time

    SevSeg sevseg;

    void setup() {
    // put your setup code here, to run once:

    //Serial.begin(9600);

    setSyncProvider(RTC.get);// the function to get the time from the RTC
    setTime(8,0,0,20,1,2020);
    time_t t = now();
    RTC.set(now());

     byte numDigits = 4;
     byte digitPins[] = {2, 3, 4, 5};
     byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12};
     bool resistorsOnSegments = false; // 'false' means resistors are on digit
     pins
     byte hardwareConfig = COMMON_CATHODE; // See README.md for options
     bool updateWithDelays = false; // Default 'false' is Recommended
     bool leadingZeros = false; // Use 'true' if you'd like to keep the leading
     zeros
     bool disableDecPoint = true; // Use 'true' if your decimal point doesn't
     exist or isn't connected. Then, you only need to specify 7 segmentPins[]

     sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins,
      resistorsOnSegments,
       updateWithDelays, leadingZeros, disableDecPoint);

    }

     void loop() {

    sevseg.setChars("hola");
    sevseg.refreshDisplay();

     if(millis()>6000) {

    int adj = 0;
    int timenumber;
    int hr = hourFormat12();
    int Min = minute();

    timenumber = (hr*100) + Min; //converts time into a number for the seven
    segment display

   sevseg.setNumber(timenumber);
   sevseg.refreshDisplay();
    }

    }

And JChristensen's Example Code:
// Arduino DS3232RTC Library
// https://github.com/JChristensen/DS3232RTC
// Copyright (C) 2018 by Jack Christensen and licensed under
// GNU GPL v3.0, https://www.gnu.org/licenses/gpl.html
//
// Example sketch to display the date and time from a DS3231
// or DS3232 RTC every second. Display the temperature once per
// minute. (The DS3231 does a temperature conversion once every
// 64 seconds. This is also the default for the DS3232.)
//
// Set the date and time by entering the following on the Arduino
// serial monitor:
//  year,month,day,hour,minute,second,
//
// Where
//  year can be two or four digits,
//  month is 1-12,
//  day is 1-31,
//  hour is 0-23, and
//  minute and second are 0-59.
//
// Entering the final comma delimiter (after "second") will avoid a
// one-second timeout and will allow the RTC to be set more accurately.
//
// No validity checking is done, invalid values or incomplete syntax
// in the input will result in an incorrect RTC setting.
//
// Jack Christensen 08Aug2013

#include <DS3232RTC.h>      // https://github.com/JChristensen/DS3232RTC
#include <Streaming.h>      // http://arduiniana.org/libraries/streaming/

void setup()
{
    Serial.begin(115200);

    // setSyncProvider() causes the Time library to synchronize with the
    // external RTC by calling RTC.get() every five minutes by default.
    setSyncProvider(RTC.get);
    Serial << F("RTC Sync");
    if (timeStatus() != timeSet) Serial << F(" FAIL!");
    Serial << endl;
}

void loop()
{
    static time_t tLast;
    time_t t;
    tmElements_t tm;

    // check for input to set the RTC, minimum length is 12, i.e. yy,m,d,h,m,s
    if (Serial.available() >= 12) {
        // note that the tmElements_t Year member is an offset from 1970,
        // but the RTC wants the last two digits of the calendar year.
        // use the convenience macros from the Time Library to do the conversions.
        int y = Serial.parseInt();
        if (y >= 100 && y < 1000)
            Serial << F("Error: Year must be two digits or four digits!") << endl;
        else {
            if (y >= 1000)
                tm.Year = CalendarYrToTm(y);
            else    // (y < 100)
                tm.Year = y2kYearToTm(y);
            tm.Month = Serial.parseInt();
            tm.Day = Serial.parseInt();
            tm.Hour = Serial.parseInt();
            tm.Minute = Serial.parseInt();
            tm.Second = Serial.parseInt();
            t = makeTime(tm);
            RTC.set(t);        // use the time_t value to ensure correct weekday is set
            setTime(t);
            Serial << F("RTC set to: ");
            printDateTime(t);
            Serial << endl;
            // dump any extraneous input
            while (Serial.available() > 0) Serial.read();
        }
    }

    t = now();
    if (t != tLast) {
        tLast = t;
        printDateTime(t);
        if (second(t) == 0) {
            float c = RTC.temperature() / 4.;
            float f = c * 9. / 5. + 32.;
            Serial << F("  ") << c << F(" C  ") << f << F(" F");
        }
        Serial << endl;
    }
}

// print date and time to Serial
void printDateTime(time_t t)
{
    printDate(t);
    Serial << ' ';
    printTime(t);
}

// print time to Serial
void printTime(time_t t)
{
    printI00(hour(t), ':');
    printI00(minute(t), ':');
    printI00(second(t), ' ');
}

// print date to Serial
void printDate(time_t t)
{
    printI00(day(t), 0);
    Serial << monthShortStr(month(t)) << _DEC(year(t));
}

// Print an integer in "00" format (with leading zero),
// followed by a delimiter character to Serial.
// Input value assumed to be between 0 and 99.
void printI00(int val, char delim)
{
    if (val < 10) Serial << '0';
    Serial << _DEC(val);
    if (delim > 0) Serial << delim;
    return;
}

Can you format your code a little bit? It is impossible to read it in this way... With wrong tabs and a lot of line feeds. An error is this: if(millis()>6000). This means that your loop will not do anything for 6 seconds and then it will refresh the display so fast as possible... If you just want update your clock, you can do it 1 time every second with a delay, or better, update the display only if the second value changed.

Do you understand, how the example sketch is setting the time? If yes, what exactly is your problem in implementing it?

It’s set through the serial monitor. So I need to make a function to send input to the serial. I haven’t yet figured out how the example code it able to do this

I figured it out. You must first set the built in arduino RTC using the time library, then set the DS3232 from there. It did not work for my code before because it has to be called outside of the setup function.
For instance, I made a function that adjusts the hour:
void adjHr() { //hour adjustment function

if(millis() >= time_now + period){
        time_now += period;
        time_now = millis();
        setTime(hour()+1,minute(),second(),day(),month(),year());
        RTC.set(now());
    }

My setup function also includes:
setSyncProvider(RTC.get);

Allows the code to get time from the DS3232.

it is not the best way

It is “a” way. But if you have a better way, do share and i’ll mark your’s as the answer

you have a better way in the code in question. tmElements_t

I assume you’re referring to using the serial monitor to set the time. That seems like a very straightforward way to do it, but I have yet to figure that out. For now, setting the time with my alternate method is good enough.

it has nothing to do with Serial. in the example the values are read from Serial (read by parseInt) and are set into the tmElements_t structure. but you can use the variables to set the elements of date and time.  Then the makeTime from TimeLib function calculates the 'epoch' value and it is set to RTC. the way in your answer will have a problem, because the time runs in TimeLib

What problem will it encounter? My clock seems to work just fine and holds time with the backup battery.


text:
Display a Random Number to Display for T Seconds With Millis() for Dice Roller
I'm coding an electronic dice roller for a project. At the press of a push button (A2), the code must display a random number to the two digit seven segment display for 20 seconds, then display blank.
Currently, my code will display a random number every t seconds while the button is continuously held. I would like the user to be able to press the button and release to let the code do it's thing.
What type of examples should I look at to achieve this? I'm quite a beginner at arduino code.
    #include "SevSeg.h"
SevSeg sevseg; //Instantiate a seven segment object

int displayPeriod = 1000; //button press delay
unsigned long time_now = 0;

long randNumber;

void setup() {

  pinMode(A2,INPUT);
 randomSeed(analogRead(3));

  byte numDigits = 2;
  byte digitPins[] = {2, 3};
  byte segmentPins[] = {4,5,6,7,8,9,10};
  bool resistorsOnSegments = false; // 'false' means resistors are on digit pins
  byte hardwareConfig = COMMON_CATHODE; // See README.md for options
  bool updateWithDelays = false; // Default 'false' is Recommended
  bool leadingZeros = false; // Use 'true' if you'd like to keep the leading zeros
  bool disableDecPoint = true; // Use 'true' if your decimal point doesn't exist or isn't connected. Then, you only need to specify 7 segmentPins[]

  sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments,
  updateWithDelays, leadingZeros, disableDecPoint);

}

void loop() {

if(digitalRead(A2) == HIGH){

  rollD20();

}

else{

  sevseg.setChars("");
  sevseg.refreshDisplay();
}

}

void rollD20(){

if(millis() >= time_now + displayPeriod){
        time_now += displayPeriod;
        time_now = millis();
        randNumber = random(21);
        }
        sevseg.setNumber(randNumber);
  sevseg.refreshDisplay();
  }

void testInput(){
sevseg.setNumber(0);
sevseg.refreshDisplay();
}

Note that analogRead(3) is a very poor entropy source. Timing the button press with micros() would be way better.

Why is it a bad source? From the arduino reference for the random() function: "If it is important for a sequence of values generated by random() to differ, on subsequent executions of a sketch, use randomSeed() to initialize the random number generator with a fairly random input, such as analogRead() on an unconnected pin." Edit: Nvm I understand why it's bad.

your code handles a button press, but it does not do anything with the button release  ... do not code for a button pressed state because that state lasts as long as the button is held ... code for transition between button released and button pressed because the transition happens only once and can only repeat if you release the button

@jsotola Yes I am currently reading on how to do that. I would love to be able to have the function finish it's code completely before going back to the main loop. Since writing this post, the code now has a for loop which is meant to display 29 random numbers back to back, then display the 30th number on the display. I can't seem to get it. What type of example should I look for?

I would recommend to not reinvent the wheel, and proper button management may not be so trivial. I would suggest this library to address your problem.

The problem is that your rollD20 function is only called when the button is pressed.  So once you release the button, it never goes back to that routine to finish.  You need to separate the calling of the function from the detecting of the button.
bool rollingDice = false;

void loop() {

if(digitalRead(A2) == HIGH){
  rollingDice = true;
}
if(rollingDice){
  rollD20();
}
else{
  sevseg.setChars("");
  sevseg.refreshDisplay();
}

And then in your rollD20 method you need to set that back to false when it is time to stop:
void rollD20(){
  if(millis() >= time_now + displayPeriod){
        time_now += displayPeriod;
        time_now = millis();
        randNumber = random(21);
        rollingDice = false;
        }
  sevseg.setNumber(randNumber);
  sevseg.refreshDisplay();
  }