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

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

Answers: 1

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.


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

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

Answers: 1

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


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

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

Answers: 1

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**.


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

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

Answers: 1

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


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

title: How to make a smooth serial print?

Answers: 2

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.


body:
I am trying to get the response from server using AT commands. This is my program

    #include <SoftwareSerial.h>

    const byte rxPin = 2; // Wire this to Tx Pin of ESP8266
    const byte txPin = 3; // Wire this to Rx Pin of ESP8266

    // We'll use a software serial interface to connect to ESP8266
    SoftwareSerial ESP8266 (rxPin, txPin);

    void setup() {
      Serial.begin(115200);
      ESP8266.begin(115200); // Change this to the baudrate used by ESP8266
      delay(1000); // Let the module self-initialize
    }

    void loop() {
      Serial.println("Sending an AT command...");
      ESP8266.println("AT+CIPMUX=1");
      delay(3000);

      ESP8266.println("AT+CIPSTART=0,\"TCP\",\"192.168.50.1\",1234");
      delay(3000);

      while (ESP8266.available()){
         String res = ESP8266.readStringUntil('\t');
         Serial.println(res);
      }

    }

My server is just sending just one string as the output.

My console is getting this kind of output? Is there a way to clean this?

    Sending an AT command...
    AZi%PSՊj
    C⸮j⸮L⸮AT+CIPSTART<0,"TCP","193.168.50.1",1234
    0,CONNECT

    OK
    +IPD,0,1:10,CLOSDD

    Sending an AT command...

I read [thread][1] and changed `SoftwareSerial.h` file. But still no luck.

Thanks in advance.

  [1]: https://arduino.stackexchange.com/questions/30760/inconsistent-response-at-command

title: AT response clean-up

Answers: 0


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

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

Answers: 2

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).


body:
I'm using an Arduino Uno to send HTTP requests to my local webserver. To communicate to the ESP8266 I created a SoftwareSerial which is set to a baud rate of 9600.

Whenever I send a HTTP request, the request looks like the following:

        192.168.2.132 - - [22/Dec/2017:12:22:57 +0100] "TP/1.1" 400 173 "-" "-"
        192.168.2.132 - - [22/Dec/2017:12:23:38 +0100] "z\x02BQQA\xBD1.1" 400 173 "-" "-"
        192.168.2.132 - - [22/Dec/2017:12:23:56 +0100] "z\x02BQQA\xBD1.1" 400 173 "-" "-"
        192.168.2.132 - - [22/Dec/2017:12:24:14 +0100] "z\x02BQQA\xBD1.1" 400 173 "-" "-"
        192.168.2.132 - - [22/Dec/2017:12:24:34 +0100] "\xE9\x09BQQA\xBD1.1" 400 173 "-" "-"
        192.168.2.132 - - [22/Dec/2017:12:25:06 +0100] "z\x02BQQA\xBD1.1" 400 173 "-" "-"
        192.168.2.132 - - [22/Dec/2017:12:27:01 +0100] "\x02BQQA\xBD1.1" 400 173 "-" "-"
        192.168.2.132 - - [22/Dec/2017:12:28:11 +0100] "\x02BQQA\xBD1.1" 400 173 "-" "-"

The code to create GET request to send over TCP:

      char *hello = "GET / HTTP/1.1\r\nHost: 192.168.2.106\r\nConnection: close\r\n\r\n";

      if (wifi.send((const uint8_t*)hello, strlen(hello))) {
        Serial.print("Wifi send succesfull\r\n");
      } else {
        Serial.print("Wifi not send succesfully\r\n");
      }

The actual send method:

    bool ESP8266::sATCIPSENDSingle(const uint8_t *buffer, uint32_t len)
    {
        rx_empty();
        m_puart->print("AT+CIPSEND=");
        m_puart->println(len - 4);

        if (recvFind(">", 5000)) {
            Serial.println("found >");
            rx_empty();

            for (uint32_t i = 0; i <= len; i++) {
                m_puart->write(buffer[i]);
            }

            return recvFind("SEND OK", 30000);
        }
        return false;
    }

This line:

    m_puart->println(len - 4);

Was in the library actually just `m_puart->println(len);`

I had to shorten the length of the buffer for esp8266 to wait to, otherwise it wouldn't send the TCP command. The counting part of bytes looks fine to me. Not sure what's causing this behaviour.

The part above is just some extra unusual behaviour but isn't the main priority. So any ideas what's causing the odd HTTP requests?

title: ESP8266 odd HTTP GET request

Answers: 0


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

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

Answers: 1

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");
    }


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

title: Problem uploading the code into an Arduino Uno

Answers: 1

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.


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

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

Answers: 2

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!


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

title: WiFi module ESP8266-01 for Arduino not working

Answers: 1

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.


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

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

Answers: 1

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.


body:
As the sensor "sees" an object nearby, it makes the LED go to full brightness and it remains like that for as long as the sensor keeps on sensing the object. Then, as soon as the sensor stops sensing it, the LED goes OFF instantly... and so on, endlessly. This part of the code works perfectly as it is right now.

MY PROBLEM:

I need all of this ON and OFF switching to happen with smooth PWM fades instead of with abrupt "instant ON" and "instant OFF" changes. I need to have a 1.5 seconds PWM fade-in of the LED from 0% to 100% as soon as the sensor gets activated; and then a 3.5 seconds fade-out as soon as the sensor stops sensing something nearby. As long as the sensor is activated, the LED needs to remain at full brightness. So, simply put: I need the LED to dim smoothly between the sensor's state-changes, instead of changing instantly in an abrupt manner.

