body:
I am trying to create a circuit with one tactile pushbutton, and LCD and two sensors: 1) temperature, and 2) pulse sensor. When the circuit is on, the LCD initially shows the reading from the temp sensor, when the button is pressed the LCD shows the reading from the pulse sensor.

The code compiles, the LCD shows both of the temperature function and pulse reading work.

I attached a picture of the schematic of the circuit.

The problem is that when the button is pressed, it takes many pushing of the button for the circuit to go from temperature reading to pulse reading. I thought maybe debouncing the button was unnecessary so I tried to write a code without the code, but it made no difference. My coding skills are still in the beginner side but I am trying my best for my coding to make sense. I just need some guidance and advice on what the problem could be and how I can tackle the problem. My code is attached here:

```
#include <LiquidCrystal.h>
#define BUTTON 2

const int rs = 12, en = 11, d4 = 7, d5 = 6, d6 = 5, d7 = 4;
LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

//TEMPERATURE
const int tempPin = A0;              // LM35 in A0

int T1=60;

//PULSE
#define USE_ARDUINO_INTERRUPTS true    // Set-up low-level interrupts for most acurate BPM math.
#include <PulseSensorPlayground.h>     // Includes the PulseSensorPlayground Library.

int PulseWire = A1;                 // Pulse Sensor purple wire connected to analog pin A0
int blinkPin = 13;                // pin to blink led at each beat
int Threshold = 550;           // Determine which Signal to "count as a beat" and which to ignore.
// Use the "Gettting Started Project" to fine-tune Threshold Value beyond default setting.
// Otherwise leave the default "550" value.
PulseSensorPlayground pulseSensor;  // Creates an instance of the PulseSensorPlayground object called "pulseSensor"

//=========BUTTON DEBOUNCE============
boolean lastButton = LOW;     // last button state
boolean currentButton = LOW; // current button state
int switchMode = 1;             //cycle between function
//====================================
void setup()
{

  lcd.begin(16, 2);
  // Configure the PulseSensor object, by assigning our variables to it.
  pulseSensor.analogInput(PulseWire);
  //pulseSensor.blinkOnPulse(LED13);       //auto-magically blink Arduino's LED with heartbeat.
  pulseSensor.setThreshold(Threshold);

  // Double-check the "pulseSensor" object was created and "began" seeing a signal.
  if (pulseSensor.begin()) {
    Serial.println("We created a pulseSensor Object !");  //This prints one time at Arduino power-up,  or on Arduino reset.

  }//end if

}//end void setup()

//Debouncing Function
boolean debounce(boolean last) {
  boolean current = digitalRead(BUTTON);
  if (last != current)
  {
    delay(T1);         //wait #ms
    current = digitalRead(BUTTON); //read it again
  }//end if
  return current;     //return the current value
}//end boolean debounce

void setMode(int mode) {

  //TEMP ON
  if (mode == 1)
  {
    Serial.begin(9600);
    int value = analogRead(tempPin); // read the value from the sensor
    lcd.setCursor(0, 1);
    float millivolts = (value / 1024.0) * 5000;
    float celsius = millivolts / 10;
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Temp = "); lcd.print((celsius * 9) / 5 + 32);  lcd.print((char) 223); //turning the celsius into fahrehait
    lcd.print("F");
    lcd.setCursor(7, 2);
    lcd.print(celsius); lcd.print((char) 223);
    lcd.print("C");
    delay(1600);

    lcd.clear();
    delay(T1);
  }//end if TEMP ON

  //RED ON
  else if (mode == 2) {
    {
      Serial.begin(9600);
      int myBPM = pulseSensor.getBeatsPerMinute();  // Calls function on our pulseSensor object that returns BPM as an "int".
      // "myBPM" hold this BPM value now.

      if (pulseSensor.sawStartOfBeat()) {            // Constantly test to see if "a beat happened".
        Serial.println("♥  A HeartBeat Happened ! "); // If test is "true", print a message "a heartbeat happened".
        Serial.print("BPM: ");                        // Print phrase "BPM: "
        Serial.println(myBPM);                        // Print the value inside of myBPM.

        lcd.setCursor(0, 0);
        lcd.print("HeartBeat Found!");
        lcd.setCursor(4, 1);
        lcd.print("BPM: "); lcd.print(myBPM);

        delay(1600);
        lcd.clear();
        delay(T1);
      }//end if
    }//end setMode void function
  }
}
    void loop()
    {
      currentButton = debounce(lastButton); //read debounced state
      if (lastButton == LOW && currentButton == HIGH) /// if it was pressed
      {
        switchMode++;
      }
      //if cycled through the different options,
      //reset the counter to 0
      if (switchMode == 3) switchMode = 1;
      setMode(switchMode);
    }//end loop
```
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/h54HE.png

I also considered doing a switch case statement, but so far it hasn't worked either. Please let me know some ideas!

Thank you!!

title: Combining 2 sensors in one code with 1 push button

Answers: 2

body:
Your code has various issues, but the main one is that you can’t use `delay()` when you’re trying to more than one thing at a time. Delay causes your program to freeze, and not do anything else.

(Basically you should forget about the `delay()` function and never write any Arduino code that uses it. It is a code smell.)

You need to rewrite your code to record the value of `millis()` and then check back the next time through your loop function to see if enough time has passed. Do a Google search on “Arduino blink without delay” for an explanation of how to do this. Here’s an example article: https://learn.adafruit.com/multi-tasking-the-arduino-part-1/using-millis-for-timing

