message:
Attempts with Sainsmart Motor Shield Not Working

I received the sainsmart motor controller a few days ago, and am now having trouble testing it. The Arduino I am using is an Arduino Mega 2560. I thought it was an I2C communication issue but that wasn't working. So here I am now asking for help.
Here is my wiring.
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/cPkKU.jpg
Here is my code:

    #include <AFMotor.h>

    AF_DCMotor motor(2);

    void setup() {
     Serial.begin(9600);           // set up Serial library at 9600 bps
     Serial.println("Motor test!");

     // turn on motor
     motor.setSpeed(200);

     motor.run(RELEASE);
    }

    void loop() {
     uint8_t i;

     Serial.print("tick");

     motor.run(FORWARD);
     for (i=0; i<255; i++) {
      motor.setSpeed(i);
      delay(10);
     }

     for (i=255; i!=0; i--) {
      motor.setSpeed(i);
      delay(10);
     }

    Serial.print("tock");

    motor.run(BACKWARD);

     for (i=0; i<255; i++) {
      motor.setSpeed(i);
      delay(10);
     }

    for (i=255; i!=0; i--) {
      motor.setSpeed(i);
      delay(10);
     }

    Serial.print("tech");
    motor.run(RELEASE);
    delay(1000);
     }

**I also tried this one:**

    #include<AFMotor.h>
     AF_DCMotor motor2(2);
    void setup() {
     // put your setup code here, to run once:
     motor2.setSpeed(255);
    }

    void loop() {
     // put your main code here, to run repeatedly:
     motor2.run(FORWARD);
      }

**None of the two worked. If someone could help me that would be great. Thank You!!!**

body: I figured out the problem. One of the terminals was damaged during transportation. Now it's all good. Thanks for the help.


sender: user

message:
Consequences of dynamically changing input/output configurations of digital pin?

I am creating an IC checker for a large chunk of the 74ls series (basic TTL logic chips), which means that I have 14 pins running to the IC to verify its functionality. One pin is power (+5V) and another ground (GND), which are both consistently in the same seven and fourteen pin positions respectively, but the remaining 12 are various inputs and outputs that vary depending on the IC type.

With that stated, will there be any consequences to dynamically reconfiguring a pin from input to output -- or vice versa -- as different IC types are selected? Weird behavior or electrical failure? What if the IC remains plugged in while the the pins reconfigure? What if said IC is powered on and providing power to a pin as it reconfigures?

If you were curious, I am using a joystick and LCD display as an interface to selecting the appropriate IC to check.

sender: assistant

body: There's no problem reconfiguring pins.  It happens all the time.  One example is with ping sensors where the pin is used as an  output to send the ping and then switched to an input to wait for the response.  The only caveat is that you must be sure what you're connected to.  For instance, if you set a pin to OUTPUT and LOW and it just happens to be connected to a HIGH OUTPUT then you just fried your board.


message:
Sending a string from RPi to Arduino - Working Code

I've been researching for 2 days now trying to figure out how to receive a string via I2C on an Arduino. There are plenty of questions online but no real solutions or full tutorials... and sadly I threw my C++ book out years ago.