title: How to fade an LED in response to a sensor?

Answers: 2

body:
Do analogRead(sensor) and check what range of values you are getting. Arduino has 10 bit adc which means you can get 0-1023 in readings. However the sensor might not go complete LOW (0) or complete HIGH (1023). So just measure what's the range you are getting. Assume the range is 125 - 980.

PWM on arduino - This one is 8 bit, which means you can write 0-255. 0 means LED is OFF and 255 means LED is fully ON. Now you need to map 125-980 to 0-255 (as far as I can understand from your comments about synchronizing it with the sensor).

Here is what your code will look like:

    /* Map an analog value (125-980) to 8 bits (0 to 255) */

        void loop()
        {
          int val = analogRead(0); //sensor attached to A0
          val = map(val, 125, 980, 0, 255);
          analogWrite(9, val); //LED attached to D9
        }

body:
This is the typical problem which calls for a [finite state machine][].
You create a “state” variable to keep track of the LED state, which can
be `OFF`, `FADING_IN`, `ON` or `FADING_OUT`. You also need another
variable to remember _when_ you started the fade-in or the fade-out. I
would start the program some declarations like the following:

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

    const uint8_t  LED_PIN       = 3;
    const uint32_t FADE_IN_TIME  = 1500;
    const uint32_t FADE_OUT_TIME = 3500;

    static enum { OFF, FADING_IN, ON, FADING_OUT } led_state;
    static uint32_t fade_start;

Now that you know the LED state, you use it to condition the LED
handling on the current state. For example, the brightness at any given
time can be computed as:

    /* Compute the LED brightness after the given fade time */
    static uint8_t led_brightness(uint32_t fade_time)
    {
        int mapped;
        switch (led_state) {
            case FADING_IN:
                mapped = map(fade_time, 0, FADE_IN_TIME, 0, 255);
                return constrain(mapped, 0, 255);
            case FADING_OUT:
                mapped = map(fade_time, 0, FADE_OUT_TIME, 255, 0);
                return constrain(mapped, 0, 255);
            case ON:
                return 255;
            default:
                return 0;
        }
    }

where `fade_time` would be `millis() - fade_start`. Note the use of the
standard `map()` function to generate a linear ramp, and `constrain()`
to avoid overflowing the range 0 – 255.

Now, switching the LED on or off is just a matter of setting the correct
state... _and_ updating `fade_start` as necessary:

    /* Set the LED pin to HIGH or LOW, through fading. */
    void ledWrite(uint8_t value)
    {
        uint32_t now = millis();
        if (value == HIGH) {
            if (led_state == OFF) {
                fade_start = now;
            }
            else if (led_state == FADING_OUT) {
                fade_start = now - map(now - fade_start,
                        0, FADE_OUT_TIME,
                        FADE_IN_TIME, 0);
            }
            if (led_state != ON)
                led_state = FADING_IN;
        }
        else {
            if (led_state == ON) {
                fade_start = now;
            }
            else if (led_state == FADING_IN) {
                fade_start = now - map(now - fade_start,
                        0, FADE_IN_TIME,
                        FADE_OUT_TIME, 0);
            }
            if (led_state != OFF)
                led_state = FADING_OUT;
        }
    }

A few things worth noting:

* trying to switch the LED on has no effect if it's already on or fading
  in, and trying to switch it off has no effect if it's either off or
  fading out
* if you switch it on while it's fading out, it will move to the state
  `FADING_IN`, and the `fade_start` time will be set to a value that
  ensures continuity of the brightness; same thing when switching from
  `FADING_IN` to `FADING_OUT`.

There is one more thing to do. Your program should periodically update
the LED state, not only to update its brightness, but also to enforce
the transitions `FADING_IN` → `ON` and `FADING_OUT` → `OFF` when needed:

    /* This should be called periodically to update the LED. */
    void update_led()
    {
        uint32_t fade_time = millis() - fade_start;
        if (led_state == FADING_IN && fade_time >= FADE_IN_TIME)
            led_state = ON;
        else if (led_state == FADING_OUT && fade_time >= FADE_OUT_TIME)
            led_state = OFF;
        analogWrite(LED_PIN, led_brightness(fade_time));
    }

With all this in place, you can write the main program just as you did
with no fading, only with the extra call to `update_led()` on every loop
iteration:

    void setup()
    {
        // Initialize the sensor.
        sensor.begin();
    }

    void loop()
    {
        // Set the LED as per the sensor reading.
        if (sensor.detects_object())
            ledWrite(HIGH);
        else
            ledWrite(LOW);

        // Update the LED brightness on every loop iteration.
        update_led();
    }

Oh, and beware not to do anything blocking in `loop()` (e.g., no calls
to `delay()`). Otherwise the LED brightness would be “jumpy”.

[finite state machine]: https://hackingmajenkoblog.wordpress.com/2016/02/01/the-finite-state-machine/


body:
I am trying to setup CLion as my workspace for my arduino. I have installed the two Arduino plugins for CLion, generated a new sketch project, but I am getting cmake errors on opening the project.

    CMake Error at /cygdrive/c/Users/user/project/cmake/ArduinoToolchain.cmake:86 (message):
      Could not find Arduino SDK (set ARDUINO_SDK_PATH)!
    Call Stack (most recent call first):
      /cygdrive/c/Users/user/project/CMakeFiles/3.9.4/CMakeSystem.cmake:6 (include)
      /cygdrive/c/Users/user/project/CMakeFiles/CMakeTmp/CMakeLists.txt:3 (project)

