message:
Arduino UNO + Ethernet Shield + LCD + RFID but RFID doesn't work

I've been working to a project that uses arduino for RFID but when connected to ethernet shield, the RFID seems to not read any card tapped to sensor but the LCD seems to do fine. Here's the code I use from this page: http://www.instructables.com/id/RFID-CARD-READER-WITH-ARDUINORFID-RC522-and-LCD-16/

    #include <EEPROM.h> //Library To read and write PICC's UIDs from/to EEPROM
    #include <SPI.h> //Library  RC522 Module uses SPI protocol
    #include <MFRC522.h> //Library  RC522 Module
    #include <LiquidCrystal.h> //Library  for LCD Display
    #include <Ethernet.h>

    EthernetServer server(80);
    boolean match = false; // initialize card match to false
    boolean programMode = false; // initialize programming mode to false
    int successRead; // Variable integer to keep if we have Successful Read from Reader
    byte storedCard[4]; // Stores an ID read from EEPROM
    byte readCard[4]; // Stores scanned ID read from RFID Module
    byte masterCard[4]; // Stores master card's ID read from EEPROM
    #define SS_PIN 10
    #define RST_PIN 9
    MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
    LiquidCrystal lcd(7, 6, 5, 4, 3, 2); //Initializing LCD PINS as (RS, EN, D4, D5, D6, D7)

    void setup() {
      Serial.begin(9600); // Initialize serial communications with PC
      lcd.begin(16, 2); //Initializing LCD 16x2
      pinMode(8, OUTPUT); //LED and Buzzer PIN OUT
      SPI.begin(); // MFRC522 Hardware uses SPI protocol
      mfrc522.PCD_Init(); // Initialize MFRC522 Hardware
      mfrc522.PCD_SetAntennaGain(mfrc522.RxGain_max);
      if (EEPROM.read(1) != 1) {
        // Look EEPROM if Master Card defined, EEPROM address 1 holds if defined
        Serial.println("No Admin Card Defined");
        //When no Master Card in Your EEROM (Serial Display)
        Serial.println("Scan A card to Define as Admin Card");
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.println("SET ADMIN CARD   ");
        //When no Master Card in Your EEROM (LCD Display)
        lcd.setCursor(0, 1);
        lcd.println("SCAN A CARD.....");
        //Scan any RFID CARD to set Your Master Card in Your EEROM (LCD Display)
        delay(1500);
        do {
          successRead = getID();
          // sets successRead to 1 when we get read from reader otherwise 0
        }
        while (!successRead);
        //the program will not go further while you not get a successful read
        for (int j = 0; j < 4; j++) {
          // Loop 4 times
          EEPROM.write(2 + j, readCard[j]);
          // Write scanned PICC's UID to EEPROM, start from address 3
        }
        EEPROM.write(1, 1); //Write to EEPROM we defined Master Card.
        Serial.println("Admin Card Defined");
      }
      Serial.println("Administrator Card's UID");
      for (int i = 0; i < 4; i++) { // Read Master Card's UID from EEPROM
        masterCard[i] = EEPROM.read(2 + i); // Write it to masterCard
        Serial.print(masterCard[i], HEX); //Master Card only view in serial
        Serial.println("Waiting PICCs to bo scanned :)");
      }
     //WAITING TO SCAN THE RFID CARDS:
      Serial.println("");
      Serial.println("Waiting cards to bo scanned :)");
      lcd.clear();
      lcd.setCursor(4, 0);
      lcd.println("WAITING     ");
      lcd.setCursor(3, 1);
      lcd.println("FOR CARD...  ");
      delay(1500);
    }

    int getID() {
     // Getting ready for Reading PICCs
      if (! mfrc522.PICC_IsNewCardPresent()) {
        //If a new PICC placed to RFID reader continue
        return 0;
      }
      if (! mfrc522.PICC_ReadCardSerial()) {
        //Since a PICC placed get Serial and continue
        return 0;
      }
     // There are Mifare PICCs which have 4 byte or 7 byte UID care if you use 7 byte PICC
     // I think we should assume every PICC as they have 4 byte UID
     // Until we support 7 byte PICCs
      Serial.println("Scanning card's UID....");
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("SCANNING");
      lcd.setCursor(0, 1);
      lcd.print("Card's UID.....");
      delay(2000);
      for (int i = 0; i < 4; i++) {
        readCard[i] = mfrc522.uid.uidByte[i];
        Serial.print(readCard[i], HEX);
      }
      Serial.println("");
      mfrc522.PICC_HaltA(); // Stop reading
      return 1;
    }
    boolean isMaster(byte test[]) {
      if (checkTwo(test, masterCard))
        return true;
      else
        return false;
    }

    boolean checkTwo (byte a[], byte b[]) {
      if (a[0] != NULL)
        // Make sure there is something in the array first
        match = true;
        // Assume they match at first
      for (int k = 0; k < 4; k++) {
        // Loop 4 times
        if (a[k] != b[k])
          // IF a != b then set match = false, one fails, all fail
          match = false;
      }
      if (match) {
        // Check to see if if match is still true
        return true;
      } else  {
        return false;
      }
    }
    boolean findID(byte find[]) {
      int count = EEPROM.read(0);
      // Read the first Byte of EEPROM that
      for (int i = 1; i <= count; i++) {
        // Loop once for each EEPROM entry
        readID(i);
        // Read an ID from EEPROM, it is stored in storedCard[4]
        if (checkTwo(find, storedCard)) {
          // Check to see if the storedCard read from EEPROM
          return true;
          break; // Stop looking we found it
        } else {
          // If not, return false
        }
      }
      return false;
    }
    void readID(int number) {
      int start = (number * 4) + 2;
      // Figure out starting position
      for (int i = 0; i < 4; i++) {
        // Loop 4 times to get the 4 Bytes
        storedCard[i] = EEPROM.read(start + i);
        // Assign values read from EEPROM to array
      }
    }
    void deleteID(byte a[]) {
      if (!findID(a)) {
        // Before we delete from the EEPROM, check to see if we have this card!
        failedWrite(); // If not
      } else {
        int num = EEPROM.read(0);
        // Get the numer of used spaces, position 0 stores the number of ID cards
        int slot;
        // Figure out the slot number of the card
        int start;
        // = (num * 4) + 6; // Figure out where the next slot starts
        int looping;
        // The number of times the loop repeats
        int j;
        int count = EEPROM.read(0);
        // Read the first Byte of EEPROM that stores number of cards
        slot = findIDSLOT(a);
        //Figure out the slot number of the card to delete
        start = (slot * 4) + 2;
        looping = ((num - slot) * 4);
        num--; // Decrement the counter by one
        EEPROM.write(0, num); // Write the new count to the counter
        for (j = 0; j < looping; j++) {
          // Loop the card shift times
          EEPROM.write(start + j, EEPROM.read(start + 4 + j));
          // Shift the array values to 4 places earlier in the EEPROM
        }
        for (int k = 0; k < 4; k++) {
          //Shifting loop
          EEPROM.write(start + j + k, 0);
        }
        successDelete();
      }
    }
    //For Failed to add the card:
    void failedWrite() {
      Serial.println("something wrong with Card");
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("SOMETHING WRONG");
      lcd.setCursor(0, 1);
      lcd.print("WITH CARD");
      delay(2000);
    }

    //For Sucessfully Deleted:
    void successDelete() {
      Serial.println("Succesfully removed");
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("SUCCESFULLY");
      lcd.setCursor(0, 1);
      lcd.print("REMOVED CARD");
      delay(2000);
    }

    int findIDSLOT(byte find[]) {
      int count = EEPROM.read(0);
      // Read the first Byte of EEPROM that
      for (int i = 1; i <= count; i++) {
        // Loop once for each EEPROM entry
        readID(i);
        // Read an ID from EEPROM, it is stored in storedCard[4]
        if (checkTwo(find, storedCard)) {
          // Check to see if the storedCard read from EEPROM
          // is the same as the find[] ID card passed
          return i;
          // The slot number of the card
          break;
          // Stop looking we found it
        }
      }
    }
    //For Sucessfully Added:
    void successWrite() {
      Serial.println("Succesfully added");
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("SUCCESFULLY");
      lcd.setCursor(0, 1);
      lcd.print("ADDED");
      delay(2000);
    }

    //For Adding card to EEPROM:
    void writeID(byte a[]) {
      if (!findID(a)) {
        // Before we write to the EEPROM, check to see if we have seen this card before!
        int num = EEPROM.read(0);
        // Get the numer of used spaces, position 0 stores the number of ID cards
        int start = (num * 4) + 6;
        // Figure out where the next slot starts
        num++;
        // Increment the counter by one
        EEPROM.write(0, num);
        // Write the new count to the counter
        for (int j = 0; j < 4; j++) {
          // Loop 4 times
          EEPROM.write(start + j, a[j]);
          // Write the array values to EEPROM in the right position
        }
        successWrite();
      } else {
        failedWrite();
      }
    }
    void loop() {
      lcd.clear();
      lcd.setCursor(4, 0);
      lcd.print("TAP YOUR");
      lcd.setCursor(4, 1);
      lcd.print("CARD HERE");
      do {
        successRead = getID(); // sets successRead to 1 when we get read from     reader otherwise 0
        if (programMode) {
          // Program Mode cycles through RGB waiting to read a new card
        } else {
        }
      }
      while (!successRead);
      //the program will not go further while you not get a successful read
      if (programMode) {
        if (isMaster(readCard)) {
          //If master card scanned again exit program mode
          Serial.println("This is ADMIN Card");
          Serial.println("Exiting ADMIN Mode");
          lcd.clear();
          lcd.setCursor(0, 0);
          lcd.print("EXITING FROM");
          lcd.setCursor(0, 1);
          lcd.print("ADMINISTRATOR MODE");
          delay(2000);
          programMode = false;
          return;
        } else {
          if (findID(readCard)) {
            //If scanned card is known delete it
            Serial.println("I know this CARD, so removing");
            lcd.clear();
            lcd.setCursor(0, 0);
            lcd.print("AVAILABLE!");
            lcd.setCursor(0, 1);
            lcd.print("SO DELETING.....");
            delay(5000);
            deleteID(readCard);
            Serial.println("-----------------------------");
          } else {
            // If scanned card is not known add it
            Serial.println("Adding this card...");
            lcd.clear();
            lcd.setCursor(0, 0);
            lcd.print("Card no:");
            lcd.setCursor(0, 1);
            lcd.print(readCard[0], HEX);
            lcd.print(readCard[1], HEX);
            lcd.print(readCard[2], HEX);
            lcd.print(readCard[3], HEX);
            lcd.print(readCard[4], HEX);
            delay(4000);
            lcd.clear();
            lcd.setCursor(0, 0);
            lcd.print("NOT AVAILABLE");
            lcd.setCursor(0, 1);
            lcd.print("SO ADDING...");
            delay(5000);
            writeID(readCard);
            Serial.println("-----------------------------");
          }
        }
      } else {
        if (isMaster(readCard)) {
          // If scanned card's ID matches Master Card's ID enter program mode
          programMode = true;
          Serial.println("Welcome to Administrator Mode");
          lcd.clear();
          lcd.setCursor(0, 0);
          lcd.print("WELCOME TO");
          lcd.setCursor(0, 1);
          lcd.print("ADMIN MODE");
          delay(3000);
          int count = EEPROM.read(0);
          // Read the first Byte of EEPROM that
          Serial.print("I have ");
          // stores the number of ID's in EEPROM
          Serial.print(count);
          Serial.print(" record(s) on EEPROM");
          Serial.println("");
          Serial.println("Scan a card to ADD or REMOVE");
          Serial.println("-----------------------------");
          lcd.clear();
          lcd.setCursor(0, 0);
          lcd.print("SCAN CARD TO");
          lcd.setCursor(0, 1);
          lcd.print("ADD OR REMOVE...");
          delay(2500);
        } else {
          if (findID(readCard)) {
            // If not, see if the card is in the EEPROM
            Serial.println("Acces Granted");
            lcd.clear();
            lcd.setCursor(0, 0);
            lcd.print("ACCESS GRANTED");
            lcd.setCursor(0, 1);
            lcd.print("YOU MAY ENTER NOW");
            digitalWrite(8, HIGH);
            delay(1500);
            digitalWrite(8, LOW);
            lcd.clear();
          } else {
            // If not, show that the ID was not valid
            Serial.println("Access Denied");
            for (int abcd = 0; abcd < 3; abcd++) {
              lcd.clear();
              lcd.setCursor(0, 0);
              lcd.print("     SORRY");
              lcd.setCursor(0, 1);
              lcd.print("  ACCESS DENIED");
              digitalWrite(8, HIGH);
              delay(1000);
              digitalWrite(8, LOW);
              lcd.clear();
              lcd.print("   YOU'RE NOT  ");
              lcd.setCursor(0, 1);
              lcd.print("   AUTHORIZED   ");
              delay(1000);
            }
            lcd.clear();
          }
        }
      }
    }