The code below compiles without error and receives the string correctly. (There are several commented out blocks that I've used to verify the data is being received.) The issue is printing the full received command string. I am unable to make it print in `receiveEvent()` or in the `loop()`. Ultimately I need it as a string such as "WIN-23-200" where I will explode the string by "-" to do something but I still can't get a hold of it.

If anyone can give me a nod in the right direction I'd appreciate it.

Thanks!

    #include <Wire.h>

    #define SLAVE_ADDRESS 0x04

    volatile boolean receiveFlag = false;
    char temp[32];
    String command;

    void setup() {
      // initialize i2c as slave
      Wire.begin(SLAVE_ADDRESS);

      // define callbacks for i2c communication
      Wire.onReceive(receiveEvent);

      Serial.begin(9600);
      Serial.println("Ready!");

    }

    void loop() {
      delay(1000);
      if (receiveFlag == true) {
        Serial.println("inFlag");
        Serial.println(command);
        receiveFlag = false;
      }
    }

    void receiveEvent(int howMany) {
      //works as expected
      /*while (0 < Wire.available()) { // loop through all
        char c = Wire.read();
        Serial.print(c);
        }*/

      int count = 0;
      while (0 < Wire.available()) { // loop through all
        temp[count] = Wire.read();
        count++;
      }
      //temp[32-1]='\0'; //make sure its 0 terminated, didn't matter
      command = temp; //put char array into a string variable named command

      Serial.print(temp); // prints nothing....

      //Verify Array is Loaded..works great.
      //for (int i = 0; i < count; i++)
      //{
      //  Serial.println(temp[i]);
      //}
      receiveFlag = true;
    }

body: onReceive is intended for use by slaves. master must request data from slave and wait for answer. look at MasterReader example from the Wire library


body:
Here's the working code.  The hangup was my Raspberry Pi Master was adding a "cmd byte" to the string before transit. So when I would send "test" the Arduino received 5 bytes; "0test".  Based on feedback here I added the null after ea char and then shifted the array to eliminate the first byte and the Serial.print started working.

Here's the working **RPi Master Python code**:

    # -*- coding: utf-8 -*-
    import smbus
    import time
    # for RPI version 1, use bus = smbus.SMBus(0)
    bus = smbus.SMBus(1)

    # This is the address we setup in the Arduino Program
    address = 0x04

    #http://www.raspberry-projects.com/pi/programming-in-python/i2c-programming-in-python/using-the-i2c-interface-2
    def writeData(value):
     byteValue = StringToBytes(value)
     bus.write_i2c_block_data(address,0x00,byteValue) #first byte is 0=command byte.. just is.
     return -1

    def StringToBytes(val):
            retVal = []
            for c in val:
                    retVal.append(ord(c))
            return retVal

    while True:
     print("sending")
     writeData("test")
     time.sleep(5)

     print('OPEN');
     writeData("OPEN-00-00")
     time.sleep(7)

     print('WIN');
     writeData("WIN-12-200")
     time.sleep(7)

And the **Arduino Slave Code**

    #include <Wire.h>

    #define SLAVE_ADDRESS 0x04

    volatile boolean receiveFlag = false;
    char temp[32];
    String command;

    void setup() {
      // initialize i2c as slave
      Wire.begin(SLAVE_ADDRESS);

      // define callbacks for i2c communication
      Wire.onReceive(receiveEvent);

      Serial.begin(9600);
      Serial.println("Ready!");

    }

    void loop() {

      if (receiveFlag == true) {
        Serial.println(temp);
        receiveFlag = false;
      }
    }

    void receiveEvent(int howMany) {

      for (int i = 0; i < howMany; i++) {
        temp[i] = Wire.read();
        temp[i + 1] = '\0'; //add null after ea. char
      }

      //RPi first byte is cmd byte so shift everything to the left 1 pos so temp contains our string
      for (int i = 0; i < howMany; ++i)
        temp[i] = temp[i + 1];

      receiveFlag = true;
    }

Hopefully this helps someone else, I searched for along time to put this together!


body:
sorry for posting here after years but i need some help

This is my arduino code, the raspberry pi code is the same as above.

#include <Wire.h>

#define SLAVE_ADDRESS 0x04

volatile boolean receiveFlag = false;
char temp[32];
String command;

void setup() {
  // initialize i2c as slave
  Wire.begin(SLAVE_ADDRESS);

  // define callbacks for i2c communication
  Wire.onReceive(receiveEvent);

  Serial.begin(1200);
  Serial.println("Ready!");

}

void loop() {

  if (receiveFlag == true) {
    Serial.println(temp);
    if (temp == 'test'){
      Serial.print("it works");
    }
    receiveFlag = false;
  }
}

void receiveEvent(int howMany) {

  for (int i = 0; i < howMany; i++) {
    temp[i] = Wire.read();
    temp[i + 1] = '\0'; //add null after ea. char
  }

  //RPi first byte is cmd byte so shift everything to the left 1 pos so temp contains our string
  for (int i = 0; i < howMany; ++i)
    temp[i] = temp[i + 1];

  receiveFlag = true;
}

i want to make it do something like just turning on an led when the received data is test (for example).I do receive the text (test) in the serial monitor but it does nothing when i used this command

if (temp == 'test'){
      Serial.print("it works");
    }

any help will be appreciated


message:
Change the sequence of LEDs with button press

I am new to arduino.
I have created a circuit , here is the image:
[![CIRCUIT][1]][1]

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

I want something that as I press the button the sequence of LEDs will change and as I press the button again , the sequence will change again.

I programmed code as following but it don't works correctly:

    int led1 = 11;
    int led2 = 10;

    int output = 2;
    int input = 4;
    int mode = 0;

    void setup() {
      pinMode(led1,OUTPUT);
      pinMode(led2,OUTPUT);
      pinMode(output,OUTPUT);
      pinMode(input,INPUT_PULLUP);
      digitalWrite(output,LOW);

    }

    void loop() {
      while(mode == 0 && digitalRead(input) == 1){
        digitalWrite(led1,HIGH);
        digitalWrite(led2,HIGH);
        delay(100);
        digitalWrite(led1,LOW);
        delay(100);
        digitalWrite(led1,HIGH);
        delay(100);
        digitalWrite(led2,LOW);
        delay(100);
        digitalWrite(led2,HIGH);
      }
      if(digitalRead(output) == 0){
        mode++;
        if(mode >= 2){mode = 0;}
      }
      while(mode == 1 && digitalRead(input) == 1){
        analogWrite(led1,255);
        delay(400);
        analogWrite(led1,150);
        delay(400);
        analogWrite(led2,255);
        delay(400);
        analogWrite(led2,150);
      }

    }

According to the above code , two leds led1 and led2 are connected with arduino. When the button is off the both LEDs turns on then led1 turns off then turn on again , next time led2 turns off and turns on again.As the button will be pressed , brightness of led1 will be less than the brightness of led2 and then
will again be equal to the brightness of led2, then brightness of led2 will be less than the brightness of led1 and then will be equal to the brightness of led1. But as I press the button , nothing happens but the led1 and led2 keeps turning on and off . However sometimes when I press the button then it works.

What is the problem with my code and how to solve it?

body:
Use a boolean:

    boolean blink = false;
    if(digitalRead(output) == 1){
        blink = !blink;
    }

    if(blink == true){
        digitalWrite(led1,HIGH);
        digitalWrite(led2,HIGH);
        delay(100);
        digitalWrite(led1,LOW);
        delay(100);
        digitalWrite(led1,HIGH);
        delay(100);
        digitalWrite(led2,LOW);
        delay(100);
        digitalWrite(led2,HIGH);
    }else{
        analogWrite(led1,255);
        delay(400);
        analogWrite(led1,150);
        delay(400);
        analogWrite(led2,255);
        delay(400);
        analogWrite(led2,150);
    }


body:
There are several issues that I can see.
To start with, you have the button wired to 2 pins, one configured as an input and one as an output. Starting out, you should connect the button as in the example below.
[![example of how to connect a button][1]][1]

This will read LOW until the button is pressed.

<del>I suspect in your case that because your using in INPUT_PULLUP, your button will read HIGH when the button isn't pressed, but will continue to read HIGH even after the button is pressed - which leads to the second issue of your first while loop - because mode is initialised to 0, and the button is always reading HIGH, the condition for your while loop will always be true, consequently, the loop will never exist.</del>

The next issue (if you change the code so the first while loop does exit) is that you're trying to do a digitalRead on an OUTPUT pin - as an OUTPUT pin, it will never detect the state of the button.

Another issue will be that when you press the button and the if statement is reached (because digitalRead(input) == 0), even if the button is pressed for the shortest time, the loop function will be run several times, and the if statement will be run several times which will effectively result in the mode containing either 0 or 1 almost at random.

While the best way to fix this is with an interrupt (another lesson for another day), a simple way is something like this:

        int buttonPressedProcessed = 0; // an indicator so we know if the button press has been processed.

    void setup() {
     ...
    }

    void loop() {
      while(mode == 0 && digitalRead(input) == 1){
     buttonPressedProcessed = 0; // reset button pressed and processed indicator
     ...
      }
            // check also the button pressed and processed indicator
      if(digitalRead(input) == 0 && buttonPressedProcessed == 0){
     buttonPressedProcessed = 1; // set button pressed and processed indicator
        mode++;
        if(mode >= 2){mode = 0;}
      }
      while(mode == 1 && digitalRead(input) == 1){
     buttonPressedProcessed = 0; // reset button pressed and processed indicator
     ...
      }
    }

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


body:
There are a few issues with your wiring.

* As already stated in comments, you should not connect the battery to
  the 5V input of the Arduino. Use the “Vin” input instead.
* You should put a current-limiting resistor in series with each of your
  LEDs. Any value in the range 330 Ω – 1 kΩ should be fine.
  Your Arduino (and your LEDs) will last longer if you stop abusing it!
* There is no point in using two digital IO pins to read a button. Just
  connect the button between a digital input and GND. Alternatively, you
  can wire it like in Holmez's answer, but that requires an extra wire
  and a resistor.

And there are two main issues with your code:

* You forgot to debounce the button. Mechanical button [are bouncy][].
  The easiest way to debounce them is to use a ready-made library like,
  e.g., [Bounce2][].
* You are using `delay()`, which means you cannot respond to user input
  while your Arduino is busy delaying. You should manage your timings
  with `milis()` instead, as explained in the [Blink Without Delay][]
  Arduino tutorial.

Here is my take at your problem. This is based on the
[finite state machine][] programming pattern, with a state defined by
two variables. There is a `mode` variable used to keep track of whether
we are in “digital” or in “analog” mode. And there is a “phase” variable
used to keep track of the phase along the blinking pattern. Phases 0
through 3 correspond to (LED1/LED2) in the states: (HIGH/HIGH),
(LOW/HIGH), (HIGH/HIGH), (HIGH/LOW). Note that, for simplicity, the LEDs
are controlled with `analogWrite()`, even in “digital” mode.

<!-- language: lang-c++ -->

 #include <Bounce2.h>

 const uint8_t BUTTON_PIN = 4;
 const uint8_t LED1 = 11;
 const uint8_t LED2 = 10;

 Bounce button;

 void setup()
 {
  button.attach(BUTTON_PIN, INPUT_PULLUP);
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  analogWrite(LED1, 255);
  analogWrite(LED2, 255);
 }

 /*
  * Vary the LED brightnesses along the following pattern:
  *
  *  phase:   0   1   2   3   0
  *          ___     ___________
  *  LED1:      \___/
  *          ___________     ___
  *  LED2:              \___/
  */
 void loop()
 {
  static enum { DIGITAL, ANALOG } mode = DIGITAL;
  static uint8_t phase = 0;
  static uint16_t phase_duration = 100;
  static uint8_t low_level = 0;
  static uint16_t last_change = 0;

  // Switch modes on button presses.
  button.update();
  if (button.fell()) {
   switch (mode) {
    case DIGITAL:
     mode = ANALOG;
     low_level = 150;
     phase_duration = 400;
     break;
    case ANALOG:
     mode = DIGITAL;
     low_level = 0;
     phase_duration = 100;
     break;
   }

   // Set initial phase.
   phase = 0;
   last_change = millis();
   analogWrite(LED1, 255);
   analogWrite(LED2, 255);
  }

  // Switch phase after phase_duration elapsed.
  if (millis() - last_change >= phase_duration) {
   last_change += phase_duration;
   phase = (phase + 1) % 4;
   switch (phase) {
    case 0:
     analogWrite(LED2, 255);
     break;
    case 1:
     analogWrite(LED1, low_level);
     break;
    case 2:
     analogWrite(LED1, 255);
     break;
    case 3:
     analogWrite(LED2, low_level);
     break;
   }
  }
 }

[are bouncy]: https://learn.adafruit.com/circuit-playground-digital-input/debouncing-inputs
[Bounce2]: https://github.com/thomasfredericks/Bounce2
[Blink Without Delay]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
[finite state machine]: https://hackingmajenkoblog.wordpress.com/2016/02/01/the-finite-state-machine/


message:
How to call an interrupt when any one of the 12 defined digital inputs go high?

I'm using an Arduino Mega 2560 board. I need to sense 12 digital pins (**pins 36-47**) coming from another board continuously and display power when they are low.

When any of the 12 pins go HIGH, an interrupt must be created. In the ISR part, I'll be making one new digital pin (**PIN 35**) go HIGH (this is initialized as low in setup function).

To reset from interrupt, I need to press the **"#"** key in the keypad. This should make PIN 35 go low again and program should function normally again.

This is my code without using Interrupt.

    #include "LiquidCrystal.h"
    #include <Keypad.h>

    // initialize the library by providing the nuber of pins to it
    LiquidCrystal lcd(8,9,4,5,6,7);
     const byte ROWS = 4; // four rows
    const byte COLS = 3; // three columns
    char keys[ROWS][COLS] = {
     {'1','2','3'},
     {'4','5','6'},
     {'7','8','9'},
     {'*','0','#'}
    };
    byte rowPins[ROWS] = {22, 24, 26, 28}; //connect to the row pinouts of the keypad
    byte colPins[COLS] = {30, 32, 34};     //connect to the column pinouts of the keypad

    Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
    float fwd_voltage = 0.0,rev_voltage = 0.0;
    float fpower,rpower;
    int sensorValue=0;

    void setup() {
      int i;
      for (i=36;i<48;i++) {
        pinMode(i,INPUT);
      }
      pinMode (35, OUTPUT);
      digitalWrite(35,LOW);
    }

    void reset () {
      while(1) {
        lcd.begin(16,2);
        lcd.setCursor(0,0);
        lcd.print("press # to reset");
        char key = keypad.getKey();
        if (key=='#') {
          digitalWrite(35, LOW);
          break;
        }
      }
    }

    void process(int pin, char* text) {
      if (digitalRead(pin) == HIGH && digitalRead(35)==LOW) {
        // Use HIGH instead of 1
        lcd.print(text);
        digitalWrite(35, HIGH);
        reset ();
      } else {
        int analog_value = analogRead(A0);//reading forward voltage
        int analog_valuer = analogRead(A1);//reading reverse voltage
        fwd_voltage = (analog_value * 5.0) / 1024.0;
        rev_voltage = (analog_valuer * 5.0) / 1024.0;
        fpower =  ((fwd_voltage)*(fwd_voltage)*10000);
        rpower = ((rev_voltage)*(rev_voltage)*10000);
        lcd.setCursor(0,1);
        lcd.print("REV= ");
        lcd.print(rpower);
        lcd.print("W");
        delay(500);
        lcd.setCursor(0, 0);
        lcd.print("FWD= ");
        lcd.print(fpower);
        lcd.print("W");
        delay(500);
      }
    }

    void loop() {
      lcd.begin(16,2);
      // set cursor position to start of first line on the LCD
      lcd.setCursor(0,0);
      process(36, "vswr");
      process(37, "thermal");
      process(38, "overdrive");
      process(39, "A1-B1 fault");
      process(40, "A1-B2 fault");
      process(41, "A1-B3 fault");
      process(42, "A1-B4 fault");
      process(43, "A2-B1 fault");
      process(44, "A2-B2 fault");
      process(45, "A2-B3 fault");
      process(46, "A2-B4 fault");
      process(47, "driver fault");
    }

How do I modify the program to add an interrupt so that my board works faster and efficiently? BTW I'm new to programming so there might be some mistakes in the program and also I didn't write the program small and efficient.

The interrupt service routine should consist of this part of the above program:

    lcd.print(text);
    digitalWrite(35, HIGH);
    reset ();

My interrupt should detect this part of the program.

    if (digitalRead(pin) == HIGH && digitalRead(35)==LOW)

body:
You are kind of unlucky. The ATmega2560 MCU has 32 pins capable of
generating interrupts (counting the INTn and PCINTn, not sure all of
them are routed to board headers), but none of the pins you have chosen
is interrupt-capable.

I suggest you combine your 12 signals, using external logic, into a
single interrupt signal. You would then, in the ISR, sort out which
individual signal triggered the interrupt. A pair of [74HC4075][] chips
should be enough to OR together the 12 inputs.

[74HC4075]: https://assets.nexperia.com/documents/data-sheet/74HC_HCT4075.pdf


body:
Get rid of the 2 `delay` calls in your `process()` function. You are just needing to display the error text, so you don’t really need interrupt speed.

You have a 1s delay In total for every time you call the `process()` function. That doesn’t seem necessary.


message:
Can we use analog input pins as a parameter of analogWrite() for PWM?

<!-- language: lang-c++ -->

    int led = A1;

    void setup() {
       pinMode(led, OUTPUT);
    }

    void loop() {
      analogWrite(led, 188.7);
      delay(100);
      analogWrite(led ,0);
      delay(100);
    }

Like this and it works! I mean I am getting the exact voltage as calculated while mapping 5V between 0-255

body:
On the Nano, only the pins D3, D5, D6, D9, D10 and D11 are PWM-capable.
If you try to `analogWrite()` to any other pin, you will get either
0 V (if you write any value less than 128) or 5 V (for any
other value).

If you get 3.7 V when 5 V is expected, that's because either
your power supply is too weak, or you are putting too a heavy load on
the pin.


message:
Read analog signal over the SPI bus using MCP3201 ADC and Arduino Uno

It is possible to use the SPI bus when the **Vref** of MCP3201 ADC is 2.5V?
On the setup i just finished, I used two linear regulators: **5V -> 3.3V** to power the *MCP602* op-amps and *MCP3201* ADC, and another one **5v -> 2.5V** for the Vref.
Everyone recommends to connect the Vref from MCP3201 to Arduino's 5V but this does not apply in my case.
[![enter image description here][1]][1]

[![enter image description here][2]][2]

The green connector is connected to **GND** and ADC's **Dout** where the measured voltage fluctuates from 0.180V when i touch the sensor and his shield, to 0.6V when i'm not touching those parts.
I have no ideea if this is a normal behaviour but everything looks fine to me.
Voltage measured at the output of A4 ( MCP3201 +IN ) is **0.85V** and the current **Iref** is **1mA**(through the yellow jumper) as they recommend.

Sorry if these details are a bit off-topic but i think they are relevant to the ADC role in this setup.

  [1]: https://i.stack.imgur.com/Qp8UV.png
  [2]: https://i.stack.imgur.com/nEsgg.jpg

body:
> It is possible to use the SPI bus when the Vref of MCP3201 ADC is 2.5V?

Of course it is. VREF is purely a reference voltage for taking measurements. It has no other role.

If you look at the functional block diagram from the datasheet:

[![enter image description here][1]][1]

You can plainly see that VREF is only connected to the DAC that is used as part of the SAR feedback loop. Everything else is fed from VDD

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


message:
Need to control 2 DC motors powered using arduino mini and l298n from about range of 100m

I need to control 2 DC motors which are arranged with arduino mini and L298N module from a distance of 100m wirelessly, what is the easiest and cheapest way of doing so?I checked RC controllers and xbee but they are way too expensive!
Any help will be appreciated!

body: The cheapest way is probably using nRF24L01+, a 2.4 GHz transceiver. It should be possible to communicate over 100 m, using a slow speed and without any obstacles in between. If you need a better/faster communication, either use a version with an external antenna and/or use other frequences (using different transceivers, below 1 GHz). The last options are more expensive.


message:
How to read ASCII values from AT24C32 IC using Arduino? And what is serial.begin(?) in that EEPROM?

#include<Wire.h>
    #include<Eeprom24C32_64.h>
    #define EEPROM_ADDRESS 0x000

    void setup() {
      Serial.begin(9600);
      eeprom.initialize();
      const word address = 0x000;
      const byte count = 94;
      byte inputBytes[count] = { 0 };
      byte outputBytes[count] = { 0 };
      Serial.println("Read bytes from EEPROM memory...");
      eeprom.readBytes(address, count, outputBytes);
      Serial.println("Read bytes:");
      for (byte i = 0; i < count; i++) {
        Serial.write(outputBytes[i]);
        Serial.print(" ");
      }
      Serial.println("");
    }

    void loop() {
    }

Next code... I have tried many sketches.

    #include <EEPROM.h>

    void setup () {
      Serial.begin (115200);
      Serial.println ();
      for (int addr = 0x0000; addr < 0x0010; addr++) {
        Serial.print ("Address = ");
        Serial.print (addr, HEX);
        Serial.print (", value = ");
        Serial.println (EEPROM.read(addr), HEX);
      }
    }  // end of setup

    void loop () {
    }

And most of the sketches check the internal EEPROM of the Arduino, not the external, stored on address 0x000. I want to read data from external AT24C32.

[![enter image description here][1]][1]

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

body:
You have to know what the I2C address of your EEPROM is. Right now you have

    #define EEPROM_ADDRESS 0x000

The [example from the library you cite][1] has this:

    /**************************************************************************//**
     * \def EEPROM_ADDRESS
     * \brief Address of EEPROM memory on TWI bus.
     ******************************************************************************/
    #define EEPROM_ADDRESS 0x50

Then, you have to create an instance of the `Eeprom24C32_64` object:

    static Eeprom24C32_64 eeprom(EEPROM_ADDRESS);

That sets up the object for the EEPROM on the right I2C address, so you can later use the `eeprom` object to read and write.

  [1]: https://github.com/jlesech/Eeprom24C32_64/blob/master/examples/WriteReadBytes/WriteReadBytes.ino


message:
How to read Serial data when multiple functions are Running?

I want to **halt the execution** of that code, when arduino is receiving **serial data** for the execution. Right now the Serial data runs when the other code has completed its execution. How can I do it ?

    void loop() {
        dmd.setBrightness(brighVal); // set the brightness to led matrix
        scroll();  //function to scroll message

    }
    void serialEvent() {
      while (Serial.available()) {
        Jsondata = Serial.readString(); //reading json data from APP
        DynamicJsonBuffer jsonBuffer;
        Serial.println(Jsondata);
        JsonObject& root = jsonBuffer.parseObject(Jsondata);
        if (root.containsKey("BiM")) {
          brighVal = root["BiM"];
          switch (brighVal) {   // set's the value of brightness according to brighVal
            case 0:
              brighVal = 2;
              break;
            case 1:
              brighVal = 10;
              break;
            case 2 :
              brighVal = 25;
              break;
            case 3 :
              brighVal = 200;
              break;
          }
        }
      }
    }
    void scroll() {
      dmd.clearScreen( true );
      dmd.selectFont(Arial_Black_16);
      dmd.drawMarquee("Scrolling Text", 17, (32 * DISPLAYS_ACROSS) - 1, 0);
      long start = millis();
      long timer = start;
      boolean ret = false;
      while (!ret) {
        if ((timer + 30) < millis()) {
          ret = dmd.stepMarquee(-1, 0);
          timer = millis();
        }
      }
    }

body:
Then let scroll return immediately

    void scroll() {
        static long timer = 0;
        static boolean scroll = true;
        if(scroll){
            dmd.clearScreen( true );
            dmd.selectFont(Arial_Black_16);
            dmd.drawMarquee("Scrolling Text", 17, (32 * DISPLAYS_ACROSS) - 1, 0);
            scroll = false;
            timer = millis()
        }else {
            if ((millis() - timer) > 30)  {
                scroll = dmd.stepMarquee(-1, 0);
                timer = millis();
            }
        }
    }

The `static` keyword means that the value of the variable will be kept across calls.

I used the fact that it will be called in a loop to remove the while loop inside. I split the function up into 2 parts: The reset and the update. We first run the reset to init the marquee. After the reset it will set the boolean so the next time it will enter the update part. Then I used the exit condition of the original loop to make it reenter the update part next time.


message:
Fill an Array with Values

I have a function in which I change the pinMode on many of my Arduino's pins based on a passed in mode. I first construct an array of bytes specifying each pin to be an input or an output and then I iterate through the array to set all the pins.

    void pinout(byte mode) {
      switch(mode) {
        case 0: char pins[13] = {'O','O','I','I','O','I','I','I','I','O','I','I','O'}; break;
        case 1: char pins[13] = {'O','I','I','O','O','I','O','O','I','O','I','O','I'}; break;
      //etc..
      }
      for(byte i = 0; i <= 13; i++) {
        if(pins[i] == 'I') pinMode(i, INPUT);
        else pinMode(i, OUTPUT);
      }
    }

However, since the array is defined inside the switch statement, I loose scope of the pins array when I move onto the for loop. I tried defining the `pins[]` outside of the switch statement, but then I am confused on how to populate it efficiently. These all threw errors when I tried to populate the variable inside the switch statement:

    pins[0,1,2,3,...,12,13] = {...};
    pins[13] = {...};
    pins[] = {...};
    pins = {...};

I know I could go through each entry individually, but this could be rather inefficient use of memory and computational power as I add more cases. Any ideas?

body:
> I know I could go through each entry individually, but this could be
> rather inefficient use of memory and computational power as I add more
> cases.

The compiler produces assembly/machine code that takes the same effort to load the array, so it's not that inefficient. The bracket arrangement is just a construct for easier to read code.


body:
Since your values are all constant you can define them all as constant values and just select between them. The simplest way is to add an extra dimension to your arrays:

    const char pins[2][13] =
        {'O','O','I','I','O','I','I','I','I','O','I','I','O'},
        {'O','I','I','O','O','I','O','O','I','O','I','O','I'}
    };

    for(byte i = 0; i < 13; i++) {
        if(pins[mode][i] == 'I') pinMode(i, INPUT);
        else pinMode(i, OUTPUT);
    }