The issue is similar to this logged issue here:
https://github.com/francoiscampbell/CLionArduinoPlugin/issues/11

As a Windows 10 user, I have the Arduino SDK installed here: `C:\Program Files (x86)\Arduino`

What's interesting is that the cmake file is calling the UNIX commands when it's running in this if statement:

        if(UNIX)
            file(GLOB SDK_PATH_HINTS /usr/share/arduino*
                /opt/local/arduino*
                /opt/arduino*
                /usr/local/share/arduino*

                    )
        elseif(WIN32)
            set(SDK_PATH_HINTS "C:\\Program Files\\Arduino"
                "C:\\Program Files (x86)\\Arduino\\libraries"
                )
        endif()

title: Clion Arduino plugin: Error:Could not find Arduino SDK (set ARDUINO_SDK_PATH)

Answers: 0


body:
    void setup ()
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    pinMode(LED_Blue_pin, OUTPUT);
    pinMode(LED_White_pin, OUTPUT);

    Serial.begin(9600);
    digitalWrite(LED_Blue_pin, LOW);
    digitalWrite(LED_White_pin, LOW);

    void loop()
    {
        long duration, cm;

        pinMode(trigPin, OUTPUT);
        digitalWrite(trigPin, LOW);
        delayMicroseconds(2);
        digitalWrite(trigPin, HIGH);
        delayMicroseconds(5);
        digitalWrite(trigPin, LOW);

        pinMode(echoPin, INPUT);
        duration = pulseIn(echoPin, HIGH);

        cm = microsecondsToCentimeters(duration);
        long distance = 70 - cm ;

        if (distance < 20) {
            Serial.println("NO ITEM");
            digitalWrite(LED_White_pin, HIGH);
        } else {
            digitalWrite(LED_White_pin, LOW);
        }

        if (distance > 20 && distance < 70) {
            digitalWrite(LED_Blue_pin, HIGH);
            Serial.print("Item : ");
            Serial.print(item++);
            Serial.println(" stk");
        } else {
            digitalWrite(LED_Blue_pin, LOW);
        }

        delay(1500);
    }

    long microsecondsToCentimeters(long microseconds)
    {
        return microseconds / 29 / 2;
    }

The code above is for the Ultrasonic Sensor HC-SR04. The sensor detects items that passes through and counts them along the way. The Blue Led indicates that the sensor detected an item while the White Led detects none. How can I store the data from HC-SR04 to EEPROM? The reason is, I just want to test it out before I sent the data from EEPROM to a database server. I'm still a novice at this.

title: Object Sensor on conveyor belt (want to record the data in EEPROM for testing)

Answers: 1

body:
You can use the [EEPROM.write()][1] function. There is a useful [tutorial][2] on the Arduino site.

The sample code from that tutorial is shown below:

    /*
     * EEPROM Write
     *
     * Stores values read from analog input 0 into the EEPROM.
     * These values will stay in the EEPROM when the board is
     * turned off and may be retrieved later by another sketch.
     */

    #include <EEPROM.h>

    /** the current address in the EEPROM (i.e. which byte we're going to write to next) **/
    int addr = 0;

    void setup() {
      /** Empty setup. **/
    }

    void loop() {
      /***
        Need to divide by 4 because analog inputs range from
        0 to 1023 and each byte of the EEPROM can only hold a
        value from 0 to 255.
      ***/

      int val = analogRead(0) / 4;

      /***
        Write the value to the appropriate byte of the EEPROM.
        these values will remain there when the board is
        turned off.
      ***/

      EEPROM.write(addr, val);

      /***
        Advance to the next address, when at the end restart at the beginning.

        Larger AVR processors have larger EEPROM sizes, E.g:
        - Arduno Duemilanove: 512b EEPROM storage.
        - Arduino Uno:        1kb EEPROM storage.
        - Arduino Mega:       4kb EEPROM storage.

        Rather than hard-coding the length, you should use the pre-provided length function.
        This will make your code portable to all AVR processors.
      ***/
      addr = addr + 1;
      if (addr == EEPROM.length()) {
        addr = 0;
      }

      /***
        As the EEPROM sizes are powers of two, wrapping (preventing overflow) of an
        EEPROM address is also doable by a bitwise and of the length - 1.

        ++addr &= EEPROM.length() - 1;
      ***/

      delay(100);
    }

  [1]: https://www.arduino.cc/en/Reference/EEPROMWrite
  [2]: https://www.arduino.cc/en/Tutorial/EEPROMWrite


body:
I'm very new to arduino and have started work on my first project, a simple little web server. I'm using a NodeMCU with an sd card module and screen. The issue is that in order to power my sd card module, I need to input 5V which the MCU doesn't provide.

In order to work around this I'm simply using an arduino nano as a power supply to pass into the vin input on the mcu.

What options do I have to exclude the need for the nano? Is there a simple module I can buy that acts as a power supply for 5v?

Any help would be great, thanks!

title: What options do I have to get 5v on my current project?

Answers: 3

body:
SD cards require 3.3V. Usually, to connect them to an Arduino running at 5V you need to get a level converter. However in your case it sounds like you are making work for yourself:

    3.3V <--> 5V <--> 3.3V

> in order to power my sd card module, I need to input 5V

**Which** SD card module? Maybe you don't need a "module".

body:
The others write that the card needs 3.3V. Your module need 5V. This means that between the input of the module and the sd card is something. it can be a voltage regulator or something like a voltage dropper (resistor in series with diodes). You can search for it on your module. If you are sure you found it you can solder a bridge around it. After this you can give 3.3V to this module.