Any help would be appreciated!

body: It may not be possible to use every optional Arduino feature with every other optional Arduino feature. Some features use the same Arduino resources.  If there is actually a hardware contention problem, you need to dive deep into the software drivers and hardware to figure out if there is a possible work around.  But this is hardly the type of effort new developers would take on.  It might be easier for a new developer to use 2 different Arduino's to host the features desired and set up a communication link between them.


sender: user

sender: assistant

body:
I recently made a similar project with a RFID reader and an SD card shield, and I had the same problem.

The explanation why it doesn't work is that some shields that use SPI communication don't really care about your slave select pin being pulled low, and interfere when Arduino is talking to another SPI device via the MISO pin.

 The only way I got it to work is by using a tri-state buffer on the MISO pins of my SPI devices. You can find plenty of info about it on the internet, as well as how to use them in your project.

The idea is simple, it works kind of like a transistor. When you pull the enable pin of the buffer to ground using SS pin, you allow the MISO pin of that device to be connected to the corresponding Arduino input. Otherwise, the MISO pin will be on a state of high impedance and would not interfere on the communication anymore.

Good luck with your project.


message:
Installing Arduino IDE on Linux

I downloaded `arduino-1.8.4-linux32.tar.xz` and ran `install.sh` as outlined (the very sketchy instructions) in https://www.arduino.cc/en/Guide/Linux

This seemed to work OK, so I removed 354M of what I thought was the installer, only to discover that I had deleted arduino.

The so-called `install.sh` on closer inspection seemed only to create links into the uncompressed download in my home directory.

The whole process seems very un-Linux like; I had assumed that it would be installed in `/usr/share/` like most Linux programs.

I realise I could extract into `/usr/share/` and set permissions for other users, but surely there must be others who have wanted to do the same. The macOS version seems to have a proper installer; does one exist for Linux?

body:
The problem here is that there are multiple flavours of linux each with their own installation and package management systems - Aptitude, Yum, EMerge, etc.

It is not easy for Arduino to keep up with creating packages for each and every system, so instead they create a single tarball that can be used on any of the systems.

At one point Arduino (or someone, anyway) used to create Debian packages for the IDE and upload them to the main Debian repository - however this has not been done for many years now and the packages in the Debian repositories are very much out of date (1.0.5 IIRC).

If you, as a system manager, choose to deploy the IDE system wide then it is your task to decide how best to do that.

One option is to just copy the contents of the archive to `/usr/share/arduino` and then run `./install.sh` from within that directory.