(Note that some solutions suggest that you increment a counter every time through your loop and see if some magic number of counts has gone past based on how frequently you expect your loop to be called. That is a bad approach. You want to use the `millis()` function.

body:
Your loop function needs to call debounce() and setMode() as often as possible, and none of your functions must use delay(). Instead, they compute the time elapsed since the last action, and if it is greater than what you now use as a delay value, perform its next action; otherwise, it should just return.

Just as a curiosity, your present code will probably function (better...) if you press and hold the button until you get a response, instead of press-and-releasing multiple times, hoping to get one. The latter way depends on your pressing the button just as the system is reading it, but the system reads it too infrequently for that to be workable, as you found out. The delay() calls are the reason.


body:
I've got the following module of SIM900a.

[![SIM90a Module][1]][1]

My connections are:

    VCC -> External 5 Volt 1.5 Amp Supply
    GND -> Common GND
    TX -> Arduino RX (Pin 0)
    RX -> Arduino TX (Pin 1)

I hear a ring when I call on the sim card that has inserted there. So it can register to a network successfully. I've uploaded a blank code in Arduino Uno to test `AT Commands`. But I'm not getting any response when I type `AT` on Serial Monitor. What am I doing wrong here?

  [1]: https://i.stack.imgur.com/YAxoU.jpg

title: Can't Interface SIM900a With Arduino Uno

Answers: 2

body: At first, make sure that the sim has connected to the network. For this, you can call to the sim number from another phone. If not ringing that means the sim wasn't able to connect with the network. For this check power supply, antenna etc. If ringing then there something wrong in connection or code. So cross check the connection and send `AT` to the module and wait for returned data. If no data returned, then there check connection again. If the returned data is `OK`, then it is ready to use. and if returned data is `ERROR` then Arduino have connected to sim module but sim network, power supply etc problem happening.

body:
I was facing the same issue and solved this issue when I have used softwareSerial.h library and used to connect TXD of sim900A with pin 13 and RXD of sim900A withpin 12 of ardunio MEGA.

You can also use 10 and 11 pins of mega instade of 12 and 13 i.e.

    #include <SoftwareSerial.h>      // Configure software serial por
    SoftwareSerial SIM900A(10, 11);  // (sim 900 connections RXD=>10 & TXD=>11)


body:
The problem of my code is in the serial monitor it print the not enough credits even i did not pressed the button. The output that i want is it must be print not enough credits when i pressed the button.

    #include <Servo.h>
    const int coinpin = 2;
    const int buttonPin = 7;

    // Variables
    volatile int credits = 0;
    int buttonState = 0;
    const int servoPin = 8;
     Servo servo;

    // Setup
    void setup() {
      servo.attach (servoPin);
      Serial.begin(9600);
      attachInterrupt(digitalPinToInterrupt(coinpin), coinInterrupt, RISING);
      pinMode(buttonPin, INPUT);
      servo.write(0);

    }

    // Main loop
    void loop() {

    Serial.println(credits);
    delay(2000);
    buttonState = digitalRead(buttonPin);
    if (buttonState == HIGH && credits == 5) {

      Serial.println(credits);
      servo.write(180);
      delay(1000);
      servo.write(0);
    }

    if(credits !=5) {
      Serial.println("NOT ENOUGH CREDITS");
      delay(2000);
    }

    }

    // Interrupt
    void coinInterrupt(){

      // Each time a pulse is sent from the coin acceptor, interrupt main loop to add 1 cent and flip on the LED
      credits = credits + 1;
    }

title: How to print not enough credits if the credits is not sufficient

Answers: 2

body:
The second if statement is standalone and not inside the button press check if statement so will always print 'not enough credit' whenever credit is not exactly 5.
You might also want to look at debouncing the button as you're liable to get multiple triggers on one press.

body:
Look at lines of code I marked:

[![Formatted code from the question][1]][1]

Each loop you check for credits being equal to 5, and if it's not equal to 5 you write "NOT ENOUGH CREDITS" You might want to modify your "if" structure to only check for credits when the button is pressed.

Immediately I see two bugs:

 1. What happens when number of credits is 6? Is it enough or not?
 2. What happens when user presses the button for 2 or more "loop"s?

The physical button press looks to the hardware as several consecutive button presses because the button "bouncess" under your finger. Fixing that issue is called "debouncing" and there are several ways to do that. Read more about that.

  [1]: https://i.stack.imgur.com/LpJVH.png


body: I need to implement CAN communication between two STM32F103 microcontroller boards. I am finding it difficult to get libraries for the same. Can anyone please suggest where I can find working CAN bus libraries for STM32F103?

title: CAN bus libraries for STM32F103 in Arduino IDE

Answers: 0


body:
I am an absolute beginner with Arduino IDE and I want to build an interesting device I stumbled upon on github
https://github.com/jstiefel/esp32_komoot_ble
Problem is I really can not add it to Arduino IDE. I did the wiring for the lcd and all, but please bear in mind i'm an electrician, with a very basic understanding of arduino/ absolute beginner.
What i'm asking is which is  the "main file" in the src folder so i can rename it 'ino' to work with the arduino IDE  and upload it to the esp32 board?
I downloaded the esp32 library and all the dependencies that says in the readme.md file. I download the esp32_komoot_ble.zip file. Now how do I get the  .cpp and .h files on the arduino IDE and finally my esp32 device. I have been watching tutorial for 1 week now  but could not figure it out yet!
Thank you for everything guys!

title: Adding esp32_komoot_ble library to Arduino IDE

Answers: 1

body:
The file, that you are searching, is the one, which contains the `setup()` and `loop` functions: `esp32_komoot_ble.cpp`

These functions are part of the Arduino framework and wrap the classic `main()` function. `setup()` is called once at startup, `loop()` after it repeating forever.


body:
I'm building a project that uses a couple of Adafruit DTH22 temp/humidity sensors. (https://www.adafruit.com/product/385)

I have them wired into my project box through 3.5mm mini plugs (The kind that are commonly used by stereo earbud headphones for MP3 players.)

More than half the time, when I plug/unplug one of my sensors, my Arduino restarts.

My guess is that as I plug in the plug, it sometimes momentarily shorts +5V and ground, causing the +5 source to my Arduino to lose voltage.

These sensors apparently draw single-digit mA of current at peak (like 1.5mA, according to the spec.)

Could I wire a 120Ω or 150Ω resistor in line with the ground connection to the DHT22? This would limit the max current it could carry to around 40mA, which would not be a problem for my power supply (which is fed through the USB port on the Arduino, and thus is limited to 500mA.) Putting a resistor on the ground would limit the current to ground from either the VCC connection to the sensor or the data connection. It would also cause a small loss of voltage to both the data line and the VCC connection.

Would the serial connection between the DHT22 and my Arduino tolerate a 120Ω resistor, even if I connect it via ≈15M of 28-gauge wire?

I could also put the resistor into the VCC wire, but that would only current-limit a VCC-to-ground short, not data-to-ground.

title: Can I put a resistor in the ground connection of my DHT22 sensor?

Answers: 1

body:
Your case :
   Check wire (shors ?) and pin configuration (out ??)

General :
 No resistor in a ground path.

 Decoupling supply :
  one can insert a 100 Ohms resistor between the arduino +5V and the +5V sensor : but ALWAYS use a decoupling capacitor : connect a 100µF betwen +5V sensor and groud. One can add a 100nF ceramic in paraller for digital devices.

 Safety in case of bad I/O config :
  Using a 1kOhms restisor between Arduino and Device is good, if next to the Arduino (not at the other end of sensor cable, or use 330 Ohms at eatch end of cable).


body:
Using a 28BYJ-48 Motor with a ULN2000 Driver. The motor works fine since I can rotate it using serial input.
Pushbutton is connected properly, Can light up an led if I connect one.
I want the motor to rotate 90 degrees everytime I push the button. When I run the code below the LEDs on the driver just blink rapidly, when I press and hold the button they stop blinking, keeping the state they were on already. e.g. if the LED A on the board was on at the moment I press the button, It stays on. If it was off, It stays off. you get the Idea.

code used:

    #include <Stepper.h>;

     // pushbutton pin
     const int buttonPin = 2;

     int STEPS = 32;
     Stepper stepper(STEPS,8,9,10,11);

    //create a variable to store a counter and set it to 0
    int counter = 0;
    void setup()
    {
      pinMode(buttonPin, INPUT);
    }

    void loop()
    {
     // local variable to hold the pushbutton states
      int buttonState;

      //read the digital state of buttonPin with digitalRead() function and store the           //value in buttonState variable
      buttonState = digitalRead(buttonPin);

      //if the button is pressed increment counter and wait a tiny bit to give us some          //time to release the button
      if (buttonState == LOW) // light the LED
      {
        counter++;
        delay(150);
      }

      if(counter == 1)
        stepper.step(512);  // zero degrees
      //else reset the counter to 0 which resets thr servo to 0 degrees
      else
       counter = 0;
    }

EDIT 1: Modifying the code @Matej gave me, I was able to debug the problem that was causing the stepper to not rotate. the code:

    #include <Stepper.h>

    // pushbutton pin
    const int buttonPin = 2;

    const int STEPS = 32;
    Stepper stepper(STEPS, 8, 9, 10, 11);
    int val = 2048;

    //create a variable to store a counter and set it to 0
    int counter = 0;

    unsigned long last_button_time = 0;   //for aving last millis

    void setup(){
      pinMode(buttonPin, INPUT);
      Serial.begin(9600);
      stepper.setSpeed(1000);
    }

    void loop(){
      bool buttonState;   // local variable to hold the pushbutton states

      //read the digital state of buttonPin with digitalRead() function and store the           //value in buttonState variable
      buttonState = digitalRead(buttonPin);
      //if the button is pressed incremen counter and wait a tiny bit to give us some          //time to release the button
      if(buttonState == HIGH && millis() - last_button_time > 200){ // light the LED
        last_button_time = millis();
        counter = 1;
        Serial.println(counter);
      }

      if (counter == 1) {
        Serial.println("Please Write the desired angle");
        val = Serial.parseInt();
        delay(5000);
        counter = 0;
        if(Serial.available() > 0) {
        Serial.println("Stepping: ");
        Serial.print(val);
        stepper.step(val);
        counter = 0;
        Serial.println(counter);
        }
        else {
          Serial.println("ERROR LOOPING THROUGH IF STATEMENT");
        }
      }

    }

The Serial output looks like this:

    1
    Please Write the desired angle
    Stepping:
    00
    1
    Please Write the desired angle
    Stepping:
    20480
    1
    Please Write the desired angle
    Stepping:
    20480

please note that In the first attempt, I wrote "2048" in Serial input to define the value of the integer (val), and nothing happened. in the second and third attempt, I also wrote 2048 (0 at the end is the counter variable) and the motor started shaking, but it didn't rotate.

title: Using pushbutton to make Stepper motor rotate 90 degrees

Answers: 2

body:
I edtied few things in your code. I am not sure if `LOW` value is correct, so I replaced it with `HIGH`. Second thing is timing. I removed all `delay()` functions instead of it you can see usage of `millis()`. That's for handling interval between button press and button release - second part of `if` will check if last time of button press is bigger than `200ms`, if yes, move stepper. Last things is stepping. You can see here `stepper.step(STEPS/4);`. `STEPS` is variable which you declared on the top of code. It's called steps per revolution, one revolution is `360°` so `90°` will be `STEPS/4`.

Here is the code, read it and test it:

```
#include <Stepper.h>;

// pushbutton pin
const int buttonPin = 2;

const int STEPS = 32;
Stepper stepper(STEPS, 8, 10, 9, 11);

//create a variable to store a counter and set it to 0
int counter = 0;

unsigned long last_button_time = 0;   //for aving last millis

void setup(){
  pinMode(buttonPin, INPUT);
  stepper.setSpeed(1000)
}

void loop(){
  bool buttonState;   // local variable to hold the pushbutton states

  //read the digital state of buttonPin with digitalRead() function and store the           //value in buttonState variable
  buttonState = digitalRead(buttonPin);

  //if the button is pressed increment counter and wait a tiny bit to give us some          //time to release the button
  if(buttonState == HIGH && millis() - last_button_time > 200){ // light the LED
    last_button_time = millis();
    counter++;
    stepper.step(STEPS/4);    //90° degrees
  }
}
```

body:
**Just a quick Tweak:**

Please note while using Adruino, using "INPUT" mode without enabling the internal pull-up resistor, you need to ensure that the switch is connected properly and that you have external pull-up or pull-down resistors in your circuit. In the code you provided, you haven't included the necessary external pull-up resistor.

To tweak and fix the code, here a simple quick option:

Usage of **"INPUT_PULLUP"** mode instead of **"INPUT"**:

This is the simpler and recommended approach. Just change the line:
```
pinMode(buttonPin, INPUT); to pinMode(buttonPin, INPUT_PULLUP);
```

It will enable the internal pull-up resistor of the Arduino, eliminating the need for external resistors in your circuit.

Here is quick fixed code:

```
#include <Stepper.h>;
// Using Stepper Motor to rotate 90 degree
// Reference: https://arduino.stackexchange.com/questions/61260/using-pushbutton-to-make-stepper-motor-rotate-90-degrees

// pushbutton pin
const int buttonPin = 2;

const int STEPS = 32;
Stepper stepper(STEPS, 8, 10, 9, 11);

//create a variable to store a counter and set it to 0
int counter = 0;

unsigned long last_button_time = 0;   //for having last millis

void setup(){
  pinMode(buttonPin, INPUT_PULLUP);
  stepper.setSpeed(1000)
}

void loop(){
  bool buttonState;   // local variable to hold the pushbutton states

  //read the digital state of buttonPin with digitalRead() function and store the           //value in buttonState variable
  buttonState = digitalRead(buttonPin);

  //if the button is pressed increment counter and wait a tiny bit to give us some          //time to release the button
  if(buttonState == HIGH && millis() - last_button_time > 200){ // light the LED
    last_button_time = millis();
    counter++;
    stepper.step(STEPS/4);    //90° degrees
  }
}
```

Connection Setup:

To connect an external switch to an Arduino using the internal pull-up resistor, ie. using "INPUT_PULLUP" instead of just "INPUT" in your above code, you will need to make the following connections:

1. Connect one terminal of the switch to the digital input pin on the Arduino. Let's assume you're using pin 2 for this example.

2. Connect the other terminal of the switch to ground (GND) on the Arduino.

With this connection setup, you're essentially creating a circuit where the switch is connected between the digital input pin and ground. When the switch is not pressed, the internal pull-up resistor will pull the input pin's voltage to a high level (logic HIGH). When the switch is pressed, it will connect the input pin to ground, resulting in a low level (logic LOW).

Alternatively, In case, you use "INPUT" instead "INPUT_PULLUP" which would not be a best approach here. You may follow the below example:

Here's an example of the circuit and code using an external pull-up resistor:

Circuit:

1. Connect one terminal of the switch to the digital input pin on the Arduino.
2. Connect the other terminal of the switch to the junction point between a pull-up resistor (e.g., 10K ohm) and Vcc (5V).

Code Example:
```
const int buttonPin = 2;  // Pin connected to the external switch

void setup() {
  pinMode(buttonPin, INPUT);
  digitalWrite(buttonPin, HIGH);  // Enable internal pull-up resistor
}

void loop() {
  // Read the state of the button
  int buttonState = digitalRead(buttonPin);

  // Perform your desired actions based on the button state
  if (buttonState == LOW) {
    // The button is pressed
    // Do something...
  } else {
    // The button is not pressed
    // Do something else...
  }
}
```

Kindly note to add below line of code inside void setup() to enable internal pull-up resistor as shown in above code
i.e.  **digitalWrite(buttonPin, HIGH);**  // Enable internal pull-up resistor

hope that helps. Great job Guyz, Happy coding.


body:
I have a certain bit of code that I believe after 10 seconds will send a high signal to the second digital pin for 50 seconds. After it will not do anything.

For some reason the nichrome wire is not heating up. I realize there could be a problem with my circuit but just want to make sure for the final time it is not an issue with my code. Thanks.

```
int nichromePin = 2;

unsigned long burnTime = 10000;
unsigned long dt = 50000;
unsigned long time;

void setup()
{
  pinMode(nichromePin, OUTPUT);
  Serial.begin(9600);
  Serial.println("Balloon Countdown...");
  Serial.print("When Will It Burn: ");
  Serial.println(burnTime);

}

void loop()
{
  time = millis();

  if (time > burnTime && time < burnTime+dt)
  {
  digitalWrite(nichromePin, HIGH);
  Serial.print("Time: ");
  Serial.println(time);
  }
}
```

title: Is my code triggering the N-Channel MOSFET as I have intended to

Answers: 1

body:
The code is as follows: After 10 seconds following Arduino power up, burn the nichrome for 60 seconds, after which do nothing. I just tested it on my UNO and it works fine, so it must be your circuit. Post your nichrome question in the EE forums for help on that.

P.S. This code is kinda silly tho there's no trigger event!


body:
I am new to Arduino and looking for advice if Arduino is the right microcontroller for this project.

My project is quite simple, I want to build 3 conveyors using 3 DC motors. At the end of each conveyor I plan to implement 3 IR break beam sensors to each respective conveyor to count when an object passes through. When **n** objects passes through each respective conveyor and falls into a catching mechanism the DC motor stops until object(s) are cleared. For the catching mechanism for each conveyor, I plan to use IR break beam sensors to detect if it’s cleared or not as well. (If you have an alternative suggestion to IR break beam sensors, please advice)

Question: Can a single Arduino uno microcontroller board handle this project? From what I know, Arduino can only run one program at a time and I’m not sure if my project can be run in one program; I believe it can. Additionally, what if I wanted to add a LCD display?

title: Conveyor and Counter Project

Answers: 1

body: Your project is pretty simple, and Arduino can handle it easilly. (Pretty much any microcontroller could do it) It's true that only ome program can be run at a time on Arduino (same as on 99% of other microcontrollers) but that one program can handle all three conveyors at the same time. Though I suggest using 3 different Arduinos and separating the systems. If somethig goes wrong on one conveyor it will not affect other ones. Price of Arduino is very low in comparison to price of industrial conveyors. (I didn't believe how much a meter of conveyor costs when you setup a facory line)