I think this must work.

body:
To supplement; if you don’t have a level converter on hand, have a look at this diagram:
http://homediyelectronics.com/projects/arduino/seriallevelconverter/

Just test it on a breadboard, and if Vcc, Rx and Tx are within 10% of 3.3V, solder it to a bit of perfboard. Haven’t needed to build one myself, since these come in tiny SMD packages which cost almost nothing:
https://rover.ebay.com/rover/0/0/0?mpre=https://www.ebay.com/ulk/itm/202151474158

... Are you sure your SD module isn’t 5V tolerant? All mine step down 5V to ~3.3V.


body:
In my recent project, I want to set my time according to the requirement. And somehow I'm able to manage that. But when I'm decreasing my time value then one weird problem happens. When decreasing my time value, when I reach ZERO (0) and when I again decrease value then it shows the maximum range of that data type even if I put the condition for stop value at ZERO(0).

My code is below:

    const int kPinSw1 = 2;
    const int kPinSw2 = 3;

    int plusBtnIncState = 0;
    int lastPlusBtnIncState = 0;

    int minusBtnDecState = 0;
    int lastMinusBtnDecState = 0;

    unsigned long currentMillis;
    unsigned long previousMillis;
    unsigned long interval = 0UL;

    void setup() {
      Serial.begin(9600);
      pinMode(kPinSw1, INPUT_PULLUP);
      pinMode(kPinSw2, INPUT_PULLUP);
    }

    void loop() {
      //---------------INC_TIMER---------------//
      plusBtnIncState = digitalRead(kPinSw1);
      if(plusBtnIncState != lastPlusBtnIncState) {
        if(plusBtnIncState == HIGH) {
          interval = interval + 1000;
        }
        delay(50);
      }
      lastPlusBtnIncState = plusBtnIncState;

      //---------------DEC_TIMER---------------//
      minusBtnDecState = digitalRead(kPinSw2);
      if(minusBtnDecState != lastMinusBtnDecState) {
        if(minusBtnDecState == HIGH) {
          interval = interval - 1000;
          if(interval <= 0) {
            interval = 0;
          }
        }
        delay(50);
      }
      lastMinusBtnDecState = minusBtnDecState;

      //---------------------------------------//
      Serial.print("Int:");
      Serial.print(interval);
      Serial.print("\n");
    }

And output:

    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:1000
    Int:1000
    Int:1000
    Int:1000
    Int:1000
    Int:1000
    Int:1000
    Int:1000
    Int:1000
    Int:1000
    Int:2000
    Int:2000
    Int:2000
    Int:2000
    Int:2000
    Int:2000
    Int:2000
    Int:2000
    Int:2000
    Int:2000
    Int:2000
    Int:1000
    Int:1000
    Int:1000
    Int:1000
    Int:1000
    Int:1000
    Int:1000
    Int:1000
    Int:1000
    Int:1000
    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:4294966296
    Int:4294966296
    Int:4294966296
    Int:4294966296
    Int:4294966296
    Int:4294966296
    Int:4294966296
    Int:4294966296

As you can see in output when I reach ZERO and then again decrease the value then the value is like 4294966296 instead of ZERO. I put the logic for that if we reached ZERO or less ZERO then it must stay at ZERO. I don't understand why this happens. Please suggest me something.

title: Can't stop my variable value at zero?

Answers: 3

body:
The `interval` variable is `unsigned long`.

In this example, we are using `int` that are 4 bits long (just to keep thing short) just to subtract 1 from 0:

        0b0000
       -0b0001
        ------
        0b1111

That is normal arithmetic, but in binary.

The result `0b1111` can read as a signed int, in which case we read the value '-1', or you can read as unsigned, and you read it as '15'.

The same thing is working in your case, only that your `int` are 32 bits long.

The `unsigned` keyword is not a promise that "0-1" will produce "0". It only indicates that whatever bit configuration is inside that variable, it will be treat as a positive value.

body:
The variable "interval" is an unsigned long.  This means it can not go negative.  It also means that it is made up of a 32 bits.

Instead of going negative, an unsigned variable will cycle to its most maximum value by following a modulo 2 math behavior.  So a 32 bit value will become 2^32 or 4294967296 if, for example, decremented 1 past 0.

In the above program the 32 bit value was decremented by 1000 past 0 resulting in 4294967296 - 1000 or 4294966296.

Testing if an unsigned number is negative is futile.  So this code:

      if(interval <= 0)
      {
        interval = 0;
      }

...does nothing.  Instead, test if "interval" is larger than 1000 before subtracting 1000.

body:
As already mentioned in previous answers, the issue is that an unsigned
number wraps modulo MAX+1. The obvious fix would be to make `interval` a
signed number.

Another option would be to avoid subtracting from `interval` anything
larger that `interval` itself. You could do this by replacing

    interval = interval - 1000;
    if(interval <= 0) {
      interval = 0;
    }

by

    if (interval >= 1000)
      interval -= 1000;
    else
      interval = 0;

Note that the `else` clause could be dropped if you can guarantee that
`interval` is always a multiple of 1000.


body:
I have a small project that I have in mind and I'm pretty new with Arduino.

I want to make a small device that if a key was pressed it would do something.

Now I know I could use a button with the device but I want to specifically use a Cherry MX Blue Switch.

So I wanted to know if the test code I wrote up would get me in the right stating place and I want to know where I would wire the key switch onto the board.