**(Note: An array of size 13 has entries 0-12.)**

However, that is very inefficient.  Since you only have two states, I and O, and there are only 13 entries, you can store each array as a single 16-bit value:

    const uint16_t pins[2] = {
        0b0110111101100,
        0b1010100100110
    };

    for(byte i = 0; i < 13; i++) {
        if((pins[mode] & (1 << i)) pinMode(i, INPUT);
        else pinMode(i, OUTPUT);
    }

**(Note: the data is stored backwards - pin 0 is on the right, pin 12 on the left.)**


message:
Battery life with Nano v3

[Easy secret knock detector to trigger anything with only an Arduino and a few cheap components
][1]

First of all I need to state that I'm new to Arduino and electronics in general. My question is about a project where the Nano is being powered up with a 12v rechargeable li-ion 2800 mAh battery on pins VIN and GND.

I'm using the 5v Nano pin to power a SRD-05VDC-SL-C relay along with the ground pin from the Nano. The IN pin on the relay is from the D11 pin on the Nano. So far so good. I'm also using the same 12v battery to power up a solenoid latch, which energizes for just a few seconds.

When I tested this setup (less the relay AND solenoid) for battery life, my volt meter read 9.8v and 1 hour later 2.8v. causing the Nano to go off.

How can I increase battery life?

This is the link to the code I used:

[![Hand drawn wiring diagram][2]][2]

  [1]: https://www.youtube.com/watch?v=-TQpgyTgcQ8
  [2]: https://i.stack.imgur.com/EKmGh.jpg

I'm not having an issue with the code or the operation of the setup but the battery life is unacceptable.

body:
Something is wrong with your setup. I don't have a Nano to hand to test, but it would consume similar current to a Uno (probably less) which is around 50 mA. Thus, using a 2800 mAh battery you should have a life of 2800/50 = 56 hours.

Li-ion batteries come in multiples of cells, where individual cells have a nominal voltage of 3.6V (thus you probably have three cells giving 10.8V). Deeply discharged they will have a voltage of 3.0V per cell (a total of 9V for your three cells). If you started at 9.8V as you stated, then the cells would have been 90% discharged already which probably accounts for the short running time.

Assuming you haven't wired it in a strange way (and it would help to show the wiring and possibly a photo) I suggest you try with a fully-charged battery.

---

Another helpful thing to do would be to measure the current consumption of the battery using a multimeter. Make sure you read up on how to measure current with a meter or you may damage something (example [here](http://www.dummies.com/programming/electronics/how-to-measure-current-on-an-electronic-circuit/)).

The basic idea is shown in this photo:

[![Measuring current][1]][1]

The meter is placed in *series* with the battery and the Arduino. The negative side of the battery goes to the Arduino in the usual way. The positive side of the battery goes into the "milliamps" input of the meter (which is set to 200 mA range in my case) and then the common (black) lead from the voltmeter goes to the positive (Vin) side of the Arduino.

You can see that in this particular case, with a 9V battery, the Arduino is consuming 57.7 mA.  I don't quite believe that reading as re-measuring with a more expensive meter gave a reading of 51.1 mA. Still, that gives you a ball-park figure. And it shows that spending a bit more on a better meter gives you more accurate results. :)

---

I have [a page about power saving](http://www.gammon.com.au/power) and you can also refer to [the Wikipedia page about Li-ion batteries](https://en.wikipedia.org/wiki/Lithium-ion_battery).

---

> my volt meter read 9.8v and 1 hour later 2.8v. causing the Nano to go off.

For a 12V Li-ion battery get down to 2.8V there is something seriously wrong with its protection circuitry. It should cut the battery out at 3V per cell, that is at 9V if you have 3 cells in series.

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


message:
Can we use serial.begin command anywhere in code?

When to use this command? What difference it would create if I add this command in loop function, setup function and declaration section?

body:
Serial.begin sets the baud rate. And the baud rate is important to the other side of the line. You can use Serial.begin where you need it, only care that the other side of the line has that baud rate too.

I use Serial1.end and Serial1.begin to change the baudrate in a [Firmata sketch for Uno WiFi][1]. Some seconds after the start the sketch detects esp flashing sequence on Serial. If detected, the sketch switches the baudrate of Serial1 from Firmata's optimal 57600 to bridge the flashing of esp at 230400 baud.

  [1]: https://github.com/jandrassy/UnoWiFiDevEdSerial1/blob/master/examples/UnoWiFiFirmata/UnoWiFiFirmata.ino


body:
You cannot call `Serial.begin()` in a declaration. Like any program
instruction, you can only use it from within a function. As stated in
Juraj's answer, you can call it as many times as you want. However,
most often it only makes sense to do this in `setup()`, in order to
initialize the serial link once and for all at the beginning of your
program. Why would you ever want to do this initialization multiple
times?

Thinking about it, I can see two possible scenarios:

1. Your UART is connected, through a suitable transceiver, to an RS-485
   bus. You have several slaves on this bus that require different UART
   configurations (different baud rates, or number of data bits, or
   parity). Then, each time you want to address one slave, you first
   set your UART to the configuration suitable for that particular
   slave. In this kind of situation, however, it would be more
   convenient to arrange for all the slaves to share the same UART
   configuration, if at all possible.

2. Your UART is connected to a device that continually sends data you
   are not interested in. This could be, e.g., a GPS module. Since you
   don't want your program to be interrupted every time a character is
   received, you keep the UART disabled. Only when you do want the data
   you enable it with `Serial.begin()`, you read as much as you need,
   then you disable it again with `Serial.end()`.

There may be other situations, but I bet they are all quite atypical
scenarios. The common practice is to call `Serial.begin()` once in
`setup()`, and have the UART enable from there on.


message:
How to connect an Arduino via an ethernet cable to a laptop directly?

Maybe a silly question, because it is a usual topic, but I have a problem with my Arduino Leonardo ETH.

I want to create a web server on the Arduino with the example sketch `File > Examples > Ethernet > WebServer`. I plugged in the ethernet cable directly to my laptop. So there is no router or switch between them.

I also set the configuration to my ethernet port to the following IPv4 properties:
[![Properties of internet protocol version 4][1]][1]

Then in the example sketch, I changed the MAC address according to the bottom sticker of my Arduino.

    byte mac[] = {0x90, 0xA2, 0xDA, 0x11, 0x33, 0xD6};
    IPAddress ip(192, 168, 1, 177);

Now when I compile and upload the sketch to the Arduino, everything is working fine until it prints the IP address. According to the IP address which I have set in the code (`192.186.1.177`), it shows me `0.46.46.46` as you can see in the picture:

[![Serial Monitor output][2]][2]

This happens when I print that:

    Serial.println("server is at ");
    Serial.println(Ethernet.localIP());

Do you have any ideas how I could fix this? And why does it show me that invalid IP address?

Thank you in advance.

  [1]: https://i.stack.imgur.com/FUcIw.png
  [2]: https://i.stack.imgur.com/6Jn9g.png

body: use the Ethernet2 library for W5500


message:
LSM9DS1: Inconsistent data from an accelerometer

I'm currently getting inconsistent data from the accelerometer of my Adafruit LSM9DS1. To be more precise I either get a value close to the correct gravity (eg. 9.496515) or some reading like it was in space/free fall (eg. -0.023928225).

This seems to happen on all three the axes (I tried rotating the LSM9DS1).

I get the same behavior with FIFO enabled or not and with the Gyro enabled or not.

This is a set of 32 consecutive samples that I read from the FIFO memory:

    result = {float[32][]@5092}
     0 = {float[3]@5100}
      0 = -0.41754755
      1 = 0.19501504
      2 = 9.519247
     1 = {float[3]@5112}
      0 = -0.421735
      1 = 0.19980069
      2 = 9.51805
     2 = {float[3]@5120}
      0 = -0.4229314
      1 = 0.20757735
      2 = 9.510274
     3 = {float[3]@5128}
      0 = -0.4127619
      1 = 0.2207379
      2 = 9.502497
     4 = {float[3]@5139}
      0 = -0.39302114
      1 = -0.06580262
      2 = -0.0017946169
     5 = {float[3]@5140}
      0 = -0.06939186
      1 = -0.045463633
      2 = -0.020937197
     6 = {float[3]@5141}
      0 = -0.05742774
      1 = -0.03469593
      2 = -0.0317049
     7 = {float[3]@5142}
      0 = -0.053838514
      1 = -0.039481573
      2 = -0.041874394
     8 = {float[3]@5143}
      0 = -0.054436717
      1 = -0.052642096
      2 = -0.043669015
     9 = {float[3]@5144}
      0 = -0.059820566
      1 = -0.068793654
      2 = -0.03469593
     10 = {float[3]@5145}
      0 = -0.06819545
      1 = 0.22731815
      2 = -0.019142581
     11 = {float[3]@5146}
      0 = -0.38644087
      1 = 0.2225325
      2 = -0.00418744
     12 = {float[3]@5147}
      0 = -0.40079778
      1 = 0.21535406
      2 = 9.505488
     13 = {float[3]@5148}
      0 = -0.40977085
      1 = 0.21355942
      2 = 9.525827
     14 = {float[3]@5149}
      0 = -0.40917268
      1 = 0.21296123
      2 = 9.540783
     15 = {float[3]@5150}
      0 = -0.40558344
      1 = 0.2207379
      2 = 9.5455675
     16 = {float[3]@5151}
      0 = -0.39960137
      1 = 0.22671993
      2 = 9.544371
     17 = {float[3]@5152}
      0 = -0.39302114
      1 = 0.22791636
      2 = 9.534203
     18 = {float[3]@5153}
      0 = -0.3906283
      1 = 0.21535406
      2 = 9.517452
     19 = {float[3]@5154}
      0 = -0.38584265
      1 = 0.19441684
      2 = 9.496515
     20 = {float[3]@5155}
      0 = -0.384048
      1 = 0.17347965
      2 = -0.023928225
     21 = {float[3]@5156}
      0 = -0.38883367
      1 = 0.15553348
      2 = -0.042472597
     22 = {float[3]@5157}
      0 = -0.39541394
      1 = -0.014356935
      2 = -0.05802595
     23 = {float[3]@5158}
      0 = -0.40259242
      1 = -0.026919257
      2 = -0.06580262
     24 = {float[3]@5159}
      0 = -0.40977085
      1 = -0.03589234
      2 = -0.071186475
     25 = {float[3]@5160}
      0 = -0.4151547
      1 = -0.040677987
      2 = -0.062213387
     26 = {float[3]@5161}
      0 = -0.421735
      1 = -0.03888337
      2 = -0.04965107
     27 = {float[3]@5162}
      0 = -0.42831525
      1 = -0.040677987
      2 = -0.032303106
     28 = {float[3]@5163}
      0 = -0.4372883
      1 = -0.04426722
      2 = -0.014356935
     29 = {float[3]@5164}
      0 = -0.445065
      1 = -0.04785645
      2 = 9.496515
     30 = {float[3]@5165}
      0 = -0.44865423
      1 = -0.04666004
      2 = 9.503693
     31 = {float[3]@5166}
      0 = -0.44865423
      1 = -0.04426722
      2 = 9.506086

As you can see 15 times the Z axis shows the correct value and 17 shows -0.

This is how I'm initializing the sensors:

            // soft reset & reboot accel/gyro
            writeRegByte(SensorType.XG, REGISTER_CTRL_REG8, (byte) 0b00000101);
            // soft reset & reboot magnetometer
            writeRegByte(SensorType.MAG, REGISTER_CTRL_REG2_M, (byte) 0b00001100);

            SystemClock.sleep(10);

            byte idXg = readRegByte(SensorType.XG, REGISTER_WHO_AM_I_XG);
            byte idMag = readRegByte(SensorType.MAG, REGISTER_WHO_AM_I_M);
            if (idXg != XG_ID || idMag != MAG_ID) {
                throw new IllegalStateException("Could not find LSM9DS1, check wiring!");
            }

            setFifoMemoryEnabled(false);

            // enable gyro continuous
            writeRegByte(SensorType.XG, REGISTER_CTRL_REG1_G, (byte) 0b11000000); // on XYZ

            // Enable the accelerometer continuous
            writeRegByte(SensorType.XG, REGISTER_CTRL_REG5_XL,
                    (byte) (CTRL_REG5_XL_ZEN_XL | CTRL_REG5_XL_YEN_XL | CTRL_REG5_XL_XEN_XL)); // enable X Y and Z axis
            writeRegByte(SensorType.XG, REGISTER_CTRL_REG6_XL, (byte) 0b11000000); // 1 KHz out data rate, BW set by ODR, 408Hz anti-aliasing
            writeRegByte(SensorType.XG, REGISTER_CTRL_REG7_XL, (byte) 0b10000000); // HR - High resolution mode

            // enable mag continuous
            writeRegByte(SensorType.MAG, REGISTER_CTRL_REG3_M, (byte) 0x00); // continuous mode

And this is how I'm reading the accelerometer data:

            byte[] buffer = new byte[6];
            int[] result = new int[3];
            readRegBuffer(SensorType.XG, REGISTER_OUT_X_L_XL, buffer, buffer.length);
            result[0] = (buffer[1] << 8) | buffer[0]; // Store x-axis values
            result[1] = (buffer[3] << 8) | buffer[2]; // Store y-axis values
            result[2] = (buffer[5] << 8) | buffer[4]; // Store z-axis values
            return result;

I'm then converting the raw values with this formula (but this is a constant change so it should not matter):

    rawAccelerometerData[i] * mAccelMgLsb / 1000f * mGravity;

I've also tried to disable the gyro and the magnetometer and left only the Z axis enabled and than tried to fetch the data using different output data rate but the result is the same.

The full code of my driver is available [here](https://github.com/leinardi/androidthings-drivers/blob/lsm9ds1/driver-lsm9ds1/src/main/java/com/leinardi/androidthings/driver/lsm9ds1/Lsm9ds1.java).

I currently have only one LSM9DS1 so I have no clue if this is a defective product or an expected behavior and if this can be fixed with a different configuration.

PS
>! as you might have guessed looking at the code I'm not really using an Arduino to access the LSM9DS1 but I still believe that this is still a good place to ask for help since I don't think my issue is platform related but is either some error in my code or a faulty sensor.
And my code is just a port of this Arduino driver: https://github.com/adafruit/Adafruit_LSM9DS1.

body:
The problem is how the accelerometer data is read, to be precise is in these lines:

    result[0] = (buffer[1] << 8) | buffer[0]; // Store x-axis values
    result[1] = (buffer[3] << 8) | buffer[2]; // Store y-axis values
    result[2] = (buffer[5] << 8) | buffer[4]; // Store z-axis values

What I'm getting from the sensor is a 16bit in two’s complement spitted in 2 bytes, for example `buffer[4]` and `buffer[5]` where 4 is the low byte and 5 is the high.

In Java the `&` and `|` are defined to operate only on `int` and `long` values, so what happens is that the `byte` is always promoted to signed `int`:

    buffer[5] = 00111100
    buffer[4] = 11110110
    (int)buffer[4] = 11111111111111111111111111110110 = FF FF FF F6
    (buffer[5] << 8) | buffer[4] = FF FF FF F6

With the original code both bytes are handled has two’s complement when actually **only the high byte is holding the sign**.

Long story short, you have to keep the sign for the high byte (cast to `int`) and threat the low as unsigned (autocast to `int` using the `&` and keeping only the original byte with `0xFF`):

    result[0] = (((int) buffer[1]) << 8) | (buffer[0] & 0xFF); // Store x-axis values
    result[1] = (((int) buffer[3]) << 8) | (buffer[2] & 0xFF); // Store y-axis values
    result[2] = (((int) buffer[5]) << 8) | (buffer[4] & 0xFF); // Store z-axis values


message:
How to start particular event for particular time using millis()?

In my recent project, I want to run particular event for the particular time. For example, If I want to Turn ON my LED for 20 Second. And rest time LED must be off. I know using delay() it is possible but If we used delay() function then that time we can't do anything. So, I tried out millis() for that. I tried the basic code for this.

The code is below:

    const int ledPin =  LED_BUILTIN;

    int ledState = LOW;
    unsigned long previousMillis = 0;
    const long interval = 5000;

    void setup()
    {
      pinMode(ledPin, OUTPUT);
    }

    void loop()
    {
      unsigned long currentMillis = millis();

      if (currentMillis - previousMillis >= interval)
      {
        previousMillis = currentMillis;

        if (ledState == LOW) {
          ledState = HIGH;
        } else {
          ledState = LOW;
        }

        digitalWrite(ledPin, ledState);
      }
    }

But the output of this is like LED ON for 5 Second and then LED OFF for 5 Second. And this thing happens continuously.But I don't want this. I just want to turn ON LED for 5 Second when I want and then LED off forever. And I tried out many logics for that somehow can't able to get this thing. Someone suggest me some idea about this.

body:
Use an extra boolean variable. Some use the previousMillis and make it zero to tell that the delay is not active, but please don't do that. Let previousMillis be the value of millis and use an extra boolean variable.

To start the millis delay, three things are needed: enable the delay, set previousMillis, and turn the led on.

To stop the millis delay, two things are needed: disable the delay, turn the led off. There is no need to do something with the previousMillis since the millis delay will be disabled.

    const int ledPin =  LED_BUILTIN;

    unsigned long previousMillis;
    const unsigned long interval = 5000UL;
    boolean enableDelay = false;

    void setup()
    {
      pinMode(ledPin, OUTPUT);
    }

    void loop()
    {
      unsigned long currentMillis = millis();

      // Trigger the delay, I use analogRead.
      if (analogRead(A0) > 500)
      {
        enableDelay = true;
        previousMillis = currentMillis;
        digitalWrite(ledpin, HIGH);
      }

      // Checking the millis delay should be done in the loop.
      // This code is not inside the code to start the delay, but
      // at the same level as other code in the loop.
      if (enableDelay)
      {
        if (currentMillis - previousMillis >= interval)
        {
          enableDelay = false;
          digitalWrite(ledPin, LOW);
        }
      }
    }

There are libraries that can do this. The above code is the basic way to make a millis delay. I have changed the variable "interval" to a unsigned long, because the other two (currentMillis and previousMillis) are also unsigned long. That makes it more straightforward. The currentMillis and previousMillis **must** be unsigned long, but it is okay if "interval" is a long.

This way of a millis delay can be used with a finite state machine. If your sketch has many states, and one of those states is to keep a fan or a motor on for some time, then you can use it. The variable "enableDelay" is probably not needed in a finite state machine, because the "state" variable tells if that specific state (with the millis delay) is active.


message:
Error while uploading code with Arduino on breadboard using FTDI 232

My circuit is as seen and I hope there is no error with the wiring. I'm using an ATmega328P. The error suggests that the programmer is not responding and ten attempts issuing not in sync code. There isn't any bootloader issue as pin 13 LED flickers as soon as I plug in USB cable. I have selected the following board specification in the Arduino IDE:

- Board: Arduino Uno
- Programmer: Arduino as ISP

Schematics I followed:

[![schematics][1]][1]

ATmega pinout reference:

[![reference][2]][2]

Connections:

- Pin 1: 10k resistor to 5V, 0.1uF capacitor pin series with DTR of FTDI

- Pin 2: Tx of FTDI

- Pin 3: Rx of FTDI

- Pins 9 & 10: 16 MHz oscillator and 22pf capacitor in series

- Pins 7, 20, 21: 5v

- Pins 8, 22: ground

- Pin 19: status LED (similar to pin 13 LED on standard Arduino Uno)

I used both ways of uploading (directly and upload using programmer) and nothing worked. The bootloader in the chip is that of the Arduino Uno and it was burned using another Uno board. SPI programming using another Uno board works fine. I tried different combination of programmer in IDE but futile. The capacitor for reset is 0.1 µf and it seems that connections are fine as there was no issue with uploading using another Uno board as ISP.I would love if anyone can help me out with this.

Related images are:

[![the error][3]][3]

[![arrangement on breadboard][4]][4]

PS:
[Post comment changes]

 -I added a 47uF and 0.1uF caps for cleaner supply to the chip based on suggestions in comment section.

 - board with changes[by pass capacitors ,resistor visible on pin 19]
[![changes made][5]][5]
 - IDE specifics
[![serial output][6]][6]

**Solution-**

 - credits- @Nickgammon

 - had problem with bootloader which was initially uploaded . later solved it by following instructions from NickGammon Forum -
 http://www.gammon.com.au/breadboard

related images-

 - snap shot from bootloading window in arduino IDE
[![serial output][7]][7]

  [1]: https://i.stack.imgur.com/Sl4iY.jpg
  [2]: https://i.stack.imgur.com/FPjnd.jpg
  [3]: https://i.stack.imgur.com/NwyCa.jpg
  [4]: https://i.stack.imgur.com/3QJzH.jpg
  [5]: https://i.stack.imgur.com/G0LTz.jpg
  [6]: https://i.stack.imgur.com/kiMRD.jpg
  [7]: https://i.stack.imgur.com/YD67f.jpg

body:
Here is a photo of the setup I used on [this page about a breadboard Arduino](http://www.gammon.com.au/breadboard). I can't see any material differences between yours and mine, except that I wouldn't connect Aref (pin 21) to anything.

[![Minimal Arduino][1]][1]

Close-up of the FTDI connection:

[![FTDI interface][2]][2]

I have 0.1 µF capacitors as decoupling capacitors on both sides of the breadboard.

> I used both ways of uploading (directly and upload using programmer) and nothing worked.

Assuming you have the Uno bootloader installed (and that the fuses are still set to what they should be for a Uno) then you want direct uploading (with board type set to Uno), not uploading via a programmer.

  [1]: https://i.stack.imgur.com/Hl0cn.jpg
  [2]: https://i.stack.imgur.com/3bgx6.jpg


message:
HM-10 send and receive data and checking received value

I am wondering what is wrong with my code below. I have 2 issues.

The first issue, I am checking if **c** equals "hi" and if it does then display **said hi**. I currently see the output of **c** when it hits `Serial.println(c);` but never see the **said hi** even though `Serial.println(c);` does say "said hi".

The second issue is that when I start up the Arduino I am sending the `AT` command using `bluetooth.println("AT");`, but all it seems to do is display `AT` on the phone instead of `OK` as it should.
<!-- language-all: lang-cpp -->

    #include <SoftwareSerial.h>

    SoftwareSerial bluetooth(8,9); // RX, TX

    void setup() {
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }
      Serial.println("PC Side Connected");
      bluetooth.begin(9600);
      while (!bluetooth) {
        ; // wait for serial port to connect. Needed for native USB port only
      }
      bluetooth.println("Bluetooth Side Connected");
      bluetooth.println("AT"); // just a check
    }

    void loop() { // run over and over
      String c;
      if (bluetooth.available()) {
        //What is sent back from the BT module
        c = bluetooth.readStringUntil('\n');
        delay(10);
        Serial.println(c);
        if (c.equals('hi')) {
          Serial.println("said hi");
        }
      }
      if (Serial.available()) {
        //Send back data to Bluetooth module
        bluetooth.write(Serial.read());
      }
    }

[![enter image description here][1]][1]

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

body:
>The first issue, I am checking if c equals "hi" and if it does then display said hi.

This is *not* how you compare:

      if (c.equals('hi')) {

Single quotes indicate a single (or multi-byte) character.  A character string (lower-case) is enclosed by double quotes:

      if (c == "hi") {

But it's better to avoid the `String` class (more info [here](https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/)).

To eliminate the `String` class, use `char` arrays instead (aka "C strings") and accumulate characters until the newline is received.  There are many, many C string functions for manipulating and searching.  In this specific case, you would use [strcmp](http://www.nongnu.org/avr-libc/user-manual/group__avr__string.html#ga46f3cbd2de457c0fb340a1f379fc33ba) or [strstr](http://www.nongnu.org/avr-libc/user-manual/group__avr__string.html#ga6a441da9211eb85881d99c60b1003552) for comparison:

    #include <AltSoftSerial.h>

    AltSoftSerial bluetooth; // pin 8 is RX, pin 9 is TX

    char btResponse[ 20 ];
    uint8_t count;
    const uint8_t BT_MAX = sizeof(btResponse);

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

      Serial.println("PC Side Connected");
      bluetooth.begin(9600);

      bluetooth.println("Bluetooth Side Connected");
      bluetooth.println("AT"); // just a check
    }

    void loop()
    {
      if (bluetooth.available()) {
        // Read what is sent back from the BT module
        char c = bluetooth.read();

        if (c == '\n') {
          btResponse[ count ] = '\0'; // NUL-terminate the character array

          // Use C string functions to parse the response

          if (strcmp( btResponse, "hi" ) == 0) {
            Serial.println("only said hi");

          } else if (strstr( btResponse, "hi" ) != nullptr) {
            Serial.println("said hi, among other things...");

          }

          // And if there is a comma in there somewhere, display all comma-separated fields
          if (strchr( btResponse, ',' ) != nullptr) {
            uint8_t fieldNumber = 0;

            char *field = strtok( btResponse, "," );
            while (field != nullptr) {

              Serial.print( "Field " );
              Serial.print( fieldNumber );
              Serial.print( " = " );
              Serial.println( field );

              // Some fields might be numbers.  Parse them into integers.
              if ( isdigit( field[0] ) ) {
                int value = atoi( field );
                Serial.print( "  value = " );
                Serial.println( value );
              }

              // get next field
              field = strtok( nullptr, "," );
              fieldNumber++;
            }
          }

          // Reset the counter to receive another response
          count = 0;

        } else if (c >= ' ') {
          // Accumulate another non-control char, if there's room
          if (count < BT_MAX-1) {
            btResponse[ count++ ] = c;
          }
        }
      }

      if (Serial.available()) {
        // Send data to Bluetooth module
        bluetooth.write( Serial.read() );
      }
    }

Notice that it shows how to use [strtok](http://www.nongnu.org/avr-libc/user-manual/group__avr__string.html#ga6ace85338eafe22a0ff52c00eb9779b8) to break the response string into individual fields, if a comma character is somewhere in the line.  For example, entering this:

    hi,123,456

... produces this output:

    said hi, among other things...
    Field 0 = hi
    Field 1 = 123
      value = 123
    Field 2 = 456
      value = 456

It also uses `AltSoftSerial` for the BT connection.  `SoftwareSerial` is very inefficient, and it cannot send and receive at the same time.  It will lose received data while it is transmitting to the BT.  This can also interfere with other parts of your sketch or other libraries.

[This answer](https://arduino.stackexchange.com/questions/34126#34130) has a good summary of the alternatives and how to select one.  Since you are already using pins 8 & 9, it would be easy to switch to the `AltSoftSerial` library.  All of the mentioned libraries are available from the Arduino IDE Library Manager, under the menu **Sketch -> Include Library -> Manage Libraries**.


message:
How to switch a low-voltage (1.5V) toy motor with an arduino?

I would like to add an Arduino to control a toy with a 1.5V battery and motor in it.  The toy is currently controlled by a SPST switch in series with a single 1.5V AA battery and a cheap motor.

I could put in a transistor like https://arduino.stackexchange.com/questions/508/how-to-switch-an-external-circuit-with-arduino or https://arduino.stackexchange.com/questions/1563/to-connect-a-simple-toy-circuit-and-trigger-with-an-arduino?noredirect=1&lq=1  but I would think the voltage drop of the transistor would be significant in the 1.5V circuit.

What would you recommend for switching a 1.5V circuit?

body:
You would be better off using a MOSFET which, when on, has quite a low resistance. For example the [RFP30N06LE datasheet](https://www.sparkfun.com/datasheets/Components/General/RFP30N06LE.pdf) shows a RDS(on) of 0.047 Ω at 30A and 5V.

Using Ohm's Law we therefore expect a voltage drop of:

    V = IR
    V = 0.5 x 0.047
    V = 0.0235

Thus, only 23 mV drop if you are drawing half an amp. I measured using a toy that drew 200 mA and found a 5 mV drop at 1.5V (compared to the theoretical 9 mV).

I have a page about [driving motors](http://www.gammon.com.au/motors) that illustrates how you might wire up such a device.

[![MOSFET driver][1]][1]

The 12V on that schematic could just as easily be 1.5V.

The diode on the schematic is a [snubber diode](https://en.wikipedia.org/wiki/Flyback_diode) which protects the transistor from flyback voltages from the motor.

---

## Comparison to transistor

BJT transistors will have a higher voltage drop between collector and emitter. For example the [2N3904](https://www.sparkfun.com/datasheets/Components/2N3904.pdf) has a 200 mV drop (0.2V) (called VCE(sat)) when conducting 50 mA. This is a somewhat larger drop than the 5 mV drop that I got with the MOSFET, and a somewhat larger percentage of the 1.5V that you are starting with.

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


message:
How to make a smooth serial print?

I have a code which make some calculations using sensor values and provide two comma separated values.

    float x;// initialization
    float y;// initialization
    //some calculations here using sensor values
    Serial.print(x);Serial.print(",");Serial.print(y);
but the issue is due to some unstable situations of the sensor readings, I don't receive sensor data in same time intervals (overall delay is 1 second). I send these values to my Android device through a Bluetooth connection. At that stage, android device cannot separate two values due to lack of smoothness of the Serial.print(). Is there any way to make it smooth (like saving to a buffer before serial print or something) ?

body:
> Are there any way to make it smooth. (like saving to a buffer before serial print or something) ?

you can use sprintf function

    char buff[50];
 sprintf(buff, "{i:%i,t:%lu,v1:%d,v2:%d,c:%u}", ix, events[ix].timestamp, events[ix].value1, events[ix].value2, events[ix].count);
 s.print(buff);

but this will not help you, I think. if you do not print nothing else only those 3 prints, then your next loop will print the first number 'glued' to the last number from the previous loop. use for example prinln to separate them with a newline.

if you have an interrupt in work which can interrupt the execution of the loop and make the prints 'not smooth', it too will be not repaired by printing a buffer. because the interrupt disrupts the Serial too


body:
I bet your problem has nothing to do with “smoothness” (whatever that
means), but is entirely due to lack of _message framing_. The serial and
bluetooth links do not transmit messages: they transmit only a stream of
bytes, with no built-in notion of where a message ends and the next one
starts. Relying on the timing of the received bytes to tell the messages
apart is very unwise. You should instead use some kind of delimiter for
your messages.

For text-based transmissions like yours, the most natural choice is to
send a line terminator at the end of each message. Typically a CR+LF
pair. The `Serial` object has the `println()` methods designed precisely
for this purpose: they send their arguments immediately followed by
CRLF:

<!-- language: lang-c++ -->

    Serial.print(x); Serial.print(","); Serial.println(y);

At the receiving end, you have to buffer all the incoming characters
until you see the line termination. Then you know the message is
complete and you can process it.


message:
Need help on the "expected primary expression before "}" token"

#include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>
    #include "Arduino.h"
    #include "SoftwareSerial.h"
    #include "DFRobotDFPlayerMini.h"

    #define M11  2
    #define M12  3
    #define M13  4
    #define M14  5

    #define M21  6
    #define M22  7
    #define M23  8
    #define M24  9

    uint32_t commands[32];
    int confirmationBuzzer = 17;
    int i = 0;
    boolean DirectionR = true;
    boolean DirectionL = true;
    int StepsR;
    int StepsL;
    int steps_left = 4095;
    int caseLeft;

    RF24 radio(10, 14); // CE, CSN
    SoftwareSerial mySoftwareSerial(15, 16); // RX, TX

    DFRobotDFPlayerMini myDFPlayer;
    void printDetail(uint8_t type, int value);

    const byte address[6] = "00001";

    void stepperR(int xw) {
     for (int x = 0;x < xw;x++) {
      switch (StepsR) {
      case 0:
       digitalWrite(M11, LOW);
       digitalWrite(M12, LOW);
       digitalWrite(M13, LOW);
       digitalWrite(M14, HIGH);
       break;
      case 1:
       digitalWrite(M11, LOW);
       digitalWrite(M12, LOW);
       digitalWrite(M13, HIGH);
       digitalWrite(M14, HIGH);
       break;
      case 2:
       digitalWrite(M11, LOW);
       digitalWrite(M12, LOW);
       digitalWrite(M13, HIGH);
       digitalWrite(M14, LOW);
       break;
      case 3:
       digitalWrite(M11, LOW);
       digitalWrite(M12, HIGH);
       digitalWrite(M13, HIGH);
       digitalWrite(M14, LOW);
       break;
      case 4:
       digitalWrite(M11, LOW);
       digitalWrite(M12, HIGH);
       digitalWrite(M13, LOW);
       digitalWrite(M14, LOW);
       break;
      case 5:
       digitalWrite(M11, HIGH);
       digitalWrite(M12, HIGH);
       digitalWrite(M13, LOW);
       digitalWrite(M14, LOW);
       break;
      case 6:
       digitalWrite(M11, HIGH);
       digitalWrite(M12, LOW);
       digitalWrite(M13, LOW);
       digitalWrite(M14, LOW);
       break;
      case 7:
       digitalWrite(M11, HIGH);
       digitalWrite(M12, LOW);
       digitalWrite(M13, LOW);
       digitalWrite(M14, HIGH);
       break;
      default:
       digitalWrite(M11, LOW);
       digitalWrite(M12, LOW);
       digitalWrite(M13, LOW);
       digitalWrite(M14, LOW);
       break;
      }
      SetDirectionR();
     }
    }

    void SetDirectionR() {
     if (DirectionR == 1) { StepsR++; }
     if (DirectionR == 0) { StepsR--; }
     if (StepsR>7) { StepsR = 0; }
     if (StepsR<0) { StepsR = 7; }
    }

    void stepperL(int xw) {
     for (int x = 0;x<xw;x++) {
      switch (StepsL) {
      case 0:
       digitalWrite(M11, LOW);
       digitalWrite(M12, LOW);
       digitalWrite(M13, LOW);
       digitalWrite(M14, HIGH);
       break;
      case 1:
       digitalWrite(M11, LOW);
       digitalWrite(M12, LOW);
       digitalWrite(M13, HIGH);
       digitalWrite(M14, HIGH);
       break;
      case 2:
       digitalWrite(M11, LOW);
       digitalWrite(M12, LOW);
       digitalWrite(M13, HIGH);
       digitalWrite(M14, LOW);
       break;
      case 3:
       digitalWrite(M11, LOW);
       digitalWrite(M12, HIGH);
       digitalWrite(M13, HIGH);
       digitalWrite(M14, LOW);
       break;
      case 4:
       digitalWrite(M11, LOW);
       digitalWrite(M12, HIGH);
       digitalWrite(M13, LOW);
       digitalWrite(M14, LOW);
       break;
      case 5:
       digitalWrite(M11, HIGH);
       digitalWrite(M12, HIGH);
       digitalWrite(M13, LOW);
       digitalWrite(M14, LOW);
       break;
      case 6:
       digitalWrite(M11, HIGH);
       digitalWrite(M12, LOW);
       digitalWrite(M13, LOW);
       digitalWrite(M14, LOW);
       break;
      case 7:
       digitalWrite(M11, HIGH);
       digitalWrite(M12, LOW);
       digitalWrite(M13, LOW);
       digitalWrite(M14, HIGH);
       break;
      default:
       digitalWrite(M11, LOW);
       digitalWrite(M12, LOW);
       digitalWrite(M13, LOW);
       digitalWrite(M14, LOW);
       break;
      }
      SetDirectionL();
     }
    }

    void SetDirectionL() {
     if (DirectionL == 1) { StepsL++; }
     if (DirectionL == 0) { StepsL--; }
     if (StepsL>7) { StepsL = 0; }
     if (StepsL<0) { StepsL = 7; }
    }

    void setup() {

     myDFPlayer.volume(7);

     radio.begin();
     radio.openReadingPipe(0, address);
     radio.setPALevel(RF24_PA_MIN);
     radio.startListening();
    }
    void loop() {

     if (radio.available()) {
      radio.read(&commands, sizeof(commands));
     }
     for (i = 0; i<15; i++) {
      switch (i) {

      case(0):

       switch (commands[i]) {
       case(0):
        goto outoftheloop;
        break;

       case(1):

        DirectionR = true;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(2);
         stepperL(2);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(2):
        DirectionR = true;
        DirectionL = false;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(3):
        DirectionR = false;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(4):

        goto function1;

        break;
       }

       break;

      case(1): {
      case1:
       int caseLeft = 1;
       switch (commands[i]) {
       case(0):
        goto outoftheloop;
        break;

       case(1):

        DirectionR = true;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(2);
         stepperL(2);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(2):
        DirectionR = true;
        DirectionL = false;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(3):
        DirectionR = false;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(4):

        goto function1;

        break;
       }

       break;
      }
      case(2): {
      case2:
       int caseLeft = 2;
       switch (commands[i]) {
       case(0):
        goto outoftheloop;
        break;

       case(1):

        DirectionR = true;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(2);
         stepperL(2);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(2):
        DirectionR = true;
        DirectionL = false;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(3):
        DirectionR = false;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(4):

        goto function1;

        break;
       }
       break;
      }
      case(3): {
      case3:
       int caseLeft = 3;
       switch (commands[i]) {
       case(0):
        goto outoftheloop;
        break;

       case(1):

        DirectionR = true;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(2);
         stepperL(2);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(2):
        DirectionR = true;
        DirectionL = false;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(3):
        DirectionR = false;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(4):

        goto function1;

        break;
       }
       break;
      }
      case(4): {
      case4:
       int caseLeft = 4;
       switch (commands[i]) {
       case(0):
        goto outoftheloop;
        break;

       case(1):

        DirectionR = true;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(2);
         stepperL(2);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(2):
        DirectionR = true;
        DirectionL = false;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(3):
        DirectionR = false;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(4):

        goto function1;

        break;
       }
       break;
      }
      case(5): {
      case5:
       int caseLeft = 5;
       switch (commands[i]) {
       case(0):
        goto outoftheloop;
        break;

       case(1):

        DirectionR = true;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(2);
         stepperL(2);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(2):
        DirectionR = true;
        DirectionL = false;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(3):
        DirectionR = false;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(4):

        goto function1;

        break;
       }
       break;
      }
      case(6): {
      case6:
       int caseLeft = 6;
       switch (commands[i]) {
       case(0):
        goto outoftheloop;
        break;

       case(1):

        DirectionR = true;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(2);
         stepperL(2);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(2):
        DirectionR = true;
        DirectionL = false;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(3):
        DirectionR = false;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(4):

        goto function1;

        break;
       }
       break;
      }
      case(7): {
      case7:
       int caseLeft = 7;
       switch (commands[i]) {
       case(0):
        goto outoftheloop;
        break;

       case(1):

        DirectionR = true;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(2);
         stepperL(2);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(2):
        DirectionR = true;
        DirectionL = false;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(3):
        DirectionR = false;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(4):

        goto function1;

        break;
       }
       break;
      }
      case(8): {
      case8:
       int caseLeft = 8;
       switch (commands[i]) {
       case(0):
        goto outoftheloop;
        break;

       case(1):

        DirectionR = true;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(2);
         stepperL(2);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(2):
        DirectionR = true;
        DirectionL = false;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(3):
        DirectionR = false;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(4):

        goto function1;

        break;
       }
       break;
      }
      case(9): {
      case9:
       int caseLeft = 9;
       switch (commands[i]) {
       case(0):
        goto outoftheloop;
        break;

       case(1):

        DirectionR = true;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(2);
         stepperL(2);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(2):
        DirectionR = true;
        DirectionL = false;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(3):
        DirectionR = false;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(4):

        goto function1;

        break;
       }
       break;
      }
      case(10): {
      case10:
       int caseLeft = 10;
       switch (commands[i]) {
       case(0):
        goto outoftheloop;
        break;

       case(1):

        DirectionR = true;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(2);
         stepperL(2);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(2):
        DirectionR = true;
        DirectionL = false;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(3):
        DirectionR = false;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(4):

        goto function1;

        break;
       }
       break;
      }
      case(11): {
      case11:
       int caseLeft = 11;
       switch (commands[i]) {
       case(0):
        goto outoftheloop;
        break;

       case(1):

        DirectionR = true;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(2);
         stepperL(2);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(2):
        DirectionR = true;
        DirectionL = false;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(3):
        DirectionR = false;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(4):

        goto function1;

        break;
       }
       break;
      }
      case(12): {
      function1:
       switch (commands[i]) {
       case(0):
        switch (caseLeft) {

        case(0):
         goto case1;
         break;

        case(1):
         goto case2;
         break;

        case(2):
         goto case3;
         break;

        case(3):
         goto case4;
         break;
        case(4):
         goto case5;
         break;

        case(5):
         goto case6;
         break;

        case(6):
         goto case1;
         break;

        case(7):
         goto case2;
         break;

        case(8):
         goto case1;
         break;

        case(9):
         goto case2;
         break;
        case(10):
         goto case1;
         break;

        case(11):
         goto case2;
         break;
        }
        break;
       case(1):

        DirectionR = true;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(2);
         stepperL(2);
         steps_left--;
        }
        steps_left = 4095;
        goto function2;
        break;

       case(2):
        DirectionR = true;
        DirectionL = false;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        goto function2;
        break;

       case(3):
        DirectionR = false;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        goto function2;
        break;

       case(4):
        goto function1;

        break;

       }
       break;
      }
      case(13): {
      function2:
       switch (commands[i]) {
       case(0):
        switch (caseLeft) {

        case(0):
         goto case1;
         break;

        case(1):
         goto case2;
         break;

        case(2):
         goto case3;
         break;

        case(3):
         goto case4;
         break;
        case(4):
         goto case5;
         break;

        case(5):
         goto case6;
         break;

        case(6):
         goto case1;
         break;

        case(7):
         goto case2;
         break;

        case(8):
         goto case1;
         break;

        case(9):
         goto case2;
         break;
        case(10):
         goto case1;
         break;

        case(11):
         goto case2;
         break;
        }
        break;
       case(1):

        DirectionR = true;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(2);
         stepperL(2);
         steps_left--;
        }
        steps_left = 4095;
        goto function3;
        break;

       case(2):
        DirectionR = true;
        DirectionL = false;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        goto function3;
        break;

       case(3):
        DirectionR = false;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        goto function3;
        break;

       case(4):
        goto function1;

        break;

       }
       break;
      }
      case(14): {
      function3:
       switch (commands[i]) {
       case(0):
        switch (caseLeft) {

        case(0):
         goto case1;
         break;

        case(1):
         goto case2;
         break;

        case(2):
         goto case3;
         break;

        case(3):
         goto case4;
         break;
        case(4):
         goto case5;
         break;

        case(5):
         goto case6;
         break;

        case(6):
         goto case1;
         break;

        case(7):
         goto case2;
         break;

        case(8):
         goto case1;
         break;

        case(9):
         goto case2;
         break;
        case(10):
         goto case1;
         break;

        case(11):
         goto case2;
         break;
        }
        break;
       case(1):

        DirectionR = true;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(2);
         stepperL(2);
         steps_left--;
        }
        steps_left = 4095;
        goto function4;
        break;

       case(2):
        DirectionR = true;
        DirectionL = false;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        goto function4;
        break;

       case(3):
        DirectionR = false;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        goto function4;
        break;

       case(4):
        goto function1;

        break;

       }
       break;
      }
      case(15): {
      function4:
       switch (commands[i]) {
       case(0):
        switch (caseLeft) {

        case(0):
         goto case1;
         break;

        case(1):
         goto case2;
         break;

        case(2):
         goto case3;
         break;

        case(3):
         goto case4;
         break;
        case(4):
         goto case5;
         break;

        case(5):
         goto case6;
         break;

        case(6):
         goto case1;
         break;

        case(7):
         goto case2;
         break;

        case(8):
         goto case1;
         break;

        case(9):
         goto case2;
         break;
        case(10):
         goto case1;
         break;

        case(11):
         goto case2;
         break;
        }
        break;
       case(1):

        DirectionR = true;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(2);
         stepperL(2);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(2):
        DirectionR = true;
        DirectionL = false;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(3):
        DirectionR = false;
        DirectionL = true;

        while (steps_left>0) {

         stepperR(1);
         stepperL(1);
         steps_left--;
        }
        steps_left = 4095;
        break;

       case(4):
        goto function1;

        break;

       }
       break;
      }
      }
     }
    outoftheloop:
    }

Sorry for the long code,I would send only a part of the code that shows error however I am not sure if the other parts are related to the code. I get this error.

>Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"

>C:\Users\TEDNOKENT2\Desktop\sketch_dec22a\sketch_dec22a.ino: In function 'void setup()':

>C:\Users\TEDNOKENT2\Desktop\sketch_dec22a\sketch_dec22a.ino:183:35: warning: invalid conversion from 'const byte* {aka const unsigned char*}' to 'uint64_t {aka long long unsigned int}' [-fpermissive]

>   radio.openReadingPipe(0, address);

>In file included from >C:\Users\TEDNOKENT2\Desktop\sketch_dec22a\sketch_dec22a.ino:3:0:

>C:\Users\TEDNOKENT2\Documents\Arduino\libraries\RF24-master/RF24.h:350:8: note: >initializing argument 2 of 'void RF24::openReadingPipe(uint8_t, uint64_t)'

>   void openReadingPipe(uint8_t number, uint64_t address);

>C:\Users\TEDNOKENT2\Desktop\sketch_dec22a\sketch_dec22a.ino: In function 'void loop()':

>sketch_dec22a:1288: error: expected primary-expression before '}' token

> }

>exit status 1
>expected primary-expression before '}' token

>This report would have more information with
>"Show verbose output during compilation"
>option enabled in File -> Preferences.

Normally, it should have been fixed adter I deleted some extra brackets but it just stayed there. I have no idea why. I know I shouldn't use gotos that often, however, I am kind of a novice programmer and goto s make it a lot easier to code. I would appreaciate any suggestions on the error. If anthing else that is not related to the error but you think is not necessary, you can mention them too.

Thanks in advance

body:
Actually, although I'm not going to check for every bracket, here are some tips to prevent the problem (and if you follow them you will find your missing/extra bracket):

- Align brackets, I know it saves one line if you put the { directly after statements, but much neater to put them separately on the next line.
- Make short functions. If you get a compiler error in a function, it's much easier to find the location. It also helps clearity, maintainability, testability etc. To do this:
- Do not use  more than 2 or 3 compound statements (while, switch, if etc).
- Put (almost) duplicate code in separate functions and call them (either without parameters or with parameters if needed).
- Never use goto statements. You can always replace them by if, while, for or do statements.


body:
My two cents here.

When you have lots of repetitive structures, like in function `stepperR`, is time to simplify, put some things as data and reduce the repetitiveness of your code.

Here is `stepperR` reimplemented

    byte values[9] = {1, 3, 2, 6, 4, 12, 8, 9, 0};
    void stepperR(int xw) {
        for (int x = 0;x < xw;x++) {
                digitalWrite(M11, values[StepsR] & 0x08);
                digitalWrite(M12, values[StepsR] & 0x04);
                digitalWrite(M13, values[StepsR] & 0x02);
                digitalWrite(M14, values[StepsR] & 0x01);
                SetDirectionR();
        }
    }

I choose `StepsR == 8` as the *default* value (all zeros).


message:
how to check 24c32 eprom is connected or not to arduino runtime?

I want to check it on runtime if runitme i remove eprom then it shows "please insert dongle " also tried using while loop showing eroor.. How can i solve it?

    Wire.beginTransmission(80);
          error = Wire.endTransmission();
        if (error == 0)
        {
        serial.print("connected");
        }
        else
        {
        serial.print("please insert dongle");
        }

also tried using while loop in loop()

    void loop()
    {
    while (error == 0){
    Serial.print("connected");
    }

    Serial.print("insert dongle");
    }

body:
You should take parts of the [I2C Scanner](https://playground.arduino.cc/Main/I2cScanner). You don't need to scan for all addresses - you can just scan for the one address you're interested in:

    Wire.beginTransmission(80);
    error = Wire.endTransmission();

    if (error == 0)
    {
      Serial.print("Connected");
    } else {
      Serial.println("Insert dongle");
    }


message:
Problem uploading the code into an Arduino Uno

I was trying to upload code for a blinking LED. It is a new Arduino Uno board. Any further help will be appreciated.I got the following error:

>Info.: OS- Ubuntu 16.04
>
>Software: Arduino IDE 1.8.5

I could not see any port.

I have tried dialout. But still it is not working.

I also have a confusion, i.e. the `Programmer` menu shows AVRISP mkll.

[![enter image description here][1]][1]

If anyone wants any information, please do comment.

Error:

>An error occurred while uploading the sketch
avrdude: ser_open(): can't open device "COM1": No such file or directory`

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

body:
Ubuntu and other Linux operating systems don’t name the serial ports “COM1” or similar.

They use special files like

    /dev/tty.[something]

The [something] depends on the USB device driver. The IDE should list available serial ports in the Port selection menu.


message:
How to control 6 servo motors with an Arduino Mega board?

I am trying to make autonomous hexapod with an Arduino Mega board. I have followed tripod mechanism of hexapod movement. First I could control simultaneously legs (0, 2, 4) and (1, 3, 5) separately but whenever I tried to combine both i.e control 6 legs at a time I could not see any movement in the hexapod. Even in the IDE I am not getting any error.

I have connected the legs (0 to 5) to signal pins (2 to 7) respectively. I have connected a common +5v voltage and common ground voltage to individual legs using a breadboard. Can anyone give me a proper solution to overcome this issue and further would like to know how to control multiple servos and source code for it?

Here is my Arduino source code for controlling 6 servo motors.

    #include <Servo.h>
    Servo myservo[6];
    int f=0;// create servo object to control a servo
    //[0] -tibia , [1] -femur , [2] -coxa motors
    void setup() {
      myservo[0].attach(2);
      myservo[1].attach(3);
      myservo[2].attach(4);
      myservo[3].attach(5);
      myservo[4].attach(6);
      myservo[5].attach(7);
    }

    void loop() {
      //alternatively making hexapod stand at its place
      //f is just flag variable to make it stop
      if(f==0) {
        myservo[0].write(130);
        myservo[2].write(130);
        myservo[4].write(90);
        myservo[1].write(130);
        myservo[3].write(90);
        myservo[5].write(0);
        f=1;
      }
    }

Note the values that are added above are calculated separately for individual legs to mount legs on ground.

body: in the odd case that you are actually powering your (small?) servo's directly through the arduino : you'll need an external power source for your servo's.


body: The Arduino Mega can handle at most 40mA on the I/O pins, and 200mA on the 5V/GND pins. Six servos will draw far more current than the max of 200mA. You could try hooking up the servo power to a separate power source and the data pins to the Arduino. Hope this helps!


message:
WiFi module ESP8266-01 for Arduino not working

I am new to using Arduino just bought my first one yesterday, and I also got an WiFi module. The Arduino I got is another brand but should be the same as the Arduino Uno rev 3 and I got the ESP8266-01 wifi module.

I've tried doing some simple examples projects following some YouYube videos, and all those have worked without problem.

What I am trying to create is a simple magnetic door switch. When it's opened I get a signal to my computer. Getting the magnetic door switch wired with the Arduino and getting an LED to light up when the magnetic switch opened worked without problem.

But to set up the wifi module, I can't get it to work.

I have spent hours and hours watching tutorials reading all I can find to trying everything to get this to work, but no luck.

I don't know If I am doing something wrong (probably) or if something is broken.

These are [the instructions][1] I am trying currently.

[Video of my Arduino setup][2]

For the Arduino board I use 12v DC in and USB from my PC.

Code:

    #include "Arduino.h"
    #include "ESP8266.h"

    #include "SoftwareSerial.h"
    SoftwareSerial  ConsoleOut(8, 9);

    #define SSID  "ASUS"
    #define PWD   "tmpPassword"

    void setup() {
      char  *ipAddress, ap[31];

      WiFi.reset(WIFI_RESET_HARD);
      WiFi.begin(9600);
      ConsoleOut.print("flag2");
      if (WiFi.join(SSID, PWD) == WIFI_ERR_OK) {
        ipAddress = WiFi.ip(WIFI_MODE_STA);
        ConsoleOut.print(F("\n\rIP address:"));
        ConsoleOut.print(ipAddress);
        ConsoleOut.print(':');
        ConsoleOut.print("flag1");
        if (WiFi.isConnect(ap))
          ConsoleOut.println(ap);
        else
          ConsoleOut.println(F("not found"));
      } else
        while (1);
    }

    void loop() {
      if (WiFi.connect((char *)"www.google.co.jp", 80) == WIFI_ERR_CONNECT) {
        if (WiFi.send((const uint8_t *)"GET / HTTP/1.1\r\n\r\n") == WIFI_ERR_OK) {
          int16_t c;
          uint16_t len = WiFi.listen(10000UL);
          while (len)
            if ((c = WiFi.read()) > 0) {
              ConsoleOut.write((char)c);
              len--;
            }
        } else
          ConsoleOut.println(F("Send fail"));
        WiFi.close();
      } else
        ConsoleOut.println(F("TCP connect fail"));
      WiFi.disconnect();
      while (1);
    }

Code:

[![enter image description here][3]][3]

Different from the example sketch is that I use 2K instead of 3K resistors for R2, R4 and 1K for R1, R3. (2K on left side in the video 1K on the right side)

The LED of the WiFi lights red constantly. I don't know what that means,  and the blue LED on the wiFi module lights up whenever I upload a sketch to the Arduino.

Thanks in advance. Any help is really, really appreciated.

  [1]: https://github.com/Hieromon/ESP8266
  [2]: https://www.youtube.com/watch?v=SEHq4nB2WCM
  [3]: https://i.stack.imgur.com/E0AhE.png

body:
Use this code to send commands to the ESP:

    #include <SoftwareSerial.h>

        SoftwareSerial esp8266(2, 3);

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

          esp8266.begin(9600);
        }

        void loop() {
          while(esp8266.available()) {
             Serial.write(esp8266.read());
          }

          while(Serial.available()) {
            esp8266.write(Serial.read());
          }
        }

This simply reads everything from the ESP chip and sends it to the console and vica versa.

To modify the baud rate on the chip, send the following command in the serial monitor:

    AT+UART_DEF=9600,8,1,0,0

This sets the baud rate to 9600 and remembers it for further use.


message:
Will Arduino Mega support stepper motor NEMA 24, NEMA 34

Will two stepper motor NEMA 24, 10 kg cm, 2. 8 amp, 24 vdc work at same time on Arduino Mega and when they stop stepper motor NEMA 34, 34 kg cm, 4amp, 24 VDC will work or not? This is my first project please help me to choose the controller.

body:
I'm using 4x Nema 24s for a CNC project of mine.  They only need a couple of signals/pins each from the Arduino to work, the rest is up to the stepper controller board.

For my steppers, I'm using TB6600s, since I need ~3.5 amps per motor/channel.  There are others out there that'll work, but it's what I saw other people at my maker space using.

Nema34s would probably need higher rated amps, so that would determine what controller you need to use.

In fact, every motor is rated for different amps and voltages, so that will always determine what motor controller you use.  Since you need a higher voltage to run the motor controllers than the Arduino, using a separate stepping power supply is a requirement.

The Arduino gets hooked to the step/pulse and direction pins of the motor controller and the other pins on the motor controller go elsewhere.  The CNC motor controller shields you normally see are for lower amp controllers and do most of the pin connections for you.  With the higher amperage motors, you'll have to do this yourself.

When you determine what motor controller you are going to use, find a wiring diagram for it (and maybe a friend) to figure out how it should be wired.