body:
Executing the following code always gives -511 as a result, I performed many tests, and it seems that results are correct from 0 * 0 to 181 * 181, beyond that, results are abnormal, I tried many types for the z variable (int, long, float) without success, any idea? I'm using the Arduino Uno.

    long z = 0;

    void setup() {

    Serial.begin(9600);

    }

    void loop() {

      z = 255 * 255;
      Serial.println(z);
      delay(200);

    }

title: Simple multiplication bug

Answers: 2

body:
Assuming long is 4 bytes, it should work.

However, if somehow a long type is only 2 bytes, or (more likely) you used another type or there is some wrong define/typedef, and it is a signed long (default if you do not used the unsigned keyword), the value range is -32,768 to 32,767 and 255 * 255 = 65,025 which is out of range.

So you can first try to use `unsigned long`.

body:
No, this is not a bug. You are using a compile time constant expression which is `signed int` unless told otherwise. Therefore you can only represent numbers between -32768 and 32767. Your computation of `255 * 255 = 65025` exceeds the range. Thus you see an overflow. In the C/C++ standard the overflow of signed types is actually undefined behavior. That means that the compiler is allowed to do anything from showing the correct answer to halt and catch fire. Only unsigned types with a known size like `uint16_t` have a well-defined overflow behaviour. You should promote your right hand side computation to unsigned type like this:

```
z = 255U * 255U;
````

This way you tell the compiler your intention and don't land in "Undefined-Behaviour-Land".


body:
When I load the Arduino IDE with `Board: Pololu A-Star 32U4` selected, I see:

```
The current selected board needs the core 'arduino:arduino' that is not installed.
```

I installed the board manually via [these instructions](https://github.com/pololu/a-star#manual-installation).

When verifying the initial empty sketch, I see:

    Arduino: 1.8.8 (Linux), Board: "Pololu A-Star 32U4"

    The current selected board needs the core 'arduino:arduino' that is not installed.
    /usr/share/arduino/arduino-builder -dump-prefs -logger=machine -hardware /usr/share/arduino/hardware -hardware /home/ravi/Arduino/hardware -tools /usr/share/arduino/tools-builder -libraries /home/ravi/Arduino/libraries -fqbn=pololu:avr:a-star32U4 -ide-version=10808 -build-path /tmp/arduino_build_299010 -warnings=none -build-cache /tmp/arduino_cache_842714 -prefs=build.warn_data_percentage=75 -verbose /tmp/untitled689103723.tmp/sketch_feb05a/sketch_feb05a.ino

    Selected board depends on 'arduino' core (not installed).

    Error compiling for board Pololu A-Star 32U4.

How do I prevent this error and compile a sketch?

Answers: 1

body:
I needed to install the boards package for:

    Arduino AVR Boards

Under Tools -> Board -> Board Manager


body:
Having the 11~ pin on OUTPUT mode that delivers a varying voltage (from 0 to 5 : 0 to 255).

and the A0 pin on INPUT mode to read the voltage, I find that the value read by A0 being either 0 or 1016 instead of it gradually taking multiple values between the two. what is the catch?

The circuit and the code i am using:

[![https://i.ibb.co/dDMJJCg/Cir.png][1]][1]

    int volt = 0;
    int sign = 1; //values: (1, -1), increments or decrements "volt" by 5.
    float potential;

    void setup() {

      pinMode(11, OUTPUT);
      pinMode(A0, INPUT);
      Serial.begin(9600);

    }

    void loop() {

    if (volt == 0){sign = 1;}
    if (volt == 255){sign = -1}

    volt = volt + sign * 5; //raises brightness to 255 from 0, then to 0 from 255.
    analogWrite(11, volt);

    potential = analogRead(A0);

    Serial.println(potential);

    delay(30);
    /*
    */

    }

  [1]: https://i.stack.imgur.com/XcDUv.png

title: AnalogRead value constant for a varying voltage (for LED brightness variation)

Answers: 2

body:
The PWM output pin does not vary voltage - it only outputs 0, or 5V. The amount of time that 5V is on, from 1/255 of about a 2mS period, to 255/255 of the same period, determines how bright the LED is perceived to be.

You really need a current limit resistor in series with the LED to keep from burning out the uC output pin, or from burning up the LED.

body:
As CrossRoads says, there really isn't any such thing as analog output on an Arduino. (Any Arduino unless it has a built-in DAC.) It uses pulse-width modulation to vary the "duty cycle" of the output from 100% on to 0% on, which simulates an analog voltage.

If you drive an LED with PWM (and the required current limiting resistor) your eyes will not see the flashes, and will average out the brightness based on the duty cycle of the PWM signal.

If you want an actual analog voltage from PWM you will need to add a filter capacitor to average out the voltage over time. With a simple single capacitor filter you'll still have flutter in the output but it will be closer. If you want a clean constant voltage you'll need a more complex filter.


body:
Given:

    const char* PROGMEM names[] = {"Foo","Bar"};
    Serial.print(names[0]);

I get garbage output. Is there some function that will print the string from PROGMEM? E.G.:

    Serial.print(<function name>(names[0]);

title: Printing elements of char array from PROGMEM

Answers: 2

body:
Among many others, check out pgmspace.h utilities at
[AVR-libc][1]

  [1]: https://www.nongnu.org/avr-libc/user-manual/modules.html

body:
    const char PROGMEM b0 = pgm_read_dword(&(names[0]));
    Serial.print(b0);


body:
I will implementate the GPRS technologity in my Arduino project, but before buy the module, I want to know which is a better. If GPRS SIM800L or GPRS SIM900? My needs are send JSON array through POST request.

Thanks and best regards.

title: Which is a better? GPRS SIM800L or GPRS SIM900?

Answers: 1

body:
SIM900 is older type. SIM800L has FM build it and it uses same AT cmds as SIM900.
Also, they are in same quadband. I guess both will work just fine.


body:
I have a beam sensor providing NPN and also PNP output. It as 4 wires and works on 24V. I hooked the brown(+) and blue(-) to a small 24V power supply and the sensor is working!!! Yeah!

Now I would like to recieve the signal in my arduino. I dont know where to plug the black and white and I dont want to frie everything. I know I need to have an NPN configuration but I dont know how to achieve that.

This is the sensor in question: https://literature.rockwellautomation.com/idc/groups/literature/documents/in/42ef-in005_-en-p.pdf

And a little shema of my conections:
[![Senseor setup][1]][1]

If someone could help me.
Thanks,
Nicolas

  [1]: https://i.stack.imgur.com/wKKhQ.jpg

title: NPN sensor to Arduino

Answers: 1

body:
I would connect the - from the supply and the sensor to Arduino Gnd.

Then the NPN output can pulldown an Arduino input with pullup resistor enabled.

Brown to 24V, Blue to Gnd, White to Arduino input.  No resistor to Brown. Black not used.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/UQnXJ.png)

<!-- End schematic -->


body:
The doubt was came in mind after seeing Arduino [documentation][1]. I have to turn my Arduino uno robot 20 degrees without using encoders. So I surfed on Internet for how can I do that. Interestingly I found the reference available on above link. They are not saying about any specific Arduino board. So I have to know that can I do this stuff on my Arduino uno? Also I have to know is that every Arduino comes with onboard compass?

  [1]: https://www.arduino.cc/en/Reference/RobotTurn

title: Is every Arduino comes with onboard compass?

Answers: 1

body:
No current Arduino board comes with an on-board compass. That function description comes from the documentation for the [Arduino Robot][1], which is a retired product.

There may be other "maker" dev boards, such as the [Adafruit Circuit Playground Express][2] which have on-board compass peripherals.

  [1]: https://www.arduino.cc/en/Guide/Robot
  [2]: https://learn.adafruit.com/circuit-playground-express-compass/overview


body:
I am planning to use an Arduino (Nano ideally, or Other) to send and receive information from several software serial ports to other arduinos, over their available pins, ideally 8 ports.

I could understand an Asynchrounous Communication having one *master* and 8 *slaves*, with the master enabling communication from one port, receiving the data from that port, and then move onto the next port, into a sampling loop.

The `SoftwareSerial` library allows to set up the pins individually, and set the `listen()` port (thanks Juraj).

I read the `AltSoftSerial` library handle [some of the limitations][1] of the `SoftwareSerial` library, but I just realized the pins cannot be configured (without... cloning the full library?).

Question is:

 - Option 1: Should I stick with the `SoftwareSerial` library?,
 - Option 2: Should I try the `AltSoftSerial` library, and figure how to duplicate it (i think this is a NO)?
 - Option 3: Understand that none of these libraries are prepared for this, and seek for other alternative?
 - Option 4: It is pointless to have several serial trunks in Arduino, if only one will work at a time, and should hence try to arrange just one serial trunk?

  [1]: https://1sheeld.com/arduinos-softwareserial-vs-altsoftserial-library-use-1sheeld/

title: Several Software Serial Ports

Answers: 2

body:
You could use a part with 2 hardware serial ports (Atmega1284P), and use a simple mux chip to switch between the slaves for the master to receive from, such as DG406
https://www.digikey.com/products/en/integrated-circuits-ics/interface-analog-switches-multiplexers-demultiplexers/747?k=dg406&k=&pkeyword=dg406&sv=0&pv1989=0&pv433=170&sf=0&quantity=&ColumnSort=0&page=1&stock=1&pageSize=25

Hardware serial will allow for faster comm's too, vs software serial.
1284P is Arduino friendly too.

body: I tried to use MIDI (which is quite slow: 31,250 bps), and that didn't work reliable with the software serial on the Arduino Uno. Since I wanted multiple ports, I switched to the Arduino Mega which has FOUR harware serial ports. I would suggest this above using so many software serial ports; it also will relieve your processor to use hardware serials.


body:
How can I figure out, if an Arduino UNO is defect?
Have on, which I can't upload sketches to.
It's not working on Windows, even on Linux.

Everytime the following warning appears:

    avrdude: stk500_cmd(): programmer is out of sync
    avrdude: stk500_loadaddr(): (a) protocol error, expect=0x14, resp=0x18

    avrdude: stk500_paged_load(): (a) protocol error, expect=0x14, resp=0x98
    avrdude: stk500_cmd(): programmer is out of sync
    avr_read(): error reading address 0x0000
        read operation not supported for memory "flash"
    avrdude: failed to read all of flash memory, rc=-2
    avrdude: stk500_disable(): protocol error, expect=0x14, resp=0xe6

I don't have a clue of how to fix it.
The IDE's version is 1.8.8

Is the Arduino Bricked? Restarting both systems, the Arduino IDE and even Arduino (Reset) didn't help.

~ JackyTech

title: Arduino UNO bricked?

Answers: 0


body:
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?

Answers: 1

body:
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);
      }
    }


body:
So I started working on a project of mine that is mostly software based which I have no problems with, but it includes electronics too. Where I am still learning a lot. Anyways, I have been trying to figure out why I couldn't properly communicate over serial to a hardware device over serial with my Arduino. Basically, I am connecting my hardware device to the Arduino using an Audio Jack.

The hardware device is running on 3.3v and the Arduino at 5v, which is probably the issue. But

Here the current Wiring:

[![wiring setup][1]

Audio Cable:

 - Rx = Green Wire
 - Tx = White Wire
 - GND = Blue Wire

I would really appreciate if someone helps me out with the following questions:

 - Is ground connected to where it's supposed to be?
 - Is the voltage a problem? If so, what kind of converter should I add?

Regards.

  [1]: https://i.stack.imgur.com/niVvK.jpg

title: Connecting Audio Jack to Arduino

Answers: 0


body:
I have a requirement to get RFID data on Arduido UNO and send it to ESP8266 to be sent to ThingSpeak via the Wifi module. However, ESP8266 is also programmed to send Temperature and humidity data to ThingSpeak and turn on a motor when temperature exceeds certain threshold.
I have followed this logic on ESP8266 loop
-

    if(millis() > time_now + period)
      {
        read temperature, humidity from DHT sensor
        Send only temp,humidity to ThingSpeak
      }
      // Outside millis()
      while (Serial.available())
      {
        Serial.readString() - to retrieve the User name sent by Arduino UNO
        Send only temp,humidity and UserId=1 to ThingSpeak
      }

However the whileloop is not executed as expected and is random. Since millis() is unblocked, my understanding is that while it is waiting and if there is data available on Serial, While loop is to be executed.
However, the readString() is not executed everytime data is available on Serial.
Full code on ESP8266 is below.
Any help is to identify the issue is much appreciated.

    #include <DHT.h>
    #include <DHT_U.h>
    #include <Stepper.h>

    #define DHTPIN 3  // what pin we're connected to D4
    #define DHTTYPE DHT11  // DHT 11  (AM2302)
    /*
    ULN2003 --- ESP-12F(WeMos D1 mini)
      ========   =======================
      IN1 >> GPIO 14 (D5)
      IN2 >> GPIO 12 (D6)
      IN3 >> GPIO 13 (D7)
      IN4 >> GPIO 15 (D8)
      VCC(+) >> ... 5V Prefer to use external 5V Source
      Gnd(-) >> GND (G)
     */
    #define IN1  14 // GPIO 14
    #define IN2  12 // GPIO 12
    #define IN3  13 // GPIO 13
    #define IN4  15 // GPIO 15

    #include <ESP8266WiFi.h>
    #include <SoftwareSerial.h>

    String apiKey = "API_KEY";     //  Enter your Write API key from ThingSpeak
    const char *ssid =  "WIFI_SSID";     // replace with your wifi ssid and wpa2 key
    const char *pass =  "WIFI_PWD";
    const char* server = "api.thingspeak.com";
    int uid =1;
    //Variables to store temperature and humidity
    float hum = 70.2;  //Stores humidity value
    float temp = 20.0; //Stores temperature value
    //Variable to store User Name
    String name =" ";
    int period = 1000; // delay period
    unsigned long time_now = 0;

    DHT dht(DHTPIN, DHTTYPE); // Initialize DHT sensor for normal 16mhz Arduino
    WiFiClient client;
    const int stepsPerRevolution = 512;  // change this to fit the number of steps per revolution
    // for your motor
    Stepper myStepper(stepsPerRevolution, 14, 13, 12, 15); // initialize the stepper library on pins 8 through 11:
    SoftwareSerial s(D3,D2);

    void setup() {
      // set the speed at 60 rpm:
      myStepper.setSpeed(60);
      // initialize the serial port:
      Serial.begin(9600);
      s.begin(9600);
      pinMode(IN1, OUTPUT);
      pinMode(IN2, OUTPUT);
      pinMode(IN3, OUTPUT);
      pinMode(IN4, OUTPUT);
      dht.begin();
      temp=dht.readTemperature();
      hum=dht.readHumidity();

      Serial.begin(9600);
      delay(10);
      Serial.println("Connecting to ");
      Serial.println(ssid);
      WiFi.begin(ssid, pass);

          while (WiFi.status() != WL_CONNECTED)
         {
                delay(100);
                Serial.print("*");
         }
          Serial.println("");
          Serial.println("***WiFi connected***");

    }

    void loop() {
      // Read temperature, humidity values from DHT sensor at constant intervals
      if(millis() > time_now + period){
            time_now = millis();
            //Read temp reading
            temp=dht.readTemperature();
            hum=dht.readHumidity();
            displayData( hum, temp);
      // Turn on motor to ON the fan when temperature exceeds 23
          if(temp > 23)
          {
            myStepper.step(stepsPerRevolution);
          }
          Serial.println("Sending only temp and hum data");
       //Send temp, humudity data to ThingSpeak
          String paramater2 = apiKey+"&field1="+String(temp)+"&field2="+String(hum)+"\r\n\r\n\r\n";
          sendToThingSpeak(paramater2);
       } //End of delay

       //Check if serial input available which is the User Id string sent by Arduino UNO on SoftwareSerial port
       if(s.available())
       {
        Serial.println("In ESP sketch.. Serial Available. Reading.....");
        //Read UID And store into String name
        name = s.readString(); //This works
        //Print name onto Serial monitor
        Serial.println(name); //This works
        //if UID available, send Temp, Humidity and Uid=1 to thingspeak
        String parameter1 = apiKey+"&field1="+String(temp)+"&field2="+String(hum)+"&field3="+String(uid)+"\r\n\r\n\r\n";
        Serial.println("Sending temp, hum and uid data");
        sendToThingSpeak(parameter1);
        Serial.println("Sending....");
       }

    }

    void displayData(float humidity, float temperature)
      {
        //delay(1000);
        //print to serial monitor
        Serial.print("Humidity: ");
        Serial.print(humidity);
        Serial.print(" %, Temp: ");
        Serial.print(temperature);
        Serial.println(" Celsius");
      }

      void sendToThingSpeak(String sendData)
      {
        if (client.connect(server,80))   //   "184.106.153.149" or api.thingspeak.com
          {
           Serial.println("Inside Send to thingspeak - Data Received");
           Serial.println(sendData);

           client.print("POST /update HTTP/1.1\n");
           client.print("Host: api.thingspeak.com\n");
           client.print("Connection: close\n");
           client.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n");
           client.print("Content-Type: application/x-www-form-urlencoded\n");
           client.print("Content-Length: ");
           client.print(sendData.length());
           client.print("\n\n");
           client.print(sendData);

           Serial.print("Temperature: ");
           Serial.print(temp);
           Serial.print("deg C. Humidity: ");
           Serial.print(hum);
           Serial.println(".. Connecting to Thingspeak.");
                  }
           client.stop();
      }

title: ESP8266 to send data to thingspeak while doing unblocked read on Serial.readString()

Answers: 0


body:
I cannot work this out!

My Ublox 7n GPS module will only print data in the serial monitor once when I either click reset on my Arduino Uno or reopen and close my Serial monitor.

So whenever I have the serial monitor open and click reset on my Arduino it quickly spits out all the data on it and then stops, same when I open the serial monitor after being closed.

Here is my code:

    #include "TinyGPS++.h"
    void displayInfo();
    const unsigned long PUBLISH_PERIOD = 1000;
    double latitude = 0, longitude = 0;
    TinyGPSPlus gps;
    unsigned long lastPublish = 0;

    void setup()
    {
        Serial.begin(9600);
    }

    void loop()
    {

        while (Serial.available() > 0) {

          if (gps.encode(Serial.read())) {
            displayInfo();
         }
        }
      delay(1000);
      Serial.println("new");
    }

    void displayInfo()
    {
      if (millis() - lastPublish >= PUBLISH_PERIOD) {
        lastPublish = millis();
        char buf[128];
        delay(1000);

        if (gps.location.isValid()) {
          snprintf(buf, sizeof(buf), "%lf,%lf", gps.location.lat(), gps.location.lng());
          //  Serial.println(buf);
         latitude = gps.location.lat();
         longitude = gps.location.lng();
         Serial.println(gps.location.lat());
         Serial.println(gps.location.lng());
         Serial.println(latitude, 8);
         Serial.println(longitude, 8);
          }
      else {
        Serial.println("no location");
      }
    }
    }

I've attached an image of my serial monitor, the gps data came through when I closed and reopened it.

[![Serial][1]][1]

  [1]: https://i.stack.imgur.com/uFsEp.png

title: GPS only works when I click Reset on Arduino or Reopen Serial Monitor

Answers: 0


body:
I want the same button to wake up (reset) and put it to sleep but this is hard if the button is tied directly to the rst pin. My thought was to read and store a value in EEPROM so tell the chip what mode we were in so it can perform the counter action. For example, on RST if the value is 0 the chip should wake up and do things. It would then set the value to 1. If the button is pressed again, the chip resets, reads there is a 1 and now just puts the chip into deep sleep after setting the value back to 0. Rinse, repeat.

Does this make sense? Will this work? Is there a better/easier way?

title: Store value in EEPROM to perform different actions on reset?

Answers: 2

body:
While it looks interesting as idea, IHMO you have keep in mind:

1. Include some code for button denouncing logic. Actually you will receive couple of “resets” during ~20ms during button press. Without denouncing you may end up with reset signal right at the moment you write to the EPROM. While EPROMs are pretty “solid” nowadays, it many not be good practice. One of potential solutions IMHO is to delay update EPROM with state switch for 20ms after boot, so it be done in stable state.

2. You may also consider to include electronic circuit to hold reset long enough to reboot the controller (it may also reduce bouncing).

3. EPROM has finite lifespan in terms of rewrite cycles, if your device turned on and off ~100 timers per day, it may die in a ~year.

4. Writing the EPROM usually consumes significant amount of energy, so it may reduce battery lifespan (if you use battery).

Probably more classic approach with sleep / wake up by button looks more reasonable, unless you have shortage of pins ;)

body:
Totally agree with Serge.
To cover issues #3 and #4 of Serge's answer I recommend you to have a look at [FRAM](https://www.fujitsu.com/global/products/devices/semiconductor/memory/fram/lineup/i2c-1m-rc1mt/press-new.html).
It has more durability with 10 trillions of write cycles.


body:
So if I have an IP address `IP Address: 192.64.5.1`, is it somehow possible to change a specific byte of that IP to like `IP Address: 192.64.**6**.1`

My idea is to change the IP Address into variables `IP Address: a.b.c.d`
Now I could say `a= 192; b= 64; c= 5 + 1; d= 1 `

But what if I receive the `IP Address: 192.64.5.1` as a String. Is it somehow possible to split it up into 4 parts that I can each individually assign to an integer (a, b, c or d)?

title: Change one specific byte of an IP address

Answers: 2

body:
Yes, you can split the string with the C library function `strtok`, than concatenate everything together with your own string with the C library `strcat`.
You can convert strings to `atoi`, so use the resulting string from strtok with atoi to an integer.

Tip: try it on a PC with a local C compiler, because you can check it very fast (unless you can implement it first time right). Than you copy it to your Arduino sketch. Make sure to start with a char buffer big enough for the biggest possible IP address string.

body:
You can do it all with the `IPAddress` class.

For instance: create an IP address from a string:

    IPAddress myAddr(myString);

Create a new IP address with one byte changed:

    IPAddress myNewAddr(myAddr[0], myAddr[1], myAddr[2] + 1, myAddr[3]);


body:
I am trying to determine the total pin power requirements for my Mega 2560 project; it will connect to 3 1m Neopixel strips and 5 RGB laser fiberoptic lights, and control them via PWM. Each strip and light will have its own external power supply. The laser lights will be controlled by an Adafruit TLC5947 LED Breakout board with 3 (R,G,B) inputs. Further, each laser light is turned on by a logic high command.

My questions are:
How can I determine the total pin outputs? Can all this be controlled safely from the Mega, or will I need to add transistors? I have read 200mA is the maximum for the Mega, however I have found a seemingly definitive post on Arduino.cc that states 800mA is the maximum.
https://forum.arduino.cc/index.php?topic=327742.0

here's my rough schematic:
[![enter image description here][1]][1]
Thank you in advance!

  [1]: https://i.stack.imgur.com/W7i2k.png

title: Mega 2560 pin output power and control question

Answers: 1

body:
Neopixels only need a control signal and Gnd when powered externally - connect the external power supply Gnd to the Mega Gnd as well.

The 2560 chip can definitely work with 800mA (200mA per VCC & Gnd pin, and there are 4 of each). The onboard supply can't cope with that - you get a max of 500mA from USB (due the 500mA PTC fuse, the big gold or green part next to the USB connector), or something under an 1000mA depending on how 5V is created. 12V into the barrel jack and high current will over heat the 5V regulator. 7.5V into the barrel will give you a better shot at high current. Then there is 1V rated reverse polarity protection diode between the barrel jack and the regulator.  You can't put 5V into the barrel and get 5V out, you need to overcome the diode and the regulator. 7.5V wallwarts work well for that. www.dipmicro.com used to carry 7.5V/1A wallwarts, I don't know if they still do.  If you decide to use an external 5V source via the power header, then the power headers are only rated for 1A current as well.
I use this one for 5V projects, 4A to power the Arduino, make yourself a power cord splitter and have 5V for other stuff as well direct from the wallwart, and not off the Mega board.

Are the lasers controlled by current into the R,G,B pins, or are they externally powered and R,G,B are just control signals? If their power comes from RGB, then you'll also want to power the TLC5947 seperately and just connect control signals and Gnd to the Mega.