From how I have the code written I'm guessing I connect the positive pin from the switch to P0 on the board and the other pin to ground on the board, is this correct?

    #include "DigiKeyboard.h"

    void setup() {
        pinMode(0, INPUT);
    }

    void loop() {
        // put your main code here, to run repeatedly:
        if(digitalRead(0)==HIGH){
            DigiKeyboard.sendKeyStroke(MOD_GUI_LEFT,KEY_R);
            DigiKeyboard.print("test");
        }
    }

title: Digispark ATtiny85 keyboard

Answers: 2

body:
I would suggest to connect one pin of the with to 5v and the other to ground. The Arduino will be able to detect 5v as logic HIGH.

The code looks correct except for better programming technique I would suggest to indent you code, this make debugging easier for longer programs:

    #include "DigiKeyboard.h"

    void setup() {

       pinMode(0, INPUT);

    }

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

      if(digitalRead(0)==HIGH){

        DigiKeyboard.sendKeyStroke(MOD_GUI_LEFT,KEY_R);
        DigiKeyboard.print("test");

      }
    }

body:
Do you want the absolute lowest power consumption? If yes then instead of using a microcontroller, use a dual D type latch. The circuit below will take the first break of the optical beam, turn on the output for that latch, and will block the other latch from turning on.

When the clock input goes high (beam broken) the high on the D input is transferred to Q and -Q will go low. That low will force the output of the other latch to stay low.

To reset the light the push button switch is used to clear the Q output. It is then ready again.

I didn't show the power supply (bypass cap). The chip is a CD74HC74. 14 pins containing two latches.The only current drawn is the LED current and the current of the opto-transistors.

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

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


body:
I'm trying to upload code from a Mac (online Arduino editor) onto an Arduino Mega2560, to connect a motor to pin 52 and Ground to get it to move. But at the top it says busy (like it does when it uploads) and doesn't do anything else. Refreshing the page doesn't work. The code is verified, and here's the code:

    void setup() {
    }

    void loop() {
      digitalWrite(52,HIGH);
    }

The Arduino application (with same code copied in) comes up with this error:

    Arduino: 1.8.4 (Mac OS X), Board: "Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)" Sketch uses 1190 bytes (0%) of program storage space. Maximum is 253952 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 8183 bytes for local variables. Maximum is 8192 bytes.
    avrdude: ser_open(): can't open device "COM1": No such file or directory
    ioctl("TIOCMGET"): Inappropriate ioctl for device
    ioctl("TIOCMGET"): Inappropriate ioctl for device
    avrdude: ser_send(): write error: Bad file descriptor
    avrdude: stk500_send(): failed to send command to serial port
    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_getsync(): timeout communicating with programmer
    the selected serial port avrdude: stk500v2_getsync(): timeout communicating with programmer does not exist or your board is not connected

I hope someone can work out why it doesn't upload!

title: Uploading code to Mega 2560 is stuck

Answers: 1