body:
I ran the following to Install the latest Arduino IDE on my Raspberry Pi3.
This should work all Pi models. [This release enables you to run the Arduino Software (IDE) on many of the mini PC boards based on ARM6+ processors currently on the market, including Raspberry Pi](https://blog.arduino.cc/2016/05/17/discover-the-latest-arduino-build-for-arm-linux/)

    # Installing Arduino IDE
    cd /usr/share/
    sudo tar xf /home/pi/arduino-1.8.9-linuxarm.tar.xz
    sudo chown root:root -R /usr/share/arduino-1.8.9/

    # Adding desktop shortcut, menu item and file associations for Arduino IDE
    # Each user needs to repeate this
    cd
    /usr/share/arduino-1.8.9/install.sh

There is a similar instruction in [MagPi61](https://www.raspberrypi.org/magpi/issues/61/) except they suggest installation in `/opt`


body:
I wrote an installation instruction for the Arduino 2.0.x IDE over at [AskUbuntu](https://askubuntu.com/q/1461941/51957).

I chose to install the files in the `/opt` directory, but opinions differ on that topic. The instruction also elaborates on adding desktop links and an icon for Ubuntu flavors.


message:
nRF24L01 not communicating

I have been using two nRF24L01 to communicate with each other using a simple Arduino Uno Board. It worked for 5 days and now all of a sudden it is now working. I tried to change the modules and the Arduino boards too, but even if trying a simple example the communication between them is not happening.

I googled everything and tried every option, it is not working.

I used `printDetails()` to check the config of the modules. It shows everything is ok but I am not able to understand if the transmitter or the receiver is the problem. Please guide me to solve this problem. Also how to make sure if both are working (any debugging technique)?

I have been trying it for 9 days now, and I badly want it to work.

The code I am using is very simple code. It doesn't have any errors.

Receiver code:

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>

    RF24 radio(7, 8); // CNS, CE
    String response;
    boolean done = false;

    void setup() {
      delay(500);
      Serial.begin(9600);
      radio.begin();
      radio.setPALevel(RF24_PA_MIN);
      radio.openReadingPipe(0,0xF0F0F0F0AA);
      radio.startListening();
    }

    void loop() {
      if (radio.available()) {
        radio.read(&response, sizeof(response));
        done = true;
      }
      if (done) {
        Serial.println(response);
      }
      done = false;
      delay(1000);
    }

Sender code:

    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>

    RF24 radio(7, 8); // CNS, CE
    String request;

    void setup() {
      delay(500);
      Serial.begin(9600);
      radio.begin();
      radio.openWritingPipe(0xF0F0F0F0AA);
      radio.setPALevel(RF24_PA_MIN);
      radio.stopListening();
    }

    void loop() {
      while (Serial.available() > 0) {
        request = Serial.readString();
        Serial.println(request);
        radio.write(&request, sizeof(request));
        delay(1000);
      }
    }

body:
Hello,

You need to set a channel to both NRF:

    void setup() {
       delay(500);
       Serial.begin(9600);
       radio.begin();
       radio.setChannel(0x55); //set the channel
       radio.openWritingPipe(0xF0F0F0F0AA);
       radio.setPALevel(RF24_PA_MIN);
       radio.stopListening();
       radio.powerUp(); //Power up the radio
    }

Change this.

    void loop() {
        if (radio.available()) {
            radio.read(&response, sizeof(response));
            done = true;
        }
        if (done) {
            Serial.println(response);
            done = false;
        }
        //done = false;
        delay(1000);
    }


body: Maybe you should check your power supply. If it worked for 5 days, then it should be ok with your boards and module. If it don't work anymore it could be broken board, broken module or power supply.


message:
Can't upload to Arduino Mini via Arduino USB 2 Serial Converter

I bought an Arduino Mini and also an Arduino USB 2 Serial Converter.
While trying to program the Arduino Mini, I get this error:

    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00

After doing some research I tried many things like changing the settings, serial port, made sure I'm using the right Arduino etcetera.

Some points to consider:

 - I tried burning the bootloader using my Arduino Uno.
 - Uploading sketches to the Arduino Mini using my Arduino Uno works (so problem is not directly with the Mini).
 - I *am* pressing the Reset button before uploading. I also tried hooking a capacitor and the Reset wire directly. No change.

The wiring (I also tried connecting TX of Mini to RX of serial converter, and vice versa):

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

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

body: The Arduino USB 2 Serial converter was defect (even though brand new). I bought a cheaper (7 Euro) FTDI to USB and I can now upload.


message:
Arduino Uno - Multiple modules for HDMI switch device

I have an Arduino Uno device that uses the following modules:

 - 16 PIN LED w/ Backlight
 - RFID - RC522 (RFID Reader)
 - HR911105A (LAN Module - HanRun)

These three modules use every digital pin available in the Uno (2-13) and
it works correctly. The problem is that I want to add a relay to this board. I am new to Arduino so I use tutorials and right now I do not fully understand how this works. So I have connected the `IN` pin of the relay to Uno pin 8 and the `NO` pin of the relay to Uno pin 13.

The problem is that when I don't use other modules the relay works correctly (using this code).

    int relay_pin = 8;
    int led_pin = 13;

    void setup() {
      pinMode(relay_pin,OUTPUT);
      pinMode(led_pin,OUTPUT);
      digitalWrite(led_pin,HIGH);
    }

    void loop() {
      digitalWrite(relay_pin,HIGH);
      delay(5000);
      digitalWrite(relay_pin,LOW);
      delay(5000);
    }

The remaining ports are 1 and 0, which I assume are TX/RX, and can't be used for relay (am I wrong?).

So obviously I should not be using those pins but I wonder which pins I am allowed to use simultaneously when using two or three modules at the same time.

Does it depend on the modules or are there some instructions?

body:
The relay wiring diagram you are following is just plain bizarre and the strangest one I have ever seen.

Ignore it. It is completely incorrect.

You only need one pin to control a relay, so disconnect it from pin 13.

The switched side can connect to anywhere where you would normally use a switch - such as to switch power to an LED *connected between +5V and GND with a suitable current limiting resistor*.

You can use any available pin to control the relay, and that includes pins 0 or 1 *if you aren't using serial communication*.  Note that with the relay connected to one of those pins it will most likely activate and buzz while you upload a sketch - best to disconnect it at that point and reconnect it afterwards.

----

Devices like relays and LEDs need their own dedicated pin. They can't be shared with other functions or each other.

The only devices that can share pins are devices which connect to a *bus*, such as SPI or I2C.


message:
SIM900a Mini Modem, IMEI 0, help with TX RX pins

I have Simcom **SIM900a** GSM *(SIM900a Mini DEV Board v3.9.2)* and I am interfacing it with **Arduino UNO**.
I have no idea how to connect SIM900a to Arduino UNO.

What I did now is:
[![SIM900a; My reference image][1]][1]

I connect the following Pin from above image to:

**5** to: `GND (Digital GND near Pin 13)`

**6** to: `5V of Arduino`

**2** to: `GND of Arduino near 5V`

**3** to: `Digital Pin 0 of Arduino (RX)`

**4** to: `Digital Pin 1 of Arduino (TX)`

**1** to: (No idea)

From Picture option **7**, **8**, **9** are not connected to anything.

Can you please guide me am I doing right?

I am getting hard time to find out what is `TX` and `RX` in my SIM900a module as it is not written there.

My SIM900a looks like [**this**][2], [**this**][3]*(Schematics given)* and [this][4].

When I upload the sketch:

**File > Examples > GSM > TestModem:**

to Arduino, I got this output from **Serial Monitor**:

> Starting modem test...ERROR, no modem answer.
>
> Checking IMEI...Modem's IMEI: 0
>
> Reseting Modem... Modem is functioning properly: IMEI: 0

**PS:**

I saw this schematic [here][5] which is way different than what I am doing.

**PSS:**

Hints, am I supposed to provide external power supply of `5 V` `2 A` OR do I need some kind of converters `(TTL to RS232 converter)` ?

  [1]: https://i.stack.imgur.com/vYUn8.png
  [2]: http://www.arduinopak.com/Prd_Detail.aspx?Prd_ID=19993
  [3]: http://upsats.com/Content/Product/img/Product/Large/SIM900V4-G36-37C.jpg
  [4]: http://www.electrodragon.com/product/sim900a-mini-dev-board/
  [5]: http://www.instructables.com/id/Using-a-SIM900A-GSMGPRS-module-in-Australia/

body:
Your wiring is correct:

    6 - VDC (+5V)
    5 - GND
    4 - RX (connect to Arduino TX - pin 1 for UNO)
    3 - TX (connect to Arduino RX - pin 0 for UNO)

5VDC/2A power supply is must, otherwise module will be resetting when wireless radio is turned on. When using separate power supply, don't forget to connect Arduino GND and module GND.

The RX/TX on the module are depicted as 5VR/5VT (and 3VR/3VT for 3.3V pins).

The better way to get started / debug would be to use USB-to-serial converter: set the baudrate as 115200, connect and type AT and enter. Shall respond with AT (echo) and OK.

PS: The red wire (6) shall be on the left and black (5) on the right side, according to the board connector.


body:
Finally I found solution to this problem:

My Pins connections were wrong, it should not be: `0` and `1` it should be `2` & `3`:

    2 - RX Arduino
    3 - TX Arduino

also `SoftwareSerial.h` is not working with `SIM900A`

**Pins:**

All connections should be like this:

    SIM900A - Arduino
    =================
    VCC     - VDC (+5V)
    GND     - GND
    5VR     - Connect to Arduino TX (Pin 3)
    5VT     - Connect to Arduino RX (Pin 2)

As discussed [here](https://arduino.stackexchange.com/a/35717/26037).

**Very important:**

Any program with header/library: `#include <SoftwareSerial.h>` is not working but `#include <GSM.h>` is working fine. As `SoftwareSerial.h` only work with `GSM Shield` and `SIM900A` isn't a shield.

**Program/Sketch to Upload:**

    /*
    SMS sender

    created 25 Feb 2012
    Originally written by Tom Igoe
    But this is modified version
    */

    // Include the GSM library
    #include <GSM.h>

    #define PINNUMBER ""

    // initialize the library instance
    GSM gsmAccess;
    GSM_SMS sms;

    void setup(){
    // initialize serial communications and wait for port to open:
    Serial.begin(9600);
    while (!Serial){
    ; // wait for serial port to connect. Needed for Leonardo only
    }
    Serial.println("SMS Messages Sender");
    // connection state
    boolean notConnected = true;

    // Start SIM900A GSM

    while (notConnected){
        Serial.println("Status 1: Please wait a while, If it taking lot of time, \nmeans you have wrong pin connections.");
        // If your SIM has PIN, pass it as a parameter of begin() in quotes
        if (gsmAccess.begin(PINNUMBER) == GSM_READY){
        Serial.println("Status 2: GSM is ready.");
        notConnected = false;
    }else{
        Serial.println("Status 3: Not connected");
        delay(1000);
      }
    }
        Serial.println("Status 4: GSM initialized. " );

        // calling function to send message
        sendMessage();
    }

    void loop(){
        // empty loop
    }

    // method to send message to specific number just once.
    void sendMessage(){
        Serial.print("Message is sending...: ");
        // send the message
        sms.beginSMS("03XXXXXXX "); // Replace XXXXXXX with your mobile number.
        sms.print("This is just some message"); // Message content, replace with your's.
        sms.endSMS();
        Serial.println("COMPLETE!\n");
        Serial.println("Message Sent...!\n");
    }

**Bam**, It is working, and it successfully can send message.

**Things to remember:**

 1. As everywhere being said you need to supply external power supply to SIM900A   it requires `5 Volts` and `2 Amphs`.

 2. Connect `GND` of SIM900A to Arduino `GND`.

 3. Connect `VCC+` *(above photo connection 2)* to `5V` pin of Arduino.

**One Problem:**
When I upload sketch of:

> Example > GSM > TestModem:

to Arduino, I got this output from **Serial Monitor**:

> Starting modem test...ERROR, no modem answer.
>
> Checking IMEI...Modem's IMEI: 0
>
> Reseting Modem... Modem is functioning properly: IMEI: 0

I cannot get IMEI from SIM900A but I can send message.


message:
PWM on Pin 4 - arduino Micro

I am using Arduino Micro. Is there any way to use PWM on pin 4 instead of Pin3 ?

I tried to change pins_Arduino.h but didnt worked.

    //#define digitalPinHasPWM(p)         ((p) == 3 || (p) == 5 || (p) == 6 || (p) == 9 || (p) == 10 || (p) == 11 || (p) == 13)

    #define digitalPinHasPWM(p)         ((p) == 4 || (p) == 5 || (p) == 6 || (p) == 9 || (p) == 10 || (p) == 11 || (p) == 13)

and

    const uint8_t PROGMEM digital_pin_to_timer_PGM[] = {
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     ////////////////////////modified///////////////
     //TIMER0B,  /* 3 */
     //NOT_ON_TIMER,
     NOT_ON_TIMER,
     TIMER0B,  /* 4 */
     ////////////////////////////////////////////////////
     TIMER3A,  /* 5 */
     TIMER4D,  /* 6 */
     NOT_ON_TIMER,

     NOT_ON_TIMER,
     TIMER1A,  /* 9 */
     TIMER1B,  /* 10 */
     TIMER0A,  /* 11 */

     NOT_ON_TIMER,
     TIMER4A,  /* 13 */

     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,

     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
     NOT_ON_TIMER,
    };

body: You cannot. There is no PWM on that pin. PWM is generated by hardware. The hardware simply does not exist.


message:
Connecting a servo via HC05 and HC06

I want to drive a servo via a HCO6 and HC05 link as a stand alone, using no android or PC.
The question is how to send a 1.5 ms signal (generated with a pulse command on a Nano) from one HC to another HC (to which my servo will be connected) ?
I do not need to care about passwords in my linking. No text to be sent, just the 1ms to 2 ms signal, at a refresh rate of 50 Hz.
I will use the HC with a OOK modulation (on - off on the data pin)?
How to achieve this ?
Thanks !

body:
You cannot. You will need an Arduino at the servo end to generate the PWM signal from serial instructions sent over Bluetooth.

Since PWM is (typically) 8-bit and serial is (typically) 8-bit you could simply have each byte as a 1:1 mapping to a PWM value.

One the transmit end:

    bluetoothSerial.write(pwmValue);

On the receive end:

    if (bluetoothSerial.available()) {
        analogWrite(9, bluetoothSerial.read());
    }


message:
DHT11 data in Arduino UNO to Firebase through ESP8266

Hello Good Day to Everyone.
I have a project where I need to send DHT11 sensor data to a Firebase database using both Arduino UNO and Esp8266 esp-01 wifi module. Both of them must work together to send the data.

[![Connection][1]][1]

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

Arduino Code:

    #include <dht.h>

    dht DHT;

    #define DHT11_PIN 7

    void setup() {
    // put your setup code here, to run once:
    Serial.begin(9600);

    }

    void loop() {
     // put your main code here, to run repeatedly:
    int chk = DHT.read11(DHT11_PIN);
    Serial.print("Temperature = ");
    Serial.println(DHT.temperature);
    Serial.print("Humidity = ");
    Serial.println(DHT.humidity);
    delay(1000);

    }

My arduino code is working fine. Now comes the part where I need to program the ESP8266 which I am really confused how to pass the data to the wifi module and send it to firebase. I tried to code some and this is my

ESP8266 Code:

    #include <ESP8266WiFi.h>
    #include <FirebaseArduino.h>
    #include <DHT.h>

    #define FIREBASE_HOST "test.firebaseio.com"
    #define FIREBASE_AUTH "authcode"

    #define WIFI_SSID "mywifi"
    #define WIFI_PASSWORD "12345"

    #define DHTTYPE DHT11
    #define DHTPIN  7

    DHT dht(DHTPIN, DHTTYPE);
    float temp_f;
    unsigned long previousMillis = 0;
    const long interval = 2300;

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

    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    Serial.print("connecting");
    while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
    }
     Serial.println();
     Serial.print("connected: ");
     Serial.println(WiFi.localIP());

    Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);

     }

    void loop() {
    delay(2000);
    float h = dht.readHumidity();
    float t = dht.readTemperature();
    delay(50);
    Firebase.setFloat("temp",t);
    Firebase.setFloat("hum",h);
    delay(1000);
    }

I don't want my esp8266 to go stand alone. I wanted the data to come from the arduino but somehow I don't know how to receive the data from the arduino in the esp8266.

I hope someone can enlighten me..
thank you

body:
First of all, FirebaseArduino.h library is for ESP8266 itself and not for Arduino UNO.
The code you have written will not work as you are giving instructions like `Firebase.setFloat("temp",t);` to UNO. It will not compile.
What you should do is set ESP8266-01 as your primary board and let the UNO transmit the data by software serial.
ESP8266-01 will capture that data and transmit it over the Internet.
YOU CAN'T USE FirebaseArduino.h FOR ARDUINO UNO! It is for the ESP8266.
All YouTube videos will show you how to code for NodeMCU esp8266-12E. Do that for ESP-01 and communicate with Arduino for data (converting data calculated to string will help to reduce problems). Get data in form of string from UNO and transmit it using ESP-01!

If you want I can share all video list that I found useful!


message:
Problem with Arduino Uno and SIM900 shield logical communication (rx & tx)

[![  these is my shield     ][1]][1]

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

The logical communication(rx & tx) between the shield and Arduino Uno doesn't  work. Arduino (rx & tx) supply  is 0 & 5 V but this is 0 & 2.8 V. What am I to do?

body:
Use a [logic level converter][1].

A logic level converter is a small device that converts between different logic levels, for example between 5V and 3.3V.

I am not affiliated with Sparkfun, I just think they are the most informative source.

  [1]: https://learn.sparkfun.com/tutorials/using-the-logic-level-converter


message:
Ultrasonic distance module works without connecting to gnd

I have a (HCSR04) ultrasonic distance module connected to arduino , i have connected all the four pins of the module properly and its working fine , then when i pull off the wire which is connected to ground in arduino , the module works totally fine . How the module works without connecting its ground pin to arduino ground ?

body:
It's not uncommon for part to "sort of" work when one of the supply rails is missing and an input signal of the some polarity somewhat substitutes for it, often through built-in ESD protection diodes.  In this case, the trigger input when idle is low, and there's probably some capacitance on the board that could hold it through the brief trigger pulse.

It's a bad idea to rely on this though, both as it typically means stressing parts by operating them outside of specified limits, and can also produce not-quite reliable behavior.

For example, I once wired an SPI flash chip on a small carrier stuck underneath an MCU eval board, in order to test some software for a board I was designing.  It worked great.  Or I should say, it did right up until I tried to write to it, which would always fail.  Eventually I discovered that I'd forgotten the ground connection when wiring it up.  It was able to return enough current through the I/Os to perform read operations, but not to support a write.


message:
Arduino with nRF24L01

I am using nRF24L01 with Arduino Nano and Mini. I feel they are very useful when we want to connect multiple Arduinos together.

In market we can buy Arduino with WiFi and Bluetooth, why don't they make Arduino model with nRF24L01? Is there any specific valid reason?

Or am I wrong in using nRF24L01 and there is a better cost and power efficient way to connect multiple Arduinos together wirelessly?

body:
nRF24L01 is a proprietary system, unlike WiFi and Bluetooth. There is only one (official) maker of nRF devices (Nordic Semiconductor).

Yes, they are very nice modules, but why would you spend the time and money developing a generic microcontroller board that has such limited scope as to only be able to communicate with the same board or one with one specific module attached?  You wouldn't - it doesn't make financial sense - especially when it's easy for an end user to add the module to any other board instead.

Bluetooth and WiFi make more financial sense because there is a huge range of devices that they can communicate with which means they can be used for a far greater range of projects thus increasing demand for them.


body:
NordicRF (the company behind nRF24L01) has released two series of SoC devices that are compatible with nRF24: [NRF51][1] and [NRF52][2]. Thanks to the effort by Sandeep Mistry and other contributors, they can be programmed using the Arduino IDE and libraries. Instructions are available here: [https://github.com/sandeepmistry/arduino-nRF5][3]

I have tested NRF51822, which is the cheapest variant (costing slightly more than Arduino Pro Mini + NRF24L01+ but in a single small and power-efficient package) and it works great.

The BBC Micro:bit is based on NRF51. More information is available at https://forum.mysensors.org/topic/9722/bbc-micro-bit-and-mysensors-a-great-match

Compared to the Atmega328-based Arduino Pro Mini, NRF51822 has 8x larger flash and 8x larger RAM. It also has Bluetooth 5 and BLE support and a 32-bit ARM Cortex M0 CPU.

There is also this alternative: https://www.ebid.net/eu/for-sale/arduino-ide-compatible-controller-with-the-nordic-nrf24l01-radio-transceiver-156695123.htm

Specifications:

 - Dimensions 59mm x 18mm
 - The Nordic nRF24L01+ 2.4 GHz Radio transceiver on board
 - Supply voltage up to 6.5 Volts
 - The Digital and Analog pins are 5 volts
 - ATMega328P frequency is 8 Mhz
 - 4 battery connector pins
 - FTDI header for programming
[![enter image description here][4]][4]

Full disclosure: I am member of the MySensors core team. A MySensors user (not affiliated with the core team) created and is selling this board.

  [1]: https://www.nordicsemi.com/Products/nRF51-Series-SoC
  [2]: https://www.nordicsemi.com/Products/nRF52-Series-SoC
  [3]: https://github.com/sandeepmistry/arduino-nRF5
  [4]: https://i.stack.imgur.com/EZXO1.jpg


message:
Set board manager as ATmega16

I tried to download the ATmega16 board in my Arduino. I have set below URL under File->Preference->Additional board manager URL

`https://mcudude.github.io/MightyCore/package_MCUdude_MightyCore_index.json`

I am getting below attach images. How can we resolve this error and install atmega16 board manager?

I am using Arduino version 1.6.9. I don't have any issue in opening MightyCare and Arudino URL from my chrome browser.

[![Error_in_BoardManager][1]][1]

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

body:
Thanks for everyone help here.

I have resolved by few steps.

1) File -> preference -> Board manager URL as like below. Basically URL are seperated by commas.
`http://arduino.esp8266.com/stable/package_esp8266com_index.json,https://mcudude.github.io/MightyCore/package_MCUdude_MightyCore_index.json`

2) Deleted the tmp file (package_index.json.tmp) which is in the path `C:\Users\SIMBU\AppData\Local\Arduino15\`

This helped me to resolve the issue.


message:
How to use and retrieve data file from AT command in Arduino D1 Mini Wemos (With esp8266)

I stumbled upon an AT command for the ESP8266 that I really need. The following command is "AT+CWLAP", but I have no idea how to use it. I can't seem to find any resource on how to implement it.

I need the SSID, RSSI, and MAC addresses of the AP and pretty much use those data internally. For example (not necessarily doing this but you get the point), depending on the signal strength, choose the best option and print the SSID of the AP.

Is it even possible?

body:
The command is documented in the [ESP8266 AT Command Reference][1], with a non-PDF option at [https://room-15.github.io/blog/2015/03/26/esp8266-at-command-reference/#AT+CWLAP][2]

The response from the `AT+CWLAP` is a series of lines listing available access points, and for each, you are given their encryption method, SSID, RSSI, MAC, and the channel (or frequency offset and a calibration value).

It would be up to the you to parse the resulting strings to obtain the APs, sort by signal strength, and decide what to do with that information.

**EDIT:**

Because you are using the Arduino environment/core to write code for the ESP8266, you won't be able to use the AT command set. The AT Commands are available when the ESP8266 has the EspressIF firmware loaded to it, and thus the ESP8266 module is intended to be a peripheral device to some other controller; contrast with your use, where the ESP8266 is the **only** controller, with the WiFi ability baked in.

In this case, you will need to examine the features of the [Arduino ESP8266 core][3], especially the [ESP8266WiFi library][4], which gives an [example sketch for scanning the available WiFi networks][5].

  [1]: https://www.espressif.com/sites/default/files/documentation/4a-esp8266_at_instruction_set_en.pdf
  [2]: https://room-15.github.io/blog/2015/03/26/esp8266-at-command-reference/#AT+CWLAP
  [3]: https://github.com/esp8266/Arduino/tree/master/libraries
  [4]: https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266WiFi
  [5]: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiScan/WiFiScan.ino


message:
myserial.available() returns zero byte

I wrote an Arduino program that requires two ports for serial communication. I intended to use both hardware serial and software serial, but the problem is receiving data from receiving buffer of the software serial: it always returns zero byte from `myserial.available()`.

For clarity I used the software serial example in Arduino IDE ver. 1.8.4.
I tried to change the baud rate but still the problem persists. I read somewhere that they made some code changes in the SoftwareSerial library's .cpp and .h files. I tried to find the site without success. And my PC where I installed those libraries was stolen. Before that it was working properly.

The mistake I made is that I just copied the code and pasted in the library without concentrating on it. Here is the example of program with two serial ports.

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(2, 3); // RX, TX

    void setup() {
      Serial.begin(57600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }
      Serial.println("Goodnight moon!");
      // set the data rate for the SoftwareSerial port
      mySerial.begin(4800);
      mySerial.println("Hello, world?");
    }

    void loop() {
      if (mySerial.available())
        Serial.write(mySerial.read());
      if (Serial.available())
        mySerial.write(Serial.read());
    }

body:
The SoftwareSerial example code
https://www.arduino.cc/en/Reference/SoftwareSerialAvailable
shows that the pins used as tx and rx for SoftwareSerial need to be defined using pinMode() as digital input and output.

>Example

    // include the SoftwareSerial library so you can use its functions:
    #include <SoftwareSerial.h>

    #define rxPin 10
    #define txPin 11

    // set up a new serial port
    SoftwareSerial mySerial =  SoftwareSerial(rxPin, txPin);

    void setup()  {
      // define pin modes for tx, rx:
      pinMode(rxPin, INPUT);
      pinMode(txPin, OUTPUT);
      // set the data rate for the SoftwareSerial port
      mySerial.begin(9600);
    }

    void loop() {
      if (mySerial.available()>0){
        mySerial.read();
      }
    }


body:
Not all pins on the Mega and Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).
Not all pins on the Leonardo and Micro support change interrupts, so only the following can be used for RX: 8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).


message:
How to calculate voltage from A0 pin

I would like to calculate the amount of voltage from my A0 pin. I am using a 9v battery to power my load in my circuit. The formula to calculate voltage from the A0 pin is:

        sens = analogRead(A0);
        vol = sens * ( 5.0 / 1023.0);
If my power source is 9v, should i replace the 5.0 to 9.0?

body:
The analog input pins are 0V-5V strictly. If you need to measure a 9V input, you need to scale the voltage to test so that it is within a 0V-5V range. Often this is done with a voltage divider circuit.

In the example below, the 9V test voltage is divided in half, so the scale is 0V-4.5V, which is within range of the input pin.

Then your algorithm is

    vol = sens * (2.0) * ( 5.0 / 1024.0);

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

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

<!-- End schematic -->


message:
Can I use my PC or Android mobile as WiFi Shield/Module for Arduino UNO?

I'm using an Arduino Uno. Currently I am using an ESP8266 WIFI module to connect to the Wifi. But is it possible to use my laptop or Android mobile as a WiFi Shield/Module? I want to connect with cloud server using the connection.

Thanks in advance.

body:
This problem can be broken into several components:

### Communications channel between the Arduino Uno and the laptop or Android mobile

There are several options. The most common and probably easiest is to do serial communication over USB. The Uno has a USB-serial chip that creates a virtual COM port (VCP) on a computer when you connect the Uno to it via the USB receptacle on the board. This VCP is commonly used to upload sketches to the Uno and also to communicate with the Arduino IDE's Serial Monitor.

Another option for communications between your Uno and the laptop or Android mobile is Bluetooth. You can buy a Bluetooth module for your Uno that will allow this. This may be preferable if you need wireless communication.

### Application on the Laptop or Android mobile that interprets communication with the Uno

Now you can communicate between the two devices but you need a program running on the Laptop or Android mobile to actually do something with the communication. This application will receive commands from the Uno, and make the desired interactions with the "cloud server", and perhaps respond to the Uno. You will need to have some sort of a command protocol. The details of this will be dependent on which type of communications channel you chose. There are many ways you can accomplish this and the best option will also depend on whether you will be writing this application yourself or trying to find an existing application that suits your needs.

### Arduino Uno firmware

This is a sketch you will write and upload to your Uno that sends commands to the laptop or Android mobile via your chosen communications channel and handles any responses.


message:
Can we use Arduino mini in eagle to create new custom modal

I want to learn pcb design in Eagle/Fritzing. So i was thinking of using existing amazing Arduino mini/nano in eagle and create a custom pcb which has all arduino capability and plus some components like 7 segment/Bluetooth radio etc.

Can we do that? Is is allowed or arduino design is not open to be modified?

body:
Arduino is open-source hardware. The Arduino website has [schematics][1] and [board layout files][2].

  [1]: https://www.arduino.cc/en/uploads/Main/Arduino-Pro-Mini-schematic.pdf
  [2]: https://www.arduino.cc/en/uploads/Main/arduino-pro-mini-reference-design.zip


body:
From https://www.arduino.cc/en/Main/FAQ#toc8:
>I want to design my own board, what should I do?
>
>The reference designs for the Arduino boards are available from their specific product pages. They're licensed under a Creative Commons Attribution Share-Alike license, so you are free to use and adapt them for your own needs without asking permission or paying a fee.

You can find the board design files on the **Documentation** tab of each product page.

Arduino Mini product page:
https://store.arduino.cc/arduino-mini-05

Arduino Nano product page:
https://store.arduino.cc/arduino-nano


message:
Error while uploading code to ESP8266 through Arduino Mega 2560

I am sorry for posting this question for the nth time but I am still not able to find a solution for this error.

I am trying to upload the WiFiScan(Arduino IDE example program)program code to ESP8266 using Arduino Mega 2560. I followed the procedure given [here](https://diyhacking.com/esp8266-tutorial/). And I tried uploading it with "Generic ESP8266 Module" and "Adafruit HUZZAH ESP8266" selected as the Board. But I am still getting the following error.

    trying to connect
      espcomm_send_command: sending command header
      espcomm_send_command: sending command payload
    warning: espcomm_sync failed
    error: espcomm_open failed
    error: espcomm_upload_mem failed

Edited to add:
[![enter image description here][1]][1]

**Connections-**

**ESP8266 - Arduino Mega2560**

Tx - Tx1(Pin 18)

Rx - Rx1(Pin 19)

Gnd - Gnd

Vcc - 3.3V (Directly from Arduino's 3.3V pin)

CH_PD - 3.3V (Directly from Arduino's 3.3V pin)

GPIO0 - Push button K2 (refer photo)

RST - Push button K1

While pressing the K2 button(Flash button - GPIO0), I clicked the K1 button(Reset button - RST) and then released K2. According to the document, this should bring the ESP8266 to flash mode. Now when I upload the code, it throws the above error.

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

body:
After googling for several hours, I was able to figure out the reason. Thanks to this [link][1]. Transferring data to ESP8266 with Arduino acting as USB to Serial converter did not work. Using a USB to TTL converter, and following this [link][2] you can easily transfer data to ESP8266.

  [1]: https://github.com/esp8266/Arduino/issues/1207
  [2]: https://diyhacking.com/esp8266-tutorial/


message:
Reload only one variable in loop()

I need some information for the TFT screen 2.8 and arduino mega.
The screen works very well and displays the data.
The small problem I encounter is for the text display, the page is reloading every second and this makes a small black screen every second.
I would like to know if it was possible to reload only one part of the screen display?

See in video
https://youtu.be/vxSa6xkH0vU

My `loop()`

    void loop(void) {
       tft.fillScreen(BLACK);
      unsigned long start = micros();
      tft.setCursor(0, 0);
      tft.setRotation(3);
      dt = clock.getDateTime();
      clock.forceConversion();

      // Go
      tft.println();
      tft.setTextColor(GREEN);
      tft.setTextSize(5);
      tft.println("Info");
      tft.println();
      tft.setTextSize(2);
      tft.println(clock.dateFormat("d-m-Y H:i:s", dt));
      tft.println();
      tft.setTextSize(2);
      tft.println("Temperature: ");
      tft.println(clock.readTemperature());

      delay(1000);
    }

body:
You can use [`tft.rect(x,y,width,height)`][1] to clear only a portion of the screen. Make sure to set `tft.fill` before calling it.

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


message:
Home devices control system using gsm and arduino mega2560

Hi dears I'm trying to do project to control app base gsm control by arduino mega 2560 gsm module SIM900A

To send SMS to open Led than reply SMS to give as the status I mean send SMS then I received SMS from GSM module  by this code same time work but same time not work also same time send SMS1111 received SMS2222 status.
I hope it is clear.

    #include <SoftwareSerial.h>
    #include <string.h>
    #include "SIM900.h"
    #include <TinyGPS.h>
    #include "sms.h"
    SoftwareSerial GSMSerial(12, 13);
    byte buffer[128];
    int count = 0;
    const int Led4 = 43;
    const int Led1 = 44;
    const int Led2 = 45;
    const int Led3 = 50;
    void SIM900power()
    {
    }
    void setup() {
        pinMode(Led1, OUTPUT);
      pinMode(Led2, OUTPUT);
      pinMode(Led3, OUTPUT);
      pinMode(Led4, OUTPUT);
      GSMSerial.begin(19200); // the SIM900 baud rate
      Serial.begin(9600); // the Serial port of Arduino baud rate.
      Sim900_Inti();
    }
    void loop() {
      GSMSerial.listen();
      if (GSMSerial.available()) // If date is comming from from GSM shield)
      {
        while (GSMSerial.available()) // reading data into char array
        {
          buffer[count++] = GSMSerial.read(); // writing data into array
          if (count == 128)break;
        }
        Serial.write(buffer, count); // if no data transmission ends, write         buffer to hardware serial port
    Cmd_Read_Act(); //Read the 'COMMAND' sent to SIM900 through SMS
    clearBufferArray(); // call clearBufferArray function to clear the storaged data from the array
    count = 0; // set counter of while loop to zero
      }
      if (Serial.available()) // if data is available on hardwareserial port ==>     data is comming from PC or notebook
        GSMSerial.println(Serial.read()); // write it to the GPRS shield
    }
    void clearBufferArray() // function to clear buffer array
    {
      delay(1000);
      for (int i = 0; i < count; i++)
      {
        buffer[i] = NULL; // clear all index of array with command NULL
        delay(100);
      }
      for (int n = 0; n < count; n++)
      {
        buffer[n] = NULL; // clear all index of array with command NULL
        delay(100);
      }
      for (int m = 0; m < count; m++)
      {
        buffer[m] = NULL; // clear all index of array with command NULL
        delay(100);
      }
      for (int p = 0; p < count; p++)
      {
        buffer[p] = NULL; // clear all index of array with command NULL
        delay(100);
      }
    }
    void Sim900_Inti(void)
        {
         GSMSerial.println("AT+CMGF=1"); // Set GSM shield to sms mode
      Serial.println("AT+CMGF=1");
      delay(500);
      GSMSerial.println("AT+CNMI=2,2");
      Serial.println("AT CMGF=1");
      delay(500);
    }
    void Cmd_Read_Act(void) //Function reads the SMS sent to SIM900 shield.
    {
      char buffer_i[128];
      for (int i = 0; i < count; i++)
      {
        buffer_i[i] = char(buffer[i]);
      }
      if (strstr(buffer_i, "1111")) //Comparing password entered with password     stored in program
      {
              digitalWrite(Led1, HIGH);
       SMS_1111();
      }
      char buffer_n[128];
      for (int n = 0; n < count; n++)
      {
        buffer_n[n] = char(buffer[n]);
      }

      if (strstr(buffer_n, "2222")) //Comparing password entered with password     stored in program
      {
              digitalWrite(Led2, HIGH);
       SMS_2222();
      }
          char buffer_m[128];
      for (int m = 0; m < count; m++)
      {
        buffer[m] = char(buffer[m]);
      }
      if (strstr(buffer_m, "3333")) //Comparing password entered with password     stored in program
      {
       digitalWrite(Led3, HIGH);
       SMS_3333();
      }
      char buffer_p[128];
      for (int p = 0; p < count; p++)
      {
        buffer[p] = char(buffer[p]);
      }
      if (strstr(buffer_p, "4444")) //Comparing password entered with password stored in program
          {
        digitalWrite(Led4, HIGH);

       SMS_4444();
      }
    }
      void SMS_1111() // complet liter Replay SMS TO Know Led1 Is ON
     {
     }
     void SMS_2222()// complet liter
    {
    }
    void SMS_3333()// complet liter
    {
    }
    void SMS_4444()// complet liter
    {
    }>

body:
For the `3333` and `4444` you are doing

    buffer[m] = char(buffer[m]);

and

    buffer[p] = char(buffer[p]);

which does nothing.

You probably meant

    buffer_m[m] = char(buffer[m]);

and

    buffer_p[p] = char(buffer[p]);


message:
ESP8266 Wemos D1 Retrieving Wrong AP Mac Address

Using `WiFi.BSSID` and `WiFi.BSSIDstr` gives me some weird mac address.

the code is:

    #include "ESP8266WiFi.h"
    #include "ESP8266WiFiScan.h"

    void setup() {
    Serial.begin(115200);
    //WiFi.mode(WIFI_STA);
    WiFi.disconnect();
    delay(100);
    Serial.println("Setup done");
    Serial.println(WiFi.macAddress());
    }

    void loop() {
       int n=WiFi.scanNetworks();
       Serial.println(n);
       for (int network = 0; network < n; network++){
          Serial.println(WiFi.SSID(network));
          Serial.println(WiFi.RSSI(network));
          uint8_t* mac=WiFi.BSSID(n);
          char APmac[13];
          APmac[0]=0;
          for (int i=0; i<6;i++) {
            char buffer[3];
            sprintf(buffer, "x", mac[i]);
            strncpy((char *)(APmac+(i*2)), buffer, 3);
            Serial.print("["); Serial.print(i); Serial.print("]"); Serial.println(buffer);
          }
          Serial.println(APmac);
          Serial.println(WiFi.BSSIDstr(n));

      }
      Serial.println();
      Serial.println();
      delay(10000);
    }

The current output is 6D:98:C9:00:00:00 which is completely off. It duplicates this output for other APs too. Is this a hardware problem? I've seen other people using the same codes and it works for them. For reference `WiFi.SSID();` and `WiFi.RSSI();` both spits out correctly.

edit: I was testing both output to see which ever one was correct and unfortunately they're both wrong

body:
This seems wrong, you are trying to get String to interpret a byte, but are passing in a pointer to a byte:

    String digit = String(*mac, HEX);

Try changing your example to:

    uint8_t* mac=WiFi.BSSID();              // Gather the byte array
    String APmac;
    for (int i=0; i<6;i++) {
       String digit = String(mac[i], HEX);  // String() should see an int, not a pointer to a byte, with the directive to print it in HEX format
       if (digit.length() <2)
         APmac += String("0")+digit;        // Corrected capitalization error
       else
         APmac +=digit;                     // Corrected capitalization error
       //mac++;                             // Not necessary
       Serial.print("["); Serial.print(i); Serial.print("]");
       Serial.println(mac[i], HEX);
    }
    Serial.println(APmac);                  // Print the constructed String
    Serial.println(WiFi.BSSIDstr());        // Print the pre-formatted string

Consider not using the String object, which may help condense the code a bit:

    uint8_t* mac=WiFi.BSSID();
    char APmac[13];
    APmac[0]=0;
    for (int i=0; i<6;i++) {
       char buffer[3];
       sprintf(buffer, "x", mac[i]);
       strncpy((char *)(APmac+(i*2)), buffer, 3);
       Serial.print("["); Serial.print(i); Serial.print("]"); Serial.println(buffer);
    }
    Serial.println(APmac);
    Serial.println(WiFi.BSSIDstr());


message:
Reading/Writing Strings with Bluetooth Windows API

I am trying to use my HC05 so my Arduino can communicate with my Windows 10 PC. I have a program written using the Window API for Serial Communication but the problem is it looks like the Arduino/HC05 can only send or the API can only read one character at a time. It is the same with Arduino; I send an entire string with the API and the Arduino has to read/parse it character by character. I was wondering if there was a solution to this problem or if I will need to develop some sort of coding protocol (like space to separate messages) to send messages. (The other issue is that it will take an age to send long messages this way.)

Windows File Reading API
https://msdn.microsoft.com/en-us/library/windows/desktop/aa364232(v=vs.85).aspx

Here is the PC side file.

    do {
  // check for data on port and display it on screen.
  ReadFile(file, buffer, sizeof(buffer), &read, NULL);
  int i;
  sscanf(buffer, "%d", &i);
  std::cout << i << std::endl;

  if (read) {
   //WriteFile(screen, buffer, read, &written, NULL);

   //When space seen, add the string to data
   if (buffer[0] == ' ') {
    int convertedDatum = std::stoi(datum, &sz);
    if (convertedDatum < 12) {
     //WriteFile(file, "S " , 2, &written, NULL);
     //WriteFile(screen, "S", read, &written, NULL);
    }
    else {
     //WriteFile(file, "G ", 2, &written, NULL);
     //WriteFile(screen, "G", read, &written, NULL);
    }
    data.push_back(convertedDatum);
    datum = "";

Arduino-side test code

    void loop() {

 while (true) {
  String sendValue = String(100);
  sendValue.toCharArray(buf, sizeof(buf));

  Serial1.write(buf);
  Serial1.write(' ');
  delay(4000);
 }
What I am seeing on the console on the PC which is represented by the **screen** variable when I debug is when I break at the line

    std::cout << i << std::endl;
1-Continue-0-Continue-0
or on the console

    1
    0
    0
    0
    0
    0
    ...

I am pretty sure that I have seen entire strings sent at once with the Android Bluetooth API so I am not sure exactly if the same can be done with Windows or if the Windows VC++ API's are incapable.

body: Serial is only ever a character at a time. That is what serial is. If you want to impose some structure on top of that then it is up to you to define that structure.


message:
How to dynamically allocate arrays

Question given in the title. I'm trying to dynamically allocate the size of an array on runtime on an arduino pro micro. I've tried realloc, malloc and the c++ variant delete and new without success. This is my current test code:

    int* test = 0;

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

    void loop() {
      Serial.println("test");
      if(test != 0){ //c++ delete and new attempt
        delete [] test;
      }
      test = new int[2];
      //test = (int*) realloc(test, 2 * sizeof(int)); //realloc attempt
      //test = (int*) malloc(2*sizeof(int));          //malloc attempt
      test[0] = 1;
      test[1] = 2;
      int answer = test[0] + test[1];
      Serial.println(" " + answer);
      Serial.print(" " + test[0]);
      Serial.println(" " + test[1]);
      Serial.println("test");
      delay(100000000000);
    }

All of my attempts result in either some garbage in the serial or in most cases:

    test

    test

Does anyone know what I'm doing wrong?

body:
`serial.println` doesn't work that way. Or more precisely `+` with string literal and an `int` does **not** create a concatenated string. Instead it treats the string literal as a `char*` and then does pointer arithmetic on it.

      Serial.print(" ");
      Serial.println(answer);
      Serial.print(" ");
      Serial.print(test[0]);
      Serial.print(" ");
      Serial.println(test[1]);
      Serial.println("test");
      delay(100000000000);


body:
This works:

    int* test = 0;

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

    void loop() {
      Serial.println("test");
      if(test != 0){ //c++ delete and new attempt
        delete [] test;
      }
      test = new int[2];
      //test = (int*) realloc(test, 2 * sizeof(int)); //realloc attempt
      //test = (int*) malloc(2*sizeof(int));          //malloc attempt
      test[0] = 1;
      test[1] = 2;
      int answer = test[0] + test[1];
      Serial.println(answer);
      Serial.print(test[0]);
      Serial.println(test[1]);
      Serial.println("test");
      delay(100000000000);
    }

In C/C++, you can't add/concatenate Strings and int.


message:
ESP8266 not working properly

It's the first time I use an ESP8266 and I didn't manage to get a proper response in the Arduino serial monitor. I only see weird characters, when I move the 3.3V wire.

You can see the connections in the following picture:

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

The code I run is the following one:

    #include <SoftwareSerial.h>
    SoftwareSerial BT1(3, 2); // RX | TX

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

    void loop()
    {
        String B= ".";
        if (BT1.available())
        {
            char c = BT1.read();
            Serial.print(c);
        }
        if (Serial.available())
        {
            char c = Serial.read();
            BT1.print(c);
        }
    }

Maybe it's something really stupid. I am a total beginner, so I appreciate any help.

EDIT: I think power supply is 3.3V[![enter image description here][2]][2]

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

SOLUTION: the problem was the power supply. I tried exactly the same using the 3.3V from the arduino instead of the power supply and it works perfectly!

body:
You may well have killed the ESP by supplying it 5v, you have to have a logic level shifter, as Juraj says.

Assuming it's not dead then your next problem is there have been posts about that hardware setup and SoftwareSerial doesn't work at high speed. I can't tell you what it is that doesn't work because turning the speed of the link cures the problem, try 9600 maximum.

[Edited to be less accusational, which was not the original intent]

**[Update]**

Please see the datasheet here:
https://www.mikrocontroller.net/attachment/231858/0A-ESP8266_Specifications_v4.pdf

The table in section 8.4.4 says that the maximum input voltage is 3.6V
Just after that it says all digital pins are "protected from over-voltage with a snap-back circuit". This snap back voltage is typically 6V.  So does that mean the GPIO are safe up to 6V?

(It might be that this datasheet has been superseded, I am unable to access the EspressIF site at the moment).


message:
Unsigned long overflow? Or something else?

I have been looking at this for hours and can't figure it out... Take the following code I ran on an Arduino Mega:

    #define MINUTES 0
    #define SECONDS 1
    #define MILLIS  2
    #define DEFAULT_SELECTED_TURN_DELAY 0, 45, 0

    unsigned long calculate_ms(int , int , int );

    int selected_turn_delay[3] = { DEFAULT_SELECTED_TURN_DELAY };

    void setup() {
      Serial.begin(115200);
      delay(1000);
      Serial.println("Values of selected_turn_delay:");
      Serial.print("minutes: ");
      Serial.println(selected_turn_delay[MINUTES]);
      Serial.print("seconds: ");
      Serial.println(selected_turn_delay[SECONDS]);
      Serial.print("milliseconds: ");
      Serial.println(selected_turn_delay[MILLIS]);

      unsigned long result = calculate_ms(selected_turn_delay[MINUTES], selected_turn_delay[SECONDS], selected_turn_delay[MILLIS]);
      unsigned long result1 = calculate_ms(selected_turn_delay[MINUTES], selected_turn_delay[SECONDS], selected_turn_delay[MILLIS]);
      unsigned long result2 = calculate_ms(0,45,0);
      unsigned long result3 = calculate_ms(0,30,0);
      unsigned long result4 = calculate_ms(0,31,0);
      unsigned long result5 = calculate_ms(0,32,0);
      unsigned long result6 = calculate_ms(0,33,0);
      unsigned long result7 = calculate_ms(0,34,0);
    }

    void loop() {
    }

    unsigned long calculate_ms(int minutes, int seconds, int milliseconds) {
      Serial.println("------------");
      Serial.println("In calculate_ms");
      Serial.println("------------");
      unsigned long calculated_total_milliseconds = 0;
      unsigned long minute_to_seconds = 0;
      unsigned long seconds_to_ms = 0;

      Serial.println("Input:");
      Serial.print("minutes: ");
      Serial.println(minutes);
      Serial.print("seconds: ");
      Serial.println(seconds);
      Serial.print("milliseconds: ");
      Serial.println(milliseconds);

      calculated_total_milliseconds = (milliseconds + (seconds * 1000) + ((minutes * 60) * 1000));

      Serial.print("Calculates ms:");
      Serial.println(calculated_total_milliseconds);
      return(calculated_total_milliseconds);
    }

It gives me the following results:

    Values of selected_turn_delay:
    minutes: 0
    seconds: 45
    milliseconds: 0
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 45
    milliseconds: 0
    Calculates ms:4294946760
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 45
    milliseconds: 0
    Calculates ms:4294946760
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 45
    milliseconds: 0
    Calculates ms:4294946760
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 30
    milliseconds: 0
    Calculates ms:30000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 31
    milliseconds: 0
    Calculates ms:31000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 32
    milliseconds: 0
    Calculates ms:32000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 33
    milliseconds: 0
    Calculates ms:4294934760
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 34
    milliseconds: 0
    Calculates ms:4294935760

What am I missing why is the calculation for values above 32s out of wack ?

Tried the same code adapted for gcc:

    #include <stdio.h>

    #define MINUTES 0
    #define SECONDS 1
    #define MILLIS  2
    #define DEFAULT_SELECTED_TURN_DELAY 0, 45, 0

    unsigned long calculate_ms(int , int , int );

    int selected_turn_delay[3] = { DEFAULT_SELECTED_TURN_DELAY };

    int main(void) {
      printf("Values of selected_turn_delay:\n");
      printf("minutes: ");
      printf("%d\n",selected_turn_delay[MINUTES]);
      printf("seconds: ");
      printf("%d\n",selected_turn_delay[SECONDS]);
      printf("milliseconds: ");
      printf("%d\n",selected_turn_delay[MILLIS]);

      unsigned long result = calculate_ms(selected_turn_delay[MINUTES], selected_turn_delay[SECONDS], selected_turn_delay[MILLIS]);
      unsigned long result1 = calculate_ms(selected_turn_delay[MINUTES], selected_turn_delay[SECONDS], selected_turn_delay[MILLIS]);
      unsigned long result2 = calculate_ms(0,45,0);
      unsigned long result3 = calculate_ms(0,30,0);
      unsigned long result4 = calculate_ms(0,31,0);
      unsigned long result5 = calculate_ms(0,32,0);
      unsigned long result6 = calculate_ms(0,33,0);
      unsigned long result7 = calculate_ms(0,34,0);
    }

    unsigned long calculate_ms(int minutes, int seconds, int milliseconds) {
      printf("------------\n");
      printf("In calculate_ms\n");
      printf("------------\n");
      unsigned long calculated_total_milliseconds = 0;
      unsigned long minute_to_seconds = 0;
      unsigned long seconds_to_ms = 0;

      printf("Input:\n");
      printf("minutes: ");
      printf("%d\n",minutes);
      printf("seconds: ");
      printf("%d\n",seconds);
      printf("milliseconds: ");
      printf("%d\n",milliseconds);

      calculated_total_milliseconds = (milliseconds + (seconds * 1000) + ((minutes * 60) * 1000));

      printf("Calculates ms:");
      printf("%lu\n",calculated_total_milliseconds);
      return(calculated_total_milliseconds);
    }

And it works great:

    Values of selected_turn_delay:
    minutes: 0
    seconds: 45
    milliseconds: 0
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 45
    milliseconds: 0
    Calculates ms:45000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 45
    milliseconds: 0
    Calculates ms:45000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 45
    milliseconds: 0
    Calculates ms:45000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 30
    milliseconds: 0
    Calculates ms:30000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 31
    milliseconds: 0
    Calculates ms:31000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 32
    milliseconds: 0
    Calculates ms:32000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 33
    milliseconds: 0
    Calculates ms:33000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 34
    milliseconds: 0
    Calculates ms:34000

It has to be something obvious, but I can't find it...

body:
Ok well, 'before bed illumination'...

Changing:

    calculated_total_milliseconds = (milliseconds + (seconds * 1000) + ((minutes * 60) * 1000));

for

    calculated_total_milliseconds = (milliseconds + (seconds * 1000UL) + ((minutes * 60) * 1000UL));

Make it work:

    Values of selected_turn_delay:
    minutes: 0
    seconds: 45
    milliseconds: 0
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 45
    milliseconds: 0
    Calculates ms:45000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 45
    milliseconds: 0
    Calculates ms:45000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 45
    milliseconds: 0
    Calculates ms:45000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 30
    milliseconds: 0
    Calculates ms:30000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 31
    milliseconds: 0
    Calculates ms:31000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 32
    milliseconds: 0
    Calculates ms:32000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 33
    milliseconds: 0
    Calculates ms:33000
    ------------
    In calculate_ms
    ------------
    Input:
    minutes: 0
    seconds: 34
    milliseconds: 0
    Calculates ms:34000


message:
using UART bridge module to have serial communication through usb port of arduino nano

This can be a silly question but I'm having a trouble with serial communication between arduino nano with other serial device. Please help me to handle it.

I'm currently doing a RF communication project using arduino nano and radio telemetry which is using serial communication. I tried to use SoftwareSerial but unfortunately, every pin is being used on arduino nano to control other extra devices. So I decided to have serial communication via usb port of arduino nano

Firstly, I directly connected rx and tx wire of RF device with D- and D+ of B type mini USB. but it did not work

Secondly, I tried to connect rx and tx wire with arduino nano via UART to USB bridge, cp2102 module. I soldered a female USB - male mini USB wire for this connection. but It did not work. the wiring that I build seems like the picture below. [![connection reference picture][1]][1]

Did I miss something? It doesn't work theoretically anyway?

Please help

Thank you in advance

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

body:
This is not possible - USB is not an ambidextrous protocol, rather there are distinct Host and Device roles, and while a few chips can switch-hit between them, the USB interface chips commonly used on Nano-style boards are strictly device only, and therefore cannot communicate with another USB device such as a USB-serial adapter.  There may well even be a duplicate here somewhere of a similar question having been asked before.

What you should probably do is just use the ATmega UART that interfaces to the USB chip, to talk to your external device directly (or through level translation and possibly inversion if it requires that).  The transmit side is no problem, however you will need to give some though to the receive side, as only one thing (the USB chip, or your external device) can drive that ATmega pin at a time.  Many of the official Arduino designs have a resistor there, which lets an external driver dominate over the on-board USB serial chip, but your board may or may not have that - if not, you may need to modify it.

And of course such a scheme requires that you disconnect the external device when uploading a new sketch via bootloader.

Another option would be instead of a traditional USB-serial converter, to use some sort of embedded USB host and have that convert to serial - the Kinetis KL25Z chip does this well, as does its close cousin on the Teensy-LC.  But at that point, you might as well just replace the Arduino Nano with a better chip having more pins, or even the ATmega328PB which has a second hardware UART.


message:
Arduino - fuse setting problem on ATmega328P-PU

I am trying to do fuse setting on ATmega328P-PU chips using an [avr programmer][1].

I was successfully able to do fuse setting on 3 ATmega328P-PU chips (which I bought from one of the sites - I forgot). So I bought three more [from Amazon][2].

When I execute `avrdude -c usbasp -p m328p` on the previous 3 chips, I got this response, and was able to do fuse setting.

>avrdude: warning: cannot set sck period. please check for usbasp firmware update.
avrdude: AVR device initialized and ready to accept instructions

>Reading | ################################################## | 100% 0.00s

>avrdude: Device signature = 0x1e950f (probably m328p)

>avrdude: safemode: Fuses OK (E:FF, H:D9, L:E2)

>avrdude done.  Thank you.

But when I execute the same command on the 3 chips I recently bought, I am getting this.

    avrdude -c usbasp -p m328p

    avrdude: warning: cannot set sck period. please check for usbasp firmware update.
    avrdude: error: program enable: target doesn't answer. 1
    avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

    avrdude done.  Thank you.

I triple-checked the wiring and soldering area. They all look fine.

Is this because the 3 chips I recently bought have a bootloader?

The description for the chip that works is here.

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

  [1]: https://www.amazon.com/gp/product/B071P2LCC9/ref=oh_aui_detailpage_o00_s00?ie=UTF8&psc=1
  [2]: https://www.amazon.com/gp/product/B018ZR3F7O/ref=oh_aui_detailpage_o04_s01?ie=UTF8&psc=1
  [3]: https://i.stack.imgur.com/nqalo.png

body:
The chips configured with a bootloader would also have the fuses set for an external clock (the factory default is the on-chip oscillator). Without an external clock they won't work.

I have a [sketch that uploads files](http://www.gammon.com.au/uploader) that also can provide an external clock for this eventuality.

As mentioned on that page an 8 MHz clock is provided on pin D8 of the programming board, so you can connect to D8 on the Uno which you are running the sketch on to pin 9 on the actual Atmega328P chip.

Alternatively find a 16 MHz crystal or resonator and connect that between pins 9 and 10 of your Atmega328P which will provide the clock that it is expecting. If you use a crystal you should also run 22 pF capacitors between each leg and ground, like in this image:

[![Atmega328 with crystal][1]][1]

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


message:
Use Arduino Uno digital pins instead of ESP8266

I would like to know if this is possible.

I am using an ESP8266-ESP01, which only has 2 digital pins. I have a project that needs 3 digital pins so I have planned to use my Arduino, so I can use more digital pins. My plan is instead of plugging the sensor in the GPIO1 of the ESP8266, I could somehow plug it in the Arduino digital pins and the data would just be transferred to the ESP8266 and be uploaded to an online cloud.

I can read the sensor data in the Arduino but I don't know how to transfer the data to the ESP8266 so the wifi module would just receive it and send it to the online cloud.

If anyone can help me to get some idea specifically on sending the data from Arduino to the ESP and receiving the data from the Arduino.

Thank you.

body:
Use the ESP's two digital pins to talk to the Arduino using SoftwareSerial. Be careful however: your Arduino (possibly, probably) runs on 5V, the ESP on 3.3V. I have an Arduino clone that can be switched between 3.3V and 5V, which makes things easier.

After that all you need is to send the sensor readings to the ESP via SoftwareSerial.


body:
DDA's answer is perfectly correct.
Like he says you need to check the voltage and use a logic level shifter.

However looking at it from another angle there are a whole range of ESP that have an increasing number of digital pins.  You could look at using an ESP-5, or an ESP-12E, these have different forms and increasing number of digital pins.

You could also look at the Wemos range, I believe there is an UNO form board and there is the Wemos D1-Mini, which has 10 digital and 1 analog.

Running on two boards is usually more of an issue than running on one board, god help you if you have synchronisation issues!


body:
> I could somehow plug it in the Arduino digital pins and the data would just be transferred to the ESP8266

Easy:

1. Program the Arduino as a master (I2C, or UART + interrupt) and the ESP as a slave. Connect the sensors to it. Once the data is read on the Arduino, it is sent to the ESP.

2. Put an I2C IO expander IC on the ESP and you don't have to deal with the Arduino at all.


message:
Arduino for kids toy with Battery (safe), Can Arduino overheat the Battery with long running code

I am making a learning toy which kids can play with and learn basics of programming. But i am tired of keep replacing the AA batteries as they run out in few days. So i am thinking of using rechargeable battery. But i am very worried to use it considering it is kids toy and people says lipo and li ion battery can explode. There are dangers or over charge and heat etc.

**Is it safe to use them? Which one to use?**

I am using **Arduino pro mini** 3.3v and some times 5v.

I was planning to use: [XCSOURCE 5 pcs 1A 5V Micro USB TP4056 Lithium Battery Power Charger Board Module TE420][1]

I think some users have misunderstood the question and have voted this question to be closed. This questions is very much to deal with programming also apologies if i have not made it clear.

 - We can get the battery level in the code, but is there any way in code we can some how turn off the charging when the battery has been fully charged.

 - I am under impression (might be wrong, you can correct me), normal
   battery single AA cell dies after some time on heavy use (using dc motor etc). But
   rechargeable batteries are bigger with multiple cells in it they will
   last longer. So if i am running some code in a loop for long time
   will the battery get over heated will it be a problem.

  [1]: https://www.amazon.co.uk/XCSOURCE-Lithium-Battery-Charger-TE420/dp/B01DRT4PWY/ref=sr_1_1?s=electronics&ie=UTF8&qid=1505294735&sr=1-1&keywords=XCSOURCE 5 pcs 1A 5V Micro USB TP4056 Lithium Battery Power Charger Board Module TE420

body:
Probably the easiest/cheapest and safest option is to buy a original USB Power Bank and there you have it. Power banks for cellphones/tablets have overvoltage/overcharge/undercharge protection on them and they are also completely sealed, so it should be perfectly safe to handle one of those to your kids (Of couse not some cheap chinese crap).

They can then charge the power bank over USB on any PC or Wall charger and then use it for hours/days.

If I'm allowed to give you a tip, you could eventually pick one of these [here][1], they are pretty good in my opinion.
[![TP-Link Power Bank][2]][2]
Of course there are a ton of others around, so you can just pick one which fit your needs.

On your case you just cut a USB cable and plug the ends on the Pro Mini. If a short is detected, Power banks often just shut off and only turn on when they are charged again (You might try this first). If you use a 3.3V Pro Mini, just put a voltage limiter between it. You might also write "3.3V" on the voltage limitor and "3.3V" on the 3.3V version of the Arduino and teach your kids that if the Arduino has "3.3V" written on it, they should put that "3.3V" voltage limitor before it (or just not use 3.3V variants for ease of use).

  [1]: https://www.google.com.br/search?q=TP Link 10400mah Power Bank
  [2]: https://i.stack.imgur.com/qX7o8.jpg


message:
ESP8266 as ISP program for ATMega16

I have used below program for ESP8266 as ISP to upload a program to an ATmega16.

**ISP program uploaded in ESP8266**

    #include <SPI.h>
    #include <ESP8266WiFi.h>
    #include <ESP8266mDNS.h>
    #include <ESP8266AVRISP.h>

    const uint8_t reset_pin = 5;
    const uint16_t port = 328;

    ESP8266AVRISP avrprog(port, reset_pin);

    void setup() {
        Serial.begin(9600);//115200
        Serial.println("");
        Serial.println("Arduino AVR-ISP over TCP");
        avrprog.setReset(false); // let the AVR run

        // listen for avrdudes
        avrprog.begin();
    }

    void loop() {
        static AVRISPState_t last_state = AVRISP_STATE_IDLE;
        AVRISPState_t new_state = avrprog.update();
        if (last_state != new_state) {
            switch (new_state) {
                case AVRISP_STATE_IDLE: {
                    Serial.printf("[AVRISP] now idle\r\n");
                    Serial.println("idle...");
                    // Use the SPI bus for other purposes
                    break;
                }
                case AVRISP_STATE_PENDING: {
                    Serial.printf("[AVRISP] connection pending\r\n");
                    Serial.println("pending...");
                    // Clean up your other purposes and prepare for programming mode
                    break;
                }
                case AVRISP_STATE_ACTIVE: {
                    Serial.printf("[AVRISP] programming mode\r\n");
                    Serial.println("Active...");
                    // Stand by for completion
                    break;
                }
            }
            last_state = new_state;
        }else{
          Serial.println("newstate not equal to old");
        }
        // Serve the client
        if (last_state != AVRISP_STATE_IDLE) {
            avrprog.serve();
            Serial.println("serve..");
        }
    }

Then I have changed the board to ATmega16 and used programmer as `AVR ISP` and fetched/written below simple blink program to upload in ATmega16.

    void setup() {
      // initialize digital pin 13 as an output.
      pinMode(1, OUTPUT);
    }

    // the loop function runs over and over again forever
    void loop() {
      digitalWrite(1, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);              // wait for a second
      Serial.println("light on");
      digitalWrite(1, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);              // wait for a second
      Serial.println("light off...");
    }

Tried uploading blink program to ATmega16 using ESP8266 as ISP by **Sketch =>Upload Using Programmer**. This resulted to compilation followed by uploading status in Arduino IDE for longer period. I didn't get any response after 10 mins of time. Then i have tried opening Serial Monitor which shows `newstate not equal to old`.

I am not sure what went wrong in my coding? How can I debug this issue ?

body:
### 1. Uploading the sketch to your ESP8266
- Tools > Board > select the appropriate ESP8266 board
- File > Examples > ESP8266AVRISP > Arduino_Wifi_AVRISP
- Change lines 7 and 8 to match the SSID and password of your WiFi router
- Sketch > Upload
- After the upload completes unplug the ESP8266 from your computer.

### 2. Generating the .hex file and the upload command
- Open the sketch you want to upload to your ATmega16
- Tools > Board > ATmega16
- File > Preferences > Show verbose output during: > upload (check)
- Sketch > Upload
- The sketch will compile and then the upload will fail. This is the expected behavior. The goal of this process is to generate the .hex file that will be uploaded and the correct upload command.
- Scroll the black console window at the bottom of the Arduino IDE window up until you see a line that looks something like:

>

    E:\Arduino\hardware\tools\avr/bin/avrdude -CE:\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM54 -b115200 -D -Uflash:w:C:\Users\per\AppData\Local\Temp\arduino_build_288143/Blink.ino.hex:i

### 3. Connecting the ESP8266 to the ATmega16
Connect the ESP8266 to your ATmega16 board as follows:

    +----------+-----------+
    | ESP8266  | ATmega16  |
    +----------+-----------+
    | GPIO12   | MISO      |
    | GPIO13   | MOSI      |
    | GPIO14   | SCK       |
    | GPIO5    | RESET     |
    +----------+-----------+

You also need to power the ATmega16. It is recommended to use 3.3 V since this is what the ESP8266 is running at. Make sure the ground of the ESP8266 is connected to the ground of the ATmega16.

### 4. Starting the ESP8266AVRISP
- Plug the ESP8266's USB cable back in to your computer
- Tools > Serial Monitor
- Select 115200 from the baud rate menu in the bottom right corner of Serial Monitor
- You should see something like

>IP address: 192.168.0.100
Use your avrdude: avrdude -c arduino -p <device> -P net:192.168.0.100:3000 -t # or -U ...

### 5. Uploading via ESP8266AVRISP

- The second line you saw in the Serial Monitor in step 4 is the sketch's attempt to give you the AVRDUDE command you need to run to upload to your ATmega16 via the ESP8266AVRISP. Unfortunately they got a bit vague at the end. Apparently they are trying to steer you towards using AVRDUDE in [terminal mode](http://www.nongnu.org/avrdude/user-manual/avrdude_7.html) via the `-t` option but also mentioning that `-U` might be preferred. I recommend the latter since the Arduino IDE has helpfully generated the `-U` command for you already.
- Since you need to run a custom AVRDUDE command to upload to your ATmega16 over the network you will not be able to do the upload via the Arduino IDE. Start the command line on your computer.
- Now you need to merge the upload command you generated when you did the intentionally failed upload to the ATmega16 in step 2 with the command that was printed to Serial Monitor in step 4. In my examples, this merged command would be:

>

    E:\Arduino\hardware\tools\avr/bin/avrdude -CE:\Arduino\hardware\tools\avr/etc/avrdude.conf -v -c arduino -p atmega16 -P net:192.168.0.100:3000 -Uflash:w:C:\Users\per\AppData\Local\Temp\arduino_build_288143/Blink.ino.hex:i

- Your command will be similar to mine but the path to avrdude, avrdude.conf, the IP address, port, and path to the .hex file will be different. Enter your merged AVRDUDE command at the command line.
- The upload should now proceed successfully.

### Comments
The above is quite a complex process. Although it will be significantly easier with subsequent uploads, it will likely still not be as easy as an upload via the Arduino IDE. I would not recommend regularly using the ESP8266 as an AVR ISP simply because it's what you have on hand. Instead I would strongly recommend you to just buy a cheap (~$3 USD with free shipping from China) 6 pin USBasp from eBay.

The primary benefit of using the ESP8266 for this application is that it can be done over the WiFi network rather than the traditional USB connection but it's questionable how often that will truly be useful.


message:
Rotate Robot head according to Sound level

I'm currently working on a robot using an Arduino and I'd like to control robot's head like this:

Imagine that it is on your desk and it can turn it's head through a range of 150 degrees like a human can do. So if I tap the desk in the the middle position, relative to his head rotation (in front of the robot), it should rotate his head by 75 degrees if he was looking at the left or right.

Likewise, I want to locate the desk tap or another sound source and make his head turn to that direction.

So in order to do that I have a solution, but I'm not confident enough to use it because I don't know whether is will give accurate results. This is what I thought:

I'll place two sound modules on the left and right sides of the robot. When a sound comes, I'll measure which microphone detects the higher sound level, and calculate an approximate angle to rotate the robot's head accordingly.

However, since I'm a newbie to Arduino, I've no real sense of whether that will work as I intend. Do people think this is a good method? If not, how can I improve it?

Also if you can, please suggest some good, Arduino compatible sound modules for this project. Thank you.

body:
A couple of years ago, I completed a MOOC on FUN called [Binaural Hearing for Robots][1] (it doesn't seem to have run since, but it may be worth keeping an eye on it to see if they open registration again. At least some of the resources seem to be archived [here][2]). Interestingly, localising sound turns out to be easier with three microphones than with two.

You scan the three inputs in sequence, and when the sound is directed to record the time-difference between the three sensors. The technique you're looking at to localise the source is called [trilateration][3].

Once you have a direction relative to the robot head, you can use a simple servo to turn the robot head to that direction.

I did play around with this a little bit, using three KY-038 microphone modules like this that I picked up cheap on eBay:

![microphone][4]

Connect them to your Arduino something like this:

![sound-localisation][5]

<hr>

I can't find my code (it was pretty untidy anyway since I was just playing around while I was working on the course), but a lot of Arduino sound-localisation projects have been published online with examples easy to find on [Instructables][6], [Hackaday][7], and many [other sites][8].

  [1]: https://www.fun-mooc.fr/courses/inria/41004/session01/about
  [2]: https://www.canal-u.tv/producteurs/inria/cours_en_ligne/binaural_hearing_for_robots
  [3]: https://en.wikipedia.org/wiki/Trilateration
  [4]: https://i.stack.imgur.com/RSM2f.jpg
  [5]: https://i.stack.imgur.com/TRrya.png
  [6]: http://www.instructables.com/id/Sound-Locator/
  [7]: https://hackaday.com/2011/05/23/sound-localization-and-a-treaded-rover/
  [8]: http://ruralhacker.blogspot.co.uk/p/micloc.html


message:
Alternate between 2 relays with one button

I have a very basic programming knowledge, but the thing I want to achieve is to alternate between switching 2 relays with a button or a RPi input pulse.

So something like this:

1. Press the button
2. Switch relay 1 on and off (1 second delay)
3. Press the button
4. Switch relay 2 on and off
5. Press the button
6. Switch relay 1 on and off (1 second delay)
7. Press the button
8. Switch relay 2 on and off
9. Press the button
10. Switch relay 1 on and off (1 second delay)
11. Press the button
12. Switch relay 2 on and off
13. etc.

Here's my code, I thought if I'd just put the second relay after the first `else` everything would work. But I'm missing some basic knowledge to figure this out.

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

    const int ledPin = 2;
    const int ledPinA = 3;

    void setup() {
      pinMode(ledPin, OUTPUT);
      pinMode(ledPinA, OUTPUT);
      Serial.begin(9600);
    }

    void loop() {
      int sensorValue = analogRead(A0);
      Serial.println(sensorValue);
      delay(1);
      if (sensorValue > 500) {
        digitalWrite(ledPin, HIGH);
      } else {
        digitalWrite(ledPin, LOW);
      }
      if (sensorValue > 500) {
        digitalWrite(ledPinA, HIGH);
      } else {
        digitalWrite(ledPinA, LOW);
      }
    }

I'm thinking I should use `while`.

body:
The way you have it, both `if` blocks will be evaluated each time you call to `loop()`. Instead, you need to create a variable that remains "alive" in between each call to `loop()` to keep track of which relay you want to activate:

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

    const int ledPin = 2;
    const int ledPinA = 3;
    int active_relay = 2;   // State variable for current relay pin

    void setup() {
        pinMode(ledPin, OUTPUT);
        pinMode(ledPinA, OUTPUT);
        Serial.begin(9600);
    }

    void loop() {
          int sensorValue = analogRead(A0);

          Serial.println(sensorValue);

          delay(1);    // This delays for 1ms, not 1s ??

          if (sensorValue > 500) {   // Pulse received
              digitalWrite(active_relay, HIGH);  // Relay on
              delay(1000);                       // Wait 1 second
              digitalWrite(active_relay, LOW);   // Relay off

              // Update variable for next call to loop
              if (active_relay == ledPin) {
                  active_relay = ledPinA;      // Swap
              }
              else {
                  active_relay = ledPin;       // Swap
              }
          }
          // Remove 2nd if block
    }


body:
> So something like this:

easy:

1. increment a counter based on button presses;

2. run a state machine on that counter to decide on relay actions.

the state machine can be a simple switch / case statement.