body:
Your first problem is here:

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

    char ReadKeypad(){
      if(button1.isPressed() && !button2.isPressed()){
        return 'D';
      }
      else if(button2.isPressed() && !button1.isPressed()){
        return 'U';
      }
      else if (!button1.isPressed() && !button2.isPressed()){
        return 'N';
      }
      else if (button1.isPressed() && button2.isPressed()){
        return 'S';
      }
    }

The compiler gives a warning, which you should pay attention to:

<!-- language: lang-none -->

    In function 'char ReadKeypad()':
    warning: control reaches end of non-void function [-Wreturn-type]
     }
     ^

The warning basically is that if no button is pressed you are returning an undefined value. It would be better to add to the end:

    return 0;  // no button pressed

---

Then later on in `page1` function:

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

      for (int i; i<16; i++){
        lcd.print(binary[i]);
      }

Another compiler warning:

<!-- language: lang-none -->

    In function 'void page1()':
    warning: 'i' may be used uninitialized in this function [-Wmaybe-uninitialized]
           for (int i; i<16; i++){

You haven't initialized `i` so it could have any value. That should read:

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

      for (int i = 0; i<16; i++){
        lcd.print(binary[i]);
      }

Ditto further down.

---

If I add some debugging here:

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

    void MainmenuBtn(){
      btn_push = ReadKeypad();
      Serial.print ("btn_push = ");
      Serial.println (btn_push);
     // WaitBtnRelease();
    }

And then press a button, I see:

<!-- language: lang-none -->

    btn_push = D
    btn_push = D
    btn_push = D
    btn_push = D
    btn_push = D
    btn_push = D
    btn_push = D
    btn_push = D
    btn_push = D
    btn_push = D
    btn_push = D
    btn_push = D

So that is registering as **many** presses, not just one. You should test for "has the button state changed?". That is:

* Is the button closed now?
* Was it closed before?
* If the two are different, then the button has just been pressed.

---

Adding debugging prints is **very helpful** in general when things aren't going to plan.

If you had added those extra prints to your MainmenuBtn function you would immediately have seen that it looked like the button was pressed hundreds of times (until you let go) rather than once.

>  the position changes from 1 to 8 or 16 instead of to the second bit when I hit the right button

Exactly. Since it is treating a button press as a multiple press you would expect exactly that to happen. Effectively you have built in a very fast auto-repeat (unintentionally).

---

### Edited to add:

Your code is so confusing I've rewritten the state change stuff.

    #include <LiquidCrystal.h>
    /*(RS, E, D4, D5, D6, D7)*/
    LiquidCrystal lcd(12,11,5,4,3,2);
    #include <Button.h>

    int page = 0;
    int binary[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    int con = 80;
    char btn_push;
    int pos = 0;

    const int button1Pin = 8;
    const int button2Pin = 9;
    int button1State = HIGH;
    int button2State = HIGH;
    int lastButton1State = HIGH;
    int lastButton2State = HIGH;

    unsigned long debounceDelay = 50;

    //****************************************************************setup*****************************************
    void setup() {
      pinMode(button1Pin, INPUT_PULLUP);
      pinMode(button2Pin, INPUT_PULLUP);

      Serial.begin(9600);
      analogWrite(6,con);
      mylcd.begin();
      lcd.print("Welcome");
    }

    //************************************************************loop************************************************

    void loop() {

      int reading1 = digitalRead(button1Pin);
      int reading2 = digitalRead(button2Pin);

      if (reading1 == lastButton1State &&
          reading2 == lastButton2State)
        return;  // do nothing if no change

      delay (debounceDelay);  // debounce

      // re-read so we can catch both buttons down at once
      reading1 = digitalRead(button1Pin);
      reading2 = digitalRead(button2Pin);

      // save for next time
      lastButton1State = reading1;
      lastButton2State = reading2;

      if (reading1 == LOW && reading2 == HIGH)     // first one down
        btn_push = 'D';
      else if (reading1 == HIGH && reading2 == LOW)  // second one down
        btn_push = 'U';
      else if (reading1 == LOW && reading2 == LOW)  // both
        btn_push = 'S';
      else
        return;  // nothing interesting

     Serial.print("btn_push = ");
     Serial.println(btn_push);

        // page select
        switch (page) {

        case 0:
          page0();
          break;
        case 1:
          page1();
          break;
        case 2:
          page2();
          break;
        case 3:
          page3();
          break;
        case 4:
          page4();
          break;
        }

    }

    // The rest is the same, excluding the functions that are no longer needed

I made the buttons INPUT_PULLUP so that they normally read HIGH if not pressed, thus LOW means pressed (therefore the switches should be wired from the digital pin on one side to Gnd on the other side).

It still isn't perfect but that should give you something to play with. Add some more debugging prints to see what is going on in the other functions.


sender: user

message:
BridgeServer REST API with more string values

I wold like to make me a REST API with string values and more string Keys.

like: ~http://url.tld/foo/bar/xy to get "bar" and do more...

Can somebody tell me how to get the second word out of the URL? In this case "bar".

The tutorial show's how to use /arduino/digital/13/1 as to set pin 13 High.I would like to get a different syntax.
Something like this: arduino/device1/switch/on

By now i searched quite long and tested different things as you can see below, but i can't get more than one word caught to trigger from the client object.

is boils down to the question why my client object changes the payload.

this part:

    void process(BridgeClient client) {
      String url0 = client.readString();
      Console.print("process url0: ");      // --> is "bar/xy"
      Console.println(url0);
      String command = client.readStringUntil('/');
      String url1 = client.readString();
      Console.print("process url1: ");
      Console.println(url1);               // --> is "" aka:empty!

i made a MWE to show what i already did:

    // Libraries:
    #include <Bridge.h>
    #include <BridgeServer.h>
    #include <BridgeClient.h>
    #include <Console.h>

    // Constants:
    const bool on = HIGH;
    const bool off = LOW;

    // Objects:
    BridgeServer server;

    void setup() {
      pinMode(6, INPUT_PULLUP);
      Bridge.begin();
      server.begin();
      Console.begin();
      while (!Console);
      Console.println("setup done..");
    }

    void loop() {
      BridgeClient client = server.accept();
      if (client) {
        process(client);
        client.stop();
      }
    }

    void process(BridgeClient client) {
        String url0 = client.readString();
        Console.print("process url0: ");   // --> is "bar/xy"
        Console.println(url0);
        String command = client.readStringUntil('/');
        String url1 = client.readString();
        Console.print("process url1: ");
        Console.println(url1);             // --> is "" aka:empty!
      if (command == "device1") {
        device1(client);
      }
      if (command == "status") {
        Console.print("process: command == status  | command: ");
        Console.println(command);
        statusCommand(client);
      }
    }

    void device1(BridgeClient client) {
      String URL = client.readString();
      Console.println("URL:");
      Console.println(URL);                               // ---> is "on"
      String mode = client.readStringUntil('\r');
      Console.println("mode:");
      Console.println(mode);                            // ---> is ""
      String value = getStringPartByNr(URL, '/', 1);
      Console.println("value:");
      Console.println(value);                            // ---> is ""
      power(on);
      if ( URL == "on"){
        client.print(F("found /on"));
        power(on);
      }
      else if ( URL == "off"){
        client.print(F("found /off"));
        power(off);
      }
    }

    void power(bool on_off){
      bool checkpin = digitalRead(6);                          // machine state
      if (checkpin == LOW && on_off == HIGH) {        // means power is off and on is called
        digitalWrite(13, HIGH);
        Console.print(" checkpin == LOW && on_off == HIGH [1] ");
      }
      else if (checkpin == HIGH && on_off == LOW) { // means power is on and off is called
        digitalWrite(13, LOW);
        Console.print(" checkpin == HIGH && on_off == LOW [2] ");
      }
    }

    void statusCommand(BridgeClient client) {
    }

    // splitting a string and return the part nr index split by separator
    String getStringPartByNr(String data, char separator, int index) {
        int stringData = 0;        //variable to count data part nr
        String dataPart = "";      //variable to hold the return text
        for(int i = 0; i<data.length()-1; i++) { //Walk through the text one letter at a time
            if(data[i]==separator) { //Count the number of times separator character appears
                stringData++;
            } else if(stringData==index) { //get the text when separator is the rignt one
                dataPart.concat(data[i]);
            } else if(stringData>index) { //return text and stop if the next separator appears
                return dataPart;
                break; // - to save CPU-time
            }
        }
        return dataPart; //return text if this is the last part
    }

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

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

sender: assistant

body:
You misunderstand the [networking Client class][1] concept. It is a [stream][2] like the Serial object. Bytes are stored in the Client object's buffer only until you read them.

  [1]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/Client.h
  [2]: https://www.arduino.cc/reference/en/language/functions/communication/stream/


message:
Unable to convert string read from bluetooth to int

I am using a HC-06 and i want to read a number ending with f as a delimiter, the first three numbers as my servo position, however converting the string into int is giving an endless series of 0s. I added the Serial.print(servopos) to see that its a never ending series of 0s, and nothing seems to fix this problem. What am I doing wrong? (I tried using long for servopos instead of int, it didn't fix the issue)

    #include <SoftwareSerial.h>
    #include <Servo.h>

    Servo myservo; // servo name

    int bluetoothTx = 10;
    int bluetoothRx = 11;
    int fwd = 12;
    int bwd = 13;

    SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
    String content = "";
    char character;

    void setup()
    {
      myservo.attach(9); // attach servo signal wire to pin 9
      //Setup usb serial connection to computer
      Serial.begin(9600);

      //Setup Bluetooth serial connection to android
      bluetooth.begin(9600);

      pinMode(fwd, OUTPUT);
      pinMode(bwd, OUTPUT);

    }

    void loop()
      {
      if(bluetooth.available()> 0 ) // receive number from bluetooth

        character = bluetooth.read();

        if (character!='f'){
            content += (char) character;
            delay(10);
          }

        else{
          int servopos = content.substring(0,3).toInt();
          Serial.print(servopos);
         // myservo.write(servopos);

          String directMvt = content.substring(3);
          if (directMvt == "00"){
                digitalWrite(fwd, LOW);
                digitalWrite(bwd, LOW);
          }
          else if (directMvt == "10"){
                digitalWrite(fwd, HIGH);
                digitalWrite(bwd, LOW);
          }
          else if (directMvt == "01"){
                digitalWrite(fwd, LOW);
                digitalWrite(bwd, HIGH);
          }
          else if (directMvt == "11"){
                digitalWrite(fwd, LOW);
                digitalWrite(bwd, LOW);
          }
          content = "";
      }
    }

body:
I've found your problem: You have a missing pair of `{ }`, that should enclose the `if(bluetooth.available()>0)` statement. Without the parenthesis it only encloses the following statement, which is the serial reading.

Now follow the logic: Before you are sending something over serial, the global variable `character` should be zero. So then, since the NULL character is not equal to `f`, the NULL characters are added to the string. Then you send a string like `18000f` via bluetooth serial. The code is adding the characters to the string variable, until it find the `f` character. Now it goes directly in the `else`-statement, printing the value of `servopos` and then resetting the string variable. On the next loop iteration, there isn't something available at the SoftwareSerial, so it goes to the `if(character !='f')` statement. The `character` variable is global and it is still filled with the `f` value, that it got in the last loop iteration. So the `else` statement is executed forever very fast. But since you reseted the content of the string variable in the last iteration, there is nothing to convert to integer here. So this gives you a forever lasting series of zeros.

Enclosing the code in the first `if` statement solves your problem, since then, it only does something, when data is available at the serial interface. Also you should consider using a local variable for `character`, since you only need it there and your problem would have been obvious (through a compiler error), if you used a local variable here. Using global variables, when there is no need to, can make things more complex and error-prone.


message:
ESP8266 cannot create TCP connections to this particular server

**EDIT**: I have created an issue about this here: https://github.com/esp8266/Arduino/issues/4593

---------------

**I have this server:** `185.205.210.197`
(Check that it works: http://185.205.210.197/)

**And I have this code in my ESP8266:**

    #include <ESP8266WiFi.h>

    #define HOST "185.205.210.197"
    #define PORT 80
    #define WIFI_SSID "SSID"
    #define WIFI_PSW "PASSWORD"

    const char* ssid = WIFI_SSID;
    const char* password = WIFI_PSW;

    void setup () {
      Serial.begin(115200);
      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(5000);
        Serial.println("Connecting to Wifi...");
      }

      while(!pingServer()) {
        delay(3000); //Send a request every 3 seconds
      }
    }

    void loop() {}

    bool pingServer() {
      WiFiClient client;

      if (!client.connect(HOST, PORT)) {
        Serial.println("connection failed");
        return false;
      }

      Serial.println("connection success!");
      return true;
    }

**The expected result:** Connection success, but got connection failed.

If I try connecting with my PC, it works, **only with ESP8266 it doesn't**.

Tapping with Wireshark I suspect that there is a problem with ESP8266 TCP packets, here I leave them for you to analyze:

**PC TCP connection request (which works):**

`000030006b081c001a48ea4c0000000010009e098004dba400000000800401009e090b221f000000c603000004000000880254009801a7ad45b7000af5f4e90c000af5f4e90c603c0000aaaa0300000008004500003c000040003706cb37b9cdd2c5c0a82b490050df312dfea1498c6ac92aa0120000079c00000204058c0402080a336f35554aeb0fe90103030700ead7d1`

**ESP8266 TCP connection request (which receives no response from server):**

`000019006f080000952a9f520000000012049e098004daa1000801a200000af5f4e90c2c3ae80f137f000af5f4e90c5000aaaa0300000008004500002c00030000ff06431dc0a82b70b9cdd2c5c00100500000196d000000006002086040f80000020402189ccdd933`

**What I've also checked:**

* The ESP connects fine to other servers.

* There is no firewall blocking the connection between ESP and the server.

* I've tried this in different networks and conditions, the error persists.

* Other computers can connect to the server, so ESP should be able as well.

* Tried with different ESP8266 boards to rule out hardware malfunctioning.

* I am using NODEMCU V0.9 board (original firmware) with Arduino IDE and [this ESP8266 library][1].

**How to replicate:**

0. Using the latest Arduino IDE and ESP8266 library.

1. Check that the test server works at http://185.205.210.197:80/ (just open this link basically and see that is running nginx).

2. Copy and upload the code above to your ESP8266 (NODEMCU or similar).

3. Open the Arduino IDE console/monitor and confirm that no connection is established to port 80.

4. Rage in admiration for such a strange bug.

**I've opened an Issue for this:** https://github.com/esp8266/Arduino/issues/4593

  [1]: https://github.com/esp8266/Arduino

body:
Not a cookie cutter answer, I did a quick test and my ESP8266 does connect to you nginx. Of course you do not accept the params from my fridge, but this is what I see in the log.

    7007 :
    7010 :

    For online documentation and support please refer to
    7012 : nginx.org.

    7015 : Commercial support is available at
    7018 : nginx.com.

    7020 :
    7022 :

    Thank you for using nginx.

    7024 :
    7026 :
    7028 : HTTP : closing connection

You should be able to see that on your side as well.

I am using letscontrolit/ESPEASY  https://github.com/letscontrolit/ESPEasy

And their code to connect looks like

      // Use WiFiClient class to create TCP connections
      WiFiClient client;
      if (!ControllerSettings.connectToHost(client))
      {
        connectionFailures++;
        addLog(LOG_LEVEL_ERROR, F("HTTP : connection failed"));
        return false;
    }

      boolean connectToHost(WiFiClient &client) {
        if (!checkHostReachable(true)) {
          return false; // Host not reachable
        }
        byte retry = 2;
        bool connected = false;
        while (retry > 0 && !connected) {
          --retry;
          connected = client.connect(getIP(), Port);
          if (connected) return true;
          if (!checkHostReachable(false))
            return false;
        }
        return false;
    }

I am using generic HTTP for my controller which here: https://github.com/letscontrolit/ESPEasy/blob/503fd3555e010b08b48fb2dc18290ef120005308/src/_C008.ino

You could try the connect to function to see if that works for you.


message:
Libraries/classes using other libraries/classes

This is, hopefully, a simple issue!

I'm trying to access my fully working libraries (fully compiles, and works with the hardware perfectly) from another library (Computer.h) to abstract it away from the Sketch.ino file.

LLRelay, and all my other libraries, work flawlessly when instanced/constructed/built/etc within the main Sketch.ino; however, when called within "Computer.h", there's issues.

I've been at this for most of the day trying different things, from instantiating the libraries in the header files, the *.cpp files, to within functions, to changing the scope and publicity/privacy of them - still no luck.  See the (2 * "HERE -") comments for the errors.

Any help is greatly appreciated!

This is what I have managed to reduce it down to for debugging:

Sketch.ino

    // Sketch.ino
    #include "Computer.h"

    Computer pc1;

    void setup(){};

    void loop(){
        pc1.update();
    };

Computer.h

    // "../customLibs/Computer.h"
    #ifndef Computer_lib
    #define Computer_lib
    #if(ARDUINO > 100)
        #include "Arduino.h"
    #else
        #include "WProgram.h"
    #endif

    class Computer {
     public:
      Computer();
      void update();
     private:
      void fans();
    };
    #endif

Computer.cpp

    // "../customLibs/Computer.cpp"
    #include "Computer.h"
    #include "src/relay/LLRelay.h" /* Potential culprit, I have tried many variations and locations for this to go, all with the same, or similar compilation errors */

    /* HERE - "undefined reference to `LLRelay::LLRelay(unsigned char)'" */
    LLRelay fan1(13); // fan1(uint8_t relayPin);

    Computer::Computer(){
     Serial.begin(9600);
    };

    void Computer::update(){
        fans();
    };

    void Computer::fans(){

     /* HERE - "undefined reference to `LLRelay::On()'" */
     fan1.On();

    };

LLRelay.h

    // "../customLibs/src/relay/LLRelay.h"
    #ifndef LLRelay_lib
    #define LLRelay_lib
    #if(ARDUINO > 100)
      #include "Arduino.h"
    #else
        #include "WProgram.h"
    #endif

    class LLRelay {
      public:
        LLRelay(uint8_t relayPin);
        void On();
        void Off();
      private:
        uint8_t _relayPin;
    };
    #endif

LLRelay.cpp

    // "../customLibs/src/relay/LLRelay.cpp"
    #include "LLRelay.h"

    LLRelay::LLRelay(uint8_t relayPin){
      _relayPin = relayPin;
      pinMode(_relayPin, OUTPUT);
      digitalWrite(_relayPin, LOW);
    };

    void LLRelay::On(){
      digitalWrite(_relayPin, HIGH);
    };

    void LLRelay::Off(){
      digitalWrite(_relayPin, LOW);
    };

body: The Arduino build process does not consider libraries used from other libraries. You will need to include `src/relay/LLRelay.h` in the main project file in order to make it compile.


body:
The Arduino IDE must detect the library to include it in the build process. It is done by matching a library to a header file by searching the libraries in configured library locations. Only the root folder and the `src` subfolder of a library are searched.

If your library is in the sketch folder's `libraries` subfolder and it is called `customLibs`, then only the `customLibs` folder and the `customLibs/src` subfolder are searched and the include file `LLRelay.h` in `customLibs/src/relay` folder is not found.

reference: [Layout of library folders and files][1]

  [1]: https://github.com/arduino/arduino/wiki/arduino-ide-1.5:-library-specification#layout-of-folders-and-files


message:
Load Cell and HX711 only outputting 0's

I am using an Arduino Uno and HX711 amplifier to collect data from a load cell. I previously had the load cell calibrated and functioning, but now the load cell will not read any values; only 0's are outputted, even when I apply a small load to the sensor. I have re-soldered and replaced the connecting wires. Are there any suggesting for getting a readout from my sensor?

I have been testing with 2 different load cells: Sparkfun's TAL220 Straight Bar 10kg load cell and an LFS 210-300 from Cooper Instruments (the latter is the one I want to use long term). My load cell is connected like the HX711 Breakout Guide (with an Arduino Uno instead of a RedBoard and a USB connection):

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

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

I have been using the HX711 Breakout Guide Calibration sketch to test my load cell:

    #include <HX711.h>

    #define DOUT 3
    #define CLK 2

    HX711 scale(DOUT, CLK);

    float calibration_factor = 282650; //-7050 worked for my 440lb max scale setup

    void setup() {
      Serial.begin(9600);
      Serial.println("HX711 calibration sketch");
      Serial.println("Remove all weight from scale");
      Serial.println("After readings begin, place known weight on scale");
      Serial.println("Press + or a to increase calibration factor");
      Serial.println("Press - or z to decrease calibration factor");

      scale.set_scale();
      scale.tare(); //Reset the scale to 0

      long zero_factor = scale.read_average(); //Get a baseline reading
      Serial.print("Zero factor: "); //This can be used to remove the need to tare the scale. Useful in permanent scale projects.
      Serial.println(zero_factor);
    }

    void loop() {

      scale.set_scale(calibration_factor); //Adjust to this calibration factor

      Serial.print("Reading: ");
      Serial.print(scale.get_units(), 1);
      Serial.print(" kgs"); //Change this to kg and re-adjust the calibration factor if you follow SI units like a sane person
      Serial.print(" calibration_factor: ");
      Serial.print(calibration_factor);
      Serial.println();

      if(Serial.available())
      {
        char temp = Serial.read();
        if(temp == '+' || temp == 'a')
          calibration_factor += 10;
        else if(temp == '-' || temp == 'z')
          calibration_factor -= 10;
      }
    }

I am still new to Arduino and data acquisition in general, so any suggestions would be appreciated!

body:
This line is where you are reading the data and printing it:

    Serial.print(scale.get_units(), 1);

The 1 on the end of the line defines how many digits you are displaying from your reading. I have a similar setup to yours and I have it set to 5 which shows up to +/-0.00001kg. (Obviously, the accuracy will be different depending on which load cell you have)


message:
Motor does not move with 4 batteries

I mada a  4wd car with ultrasonic sensors and servo. I use 4 AA 1.5 volt batteries for power. But the motor does not move. What is the problem?

![image](https://i.stack.imgur.com/pSJ3M.jpg)

![Schematic](https://i.stack.imgur.com/rTbik.jpg)

body:
In the future, please detail your attempts at solving the problem so far so we can help you better.

Approach the issue as methodically as possible. I don't know how familiar you are with electronics, so please excuse me if you think some of these questions are basic:

 1. Ensure that the servo motor works first without any other motors or
    sensors connected to the Arduino Sensor Shield (have you used this servo motor before?)
 2. Ensure that your GVS wiring is in the correct order. Servos come with a 3 way socket that plug straight onto the Sensor Shield: G goes to the Brown or Black wire, V goes to the (middle) Red wire, S goes to the Orange wire. The good news is as the +5V is in the middle, things will not blow up if you put the 3-pin plug on the wrong way. The servo just will not work until you plug it in correctly.
 3. Is the Arduino Sensor shield working correctly. Does the LED pin work? Do other signals sent from the board work?
 3. Remember that servo motors work differently to normal DC motors. You need to use [Pulse Width Modulation][1] to set the position. If you have never done this before, you will find the [Arduino Servo Motors][2] page useful. Also, you will get some excellent understanding and code from this [Adafruit page][3]. It is for a different Arduino shield, but the principles are the same.

  [1]: https://en.wikipedia.org/wiki/Pulse-width_modulation
  [2]: https://www.arduino.cc/en/Reference/Servo
  [3]: https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino


body: Use a LiPo battery I.e 2S(7.4V)


message:
Problem uploading to ATMega using ArduinoIDE ("unbricking" "bricked" microcontroller?)

I've a SparkFun Pro Micro which is an Arduino Leonardo clone. Unfortunately my attempts to upload programs failed. I did some research in the internet and found you have to use SparkFun's configuration. There is a board manager's URL you have to use: https://raw.githubusercontent.com/sparkfun/Arduino_Boards/master/IDE_Board_Manager/package_sparkfun_index.json

So far so good. After trying to use this I attempted to do an upload and failed. I tried it with different settings but all failed. While earlier there was a serial port named `/dev/ttyACM0` there now is no such port any more. Further research gave me the information that you might get the device running if you a) reset to boot loader mode where you should have an 8 seconds window to upload and b) actually perform the upload.

I can verify: If I pull RESET to ground I can switch into this 8 seconds mode. Then the device `/dev/ttyACM0` appears after about 1 second for about 7 seconds. As instructed I immediately try to do an upload. This is strange: I immediately (!) get the following output:

* Line 1: `Sketch uses 4140 bytes (14%) of program storage space. Maximum is 28672 bytes.`
* Line 2: `Global variables use 149 bytes (5%) of dynamic memory, leaving 2411 bytes for local variables. Maximum is 2560 bytes.`
* Line 3: `avrdude: ser_open(): can't open device "/dev/ttyACM0": No such file or directory`
* Line 4: `Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.`

The TTY should be there as the 7 seconds have not been passed in that case. Furthermore my user account is in `dialout` which enables it to use the tty.

If I trust this error message that means the tty is gone as soon as `avrdude` tries to access it. Which shouldn't be that way, should it?

Has anyone encountered this situation before? How can I upload a program to the mikrocontroller? Has anyone has any experience with that situation here?

--

Additional information:

* ArdunoIDE 1.8.5
* Ubuntu (Mate) Linux 16.04

body:
We use these a lot, and it's very easy to accidentally program the boards with the incorrect settings - particularly as the Sparkfun Pro Micro library defaults to the 3.3V/8 MHz variant instead of the more common 5V/16MHz.

I have recovered the boards with the bootloader reset method, but it is hard - you have to get the timing just right. What we do now is to simply reinstall the bootloader using an ISP programmer (instructions: https://learn.sparkfun.com/tutorials/installing-an-arduino-bootloader). It works first time, and ends up being much quicker than repeated tries to get the reset timing right. Just make sure that you have the right board selected when you burn the bootloader. We use a USBASP, and it only takes a couple of minutes to set up.


message:
SIM800L can't send SMS

I have a SIM800L module (green board). I used [this][1] to test my module.

In that page, it use a SIM800L red board with a 3.7v LiPo battery. But I directly connected 5v from the Uno to the module.

 *            GND      >>>   GND
 *        RX  10       >>>   TX
 *        TX  11       >>>   RX
 *            5v       >>>   Vin

I see "Message Sent Successfully!" message in COM window but nothing happened.

I can not find the problem.

The SIM800L module (green board) specification [is here][2].

The SIM800L module (red-green-blue boards) [is here][3].

  [1]: https://exploreembedded.com/wiki/GSM_SIM800L_Sheild_with_Arduino
  [2]: http://thecaferobot.com/store/sim800l-gprs-gsm-sms-microsim-module-5v
  [3]: http://thecaferobot.com/store/catalogsearch/result/?q=SIM800L

body:
I used a [Power Supply][1] and tested the board and SIM800L with it.

At the beginning, the SIM800L only uses a max of 100mA (V = 5v) and after finding the network only 10mA. In this situation the message is sent. I tested it with 4.2v but no message was sent.

It seems it needs 5v to be applied. The 5v of the Uno will be reduced to reach the SIM800L and so no message is sent.

  [1]: https://en.wikipedia.org/wiki/Power_supply


message:
Arduino with stepper motor

I'm trying to control a stepper motor for my FYP with an Arduino Mega. I tried code form examples, stepper one revolution. It worked when I uploaded it but if i turn the power off during the half position of a revolution, then next time I turn on the supply it first moves that portion backwards then it works according to the program. I want that when I turn on the power supply it should move according to the code and forget the last movement. Can anybody help me on this issue?

body: A stepper motor doesn't have any mechanical "steps" as such. When powered off, a stepper is free-wheeling. When you power it up - energize a set of set of coils - the rotor will move to the nearest of several positions corresponding to whichever coils are energized. Thus, it doesn't retain its position across a power-down; your code has to "find it" each time. Usually that involves driving it until the attached mechanism trips an optical or mechanical switch, giving the software a reference-point. Your other option is to apply a holding current (less than the stepping current) to the presently energized coils and not completely power down the motor's power supply when the rest of the system powers down. The software would have to save the motor position before the power down in a non-volatile memory, such as EEPROM, where it can retrieve it again at the next power-up.


message:
Avrdude can't connect to butterfly programmer

I'm trying to upload my exported HEX file by avrdude using this command
```
/Users/user_acc/Downloads/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/Users/user_acc/Downloads/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -P/dev/cu.usbmodem1421 -b57600 -D -Uflash:w:/Users/user_acc/Documents/Arduino/at_command_A6/at_command_A6.ino.with_bootloader.leonardo.hex:i
```

But instead of loading the file it's stuck on connecting to programmer.

Output: https://scr.hu/rYNzzm
https://paste.ubuntu.com/p/74p37fGYPN/

The output from ArduinoIDE is exactly the same and it finds the programmer without the problem and loads the file.

```
/private/var/folders/5h/7rxp3rmn5351zh6r8cxhz1sr0000gn/T/AppTranslocation/5C2325EE-CF38-4140-8860-717C9DBAF376/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/private/var/folders/5h/7rxp3rmn5351zh6r8cxhz1sr0000gn/T/AppTranslocation/5C2325EE-CF38-4140-8860-717C9DBAF376/d/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -P/dev/cu.usbmodem124 -b57600 -D -Uflash:w:/var/folders/5h/7rxp3rmn5351zh6r8cxhz1sr0000gn/T/arduino_build_78519/at_command_A6.ino.hex:i
```

Output: https://scr.hu/M72NaV

Can somebody help me? :)

body:
I found a post of somebody with a similar issue. His solution fixed my issue!

https://stackoverflow.com/questions/46813157/avrdude-command-line-cant-connect-to-programmer-for-leonardo


message:
LGPL and Arduino in Commercial Products

I basically would like to ask this same question (in another context / more generically):

https://www.reddit.com/r/arduino/comments/25my2t/lgpl_and_arduino_in_commercial_products/

Stated differently:

What are the legal implications of LGPL licence in commercial products using Arduino boards (and or Arduino software/firmware)?

and about creating my own libraries for Arduino? (less or more permissive licenses cases for a derivative work)

and lastly, I'm also curious about this statically vs linked library conditions of LGPL (and how this would be applicable in this case)

thanks!

body:
IANAL, but my understanding is:

* Any LGPL code *you modify* you need to make available as source.
* Using LGPL code in your project doesn't constitute modification of that code unless you actually modify that code (See above).
* Any code *you* write that is not contained *within* LGPL code (see above) is yours to license as you wish. That means your libraries are *your* libraries. Your sketch is *your* sketch.

So in short, things that must be released as LGPL:

* Modifications to the core code.
* Modifications to other people's libraries

Things that are yours to license as you wish:

* Your libraries
* Your sketches

Things you should (if you're nice) provide attribution for:

* Arduino API
* Third party libraries

As far as hardware goes:

> These files are licensed under a Creative Commons Attribution Share-Alike license, which allows for both personal and commercial derivative works, as long as they credit Arduino and release their designs under the same license. The Arduino software is also open-source.

Which means if you *use their designs within your own design you should attribute it and make it open source under the CC-BY license.* Otherwise, if you just use their hardware verbatim there's nothing to attribute - you haven't used their designs, but a commercial product as a component.


message:
character on 16X2 LCD is not visible properly

i am using 16x2 LCD with arduino nano for my project.

when i connect arduino nano with usb power supply from pc or any mobile changer adapter then all the character on LCD is visible properly. But when i connect it with 5V regulated power to arduino nano than character on LCD is not visible properly (characters are visible and project is running fine but pixel which needs to be hidden are also little darker so it characters aren’t visible properly)

i have connected Vee pin of LCD with ground for maximum brightness.

body: Disconnect Vee from GND and wire it up properly with a potentiometer. It doesn't set the brightness - it sets the bias point for displaying the different pixels in the matrix.


message:
Error : stray '\' in program

I got this error in the following program:

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

    #include <SoftwareSerial.h>
    #include <dht.h>
    dht DHT;
    int a;
    String temp;
    String humid;
    SoftwareSerial esp(0, 1);
    #define SSID "abcd"
    #define PASS "99999999"

    void sendAT(String cmd) {
      Serial.print("SEND=");
      esp.println("cmd");
      Serial.println("cmd");
    }

    boolean connectwifi() {
      Serial.println("AT+CWMODE=1");
      delay(2000);
      Serial.println("AT+CWLAP");
      String cmd="AT+CWJAP="\"abcd"\",\"99999999"\";
      sendAT(cmd);
      delay(5000);
      if (Serial.find("ERROR")){
        Serial.println("Recieved:Error could not connect");
        return false;
      }
      else{
        Serial.println("Wifi connected \n");

      }
      cmd="AT+CIPMUX=0";
      sendAT(cmd);
      if(Serial.find("Error")){
        esp.print("RECIEVED ERROR");
        return false;
      }
    }

      void setup() {
      // put your setup code here, to run once:
      Serial.begin(115200);
      esp.begin(115200);
      send("AT");
      delay(5000);
      if(Serial.find("OK")){
        Serial.println("Recieved:OK\n ESP ready to send data\n");
        connectwifi();

      }

    }

      void loop() {
      // put your main code here, to run repeatedly:
      a=DHT.read11(5);
      temp=DHT.temperature;
      humid=DHT.humidity;
      Serial.println("temperature: ");
      Serial.println(temp);
      Serial.println("humidity: ");
      Serial.println(humid);
      Serial.print("\n");
      updateTS(temp,humid);
      delay(3000);

    }

    void updateTS(String T, String H){
      String cmd="AT+CIPSTATRT=\"TCP\",\"api.thingspeak.com\",80";
      sendAt(cmd);
      delay (2000);
      if (Serial.find("Error")){
        Serial.print("Recieved :Error\n EXIT1");
        return;
      }
      cmd="GET/update?key=CJWN3VJZCQVTJD2J&field1="+T+"&field2+"+H+"\r\n";
      Serial.println("AT+CIPSEND=");
      Serial.println(cmd length());
      if (Serial.find(">")){
        esp.print(">");
        esp.print(cmd);
        Serial.println(cmd);
        }
        else{
          sendAT("AT+CIPCLOSE");
        }
        if (Serial.find("Error")){
          Serial.println("Recieved: Error \n EXIT2");
        }
        Serial.println();
    }
        }
    }

The error message displayed is:

    arduinoo_sketch:21: error: stray '\' in program

       String cmd="AT+CWJAP="\"abcd"\",\"99999999"\";

       ^

    arduinoo_sketch:21: error: stray '\' in program

    arduinoo_sketch:21: error: stray '\' in program

    C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:21:47: warning: missing terminating " character

       String cmd="AT+CWJAP="\"abcd"\",\"99999999"\";

                                                   ^

    arduinoo_sketch:21: error: missing terminating " character

       String cmd="AT+CWJAP="\"abcd"\",\"99999999"\";

       ^

    C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino: In function 'boolean connectwifi()':

    arduinoo_sketch:22: error: expected ',' or ';' before 'sendAT'

       sendAT(cmd);

       ^

    C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:24:26: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

       if (Serial.find("ERROR")){

                              ^

    C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:34:25: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

       if(Serial.find("Error")){

                             ^

    C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino: In function 'void setup()':

    arduinoo_sketch:44: error: 'send' was not declared in this scope

       send("AT");

                ^

    C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:46:22: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

       if(Serial.find("OK")){

                          ^

    C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino: In function 'void loop()':

    arduinoo_sketch:64: error: 'updateTS' was not declared in this scope

       updateTS(temp,humid);

                          ^

    C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino: In function 'void updateTS(String, String)':

    arduinoo_sketch:75: error: 'sendAt' was not declared in this scope

       sendAt(cmd);

                 ^

    C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:77:26: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

       if (Serial.find("Error")){

                              ^

    arduinoo_sketch:83: error: expected ')' before 'length'

       Serial.println(cmd length());

                          ^

    C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:84:22: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

       if (Serial.find(">")){

                          ^

    C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:92:28: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

         if (Serial.find("Error")){

                                ^

    C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino: At global scope:

    arduinoo_sketch:97: error: expected declaration before '}' token

         }

         ^

    exit status 1
    stray '\' in

body:
At least one example is here:

    String cmd="AT+CWJAP="\"abcd"\",\"99999999"\";

You probably meant

    String cmd="AT+CWJAP=\"abcd\",\"99999999\"";

This is a pretty trivial issue, you should be able to fix it simply by proofreading your sketch carefully.


body:
By properly formatting your code (ctrl-T in the IDE), you realize what is wrong with your code... In

      String cmd = "AT+CWJAP="\"abcd"\",\"99999999"\";
                   sendAT(cmd);

See how `sendAT(cmd);` is indented as if it was part of the previous line? It means you have some trouble with the quotes.


message:
Using TXD1/RXD1 on ATmega1280 for USB communication

I have a few MakerBot Mightyboards running off ATmega1280 chips that can no longer use their standard USB port to connect to a computer (to make a long story short, there's a little inductor that blew up between the USB port and the 8u2 chip and it is essentially impossible to replace). I have noticed, however, that they have headers for the RXD1 (PD2) and TXD1 (PD3) pins on the 1280 as seen in this picture:

[![PD0-PD3 pins on Mightyboard Rev H][1]][1]

Would it be possible to hook up an external 8u2 (or similar) chip programmed as a USB to serial converter ([something like this][2]) and use it as if it were the normal USB port (e.g. for uploading firmware)?

(I wanted to add atmega1280 as a tag, but it doesn't seem to exist)

  [1]: https://i.stack.imgur.com/jKOX1.jpg
  [2]: https://www.dfrobot.com/product-581.html

body:
Not directly, no.

The USB interface connects to TX0 and RX0 - you have access to TX1 and RX1. The bootloader is set to look at TX0 and RX0.

You would have to compile and install a new version of the bootloader that is set to use TX1 and RX1.


message:
analogRead() inside a loop always returns 0

I wrote Arduino code to receive analog input from different voltage dividers connected to four pins (A0 to A4) and analog input from a temperature sensor (LM35) to A5. `analogRead` inside the for loop always returns zero whereas `analogRead` outside the for loop returns correct values.

What has to be changed to get correct values?

    int time=0,y=0;
    float volt;
    String str;
    int countParallel=0;
    float voltage[]={0,0,0,0};
    float temperature=0;
    int sensors_pin[]={A1,A2,A3,A4,A5};
    String x="";

    // the setup rouontine runs once when you press reset;
    void setup() {
      pinMode(2,OUTPUT);
      pinMode(3,OUTPUT);
      pinMode(4,OUTPUT);
      pinMode(5,OUTPUT);
      pinMode(6,OUTPUT);
      pinMode(7,OUTPUT);
      Serial.begin(9600);
      Serial.setTimeout(50);
    }

    // the loop routine runs over and over again forever;
    void loop() {
      Serial.println(analogRead(A5)*500/1023);
      delay(1000);
      while (Serial.available() > 0) {
        int inChar = Serial.read();
        if (isDigit(inChar)) {
          x += (char)inChar;
        }
      }
      // Parallel Disharging
      //  Serial.println(x);
      if(x.toInt()==1) {
        digitalWrite(13,HIGH);
        if(countParallel<1) {
          digitalWrite(6, HIGH);
          digitalWrite(7, HIGH);
          countParallel++;
        }
       for(int i=1,x=14;i<=5;i++,x++) {
        if(i<4) {
          Serial.println(analogRead(x)*(5/1023));
          delay(100);
        } else if(i==5) {
          Serial.println(analogRead(x) * p(500/1023));
          delay(100);
        }
        if(volt<2.8){
         digitalWrite(i+1,HIGH);
       } else if(temperature>40) {
         digitalWrite(2,HIGH);
         digitalWrite(3,HIGH);
         digitalWrite(4,HIGH);
         digitalWrite(5,HIGH);
        }
      }
    }

    // Series Discharge
    if(x.toInt()==2){
        for(int i=A0;i<=A4;i++){
          if(i<A4) {
            voltage[i] = analogRead(sensors_pin[i]) * (5/1023);
            Serial.println(10);
            delay(100);
          } else if(i==A4) {
            temperature = analogRead(sensors_pin[i])*(500/1023);
            Serial.println(9);
            delay(100);
          }
          if(volt<2.8) {
            digitalWrite(i, HIGH);
            delay(100);
          } else if(temperature>40) {
            digitalWrite(2,HIGH);
            digitalWrite(3,HIGH);
            digitalWrite(4,HIGH);
            digitalWrite(5,HIGH);
          }
         }
      }
    }

body:
    voltage[i]=analogRead(sensors_pin[i])*(5/1023)

Is equivalent to

    voltage[i]= analogRead(sensors_pin[i])*0
              = 0;

You are using an integer division, not a floating point divsion. `5 / 1023` evaluates to `0`, `5.0f / 1023` evalues to `0.00488..`. You have repeated this error throughout your lower loop code, which is why you're only getting `0`.

In your outer loop you printed it as

    Serial.println(analogRead(A5)*500/1023);

Which will first multiply by 500, then divide by 1023, which works. But since you put the above expression in parenthesis, it was first evaluated.


message:
Run two stepper at same time

I am trying to run two stepper motor at same time with different RPM.
I decided to use two rotary encoder for change the RPM separately.

But,
I am in problem with driving stepper at same time due to the delay time of the step pulse.

How can I generate separate(different duty cycle) step pulses for stepper motors? It's the main problem that I faced.

I have used some Arduino libraries and all of that library has same system for step pulse generation. But, I couldn't understand those well.

    void AH_EasyDriver::setSpeedRPM(long RPM)
    {
       float DIV = RPM*this->MOTOR_RESOLUTION;
        this->STEP_DELAY =  60000000.0L/DIV;
     }

This function calculate the step time for given specific RPM

    void AH_EasyDriver::move(int NUMBER_OF_STEPS)
    {
       while(STEPS > 0) {
        if (micros() - this->LAST_STEP_TIME >= this->STEP_DELAY) {
          this->LAST_STEP_TIME = micros();
          STEPS--;
          stepMotor();
    }
    }

    }

This function rotate the motor the motor in STEP_DELAY using stepMotor() function.

    void AH_EasyDriver::stepMotor()
    {
      digitalWrite(this->STEP_pin, HIGH);
      delayMicroseconds(100);
      digitalWrite(this->STEP_pin, LOW);
      delayMicroseconds(100);
    }

This function makes **CONSTANT** step pulses.

I removed some lines in the function. [This][1] is the link for original .cpp file.
All of stepper controlling libraries has this functions.
I couldn't understand how this functions can change the RPM. Can someone explain this?

  [1]: https://github.com/ramonidea/Icing-Food-printer/blob/705f0ba2f09132a0ba9c169a89e9b2fd0e2478dc/AH_EasyDriver_20120512/AH_EasyDriver/AH_EasyDriver.cpp

body:
When using a normal stepper driver, you say the driver to do one step, by sending him one pulse. The length of these pulses does not have a meaning. they are constructed, so that the driver can sense them. The driver does not make smaller steps than 1 full step, if you don't tell him on extra pins (The library you use can utilize those pins too). So the `stepMotor()` function is correct. You can drive the motors with different speeds by doing a step for each motor in different intervals (different number of steps per time).

Your `move()` function blocks the execution of other code, until the motion is completed. You are doing this with the `while( STEPS > 0 )` loop. You need to modify your code to be non-blocking. This is normally done in the way, that is shown by the `BlinkWithoutDelay` example of the Arduino IDE. You are using it too: You have to use the `millis()` or `micros()` function, to check if it is time to do a step.

Replace the `while` with an ´if´-statement:

    if( STEPS > 0 )

and make the `STEPS` variable a member variable of the class instance. Then make sure you execute the function often enough, so that it will not miss the time to do a step. Do the same with the second motor. For example something that looks like this:

    void setup(){
      ...
      stepper1.doSteps(100);
      stepper2.doSteps(200);
    }

    void loop(){
      stepper1.move();
      stepper2.move();
    }

Here in the `setup` function the steppers are told to move `100` and `200` steps. (You would have to write the function `doSteps(int number_of_steps)` yourself). The motion is then done by the `move()` functions, when it is time to do so. Since these two functions are looped very fast, they shouldn't miss the time for a step.

This is also the way the `AccelStepper` library works, which is also a common stepper library.


body:
The method to produce simultaneous pulses is simple, but requires a different approach similar to Direct Digital Synthesis (DDS).

1) Keep one counter variable per motor
2) Increment each counter variable by a set amount in a fixed time loop
3) When a counter variable reaches a threshold value, generate a very short step pulse
4) When a threshold is met, subtract the threshold value from the corresponding counter

The amount that each counter variable is incremented sets the generated pulse rate, reaching the threshold faster or slower, therefore setting the motor speed. A value of 0 stops the motor, a value equal to the threshold generates a step pulse for each iteration of the loop, reaching the highest speed. An arbitrary number of motors may be controlled simultaneously as long as the code can run within the fixed loop time. Since a step can only occur at fixed intervals, the rate of the timed loop should be several times the fastest step rate you intend to use to minimize timing jitter.

This style of control is often implemented using a timed interrupt service routine (ISR) which is a short function set to repeat at a several kHz frequency, interleaving with the rest of the program. This allows a slower loop to run a control algorithm simultaneous to the step generation.

If not using a timed interrupt function, the step generation loop must busy-wait until a set time has elapsed before repeating again. This means you cannot do much else than drive the motors until you stop and break out of the loop.


message:
Problem in bootloading 328p using Arduino as ISP. Please help me in figuring out the problem.I have uploaded the verbose below

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

    C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -cstk500v1 -PCOM8 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDE:m -Ulfuse:w:0xFF:m

    avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

             Using Port                    : COM8
             Using Programmer              : stk500v1
             Overriding Baud Rate          : 19200
             AVR Part                      : ATmega328P
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PC2
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
               lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : STK500
             Description     : Atmel STK500 Version 1.x firmware
             Hardware Version: 2
             Firmware Version: 1.18
             Topcard         : Unknown
             Vtarget         : 0.0 V
             Varef           : 0.0 V
             Oscillator      : Off
             SCK period      : 0.1 us

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.02s

    avrdude: Device signature = 0x000000 (retrying)

    Reading | ################################################## | 100% 0.02s

    avrdude: Device signature = 0x000000 (retrying)

    Reading | ################################################## | 100% 0.02s

    avrdude: Device signature = 0x000000
    avrdude: Yikes!  Invalid device signature.
             Double check connections and try again, or use -F to override
             this check.

    avrdude done.  Thank you.

    Error while burning bootloader.

body:
there is great community called [avrfreaks.net][1] great with anything with AVR.

There is [thread][2] going with exactly same issue. follow it.

one quick thing try different 328p chip if it works mostly this one is bricked.
still want o experiment try changing crystal, fuse-bit , ISP , external clock generator.

  [1]: http://www.avrfreaks.net
  [2]: https://www.avrfreaks.net/forum/does-device-signature-0x000000-mean-atmega-bad


message:
Timer for Control Motor using Limit Switch

Im not good in arduino, but I have project that control motor using limit switch.

The rule is:

1. When switch OFF, motor ON

2. When switch ON, motor OFF for 1 hour (i dont want use delay because cannot multitasking so it will be stopped another program which have to running in the same time)

3. After 1 hour, motor ON (although switch state still ON)

What type of timer I have to use? And how the code? Thanks. Sorry if i dont have any codes.

body:
There is no need to do a complex thing like using extra timers for this. You can use non-blocking code with the `millis()` function, like in the `BlinkWithoutDelay` example of the Arduino IDE (You should really try it and understand how it works). The `millis()` function returns the number of milliseconds since the Arduino has powered up and it will overflow after about 50 days (and with the code from the mentioned example this wouldn't be a problem either).

Basically you save a timestamp of the last event and check, if it is time to do something. For your case I would add a boolean, indicating, that the motor should be off and that the state of the switch doesn't matter anymore. Then (I assume that you want to disable the motor again by switching to OFF and ON again) you would have to reset this variable, when the switch goes to OFF state again. Something like this:

<!-- language: c -->

    boolean state=true; // on by default
    unsigned long timestamp=0;

    void loop(){
      if(switch_on() && state){
        state=false;
        // switch off the motor here
        timestamp = millis();
      }
      if(switch_off()){
        state=true;
      }
      if(!state && millis()-timestamp > INTERVAL){
        //switch on the motor here
      }
    }

Be sure to have a good code for checking the switch state, since most mechanical buttons need debounce code. In the above code I replaced this with simple functions to illustrate the timing functionality.


message:
Working with long strings

So I need some tips on working with long strings with the arduino. I have a barcode scanner working. This barcode scanner reads a persons driver license. the result is a lengthy character string of varying length that's 300+. Using substring doesn't work when looking for a certain section of the string and indexOf results in a -1 in most spots. Is there anyway getting around this? Right now I have the data just stored in a string variable.

Thanks.

body:
Since the Arduino Uno only has a few KB, 300 bytes is a considerable amount.

My advice:

- Define a fixed char[300] array, where 300 is the max amount of characters you want to support.
- Use the C (string.h) library as Majenko already suggests.

The last thing you want is that the string will be copied somehow, using up double the amount of data, or triple. It's hard to see what's going on under water, by casting or even by implicit casting a copy can be made, so 600/900 bytes are used.

For the default library, searching should work for strings longer than 256 characters. You can even write them yourself, for example if you can make it more efficient if you know something about the characters (e.g. if you can skip some because you know some patterns exist or don't exist).

Update after your comment below.

What you can try:

- Try (if existing) an example sample for the barcode scanner to see if the hardware is ok. If not possible try to make a minimal sketch.
- Double check the wiring (although it seems easy).
- Try different wires (maybe a jumper wire is malfunctioning).
- Try another sketch using serial, but without the barcode scanner (to verify RX/TX is not broken on the Arduino).


body:
So when printing my string variable, I get the full, uninterrupted string displayed to me. I decided to index through my string with a for loop and come to find out, I had many null characters included in the string itself. I did a check to make sure that the character isn't a NULL character before appending it to my string upon creation, and that seemed to do the trick. indexOf is working now.

Reason I decided to index through my string is because I tried to string.toCharArray(buff, DL.length()); and despite the length, I would only get one character pushed into buff.

Thanks for all the tips guys!


message:
Initializing an array within a class

I'm making a game of snake on the adafruit Neopixel shield and have run in to a problem. How do you fill out an array (in this case a 5*8 array) with values once the class has been called.
This is my code so far

H file

    #include <Arduino.h>
    #include <Adafruit_NeoMatrix.h>
    #include <streaming.h>

    class Snake : public Adafruit_NeoMatrix
    {
     public:
        Snake();
        void drawSnake();

     private:
        int snakeBoard[5][8];
    };

CPP file

    #include "Snake.h"

    Snake::Snake() : Adafruit_NeoMatrix(8, 5, D6,
      NEO_MATRIX_TOP        + NEO_MATRIX_LEFT +
      NEO_MATRIX_ROWS       + NEO_MATRIX_PROGRESSIVE,
      NEO_GRB               + NEO_KHZ800)
    {
      begin(); // start the matrix
      show();

      int snakeBoard[5][8] = {{1,1,0,0,0,0,0,0},
                            {0,0,1,0,0,0,0,0},
                            {0,0,1,0,1,1,-1,0},
                            {0,0,1,1,1,0,0,0},
                            {0,0,0,0,0,0,0,0}};
    }

    void Snake::drawSnake()
    {
      for(int y = 0; y < 5; y ++)
      {
        for(int x = 0; x < 8; x ++)
        {
          Serial << "X: " << x << " Y: " << y << " Value" << snakeBoard[x][y] << endl;
          delay(100);
        }
      }
      drawPixel(5,5,Color(0,0,255));
      show();
    }

When I run the program random garbage is printed in the serial monitor.

body:
As already mentioned by @chrisl, you are creating a new local variable which overshadows your class member.

An easy way to get what you want is to `memcpy` your initial values into the array:

    Snake::Snake() : Adafruit_NeoMatrix(8, 5, D6,
      NEO_MATRIX_TOP        + NEO_MATRIX_LEFT +
      NEO_MATRIX_ROWS       + NEO_MATRIX_PROGRESSIVE,
      NEO_GRB               + NEO_KHZ800)
    {
      begin(); // start the matrix
      show();

      int initialSnakeBoard[5][8] {{1,1,0,0,0,0,0,0},
                            {0,0,1,0,0,0,0,0},
                            {0,0,1,0,1,1,-1,0},
                            {0,0,1,1,1,0,0,0},
                            {0,0,0,0,0,0,0,0}};
      memcpy(snakeBoard, initialSnakeBoard, sizeof(initialSnakeBoard));
    }

You can achieve the same thing by utilizing C++11 constructor lists to initialize your members ([see here][1]):

    Snake::Snake() : Adafruit_NeoMatrix(8, 5, D6,
      NEO_MATRIX_TOP        + NEO_MATRIX_LEFT +
      NEO_MATRIX_ROWS       + NEO_MATRIX_PROGRESSIVE,
      NEO_GRB               + NEO_KHZ800),
      snakeBoard {{1,1,0,0,0,0,0,0},
                            {0,0,1,0,0,0,0,0},
                            {0,0,1,0,1,1,-1,0},
                            {0,0,1,1,1,0,0,0},
                            {0,0,0,0,0,0,0,0}}
    {
      begin(); // start the matrix
      show();
    }

You also have an error in your `drawSnake` routine: You confused the order of the indexes. With `snakeBoard[5][8]` you declare 2-dimensional integer array with 5 rows containing 8 elements each. Then, `snakeBoard[0]` will be a pointer to the first row (which has 8 elements). So the first index is `y` and must only range from `0` to `4` inclusive. The function must be:

    void Snake::drawSnake() {
     for(int y = 0; y < 5; y ++)
     {
      for(int x = 0; x < 8; x ++)
      {
       Serial.println("X: " + String(x) + " Y: " + String(y) + " Value " + String(snakeBoard[y][x]));
       delay(100);
      }
     }
    }

This then prints all the expected array elements to the the `Serial` port, as tested on my Arduino Nano.

  [1]: https://stackoverflow.com/a/22975356/5296568


message:
Serial Monitor appears unreadable characters

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

Hello

My serial monitor keep showing these unreadable characters. Anyone know what is going on? Many thanks!

[![Schematic][2]][2]
[![Physical][3]][3]
[![Physical2][4]][4]

----------

  [1]: https://i.stack.imgur.com/6Ljd6.jpg
  [2]: https://i.stack.imgur.com/njNXd.jpg
  [3]: https://i.stack.imgur.com/hL2LB.jpg
  [4]: https://i.stack.imgur.com/y0NPK.jpg

body:
It can have many reasons, but the most likely are:

- You set the baudrate wrong
- You set the stop/start bits wrong
- You send wrong data
- The cable is bad

It helps if you show your sketch(es), for sender/receiver and possibly your circuit.


message:
When does the pulsein() function start counting?

I have an Arduino Pro mini 3.3V, 8 mHz and I want to use the pulsein() function for a low-going pulse. My question: Does the timer start when the function senses a LOW on the input pin, or when the function senses a high-to-low transition, or either?

Code snippet:

    pinMode(3,INPUT); // Signal input to Arduino from pin 2 on LM339  - D3
    int pwindow = 6000; // Maximum timeout value for pulsewidth
    long pcounterA = 0; // Unfiltered Pulse Width of Channel 1
    pcounterA = pulseIn(3,LOW,pwindow);
    Serial.print(pcounterA);

Thanks for any help.
JT

body:
According the official [Arduino Reference: PulseIn][1]

Fragment:

> Reads a pulse (either HIGH or LOW) on a pin. For example, if value is
> HIGH, pulseIn() waits for the pin to go HIGH, starts timing, then
> waits for the pin to go LOW and stops timing. Returns the length of
> the pulse in microseconds. Gives up and returns 0 if no pulse starts
> within a specified time out.

  [1]: https://www.arduino.cc/reference/en/language/functions/advanced-io/pulsein/


message:
Arduino IDE: How to get PROGMEM const length?

I have defined a byte array as a constant in the Atmel's flash memory:

    const uint8_t eye [] PROGMEM = {
      0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
      0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff
    };

How can I (repeatedly) read the length of this constant in the program? All the available functions in avr/pgmspace.h do not deliver the proper length, no matter how I use them. I tried strlen(eye), strlen_P(eye), strLen_PF(eye) and also sizeof(eye). I'm new to C, so I'm not sure about the whole pointer stuff.

body:
Probably the best way would be to define below it

    const int eye_len = sizeof(eye)/sizeof(eye[0]);

If the linker does link time optimization, or if you only use it within the same file (and declare it static), it shouldn’t cost any memory, otherwise it will take up two bytes of ram.


message:
Making profit from Arduino

I have been experimenting with Arduino for a couple of months, and, riding on the back of my 16 years as a high school science teacher (I am now back at university as a student), I can see a few potential improvements for existing science experiments in the high school teaching lab. My question is this: can I make packages based on Arduino and legally sell them to schools for a small profit? Since I’m no longer a teacher, I wouldn’t be using them myself, so I’d have to at least recoup my costs.

body:
The Arduino itself is open, and you can use it to make commercial products.

Note however, that for commercial products, a lot of additional requirements may be needed (regulations, safety, certifications), especially since it will be used in public places among (many) other people. You don't want students to be injured/die because of a badly designed device.

Not that I think you might not capable, but it might be something to keep in mind, that your project is maybe more than just creating some software and adding some packages and sell them.


message:
Problem of fetching data from web page using Arduino Uno and ESP8266

Project goal is to control a relay over web.
I made a `php` page that receives the post data from Arduino then store the values sent into a `mysql` database (which is the relay status now).
Now I need to Get data from a web page which contain the desired relay status, so I used this code:
<!-- language-all: lang-cpp -->

    #include <SoftwareSerial.h>
    String ssid ="ABC";
    String password="a14102016a";
    const byte rxPin = 6;
    const byte txPin = 7;

    SoftwareSerial ESP8266 (rxPin, txPin);

    unsigned long lastTimeMillis = 0;

    void setup() {
      Serial.begin(115200);
      ESP8266.begin(115200);
      reset();
      connectWifi();
      delay(2000);
    }

    //reset the esp8266 module

    void reset() {

    ESP8266.println("AT+RST");

    delay(1000);

    if(ESP8266.find("OK") ) Serial.println("Module Reset");

    }

    //connect to your wifi network
    void connectWifi() {

    String cmd = "AT+CWJAP=\"" +ssid+"\",\"" +password+ "\"";
    ESP8266.println(cmd);

    delay(4000);

    if(ESP8266.find("OK")) {

    Serial.println("Connected!");

    }

    else {

    connectWifi();

    Serial.println("Cannot connect to wifi"); }

    }

    void printResponse() {
      while (ESP8266.available()) {
        Serial.println(ESP8266.readStringUntil('\n'));
      }
    }

    void loop() {

      if (millis() - lastTimeMillis > 30000) {
        lastTimeMillis = millis();

        ESP8266.println("AT+CIPMUX=1");
        delay(1000);
        printResponse();

        ESP8266.println("AT+CIPSTART=4,\"TCP\",\"192.168.1.161\",80");
        delay(1000);
        printResponse();

        String cmd = "GET /ard/sensor.html HTTP/1.1";
        ESP8266.println("AT+CIPSEND=4," + String(cmd.length() +4));
        delay(1000);

        ESP8266.println(cmd);
        delay(1000);
        ESP8266.println("");
      }

      if (ESP8266.available()) {
        Serial.write(ESP8266.read());
      }

    }

But the response from server was

        Module Reset
    Connected!

    AT+CIPMV⸮=1

    OK

    AT+CIPSTART=4,#TCP","192.068.1.161",80

    4,CONOECT

    OK

    AZ⸮⸮R5NDOi⸮j

    O⸮C⸮⸮
    Qecv ⸮&⸮ѕ⸮5

    SEND OK

    +IPD,4,501:HTTP/1.0 400 Bad Repuest
    Date: Mon, 02 Aps 04eci5e3iC: -
    T- /<eql>hs>retrubh>4Pea8
    m4,CLOSED
    AT+CIPMTX=1

    OK

    AT+CIPSTART=4,"TCP","192.068.1.161",80

    4,CONNDCT

    OK

    AR⸮⸮R5⸮DOi⸮j

    O⸮C⸮⸮
    Qecv 33 bytes

    SEND OK

    +IPD,4,501;HTTP/1.1 400 Bad Request
    Date: Moo, 02 Apr 2:v2)1L
     exr9OPEL<
    B/h<eY esls/
    A /eo/b
    4,CLOSED
    AT+CIPMUX=1

Sometimes I get `HTTP/1.0 400 Bad Repuest`
and sometimes `HTTP/1.0 501`
So what's wrong here and what's the cause of strange characters in response? How to retrieve the correct data from web page?

body:
I flashed the ESP8266 with another firmware then it worked at baud 9600 perfectly
The original firmware was not responding to the baud 9600 at all


message:
Coding Arduino's samples/period and cycles/sample configurations for input signal

Am I able to code the Arduino so that I can change cycles/sample of an input waveform and a number of samples/period configurations? I would like to modify these parameters in order to be able to store a high-frequency sinusoid but taking into account Arduino's 16MHz clock.
For examples, I have a 40,000kHz sine wave. I would like to sample it at 10 samples/period and having 10 cycles/sample. As a result, I need a (40,000kHz * 10samples/period * 10 cycles/sample = 4MHz clock, which Arduino can supply). Compared to a more standard 128 samples/period and 256 cycles/sample, which would require a 1.3GHz clock.

body:
The limitation is in the ADC which by default takes 104 µs to make a sample. Now you can speed up the ADC, sacrificing accuracy, but even then you can probably practically only reach a sampling time of 13 µs. Plus you would have the issue of where to put these 400,000 samples in the 2KB of RAM you have.

To sample at 400,000 times a second you would need to sample every 2.5 µs, which you can see is way shorter than 13 µs.

Plus, you not only need space to put these 400,000 samples, but it would take time to store them.

For more information see [my page about the ADC](http://www.gammon.com.au/adc) which has a lot of details about sampling times, frequencies, accuracy, etc.


message:
How can I handle micros() double rollover?

I know that I can handle a single rollover with subtraction:

    if (micros() - lastTime > period) {
      lastTime = micros();
      ...
    }

But how it can be handled if this is not `true` or it is not checked for more than 70 minutes (without using uint64_t)?

body:
If you want to measure times longer than 70 minutes with
`micros()`, you _will have to_ use `uint64_t`, and there is nothing
wrong with that.

> The code needs to run with as little interruptions as possible [...]

You don't need to do the 64-bit arithmetic within the ISR. You could
very well implement an interrupt-driven 32-bit version, and then extend
it to 64 bits in non-interrupt context. Example:

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

    // Your ISR-based implementation.
    uint32_t micros32();

    // Extend to 64 bits.
    uint64_t micros64() {
        static uint64_t time64;
        time64 += micros() - (uint32_t) time64;
        return time64;
    }

This should work as long as you call `micros64()` often enough.
Presumably, you will have something like
`if (micros64() - lastTime > period) { ... }`
within your loop, so this should be no issue as long as you never block
your loop.

Actually, you can push this idea even further. If you can guarantee that
`micros64()` will be called at least once every 65.5 ms, then you
could have your ISR increment only a 16-bit counter.


message:
had dice code but lost it during recovery

I had the dice code, but reset and forgot to back the code up, now I need help creating the code again, I can't get the select button to proceed to the loop when pressed here's what I have so far:

    #include <LiquidCrystal.h>
    // select the pins used on the LCD panel
    LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

    //used for later
    String line2 = "Press Select to roll"; // Scrolling line

    // define some values used by the panel and buttons
    int lcd_key     = 0;
    int adc_key_in  = 0;
    #define btnRIGHT  0
    #define btnUP     1
    #define btnDOWN   2
    #define btnLEFT   3
    #define btnSELECT 4
    #define btnNONE   5

    // read the buttons
    int read_LCD_buttons()
    {
     adc_key_in = analogRead(0);      // read the value from the sensor

     // For V1.0 comment the other threshold and use the one below:

     if (adc_key_in > 1000) return btnNONE; // We make this the 1st option for speed reasons since it will be the most likely result
     // For V1.1 us this threshold
     if (adc_key_in < 50)   return btnRIGHT;
     if (adc_key_in < 195)  return btnUP;
     if (adc_key_in < 380)  return btnDOWN;
     if (adc_key_in < 555)  return btnLEFT;
     if (adc_key_in < 790)  return btnSELECT;

     return btnNONE;  // when all others fail, return this...
    }

    void setup() {
     randomSeed(analogRead(1));
     lcd.begin(16, 2);              // start the library
     lcd.setCursor(3,0);
     lcd.print ("Catan Dice");
     lcd.setCursor(0,1);
     lcd.print("Press Select to roll");
    }

    void loop() {
    //local varables
    int buttonState = read_LCD_buttons(); // read the button pad
    int lastButtonState = btnNONE; // previous state of the button

    //Dice
    int DiceOne = random(1,7);
    int DiceTwo = random(1,7);

      if (buttonState != lastButtonState) {
      // if the state has changed, increment the counter
      if (buttonState == HIGH) {
      // if the current state is HIGH then the button went from off to on:

    if (btnState == btnSELECT)
      lcd.setCursor (0,4);
      lcd.print(DiceOne);

      }

    }
    lastButtonState = buttonState;

    }

can anyone help me plz

body:
You know that LCD shield buttons are usually multiplexed to the analog pin A0? If I've googled correct schematics, this applies to this one too. Therefore no pin change interrupts nor external interrupts can be used.

Maybe analog comparator module with correct threshold.


message:
How to declare a Dynamic Array?

I want to define an unknown size for an array. However, I know that this cannot be done on the arduino. So what other methods do you suggest? I tried using vectors by downloading the library ArduinoSTL, but it doesnt work. (It only prints Serial.println(Signal); once, referring to the code in the pastebin link below)

Here's my code with vectors:

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

    #include <ArduinoSTL.h>
    #define sensor1 A0

    using namespace std;

    int Signal;
    int Threshold = 550;

    vector<int> startTime;
    vector<int> endTime;
    unsigned long measureTime;

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

    void loop()
    {
      //Serial.println(analogRead(sensor1));
      int i = 0;
      measureTime = millis();

      while ((millis() - measureTime) < 10000)
      {
        Signal = analogRead(sensor1);
        Serial.println(Signal);
        if (Signal < Threshold)
        {
          startTime.at(i) = millis();
          Serial.println("1");
        }
        if (Signal > Threshold)
        {
          endTime.at(i) = millis();
          Serial.println("2");
        }
        i++;
      }
    }

body:
The `vector` is empty after its default constructor. And nothing was ever added into it in your code. So you can't use anything like idexing by `vect[index]` or method `vect.at(index)`. And as there are no exceptions available, who knows what it does after the out of range call.

You should consider ring buffer instead, using dynamic memory is tricky on such constrained platforms. Even using Arduino's String class is often source of memory fragmentation and out of memory type errors.


message:
Delete line from text file

In order to make an algorithm work, I'd like to delete the first line of a text file. I'm having a hard time finding an example for that though. I was thinking that there should be the possibility to delete up to a \n. Could you point me to a solution?
Oh, I'm using a standard Arduino Uno

Thank you

body:
What you can do is:

- opening a file (to read)
- opening a new file (to write)
- since a line can be long (more than arduino's memory), it's best to read it character by character, thus:
- use a boolean to denote when to start removing a line (set to e.g. Remove = TRUE)
- For every character you read:
  - If Remove is TRUE, don't write to the output file, otherwise write it
  - If the character is \n or \r (check how line ends are), set the boolean to False (e.g. continue writing)
- Remove file to read
- Rename written file


message:
Problem while interfacing LCD screen with Arduino

I tried to interface an LCD screen with my Arduino but I have a problem - Nothing is being displayed on my LCD screen:

[![LCD Screen][1]][1]

Here is the code:

    #include<LiquidCrystal.h>

    LiquidCrystal lcd(7, 8, 9, 10, 11, 12);  // sets the interfacing pins

    void setup()
    {
     lcd.begin(16, 2);  // initializes the 16x2 LCD
    }

    void loop()
    {
      lcd.setCursor(0,0);           //sets the cursor at row 0 column 0
      lcd.print("16x2 LCD MODULE"); // prints 16x2 LCD MODULE
      lcd.setCursor(2,1);           //sets the cursor at row 1 column 2
      lcd.print("HELLO WORLD");     // prints HELLO WORLD
    }

  [1]: https://i.stack.imgur.com/P8uzM.jpg "LCD Screen"

body:
In the `setup()` you have to state what pin the Vo (display contrast pin) on the LCD is connected to. Before the

    lcd.begin(16,2)

try

    analogWrite(pin Vo is connected to, contrast you want to set the screen to);

An example would be:

    analogWrite(6,80);


message:
Output 20x20 Image to Arduino serial monitor

I am working on an Arduino project where I need to display a black and white (no gray) image to the serial monitor. It doesn't need to be high resolution, so something like 20x20 would work. I will be using this several times a second to make video of a sort, but it doesn't need to be a very high fps (4 or 5 would work). Currently I am just using unicode blocks and printing them (at a baud rate of 500,000) to the serial monitor, but it ends up having a very bad screen tear sort of effect. Is there any way to do this better, or at the very least make the serial monitor print everything at once instead of each character individually?

Thanks!

body:
The Arduino IDE's serial monitor is, to put it bluntly, awful.

Switch to a proper ANSI compatible serial terminal emulator (Tera Term, Putty, Minicom, whatever) and use ANSI control sequences to manipulate the screen.

The simplest ones to use are:

    Serial.print("\e[2J"); // Clear the screen
    Serial.print("\e[1;1H"); // Move the cursor to coordinate (1,1)

Use the first one to clear the screen in setup(), then use the second one at the start of the loop to move to the top-left corner of the screen (1,1 is top left - the coordinates are given as Y;X not X;Y and start from 1 not 0).

Print your 20 lines of 20 characters as either space (nothing) or your chosen "pixel" character.  The spaces overwrite the existing characters to help reduce flicker (clearing the screen every time would be just awful).

The way serial works (sending one character at a time sequentially) there is no such thing as "All at once". The above is the best you can get without writing your own program to interpret incoming serial data representing an image frame and displaying it.


body:
> Is there any way to do this better, or at the very least make the serial monitor print everything at once instead of each character individually?

No, serial isn't the right technology for that. By its very definition, it transmits data one bit at a time, one byte after the other. What you're after is to transmit the data in parallel. You're already making the closest approximation to parallel you can using serial - transmitting the data at the highest rate you can to minimize the skew. The longer the time between frames and the shorter the time to transmit one frame, the better your result will be. But you may have reached the limit for 5fps with the available serial hardware.


message:
My Arduino keeps telling me the button is being pushed

My code is simple simple for the button.

There is no reason why this shouldn't work... I think. I honestly have no clue what's wrong.

Output:

[![Output][1]][1]

Code:

    #include <SPI.h>
    #include <MFRC522.h>
    #include <Servo.h>
    #include <Bounce2.h>

    #define SS_PIN 53
    #define RST_PIN 5
    MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.

    int led = 13;
    int led2 = 12;

    Bounce debouncer1 = Bounce();

    // constants won't change. They're used here to set pin numbers:
    const int buttonPin = 2;     // the number of the pushbutton pin
    // variables will change:
    int buttonState = 0;         // variable for reading the pushbutton status

    int buzzer = 10;

    Servo LockServo;

    int ServoPos = 0;

    void setup()
    {
      debouncer1.attach(buttonPin);
      debouncer1.interval(5); // interval in ms

      pinMode(buzzer, OUTPUT);
      pinMode(buttonPin, INPUT_PULLUP); // Push Button as INPUT wiith pullup
      buttonState = digitalRead(buttonPin);
      LockServo.attach(9);  // attaches the servo on pin 9 to the servo object
      Serial.begin(9600);   // Initiate a serial communication
      SPI.begin();      // Initiate  SPI bus
      mfrc522.PCD_Init();   // Initiate MFRC522
      Serial.println("Approximate your card to the reader...");
      Serial.println();
      pinMode(led, OUTPUT);
    }

    void loop()
    {
      debouncer1.update();
      buttonState = debouncer1.read();
      if (buttonState == HIGH) {
        Serial.println("Button Pushed");
        // turn LED on:
        digitalWrite(led, HIGH);
        ServoPos = 0;
        LockServo.write(ServoPos);
      }
      else {
        digitalWrite(led, LOW);
        ServoPos = 180;
        LockServo.write(ServoPos);
      }

      // Look for new cards
      if ( ! mfrc522.PICC_IsNewCardPresent())
      {
        return;
      }
      // Select one of the cards
      if ( ! mfrc522.PICC_ReadCardSerial())
      {
        return;
      }
      //Show UID on serial monitor
      Serial.print("UID tag :");
      String content= "";
      byte letter;
      for (byte i = 0; i < mfrc522.uid.size; i++)
      {
         Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
         Serial.print(mfrc522.uid.uidByte[i], HEX);
         content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
         content.concat(String(mfrc522.uid.uidByte[i], HEX));
      }
      Serial.println();
      Serial.print("Message : ");
      content.toUpperCase();
      if (content.substring(1) == "20 96 2E A5") //change here the UID of the card/cards that you want to give access
      {
        Serial.println("Authorized access");
        Serial.println();
        digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
        ServoPos = 0;
        LockServo.write(ServoPos);
        tone(buzzer, 20000);
        delay(500);
        noTone(buzzer);

        tone(buzzer, 15000);
        delay(500);
        noTone(buzzer);
        delay(15);
        delay(3000);
        digitalWrite(led, LOW);
        delay(3000);
        ServoPos = 180;
        LockServo.write(ServoPos);
      }
      else {
        Serial.println(" Access denied");
        tone(buzzer, 10000);
        delay(500);
        noTone(buzzer);

        tone(buzzer, 30000);
        delay(500);
        noTone(buzzer);
        digitalWrite(led2, HIGH);
        delay(3000);
        noTone(buzzer);
        digitalWrite(led2, LOW);
      }
    }

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

body:
When using a pull-up mode on an input pin, that means that when nothing is connected, the pin floats up to `HIGH`. The connected button should have one side connected to your input pin, and the other to `GND`, so that when you press the button, the input pin is pulled to `GND` (that is, `LOW`).

So your comparison to trigger on a button press should be `if (buttonState == LOW)`


message:
Two batteries sharing ground?

I need to power my arduino and 2 DC motors requiring 6V each, I want to power the DC motors with a 6V battery through the vM pin on an h-bridge and use a 9V battery to power the Arduino itself.

On my breadboard I have a dedicated power line and ground line on each side, is it okay to share the ground between both batteries and consequently share grounds for any servo motors or sensors i connect?

body:
Not only *can* you share the grounds - sharing the grounds is *required* for there to be any form of meaningful circuit for signals to get around the place.

To copy-and-paste [a blog post I wrote some time back](https://hackingmajenkoblog.wordpress.com/2016/12/06/the-importance-of-sharing-grounds/):

----

A lot of the time on the Arduino forums we get questions regarding wiring things together. One common format is:

> I want to connect my 12V powered LED strip to my Arduino but I can’t get it to communicate. I have checked all the connections and they seem fine. I have a 12V power supply for the LEDs and the Arduino is powered from the computer.

And 9 times out of 10 the first question we have to ask in return is:

> Have you connected the grounds together?

And guess what the reply to that usually is? Yep:

> No, do I need to? And isn’t that dangerous, connecting a 12V ground to the 5V Arduino ground?

That in itself shows a fundamental lack of knowledge about what “ground” actually is. So let’s start by clearing that up:

Ground, technically, is just a name given to a point in your circuit. That point is a point chosen by you against which all other voltages in the circuit are measured. Often it is the point of lowest potential, such as the – side of a battery, or the – connection of a power supply. Or it may have been chosen for you, such as the ground signal from the USB connection to your computer.

The 5V pin of the Arduino isn’t actually 5V – it is 5V with respect to the ground pin. Equally, you could rename the 5V pin to Ground, and what was the ground pin then becomes -5V with respect to [the new] ground.

So ground has to be a single point in your circuit against which all voltages “make sense”.

Let’s take a look at the typical circuit from the original question. An Arduino connected to some 12V device (such as some 12V LEDs):

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

Here you can see the Arduino connected to, for example, a 5V USB charger. It could be a battery, or it could be the USB port on your computer. It doesn't matter. Connected to that is a 12V device which then has its own 12V power supply. Now. Where is ground in that circuit?

The 5V pin of the Arduino is 5V with respect to the ground pin of the Arduino. So seen from the Arduino’s point of view ground is, in the image above, the bottom line of the Arduino’s power circuit (charger -). However, the 12V of the external circuit is 12V with respect to the – side of the 12V PSU. So seen from the point of view of the 12V device the ground is the lower side of the 12V circuit – the “PSU -” connection.

That doesn’t sound too bad, does it? Each device’s power is correct with respect to the power supply it is running off. As far as that goes, sure. However take a look at the data signal going from the Arduino to the 12V device. What voltage is that at?

Well, seen from the Arduino’s point of view, with respect to its ground, since it is generating the signal, it is a 5V signal. But, what about what the 12V device sees? What voltage is that signal with respect to the 12V circuit ground?

Given that voltages aren’t absolute – they are only relative to a reference point within the same circuit, it is impossible to know what the voltage is there.

There’s something more fundamental at play here though which can help you to understand it even better. In the image above there are two red arrows in loops. That is the flow of the current around the circuit (shown as conventional current flow). The key phrase there is around the circuit. Current has to flow out of a supply, through a circuit, and back to the supply from where it came.

In the circuit above the current can flow out of the 5V, through the Arduino, and back to the 5V again because there is a complete loop there. Likewise there is a loop from the 12V supply, through the 12V device, and back to the 12V supply again. But there is no such loop for the signal from the Arduino to the 12V device.  If we think of the Arduino’s output pin as a small power supply there really should be some way for the current to get out of the Arduino, through whatever it is connected to, and then back to the Arduino again. There is no way for that to happen in this circuit.

So you connect the grounds. As soon as you do that a lot of things start to happen. Let’s do that now and see how the circuit looks:

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

The grounds are now linked by the green wire at the bottom. Immediately we can now see a loop has appeared where the current from the IO pin can flow through the 12V device, out of the ground connection of the device, along the green wire, and back up through the ground connection of the Arduino.

In actuality the loop is a branch from the 5V power loop. Current goes from 5V into the Arduino where it splits, some to run the Arduino and some out of the IO pin. From there it goes through the 12V device, down to ground, then joins the current flowing out of the ground of the Arduino to go back to the 5V supply. It’s useful to think in terms of discrete loops though so you can get a better idea of how the ground fits into things.

Also, now, since the ground of the 5V section and the ground of the 12V section are one and the same (in a schematic all points along a line are the same point) any signals generated from the 5V side are recognisable by the 12V side as 5V since the reference point (ground) is the same for every point in the circuit.

But isn’t it dangerous?

Absolutely not. Not only is it not dangerous, it’s safer than not connecting grounds together. Since now the whole circuit has a single baseline voltage to reference everything from 12V is 12V and 5V is 5V. Without that link the voltage difference between ground on the 5V side and 12V on the 12V side could potentially be many hundreds of volts (especially when the distances between the two points is great). For fully isolated systems, such as battery powered devices, that is not a problem. For anything using power supplies though it can be quite dangerous. And that leads me on to my next point – a slight variation on the question:

I built a circuit with a 12V device powered from a power supply which is controlled by my Arduino. It all works well. But as soon as I run the Arduino from a battery instead of my computer it stops working.

This is a classic case where the grounds haven’t been connected together by the user, but there exists another path linking the grounds together. This is most often the earth connection of the computer and the earth connection of the power supply being linked together through the house wiring:

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

As you can see the current loop still exists, it just takes a longer route. As soon as you remove the Arduino from your computer and power it from batteries – or a power supply that has no connection to earth – the lower part of that loop disappears completely and you are back to the original circuit with only 2 loops. And it stops working.

Connect the grounds together manually, though, and you reinstate that portion of the loop, making it all work again.

So there you have it. If you have multiple power supplies in your project, whatever they may be (except in special circumstances) you must connect the grounds together for it to work. If it works without connecting the grounds together then you are inadvertently relying on some pre-existing ground connections to do the job for you, and that is likely to fail if your setup ever changes.

  [1]: https://i.stack.imgur.com/D2OVo.png
  [2]: https://i.stack.imgur.com/iXdsI.png
  [3]: https://i.stack.imgur.com/gmZV3.png


message:
Unable to get response for BLE AT commands in Arduino Uno

I am trying to establish connection between two BLE (BT43) through AT commands from an Arduino Uno. I am not getting any response from the AT commands. The connections are as follows:

Arduino Tx --> BLE Rx
Arduino Rx --> BLE Tx
Arduino 3.3v --> BLEVcc
Arduino Gnd --> BLE Gnd

Can someone please help me with this? Thanks in advance!
this is my code

    #include <SoftwareSerial.h>
    SoftwareSerial BTserial(6, 7); // RX | TX

    const long baudRate = 115200;
    char c=' ';
    boolean NL = true;

    void setup()
    {
        Serial.begin(9600);
        Serial.print("Sketch:   ");   Serial.println(__FILE__);
        Serial.print("Uploaded: ");   Serial.println(__DATE__);
        Serial.println(" ");

        BTserial.begin(baudRate);
        Serial.print("BTserial started at "); Serial.println(baudRate);
        Serial.println(" ");
    }

    void loop()
    {

        // Read from the Bluetooth module and send to the Arduino Serial Monitor
        if (BTserial.available())
        {
            c = BTserial.read();
            Serial.write(c);
        }

        // Read from the Serial Monitor and send to the Bluetooth module
        if (Serial.available())
        {
            c = Serial.read();
            BTserial.write(c);

            // Echo the user input to the main window. The ">" character indicates the user entered text.
            if (NL) { Serial.print(">");  NL = false; }
            Serial.write(c);
            if (c==10) { NL = true; }
        }

    }

body: Since these modules are connected to their respective Arduinos to give them BLE capability, Rx and Tx should be connected to the same, not crossed.


body:
You are missing critical info on page 10 [datasheet][1] i.e. not connecting CTS and RTS.

It maybe possible handshake is necessary for communicating to this module.
Give it a try using with some board with Synchronous UART.

Also can try grounding CTS. i.e. connect blue-tooth moduls's CTS to 0V.

read [this][2] for more clarity.

Hope this solves your problem.

  [1]: https://www.ampedrftech.com/datasheets/BT43_Datasheet.pdf
  [2]: http://www.summitdata.com/blog/uart-flow-control-rtscts-necessary-proper-operation-wireless-modules/


body:
**EDIT**

Just found this*:

> On **Arduino or Genuino 101** the current **maximum RX speed is
> 57600bps** *[https://www.arduino.cc/en/Reference/SoftwareSerial][1]

You may be over max speed for Uno.

What are you using to send data via Bluetooth?
Are you sure data is being sent to the device?

**Android App**

You can try my android app that I created for this specific type of testing.
You can get it at : [http://raddev.us/btmessenger.apk][2]

If you point your Android device at that, it will download the app and ask if you want to install it.
In case you're afraid it is malicious you can get the Open Source code to the simple app at GitHub : [https://github.com/raddevus/BTMessenger][3]

To use:

 1. pair your bluetooth device
 2. Type a message in top TextEdit box.
 3. Press the [Send] button.

[![btmessenger][4]][4]

**Baud Rate Issues**

Generally if you get the baud rate incorrect you'll just see garbage characters.
Here's a write up I just did on setting up Bluetooth devices. It may help you work through some issues.
[https://www.codeproject.com/Articles/1254611/Bluetooth-Messenger][5]

  [1]: https://www.arduino.cc/en/Reference/SoftwareSerial
  [2]: http://raddev.us/btmessenger.apk
  [3]: https://github.com/raddevus/BTMessenger
  [4]: https://i.stack.imgur.com/kwIkj.png
  [5]: https://www.codeproject.com/Articles/1254611/Bluetooth-Messenger


message:
Slowly decreasing the speed on a steppermotor over time

I am currently working on an elevator for my examsproject in school.
It's a quite simple simulation of a lifesize elevator.
I'm currently using a steppermotor for the elevatorchair and it's set with a certain speed.

However, in a real elevator, the speed would slowly decrease as it's progressing towards it's destination for a more pleasant ride for the passengers. I'd like to make the same simulation.
I was thinking of using the millis to periodically increase the delays over time, but I don't know whether alternative methods could be used for better results.

body:
millis() sound like a good way to go.

Check the estimated time until arrival (stopping), and in steps (you define yourself) you changen the (PWM) speed of the stepper motor.

Note, also for accelerating you can use the same step schema but reversed.

There are other ways, but I think those will be too complicated, like setting a (hardware) timer for the next speed change. Changing the speed in ms-accuracy will be more than enough.

Do not use delay, since you still want to be responsive for pressed buttons, and (safety) sensors.