body:
I would suggest to download the Arduino app (https://www.arduino.cc/en/Main/Software).

Download both the latest version and an a legacy build (https://www.arduino.cc/en/Main/OldSoftwareReleases#00xx). Within the DMG for the legacy you'll need to install the FTDI drivers to allow Arduino app to see the Arduino in ports.


body:
I have had a DS18B20-PAR for some time and have often used it without a problem until now. Yesterday it just suddenly stopped working. I was trying to use it along with two i2C sensors at the time. I don't really know of anything which could have fried it, though.

**Edit**: It is turning out much more complicated than I thought. I can't ever get it to work on pin 10. The sensor sometimes works on other pins (3, 9 and 11), but it often does not. I can still use pin 10 to blink and fade an LED, and receive input from a button, but it never picks up my DS18B20-PAR. What is happening here?

# My setup:

I have just one DS18B20-PAR connected to my Arduino Uno look-alike as shown in the following image:

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

Please note that on the DS18B20-PAR the third pin is internally not connected.

# The code:

My Arduino is running this code (a OneWire example sketch which has always worked before):

    #include <OneWire.h>

    // OneWire DS18S20, DS18B20, DS1822 Temperature Example
    //
    // http://www.pjrc.com/teensy/td_libs_OneWire.html
    //
    // The DallasTemperature library can do all this work for you!
    // http://milesburton.com/Dallas_Temperature_Control_Library

    OneWire  ds(10);  // on pin 10 (a 4.7K resistor is necessary)

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

    void loop(void) {
      byte i;
      byte present = 0;
      byte type_s;
      byte data[12];
      byte addr[8];
      float celsius, fahrenheit;

      if ( !ds.search(addr)) {
        Serial.println("No more addresses.");
        Serial.println();
        ds.reset_search();
        delay(250);
        return;
      }

      Serial.print("ROM =");
      for( i = 0; i < 8; i++) {
        Serial.write(' ');
        Serial.print(addr[i], HEX);
      }

      if (OneWire::crc8(addr, 7) != addr[7]) {
          Serial.println("CRC is not valid!");
          return;
      }
      Serial.println();

      // the first ROM byte indicates which chip
      switch (addr[0]) {
        case 0x10:
          Serial.println("  Chip = DS18S20");  // or old DS1820
          type_s = 1;
          break;
        case 0x28:
          Serial.println("  Chip = DS18B20");
          type_s = 0;
          break;
        case 0x22:
          Serial.println("  Chip = DS1822");
          type_s = 0;
          break;
        default:
          Serial.println("Device is not a DS18x20 family device.");
          return;
      }

      ds.reset();
      ds.select(addr);
      ds.write(0x44, 1);        // start conversion, with parasite power on at the end

      delay(1000);     // maybe 750ms is enough, maybe not
      // we might do a ds.depower() here, but the reset will take care of it.

      present = ds.reset();
      ds.select(addr);
      ds.write(0xBE);         // Read Scratchpad

      Serial.print("  Data = ");
      Serial.print(present, HEX);
      Serial.print(" ");
      for ( i = 0; i < 9; i++) {           // we need 9 bytes
        data[i] = ds.read();
        Serial.print(data[i], HEX);
        Serial.print(" ");
      }
      Serial.print(" CRC=");
      Serial.print(OneWire::crc8(data, 8), HEX);
      Serial.println();

      // Convert the data to actual temperature
      // because the result is a 16 bit signed integer, it should
      // be stored to an "int16_t" type, which is always 16 bits
      // even when compiled on a 32 bit processor.
      int16_t raw = (data[1] << 8) | data[0];
      if (type_s) {
        raw = raw << 3; // 9 bit resolution default
        if (data[7] == 0x10) {
          // "count remain" gives full 12 bit resolution
          raw = (raw & 0xFFF0) + 12 - data[6];
        }
      } else {
        byte cfg = (data[4] & 0x60);
        // at lower res, the low bits are undefined, so let's zero them
        if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
        else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
        else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
        //// default is 12 bit resolution, 750 ms conversion time
      }
      celsius = (float)raw / 16.0;
      fahrenheit = celsius * 1.8 + 32.0;
      Serial.print("  Temperature = ");
      Serial.print(celsius);
      Serial.print(" Celsius, ");
      Serial.print(fahrenheit);
      Serial.println(" Fahrenheit");
    }
On the serial monitor is just prints "No more addresses." every 250 milliseconds.

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

title: Why is my DS18B20-PAR not picked up?

Answers: 1

body:
If the setup worked fine and then stopped, you must examine what changed. If your code is unchanged then it could be your sensor or your Arduino.

You can try putting the sensor on a different input pin and update the code accordingly.

You can try the sensor on a different Arduino or a new sensor if the same type on your Arduino.

These are the first steps to troubleshooting.


body:
I need help adding a pushbutton to provide power to an Arduino to save power, as I am using a battery and the same button to power it off. This is the circuit I wish to implement.

[![this is the circuit I wish to implement][1]][1]

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

Thanks.

title: Using a pushbutton to power Arduino on and off

Answers: 3

body: You can attach an interrupt and just turn the arduino in sleep mode. If one of your mudules drain power while beeng inactive and drains less than 20mah while working than connect the VCC to one of the digital pins and when the arduino wakes up just turn the pin to HIGH.

body: You can use the button as a switcher for the Arduino power. Just wire up the button between the battery + out and the Arduino's Vin port.

body:
This is a hardware/software "bootstrapping" problem: you need a power switch to be controlled by an Arduino, but the power switch also feeds power to, or turns ON the Arduino, which means the Arduino can't control the power switch until the Arduino is ON, and the Arduino can't be ON until the power switch is ON. Each relies on the other, so you must "bootstrap" it to turn it on and get the cycle started.

The process will look like this: you mechanically press a button with your finger, which controls either the Gate of a MOSFET transistor or the Base of a BJT transistor (or it could even power ON a normally-off relay), momentarily turning it ON. This split-second of ON time is just enough to turn on the Arduino, which now commands a signal to the Gate or Base to keep the transistor ON. Now, the Arduino maintains its own power, continually sending the necessary signal to the transistor to keep the transistor ON, which in turn powers the Arduino to keep the Arduino ON. Now, you can press another button to turn the Arduino OFF. This other button press will be read simply as a button press and the Arduino will then command the digital output pin to stop sending the signal which keeps the transistor ON, thereby turning the transistor OFF, which then turns the Arduino OFF. Now, the whole system is 100% OFF. The Arduino isn't even in sleep mode, it's just 100% not powered anymore. You use your finger press on the ON button again to bootstrap the whole system and start the process over again.

As for all of the details, this is an interesting problem I've been wanting to implement for years. I suspect it could be done with a single button, but haven't gone through the design to prove it yet. Meanwhile, for simplicity's sake, just use two separate buttons: one for ON and one for OFF, as I describe above.


body:
I'm able to get json data and storing in String object, now i want to convert string into Char Array for parsing json data

I'm tried with this code, but it is not responding

          String data = http.getString();   //Get the request response payload
          Serial.println(data);                     //Print the response payload
          int len=data.length();
          Serial.println(len);

          char  buf[len + 1];
          data.toCharArray(buf, len + 1);
          int bufLength = sizeof(buf);
          Serial.println(bufLength);   //Printing nothing

title: Convert String data To char Array in Arduino

Answers: 0


body:
I'm new to this forum, so hello to everyone out there.

So I have an Uno with A0 connected to the positive end of a chain of LEDs (they light up when a motion sensor goes off, clunky, but it works), and the negative end is hooked up to the GND of the analog side of the Uno. It runs the following code:

    void setup()
    {
      Serial.begin(115200);
      pinMode(A0, INPUT);
      pinMode(A1, INPUT);
    }

    void loop()
    {

      Serial.println(printVals(A0));
    }

    float printVals(uint8_t pin)
    {
      int sensorValue = analogRead(pin);
      float voltage = sensorValue * (5.00 / 1023.00);
      return voltage;
    }

And when I open the Serial Plotter, I get a weird square wave for the voltage (when there is 0V on the LEDs, I used a volt meter).
Out of curiosity, I added a jumper cable from A2 to +5V (the red wire in the diagram) and added plotting for A2, and this solved the problem - except now, the read on A0 is about 0.53.

Now, I'm more of a software guy, so I figure just subtract 0.53 and move on (varies only +- 0.03V), but I want to know: What in the world did that jumper cable do?![enter image description here](https://i.stack.imgur.com/Bc9XT.png)![enter image description here](https://i.stack.imgur.com/7u1nq.png)![enter image description here](https://i.stack.imgur.com/voQYE.png)

title: Weird Voltage Noise

Answers: 2

body:
Why are you connecting a chain of leds to a pin setted as an input and then connected to GND? I think that is like connect the pin to nothing.
in the documentation of arduino they have a note about the funcion analogRead() and a fluctuation of data.
https://www.arduino.cc/reference/en/language/functions/analog-io/analogread/
i think if you need to read an input put a button (or maybe i didnt understand you scheme)

body:
@Ferba, my chain of LEDs is actually part of a circuit board for a driveway monitor receiver. When it detects motion, the LEDs light up and the voltage measured by analogRead increases by about a volt.

Also, as it turns out, the jumper to +5v was functioning as a pull-up wire... not a good idea. It burned out the chip in the driveway monitor by backfeeding an output.
In the end, I added an "_PULLUP" after the INPUT in setup and that solved the problem.


body:
I'm building a MIDI synthesizer on Arduino Uno, and am considering user interface options.

I see on Adafruit and Sparkfun there are 16x2 LCD panels available that interface via I2C serial or by UART, but I think neither of those will work in my application:

 * The UART is clocked at 31250 baud to receive MIDI, and that's not a supported baud rate for these LCD devices;

 * I'm producing audio by driving an external DAC (MCP4725) over full-speed I2C; any transmission to another device would audibly jitter the DAC output;

 * SoftwareSerial would get around the UART clocking problem, but I believe it would stall the main loop while driving the output.

One option might be to roll my own software serial routine, carefully clocking it on the main loop, which (I believe) reliably runs at either 14.8KHz or 22.2KHz depending on the DAC protocol in use. I could set a SparkFun SerLCD into a slow data rate (2400 baud) and count passes through the main loop to time the data output.

Another option would be to use a secondary MCU -- I have a surplus Trinket M0 on hand -- and define a custom synchronous serial protocol between the two MCUs, and have the secondary relay commands to the LCD but that's getting into Rube Goldberg territory.

Any obvious options I'm overlooking?

title: Alternative to UART/I2C LCD displays?

Answers: 1

body:
One obvious option would be to get a display with SPI interface, since you have it available. Another option is to get a DAC running on SPI, and use the I2C for the display.

If you insist on using one of these 16x2 LCDs, there are SPI adapters for them as well. [Example](http://bitwizard.nl/shop/LCD-I2C-SPI-Interface-with-16x2-LCD)


body:
I want to post data that I'm getting from the sensor every 5 seconds to my application in JSON format. Initially, I'm getting data as int and converting into String.

For example:

if data=15, it is converting into string.

    String st=String(data);

Now I want to post `st` every 5 seconds.

        int S2 = http.sendRequest("PUT", "{\"itemId\":\"64006A962B71A1E7B3A0428637DA997C.327681\",\"item\":{\"Properties\":{\"AssetSensorDistance\":\"+st+\"}},\"operationType\":\"Update\",\"originalItem\":{\"Work_Order\":{\"ItemId\":\"64006A962B71A1E7B3A0428637DA997C.327681\"},\"Properties\":{\"AssetSensorDistance\":\"+st1+\"}}}");
        Serial.print("Sensor Status: ");
        Serial.println(S2);

st1 is the previous value, it is printing httpcode -2(invalid Syntax).

Can anyone help me with this issue?

Thanks in advance.

title: How to post JSON data from Arduino?

Answers: 1

body:
The string

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

    "{\"AssetSensorDistance\":\"+st+\"}"

contains a literal "+st+". If you want to do string concatenation, you
should terminate the string with a double quote character, then add st,
then use another double quote to start the second part of the string:

    "{\"AssetSensorDistance\":\""+st+"\"}"


body:
I have written a simple code to delay the blinking of LED 13, the delay time is set by us.I have incurred a problem when I enter a 2 digit value in the serial monitor.There is some problem with the ASCII. Is there a way to solve this problem without using `Serial.parseInt()`.

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

    void setup()
    {
      Serial.begin(9600);
      Serial.println("Programming is starting");
      pinMode(13,OUTPUT);
    }

    void loop()
    {
      if(Serial.available())
      {
        int val=Serial.read();
        int val1=val-'0';
        Serial.println(val1);
        digitalWrite(13,HIGH);
        delay(val1*1000);
        digitalWrite(13,LOW);
      }
    }

title: LED Programme where it delays the amount written in the Serial Monitor

Answers: 1

body:
Here you have.

No error checking. Anything not digit produce zero as output.

    void setup()
    {
     Serial.begin(9600);
     Serial.println("Programming is starting");
     pinMode(13,OUTPUT);
    }

    void loop()
    {
     static int value = 0;

     while(Serial.available() > 0) {
      int c = Serial.read();

      if(isDigit(c)) {
       value = value * 10 + (c - '0');
      } else {
       Serial.println(value);
       digitalWrite(13,HIGH);
            delay(value*1000);
       digitalWrite(13,LOW);
                value = 0;
      }
     }

It convert chars to values as they are being readed, one by one. There are no size limit for the input string, other that final value must fit in an `int`

You write a value in the Serial Monitor and end it with return, space bar or whatever non digit key you want.


body:
From various example on how to use optocouplers ( eg 4N25)  I gathered that they
work in inverted way meaning that for the optocoupler to output a signal,
the input LED must be OFF.

This is very easy to process by code as I just need to use digitalWrite LOW
instead of digitalWrite HIGH to activate the output of the optocoupler.

My problem is that when I reboot the arduino, the optocupler LED goes OFF and thus activate the ouput of the optocoupler for a few seconds until the code is loaded on the arduino.

How can I prevent this behavior ? Should I connect the optocoupler in a non inverted way ? ( And if so how ? ). Should I use an inverter ?

title: How to prevent optocoupler to activate when resetting the arduino?

Answers: 1

body:
The Fairchild datasheet for 4N25 shows this diagram:

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

describing the (or 'an') operation of the device. If this is how yours is operating, and if the input side is connected between an output pin and ground, then yes, on reset, the LED will go out and the switched output will go high. If you connect the device's input between the pin and +5v, the LED will light on reset, taking the switched output low. Plus, the switched output will now have the same sense as the Arduino output pin: i.e., `digitalWrite(PIN, HIGH)` will turn the switched output on, and vice-versa.

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


body:
Hey all I am wondering if my code below can be modified in order for the Arduino to send more than 300 chars to a HM-10 bluetooth 4.0 le module?

<!-- language-all: lang-cpp -->

    #include <SoftwareSerial.h>
    #define SERIAL_BUFFER_SIZE 512

    SoftwareSerial bluetooth(8,9); // RX, TX
    String btString;
    String comString;
    int isVS;

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(115200);
      while (!Serial) {;}

      Serial.println("PC Side Connected");

      bluetooth.begin(115200);
      while (!bluetooth) {;}

      bluetooth.println("Bluetooth Side Connected");
    }

    void loop() {
      if (Serial.available() > 0) {
        //The IDE Sends and the phone receives
        comString = Serial.readString();

        //Check to see if this request is coming from Visual Studio
        isVS = comString.indexOf("_VS");

        if (isVS > -1) {
          //Is coming from Visual Studio so display it over serial port
        } else {
          //Not coming from VS so send it to the bluetooth phone
          //bluetooth.write(comString);
          bluetooth.println(comString);
        }
      }

      if (bluetooth.available() > 0) {
        //The phone sends and the IDE receives
        btString = bluetooth.readStringUntil('\n');
        Serial.println(btString);
      }
    }

As in my code above, I've already tried to add the **#define SERIAL_BUFFER_SIZE 512** to the top to give the software serial more buffers but that does not allow me to send more than ~310 chars.

So sending this string:

> {MAC:'00-14-22-01-23-45',settings:{rgb:true,quotes:true,sleep:false,timeFrame:{on:'05:30:00',off:'22:30:00'},reset:false,weatherZip:'57104',userInfo:{left:'John
> Rambo',right:'T100'}},wifiInfo:{Name:'ItBurnsWhenIP',Pwd:'AwHk6gKnsMdxw3boWWAhus5NNCV304YQb/2287QqzH0WnS5W59vCzzW2pR8kgHI79hAUglQOCcBiEKiNWRBQ3oyvyJ0/fDfM1aKa9gfoy3kGHA=='}}

works just fine but if i send out a little more information:

> {MAC:'00-14-22-01-23-45',settings:{rgb:true,quotes:true,sleep:false,timeFrame:{on:'05:30:00',off:'22:30:00'},reset:false,weatherZip:'57104',userInfo:{left:'JohnRambo',right:'T100'}},wifiInfo:{Name:'ItBurnsWhenIP',Pwd:'AwHk6gKnsMdxw3boWWAhus5NNCV304YQb/2287QqzH0WnS5W59vCzzW2pR8kgHI79hAUglQOCcBiEKiNWRBQ3oyvyJ0/fDfM1aKa9gfoy3kGHA==','testing
> out some more strings'}}

It shows everything but the **gs'}}** at the end on the iphone.

How would i go about fixing this so i can send much more than this?

title: Arduino hardwareSerial Bluetooth.println not sending string over 310 chars

Answers: 0


body:
What is a rev id? I have looked everywhere for a proper definition but I haven't found anything. I am trying to understand the code below. I don't understand why this read_rev_id function is necessary and yes, I tried to look in the user manual for the IMU I am using but it is practically none-existent. I am using the myAHRS IMU and the only manual I could find, on GitHub, didn't even show a register by this name.

    void setup()
    {
      //Initialization
      Wire.begin();
      Serial.begin(115200);
      who_am_i();
      read_rev_id();
      delay(1000); //Wait for 1second.
    }

title: rev id and read_rev_id() function

Answers: 1

body:
You haven't provided enough information for anyone to easily help you. Assuming that you took your code from GitHub myAHRS_plus_i2c.ino you can look further down the file to find the definition of **read_rev_id()**. It simply reads the revision number from the AHRS chip and displays it on the console. Since this is all that it does you could leave out the call to read_rev_id(). But if you are going to use it then be aware that it contains an obvious bug. The second **read()** should be to I2C_SLAVE_REG_REV_ID_MINOR.

    //READ REVISION ID
    int read_rev_id()
    {
        uint8_t id_1 = 0;
        uint8_t id_2 = 0;
        read(I2C_SLAVE_REG_REV_ID_MAJOR, &id_1, 1);
        read(I2C_SLAVE_REG_REV_ID_MAJOR, &id_2, 1);
        Serial.print("READ REVISION ID= "); Serial.print(id_1); Serial.println(id_2);
    }