body:
It all started when I tried connecting an hm10-nano to a relay board which is Bluetooth enabled.  Here is my nano with the hm10 module:

[![nano-hm10][1]][1]

And here is the relay board's BT module, which looks like an hm12:

[![relay'sBT][2]][2]

I started by connecting the nano-hm10 to my mac and using the Arduino IDE to send the module commands.  The hm12 has a mac for ble and another for edr:

ble:00-0e-0b-00-75-12
edr:00-0e-0e-00-75-12

The hm10 does connect because:

1. I get a steady blue led on the hm10 after AT+COmacble
2. I get the macble from the hm10 module after AT+RADD?
3. I hear the relay (channel1) open on the relay board after AT+COmacble

When I try the following steps -> I get these results
1. Unplug relay board -> hm10 blue blinking
2. Plug relay board -> hm10 blue steady, relay BT module blue led steady
3. AT commands to hm10 thru serial monitor stop working (expected)
4. AT+CO000e0e007512 to hm10 -> turns on relay 1 for some reason
5. Unplug relay -> RADD on hm10 = 00-0e-0b-00-75-12 instead of 00-0e-0e-00-75-12

My questions are:
A. Is it possible to send data from an hm10 to hm12?
B. Why does the relay get activated when I connect to the hm12-relay board?
C. I just realized my sketch's bluetooth.print() sends a command from the nano to the hm10, not to from the hm10 to the hm12.  How can I send the data from the nano to the hm12?

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

    #include <SoftwareSerial.h>
    int bluetoothTx = 10;  // TX-O pin of bluetooth
    int bluetoothRx = 11;  // RX-I pin of bluetooth
    SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
    void setup(){
      Serial.begin(9600);  // Begin the serial monitor at 9600bps
      delay(200);
      bluetooth.begin(9600);  // Start bluetooth serial at 9600
      Serial.print("send...");
      bluetooth.print("AT");
        bluetooth.print("110"); //open relay 1
        delay(2000);
      bluetooth.print("100"); //close relay 1
    }
    void loop(){
      if(bluetooth.available()){
        Serial.print((char)bluetooth.read());
      }
      if(Serial.available()){
        bluetooth.print((char)Serial.read());
      }
    }

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

title: Sending data from Arduino w/HM10 to relay board with hm12

Answers: 0


body:
I am new in PIC programming

my question is, how can i communicate arduino UNO with  PIC18f4550. i am using [THIS](http://g01.a.alicdn.com/kf/HTB11cl0KXXXXXb.XVXXq6xXFXXXZ/-font-b-PIC-b-font-font-b-Development-b-font-font-b-Board-b-font.jpg) programmer board for PIC controller and it has a builtin RS232 serial interface.

Can any body tell me how to communicate between them. I want to communicate in such a way that only Rx & Tx pins and the power pins of arduino will be used.

title: How to serially communicate arduino uno to PIC18f4550?

Answers: 1

body:
yeah you can quite easily do the Serial communication between Arduino and PIC Microcontroller. You need to connect the below pins:

 - Arduino TX will be connected to PIC RX.
 - Arduino RX will be connected to PIC TX.
 - GND of Arduino must be connected to GND of PIC.

Next thing you need to remember is to have same baud rate for both Arduino and PIC. Now you should check these two posts:

 - [Arduino Serial Communication][1].
 - [PIC Serial Communication][2]

First one is explaining the Serial Communication of Arduino while the second one is Serial Communication of PIC Microcontroller. You should also read [What is Serial Port?][3] to get more idea about Serial communication.

I hope they will help you out. If you still got into some issues then let me know.

  [1]: https://www.arduino.cc/en/Reference/Serial
  [2]: http://learn.mikroe.com/ebooks/picmicrocontrollersprogramminginassembly/chapter/serial-communication-modules/
  [3]: http://www.theengineeringprojects.com/2015/06/serial-port.html


body:
I recently bought an Arduino Nano ( a clone actually), I installed the CH340G drivers for it and got it working perfectly fine... Played around with it for a while and then kept it aside...

Now after sometime I get time to play with it again, I was actually trying to power it with my 11.1V 2200mAh 8C LiPo battery. So I plug the JST connector to the Vin and GND pin and the LED doesn't light up. I noticed that I had plugged it in the wrong way and I immediately unplugged it. Next I make another attempt and this time I plugged the pins entirely somewhere else, again I disconnect quickly. The third time I connect it properly and the power LED lights up (phew...)

Now I move on to my computer to program it but the Arduino IDE is stuck at uploading. It was working fine before, when I hit upload, the RX LED glows *VERY* dimly and the board just stays like that. Only the power LED glows up, not even the LED on pin 13 glows up.
Uploading to a UNO works perfectly fine.

This is the error I get after a while-
>avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x7d

Did I burn my board? Or is it just a bootloader issue?

title: Arduino Nano stuck on uploading

Answers: 1

body:
> So I plug the JST connector to the Vin and GND pin and the LED doesn't light up. I noticed that I had plugged it in the wrong way and I immediately unplugged it. Next I make another attempt and this time I plugged the pins entirely somewhere else, again I disconnect quickly. The third time I connect it properly and the power LED lights up (phew...)

Unfortunately Vin on an [Arduino Nano][1] does not have a reverse polarity protection diode such as the [Arduino Uno PWRin][2]

> Did I burn my board?

Very probable. For more details please see "[10 Ways to Destroy an Arduino][3]".

Cheers!

  [1]: https://www.arduino.cc/en/uploads/Main/ArduinoNano30Schematic.pdf
  [2]: https://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf
  [3]: http://www.rugged-circuits.com/10-ways-to-destroy-an-arduino/


body:
I'm using arduino Ethernet shield 2 form arduino.org and the arduino IDE 1.7.10 also from arduino.org
the code is :

    #include <Dhcp.h>
    #include <Dns.h>
    #include <Ethernet2.h>
    #include <EthernetClient.h>
    #include <EthernetServer.h>
    #include <EthernetUdp2.h>
    #include <Twitter.h>
    #include <util.h>

    #include<SPI.h>

    EthernetUdp2 udp;
    void setup() {
      // put your setup code here, to run once:

    }

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

    }

and it is giving the following Error :

    Arduino: 1.7.10 (Windows 8.1), Board: "Arduino Uno"

    UDPMessages002.ino:14:1: error: 'EthernetUdp2' does not name a type

    Error compiling.

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

after Enabling Show verbose output I got :

    Arduino: 1.7.10 (Windows 8.1), Board: "Arduino Uno"

    Build options changed, rebuilding all

    Using library Ethernet2 in folder: C:\Program Files\ArduinoOrg\libraries\Ethernet2

    Using library SPI in folder: C:\Program Files\ArduinoOrg\hardware\arduino\avr\libraries\SPI

    C:\Program Files\ArduinoOrg/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -IC:\Program Files\ArduinoOrg\hardware\arduino\avr\cores\arduino -IC:\Program Files\ArduinoOrg\hardware\arduino\avr\variants\standard -IC:\Program Files\ArduinoOrg\libraries\Ethernet2\src -IC:\Program Files\ArduinoOrg\hardware\arduino\avr\libraries\SPI C:\Users\friend\AppData\Local\Temp\build8617491196975133384.tmp\UDPMessages002.cpp -o C:\Users\friend\AppData\Local\Temp\build8617491196975133384.tmp\UDPMessages002.cpp.o

    UDPMessages002.ino:14:1: error: 'EthernetUdp2' does not name a type

    Error compiling.

any Help please

These libraries came with the IDE and were not added by me and all the includes
were added automatically after using Sketch --> Import Library --> Ethernet2

title: EthernetUdp2 does not name a type

Answers: 2

body:
The error you see, `'EthernetUdp2' does not name a type`, means exactly that - there is no type `EthernetUdp2` defined.

If you look at the source of [EthernetUdp2.h](https://github.com/adafruit/Ethernet2/blob/master/src/EthernetUdp2.h), you'll see that the class declaration is `EthernetUDP`. See:

    class EthernetUDP : public UDP {
        private:
            // Private members...
        public:
            EthernetUDP();  // Constructor

          // Public members...

    };

`class EthernetUDP : public UDP` defines a class called `EthernetUDP` that inherets from the base class `UDP`. The constructor is what gets called when you instantiate a new object of type `EthernetUDP`.

Replace the line `EthernetUdp2 udp;` in your code with `EthernetUDP udp;` and it should work because the types will match. For reference:

    #include <Dhcp.h>
    #include <Dns.h>
    #include <Ethernet2.h>
    #include <EthernetClient.h>
    #include <EthernetServer.h>
    #include <EthernetUdp2.h>
    #include <Twitter.h>
    #include <util.h>

    #include<SPI.h>

    EthernetUDP udp; // <---- This works

    void setup() {
      // put your setup code here, to run once:

    }

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

    }

body:
As it was answered above by Cheirbriados, the library is `EthernetUdp.h` not `EthernetUdp2.h`. I'll post you an example code, but you can also analyze it by yourself, by going on tab Examples of the Arduino IDE and choosing Ethernet -> UDPSendReceiveString:

    #include <SPI.h>         // needed for Arduino versions later than 0018
    #include <Ethernet.h>
    #include <EthernetUdp.h>         // UDP library from: bjoern@cs.stanford.edu 12/30/2008

    // Enter a MAC address and IP address for your controller below.
    // The IP address will be dependent on your local network:
    byte mac[] = {
      0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
    };
    IPAddress ip(192, 168, 1, 177);

    unsigned int localPort = 8888;      // local port to listen on

    // buffers for receiving and sending data
    char packetBuffer[UDP_TX_PACKET_MAX_SIZE];  //buffer to hold incoming packet,
    char  ReplyBuffer[] = "acknowledged";       // a string to send back

    // An EthernetUDP instance to let us send and receive packets over UDP
    EthernetUDP Udp;


body:
I know this question is not so releavant as it does not include any research, but I am in search of a barcode scanner that i can easily interface with arduino and get output from it but unfortunately the Scanner models which are listed from the people doing the same stuff are not easily available in India. So if anyone knows which barcode scanner would best suit the requirement please suggest.
Availabilty in **Indian** market would be much appreciated :)

title: Which Barcode Scanner to be used with arduino in India

Answers: 1

body:
Most barcode scanners behave just like a regular keyboard.

Try getting one with a PS2 port. You can pretty easily interface a PS2 keyboard to an Arduino. There are already libraries for it.


body:
avrdude:

> no programmer has been specified on the command line or the config
> file
>          Specify a programmer using the -c option and try again

title: Uploading a sketch causing an error message in Arduino Uno

Answers: 2

body:
On the "Tools" menu choose "Programmer:" and specify AVRISP mkII; be sure that you've also chosen the appropriate "Board:" entry for the Uno.
[![enter image description here][1]][1]

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

body: I fixed it. I just reinstalled the drivers.


body:
I am using an Arduino Mega 2560 board. I have tried connecting a 115 Ω resistor from 5V to Reset, and 10 µf capacitor form reset to GND (to disable autoreset), and the variables still seem to reset themselves when I unplug and replug-in the Arduino. Any way to stop this from happening?

Basically I am making a device that is sensitive to time, and must run for about 2 months, but if it is unplugged, it can't lose its place in time and reset the whole program.

I think one alternative would be for me to have it actually write how long it has been running into a `.txt` file on the microSD card and then verify that in the start-up...

Any ideas?

title: Is there any way I can stop the Arduino Mega 2560 from resetting all variables after losing and reconnecting power?

Answers: 4

body:
Arduino Mega board has RESET-EN "jumper". If you cut the trace, it won't reset MCU by DTR from USB-to-Serial chip. If you have to upload new sketch, you'll have to short it by piece of metal.

There is also possibility to use `.noinit` section for storing variables, so if you don't loose power, it won't get overwritten by automatic init. However, bootloader could be messing with that memory too. So it might not help without erasing this bootloader and using ISP(SPI) interface to program it.

Or you can use for example RTC (if you already have one) and it's battery backed RAM.

body: Save the variables you need to EEPROM.

body:
If you can't give the MCU enough warning of a power-down to save its critical variables, you'll have to keep it alive with batteries, sleeping if necessary, until the power comes back.

Tying Reset high won't help. The chip resets at power-up - that's built in. In fact, a power-up reset and a grounded-Reset-pin reset behave a bit differently - see the datasheet. Even if it didn't reset on power-up, the RAM needs power to maintain its contents, so it loses them when it drops.

body: Take power from UPS (uninterruptable power supply).


body:
Here is the image of Ethernet shield near RJ45 socket:

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

These small boxes are probably SMD capacitors which may mean, that internal board is glavanically disconnected from the UTP line.

Is this true?

If this is true, then what will happen, if I pass `5V` `DC` current just into my UTP? Won't I be able to wire appropriate conductors just into Arduino power input? Won't I be able to power Arduino this way?

The question is about not using premade PoE splitter. I have an injector, which injects `5V` into line.

**UPDATE**

I found my injector put power to lines 4,5 and GND to 7,8. Can I take this power on Arduino side?

  [1]: https://i.stack.imgur.com/hxDeR.jpg
  [2]: https://i.stack.imgur.com/kbvMx.png

title: What if I just connect 5V DC to my UTP?

Answers: 1

body:
Not exactly. That RJ45 connector labeled HR911105A is internally connected like this:
[![scheme][1]][1]

It's possible with PoE version (but I suppose not with 5V but more like 12V or so)

Or there are variants without PoE module connected but with support, that should be possible to use 5V if you wire it correctly)

Or you can use external PoE injector and extractor: [![injector/extractor][2]][2]

For 100Mb networks are two unused communication pairs used as power lines:
[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/NQHXn.gif
  [2]: https://i.stack.imgur.com/JggQK.jpg
  [3]: https://i.stack.imgur.com/dbGJg.png


body:
I have 2 LED strips with 6 LEDs on each. They use a 12V power supply.

 My question, how can I use them like regular LEDs using Arduino UNO? Without any MOSFETS or transistors if possible.

And can I use PWM?

title: Controlling 12v DC LED strips using Arduino UNO

Answers: 1

body:
It's not safe for the MCU without transistors or so.

You can use some kind of LED driver (for example TLC5940 with on chip PWM) or ULN2003 as 8 channel low side switch (instead of 8 transistors, PWM is possible if you do it programmatically) or many others.

With single transistor it looks like:
[![enter image description here][1]][1]

Where R_1 can be about 1K and transistor can be any NPN that could handle led current.

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


body:
I'm doing a device to recongnize NFC cards with an Arduino UNO, a CC3000 wifi shield, and a PN532 NFC shield. That's ok.

So, I created a sketch with this library: https://github.com/nathanchantrell/pubsubclient

I subscribed a topic /ocean/nfc/porta. When I publish a message to it, the callback function isn't called. Moreover, when it takes a card ID it publishs to a topic sometimes then don`t work more. How to solve it?

    #include <Wire.h>
    #include <SPI.h>
    #include <Adafruit_PN532.h>
    #include <Adafruit_CC3000.h>
    #include <cc3000_PubSubClient.h>

    #define PN532_IRQ   (4)
    #define PN532_RESET (3)  // Not connected by default on the NFC Shield

    char cardID[ 16 ];

    Adafruit_PN532 nfc(PN532_IRQ, PN532_RESET);

    #if defined(ARDUINO_ARCH_SAMD)
    // for Zero, output on USB Serial console, remove line below if using programming port to program the Zero!
    // also change #define in Adafruit_PN532.cpp library file
       #define Serial SerialUSB
    #endif

    // These are the interrupt and control pins
    #define ADAFRUIT_CC3000_IRQ   2  // MUST be an interrupt pin!
    // These can be any two pins
    #define ADAFRUIT_CC3000_VBAT  7
    #define ADAFRUIT_CC3000_CS    10

    // Use hardware SPI for the remaining pins
    // On an UNO, SCK = 13, MISO = 12, and MOSI = 11
    Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT, SPI_CLOCK_DIVIDER);

    #define WLAN_SSID       "Ocean Convidado"
    #define WLAN_PASS       "ocean2901"
    //#define WLAN_SSID       "Ocean Lab"
    //#define WLAN_PASS       "ocean3101"

    // Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2
    #define WLAN_SECURITY   WLAN_SEC_WPA2

    Adafruit_CC3000_Client client;

    // We're going to set our broker IP and union it to something we can use
    union ArrayToIp {
      byte array[4];
      uint32_t ip;
    };

    ArrayToIp server = { 25, 0, 25, 172 };

    void callback (char* topic, byte* payload, unsigned int len) {

        Serial.println(F("CALLBACK"));
    /*
        char payload_buffer[20];

        if (strcmp (topic,"/ocean/nfc/porta") == 0) {

            byteToChar(payload, payload_buffer, len);

            if (strcmp(payload_buffer, "permitir") == 0) {
              Serial.println(F("Abreeee!!!!!!"));
            } else {
              Serial.println(F("Não abre!!!!!!"));
            }

        }*/
    }

    cc3000_PubSubClient mqttclient(server.ip, 1883, callback, client, cc3000);

    void setup(void) {

      #ifndef ESP8266
        while (!Serial); // for Leonardo/Micro/Zero
      #endif
      Serial.begin(115200);
      Serial.println(F("Hello OCEAN NFC Reader!"));

      Serial.println(F("Inicializando NFC Reader...."));

      nfc.begin();

      uint32_t versiondata = nfc.getFirmwareVersion();
      if (! versiondata) {
        Serial.print(F("Didn't find PN53x board"));
        while (1); // halt
      }
      // Got ok data, print it out!
      Serial.print(F("Found chip PN5")); Serial.println((versiondata>>24) & 0xFF, HEX);
      Serial.print(F("Firmware ver. ")); Serial.print((versiondata>>16) & 0xFF, DEC);
      Serial.print(F(".")); Serial.println((versiondata>>8) & 0xFF, DEC);

      // configure board to read RFID tags
      nfc.SAMConfig();

      Serial.println(F("Waiting for an ISO14443A Card ...\n\n"));

      Serial.println(F("Inicializando Wifi CC3000"));

      displayDriverMode();

      Serial.println(F("\nInicializando o CC3000 ..."));
      if (!cc3000.begin()) {
        Serial.println(F("Nao foi possivel inicializar o CC3000! Os cabos estao conectados corretamente?"));
        for(;;);
      }
      else {
        Serial.println(F("Carregou"));
      }

      uint16_t firmware = checkFirmwareVersion();
      if ((firmware != 0x113) && (firmware != 0x118)) {
        Serial.println(F("Versao do firmware errada!"));
        for(;;);
      }

      displayMACAddress();

      Serial.println(F("\nDeletando perfis de conexoes antigas"));
      if (!cc3000.deleteProfiles()) {
        Serial.println(F("Falhou!"));
        while(1);
      }

      /* Attempt to connect to an access point */
      char *ssid = WLAN_SSID;             /* Max 32 chars */
      Serial.print(F("\nTentando conectar-se a(o) ")); Serial.println(ssid);

      /* NOTE: Secure connections are not available in 'Tiny' mode! */
      if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
        Serial.println(F("Falhou!"));
        while(1);
      }

      Serial.println(F("Conectado!"));

      /* Wait for DHCP to complete */
      Serial.println(F("Requisitando DHCP"));
      while (!cc3000.checkDHCP()) {
        delay(100); // ToDo: Insert a DHCP timeout!
      }

      /* Display the IP address DNS, Gateway, etc. */
      while (!displayConnectionDetails()) {
        delay(1000);
      }

       // connect to the broker
       if (!client.connected()) {
         client = cc3000.connectTCP(server.ip, 1883);
         Serial.println(F("Conectando em TCP"));
       }

       // did that last thing work? sweet, let's do something
       if(client.connected()) {
        if (mqttclient.connect("ArduinoUnoClient-CC3000-A2", "iotocean", "NZZOLd0O66oLS0vpajiA123")) {
          Serial.println(F("Publicando"));
          mqttclient.publish("/ocean/nfc/debug","A2 está online");
          mqttclient.subscribe("/ocean/nfc/porta");
        }
        else {
          Serial.println(F("Ouve um erro ao conectar-se ao broker"));
        }
       }

    }

    void loop(void) {

      delay(1000);

      Serial.println(F("Entrei no loop\n"));
      uint8_t success;
      uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
      uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)

      // Wait for an ISO14443A type cards (Mifare, etc.).  When one is found
      // 'uid' will be populated with the UID, and uidLength will indicate
      // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
      success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);

      if (success) {
        // Display some basic information about the card
        Serial.println(F("Found an ISO14443A card"));
        Serial.print(F("  UID Length: "));Serial.print(uidLength, DEC);Serial.println(" bytes");
        Serial.print(F("  UID Value: "));
        nfc.PrintHex(uid, uidLength);

        if (uidLength == 4)
        {
          // We probably have a Mifare Classic card ...
          uint32_t cardid = uid[0];
          cardid <<= 8;
          cardid |= uid[1];
          cardid <<= 8;
          cardid |= uid[2];
          cardid <<= 8;
          cardid |= uid[3];
          Serial.print(F("Seems to be a Mifare Classic card #"));
          Serial.println(cardid);

              // Testa se ainda esta conectado
              if (!client.connected()) {
                Serial.println(F("!client.connected()"));
                 client = cc3000.connectTCP(server.ip, 1883);

                 if(client.connected()) {
                   if (mqttclient.connect("ArduinoUnoClient-Office-A2")) {
                      mqttclient.publish("/ocean/nfc/debug","A2 está novamente online");
                   }
                 }
              } else {
                Serial.println(F("else !client.connected()"));
                // as per comment from LS_dev, platform is int 16bits
                sprintf(cardID,"%lu", cardid);

                mqttclient.publish("/ocean/nfc/id", cardID); delay(1000);
              }
              //delay(1000);

        }
        Serial.println(F(""));
      }

      Serial.println(F("Sai do loop\n"));
    }

    void displayDriverMode(void)
    {
      #ifdef CC3000_TINY_DRIVER
        Serial.println(F("CC3000 is configure in 'Tiny' mode"));
      #else
        Serial.print(F("RX Buffer : "));
        Serial.print(CC3000_RX_BUFFER_SIZE);
        Serial.println(F(" bytes"));
        Serial.print(F("TX Buffer : "));
        Serial.print(CC3000_TX_BUFFER_SIZE);
        Serial.println(F(" bytes"));
      #endif
    }

    void charToByte(char* chars, byte* bytes, unsigned int count){
        for(unsigned int i = 0; i < count; i++)
          bytes[i] = (byte)chars[i];
    }

    void byteToChar(byte* bytes, char* chars, unsigned int count){
        for(unsigned int i = 0; i < count; i++)
           chars[i] = (char)bytes[i];
    }

    uint16_t checkFirmwareVersion(void)
    {
      uint8_t major, minor;
      uint16_t version;

    #ifndef CC3000_TINY_DRIVER
      if(!cc3000.getFirmwareVersion(&major, &minor))
      {
        Serial.println(F("Unable to retrieve the firmware version!\r\n"));
        version = 0;
      }
      else
      {
        Serial.print(F("Firmware V. : "));
        Serial.print(major); Serial.print(F(".")); Serial.println(minor);
        version = major; version <<= 8; version |= minor;
      }
    #endif
      return version;
    }

    /**************************************************************************/
    /*!
        @brief  Tries to read the 6-byte MAC address of the CC3000 module
    */
    /**************************************************************************/
    void displayMACAddress(void)
    {
      uint8_t macAddress[6];

      if(!cc3000.getMacAddress(macAddress))
      {
        Serial.println(F("Unable to retrieve MAC Address!\r\n"));
      }
      else
      {
        Serial.print(F("MAC Address : "));
        cc3000.printHex((byte*)&macAddress, 6);
      }
    }

    /**************************************************************************/
    /*!
        @brief  Tries to read the IP address and other connection details
    */
    /**************************************************************************/
    bool displayConnectionDetails(void)
    {
      uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv;

      if(!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv, &dnsserv))
      {
        Serial.println(F("Unable to retrieve the IP Address!\r\n"));
        return false;
      }
      else
      {
        Serial.print(F("\nIP Addr: ")); cc3000.printIPdotsRev(ipAddress);
        Serial.print(F("\nNetmask: ")); cc3000.printIPdotsRev(netmask);
        Serial.print(F("\nGateway: ")); cc3000.printIPdotsRev(gateway);
        Serial.print(F("\nDHCPsrv: ")); cc3000.printIPdotsRev(dhcpserv);
        Serial.print(F("\nDNSserv: ")); cc3000.printIPdotsRev(dnsserv);
        Serial.println();
        return true;
      }
    }

Output of Arduino IDE:

> O sketch usa 28.438 bytes (88%) de espaço de armazenamento para
> programas. O máximo são 32.256 bytes. Variáveis globais usam 1.546
> bytes (75%) de memória dinâmica, deixando 502 bytes para variáveis
> locais. O máximo são 2.048 bytes. Pouca memória disponível, problemas
> de estabilidade podem ocorrer.

title: MQTT Callback function don't called

Answers: 1

body: I solved the problem. There is a bug on CC3000, so need to use WatchDog to reset for each while.


body:
I've an Arduino Nano to which a [Micro Servo 9g](http://www.robotelettronica.altervista.org/immagini/tower-pro-sg90.jpg) is connected. The Arduino board and consequently the servo are powered by a USB powerbank connected to the board with a USB mini cable.

My question is: Is there a way to insert a power switch so I can turn on/off the board without plug/unplug the USB (that now is the way I use) ?
I was thinking to cut the USB cable and work with the positive of it but if someone has an alternative or any tips I'd really appreciate it. Thanks!

EDIT: If is needed I could make a wiring diagram.

title: How to insert a power button on Arduino Nano

Answers: 2

body:
Cutting a usb wire would be the easiest. Otherwise you'd have to cut traces in the pcb and attach wires. Not recommend for beginners. You can actually buy usb cable with a switch.

 Another alternative would be to put the microcontroler in sleep mode and have it use very little power.

body:
As Gerben said, you can buy a cable with a switch built in.

[![Usb cable with switch][1]][1]

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


body:
I am trying to transmit from an ATtiny85 running at 16MHz internal clock to an Arduino Uno with the [Manchester Library][1].

The problem is that the Arduino is not receiving any data.

I have hooked an oscilloscope to the ATAD/DATA pin of the transmitter, and I can see data being transmitted. I have also done the same thing on the DATA pin of the receiver, and it shows data being received. But the Arduino Uno is not detecting anything.

I have tried having an Arduino Uno sending data to itself, which does work, but the data gets dropped very often.

Here is the source code of the transmitter:

 #include <Manchester.h>

 #define TX_PIN 3  //pin where your transmitter is connected

 uint16_t transmit_data = 2761;

 void setup() {
   pinMode(1,OUTPUT);
  man.setupTransmit(TX_PIN, MAN_1200);
 }

    void loop() {
      digitalWrite(1,HIGH);
      man.transmit(transmit_data);
      delay(200);
      digitalWrite(1,LOW);
      delay(200);
 }

And this is the code on the receiver:

 #include "Manchester.h"

 #define RX_PIN 4
 #define BUFFER_SIZE 22

 uint8_t buffer[BUFFER_SIZE];

 void setup() {
      Serial.begin(9600);
      man.setupReceive(RX_PIN, MAN_1200);
      man.beginReceiveArray(BUFFER_SIZE, buffer);
 }

 void loop() {
      if (man.receiveComplete()) {
        uint8_t receivedSize = 0;
        // do something with the data in 'buffer' here before you start receiving to the same buffer again
        receivedSize = buffer[0];
        for(uint8_t i=1; i<receivedSize; i++)
          Serial.write(buffer[i]);
        Serial.println();
        man.beginReceiveArray(BUFFER_SIZE, buffer);
      }
    }

This is the code I used to test with only the Arduino Uno:

 #include <Manchester.h>

 #define RX_PIN 7
 #define TX_PIN 8  //pin where your transmitter is connected

 uint16_t transmit_data = 2761;
 int lastTransmit = 0;

    void setup() {
      Serial.begin(9600);
   man.setupReceive(RX_PIN, MAN_1200);
   man.setupTransmit(TX_PIN, MAN_1200);
   man.beginReceive();
 }

 void loop() {
   if (millis() - lastTransmit > 200) {
  man.transmit(transmit_data);
  lastTransmit = millis();
   }

   if (man.receiveComplete()) {
  uint16_t m = man.getMessage();
  Serial.println(m);
  man.beginReceive();
        //start listening for next message right after you retrieve the message
   }
 }

  [1]: https://mchr3k.github.io/arduino-libs-manchester/

title: Problems with transmission between ATtiny85 and Arduino Uno with 433MHz RF modules and Manchester

Answers: 1

body:
You set **receivedSize** to zero at instantiation, then load it with buffer[0], which also appears to be zero.  You should check that value to ensure it's correct and that it's at least 2 as 1 isn't less than. Otherwise when you go into the loop, i is 1 and **receivedSize** is zero (i is > **receivedSize**.)  So it fails to enter the loop, so no write.

    uint8_t receivedSize = 0;

    receivedSize = buffer[0];
    for (uint8_t i = 1; i < receivedSize; i++)
         Serial.write(buffer[i]);

There may also be a logic problem. If you receive one byte, the **receivedSize** will be 1 and it still won't print.  Keep in mind that the array goes from 0 to limit and your 'data' lives starting in buffer[1].  Meaning if 6 characters are in the buffer only 5 (1 thru 5) will print. It may be much more clear to add the index at the position 'buffer[i + 1]' then the i can run it's normal 0 to n.


body:
I have successfully wrote a sketch for Ethernet Shield and Arduino. If I plug it into computer's USB, it works.

But if I plug into any other power source, like USB power adapter from iPhone or laboratory power source to power socket -- it doesn't work.

LEDs are doing various strange bursts, very different than if powered from computer.

What can be the reason?

**UPDATE**

I have updated sketch so that it doesn't refer serial:

    #include <SPI.h>
    #include <Ethernet.h>

    // Enter a MAC address and IP address for your controller below.
    // The IP address will be dependent on your local network:
    // B6-62-C5-CC-48-81
    byte mac[] = {
      0xB6, 0x62, 0xC5, 0xCC, 0x48, 0x81
    };
    IPAddress ip(192, 168, 10, 90);

    // Initialize the Ethernet server library
    // with the IP address and port you want to use
    // (port 80 is default for HTTP):
    EthernetServer server(80);

    long requestCount = 0;
    long upCounts[] = {0, 0, 0, 0, 0, 0};
    long downCounts[] = {0, 0, 0, 0, 0, 0};
    int currVals[] = {0, 0, 0, 0, 0, 0};
    int prevStats[]= {0, 0, 0, 0, 0, 0};
    int upThreshold = 1024-32;
    int downThreshold = 32;

    void setup() {
      // Open serial communications and wait for port to open:
    //  Serial.begin(9600);
    //  while (!Serial) {
    //    ; // wait for serial port to connect. Needed for native USB port only
    //  }

      // start the Ethernet connection and the server:
      Ethernet.begin(mac, ip);
      server.begin();
    //  Serial.print("server is at ");
    //  Serial.println(Ethernet.localIP());
    }

    void loop() {

      for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
        int sensorReading = analogRead(analogChannel);
        currVals[analogChannel] = sensorReading;

        if( prevStats[analogChannel] == 0 ) {
          if( currVals[analogChannel] >= upThreshold ) {
            prevStats[analogChannel] = 1;
            if( requestCount>0 ) {
              upCounts[analogChannel] ++;
            }
          }
        }
        else {
          if( currVals[analogChannel] < downThreshold ) {
            prevStats[analogChannel] = 0;
            if( requestCount>0 ) {
              downCounts[analogChannel] ++;
            }
          }
        }
      }

      // listen for incoming clients
      EthernetClient client = server.available();
      if (client) {
        //Serial.println("new client");
        // an http request ends with a blank line
        boolean currentLineIsBlank = true;
        while (client.connected()) {
          if (client.available()) {
            char c = client.read();
            //Serial.write(c);
            // if you've gotten to the end of the line (received a newline
            // character) and the line is blank, the http request has ended,
            // so you can send a reply
            if (c == '\n' && currentLineIsBlank) {
              // send a standard http response header
              client.println("HTTP/1.1 200 OK");
              client.println("Content-Type: text/html");
              client.println("Connection: close");  // the connection will be closed after completion of the response
              client.println("Refresh: 2");  // refresh the page automatically every 2 sec

              client.print("X-Inthemoon-Request-Count: ");
              client.println(requestCount);
              for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
                client.print("X-Inthemoon-Analog-To-Digital: ");
                client.print("Channel=");
                client.print(analogChannel);
                client.print("; ");
                client.print("Min-Value=0; ");
                client.print("Max-Value=1023; ");
                client.print("Value=");
                client.print(currVals[analogChannel]);
                client.print("; ");
                client.print("Up-Change-Count=");
                client.print(upCounts[analogChannel]);
                client.print("; ");
                client.print("Down-Change-Count=");
                client.print(downCounts[analogChannel]);
                client.println(";");
              }

              client.println();
              client.println("<!DOCTYPE HTML>");
              client.println("");
              // output the value of each analog input pin
              client.print("Was counting: ");
              if( requestCount>0 ) {
                client.print("YES (request count is ");
                client.print(requestCount);
                client.print(")");
              }
              else {
                client.print("NO");
              }
              client.println("
");
              for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
                client.print("analog input ");
                client.print(analogChannel);
                client.print(" is ");
                client.print(currVals[analogChannel]);
                client.print(", up changes count is ");
                client.print(upCounts[analogChannel]);
                client.print(", and down changes count is ");
                client.print(downCounts[analogChannel]);
                client.println("
");
              }
              client.println("");

              requestCount++;
              break;
            }
            if (c == '\n') {
              // you're starting a new line
              currentLineIsBlank = true;
            } else if (c != '\r') {
              // you've gotten a character on the current line
              currentLineIsBlank = false;
            }
          }
        }
        // give the web browser time to receive the data
        delay(1);
        // close the connection:
        client.stop();
        //Serial.println("client disconnected");
      }
    }

The situation is the same:

https://youtu.be/vypaNOxZ5KI

It is plugged into Samsung tablet USB power of 2A, so insufficient current is unprobable reason.

**UPDATE 2**

I also tried to remove inclusion of `SPI.h`

**UPDATE 3**

If I connect another Arduino board  (but of the same vendor, it is from AliExpress), the behavior is the same.

**UPDATE 4**

I have compiled [blink example][1] and it works in any combination. If I connect Ethernet shield, then it blinks with both LEDs on Arduino board and on Ethernet shield.

**UPDATE 5**

I bought different Ethernet Board and it doesn't work too.

Please help. Have anybody ever powering Arduino + Ethernet not from USB?

  [1]: https://www.arduino.cc/en/Tutorial/Blink

title: Cannot power up Arduino Uno + Ethernet Shield with other than computer USB

Answers: 4

body:
There should be absolutely no difference between powering your Arduino from a computer USB port or a wall plug, especially if you keep your serial monitor closed.

So this is the debug procedure I would advice:

 1. disconnect the shield
 2. connect the Arduino and upload a firmware with

   - no calls to `Serial`, but the most important one you must avoid is the `while` loop in the `setup()` function

   - a short blink of an LED (you can use the onboard one, if you wish so) every time the `loop()` function iterates
 3. power your Arduino (without the shield attached) from your computer with **no serial consoles** and check the LED blinks at constant intervals
 3. power your Arduino (without the shield attached) from your wall plug and check the LED blinks at constant intervals
 4. disconnect the wall plug, attach the ethernet shield **without** an ethernet cable, reconnect the wall plug and check the *debug* LED and the LEDs on the shield are all blinking as expected
 5. plug the ethernet cable and hit the Arduino reset button and check all the LEDs are blinking as expected

Possible faults i can currently think of:

 - **STEP 3**
  - the firmware running on your board is incorrect: double check the compilation and upload process has completed successfully and you have no error in the Arduino IDE console
 - **STEP 4**
  - the firmware still contains some code which expects some input from the serial console: start opening the libraries you use in search for such code
  - the voltage measured at the board between `GND` and `5V` pins is insufficient and the board browns out: check the voltage is above 4.5V and the USB cable is not damaged or faulty
 - **STEP 5**
  - some of the code inside the ethernet shield library is trying to read data from a serial connection: check the library code again
  - some of the components on the ethernet shield are faulty and they are pulling enough current from your wall wart to actually make your board go into protection (hard to believe, a 2A _serious_ wall plug should be much better power source than your PC)
 - **STEP 6**
  - same as for step 5, but your ethernet cable might be playing a role

This might not be an answer _per se_, but it might help you find out the answer you need.

body:
Sorry I didn't see this earlier but I suspect you have a bad earth, because:

 1. It works with the PC
 2. You are using a wall wart
 3. You are wiring your board to another electrical source (Ethernet)
 4. You are saying the LEDs are flashing differently.

Run a lead from the GND connector on the board to an Earth point.
(It might be the Ethernet that is at fault, but unless you have access to the switch I don't know how you could ground that properly)

body: Maybe your laboratory power source is of poor quality. A computer's USB is a good power source. Try using a pack of 4x1.5v AA batteries. I have use this setup with arduino+ethernet shield+cheap servo.

body:
I too have had this problem with a Mega.  It was working with my SCADA package, running on linux and you could ping the Mega/ Ethernet board, but then something changed, and it wouldn't run/ read using the ehternet port.  Had two units, and both behaved the same.

When connected to the programming laptop ( runing W7) and the ethernet port, and running serial monitor, ethernet functions would work.  De powering and repowering using W7 usb port wouldn't work.  Tried removing all calls to Serial.print(ln) via if Debug type logic , didn't fix the problem.

Restoring the Serial messages didn't change the behaviour.

The "fix" is to press the reset button on the ethernet board after powering up, power source independent.
Giving the stack a general reset via the reset pins doesn't work, it needs to be the reset button on the ethernet module.

Did it via the unit connected to the linux machine and instantly got ping, and the SCADA system reading data.

If anyone can shed more light on the need to reset the ethernet module after power up I would be delighted.


body:
I would like to upload a .hex to ATTiny13V (or '13A) using Arduino Uno R3.
I think I know everything to do, but ATTiny13 ISP support and Arduino IDE is a bit search-and-find, and I have some grey-areas in my understanding of how this all works together.

I got here by:

-Finding an Instructable that did something I liked, and there's a ATTiny13V used, a .hex to upload, and C source if I want to modify the source.  Right now I do not need to modify the source, the available .hex is fine.

-I then looked for a way to have AVR programing from OS X.  This seems a little problem, many AVR programmer hardware work great under Windows but seem to have mixed results under OS X.  I saw Arduino could be used for this under OS X.

-I looked on local craigslist for Arduino, someone was selling a Uno R3 with some extras for a great price, and here we are.   And now I have a lot more projects I wish to complete!

I am using Arduino 1.6.10 (from the .cc not the .org).

I read on stackexchange and other places that smeezekitty's core13 works for the ATTiny13.
elabz.com/arduino-shrunk-how-to-use-attiny13-with-arduino-ide/

That's great, but: If I am not using any of the Arduino-specific commands, I don't think I need the bootloader, correct?  I think it is not really a bootloader but builds support for some of the Arduino-specific higher-level commands used by sketch files.

Do I even need the ATTiny13 core files if I hook the pins up properly between the '13 on a breadboard and the Arduino (as per here:  https://create.arduino.cc/projecthub/arjun/programming-attiny85-with-arduino-uno-afb829 ).

I really do not understand what the Arduino IDE/bootloader is doing for me as an abstraction layer.  Do I need the bootloader if I'm not using any of the higher-level Arduino-specific commands on the chip?  HOw about the core files for ATTinyanything vs specifically ATTiny13?

The hex file and C source I will be using are here:
http://www.instructables.com/id/Programmable-LED/
My nextstep will be to modify the source. The C source looks like it references some AVR-specific header files.  I see that the ArduinoIDE uses avrdude so maybe things will compile anyway?

I feel like I'm close but not 100% in my understanding of what I need to do, with the tools I have on hand.

Thanks for your help- I am not above a step-by-step.

Main question 1:  I have a .hex file, an Arduino and IDE 1.6.10, OS X, and breadboard and useful components.  What do I need to do to put the hex on this ATTiny13?

Main question 2: Jumping-off points for taking the C source I linked, tweaking it a bit, building a hex, and uploading that.  I am not against moving it to a sketch if I have to, but it would be good for me to learn how this works before I mode to the IDE.

I have a small software background, am comfortable taking that C source and making changes and compiling (assuming I can find the needed .h files), but this is my first time working with any multiprocessors.

title: Uploading .hex to ATTiny13 using Arduino

Answers: 1

body:
Your computer cannot talk directly to the ATtiny. You need some piece of
interfacing hardware between them. This is called an ICSP (or ISP)
programmer. You also need software to drive the programmer, typically
avrdude.

If you do not have a programmer, you can buy one (I had success with
some very cheap USBASPs), or you can program an Arduino Uno to behave
like an ISP programmer. You do this by uploading into the Arduino a
program called ArduinoISP, like explained in the tutorial [Using an
Arduino as an AVR ISP (In-System
Programmer)](https://www.arduino.cc/en/Tutorial/ArduinoISP). You will
typically use the Arduino IDE and the Arduino core for the Uno to
compile and load ArduinoISP into your Uno. Once this is done, you can
use the Arduino as a programmer and burn your .hex into your ATtiny.

If you want to compile your own programs for the ATtiny, you will need
the avr-gcc compiler and the avr-libc. These are bundled with the
Arduino IDE, so you already have them. You will need an Arduino core for
the ATtiny _only_ if you want to use the Arduino APIs and libraries.
Otherwise you can write plain C programs with noting else than the
avr-libc and avr-gcc.

**Edit**: To compile a plain C program, you can type something like
this:

    avr-gcc -mmcu=attiny13a -DF_CPU=1200000 -Os -Wall -Wextra flickled.c -o flickled.elf
    avr-objcopy -O ihex flickled.elf flickled.hex

This assumes your source file is called `flickled.c` and your ATtiny
runs at 1.2 MHz.


body:
I recently bought the HC 08 Bluetooth module (link [here][1]). As the specs state, this module supports Bluetooth 4.0 which indicates that it supports BLE (Bluetooth low energy).

My goal is to be able to use something similar to the CurieBLE library: I want to code services and characteristics on my Arduino so I can discover those on LightBlue (iOS).

I searched the internet for some guidelines, but I only found code using AT commands and honestly I don't know anything about those.

Can you please recommend any source to achieve the goal?

**Update**

After following the connections in this [link][2] (In Spanish I guess but helpful), I was able to discover the Arduino on LightBlue. The characteristic name was Tx/Rx and I was able to write, read and subscribe to notifications (data coming in). Of course if would be better to find something that allows the definition of services and characteristics.

  [1]: https://www.aliexpress.com/item/SH-HC-08-CC2541-Bluetooth-4-0-BLE-to-UART-Transceiver-Module-with-Transparent-Serial-Port/32392960671.html
  [2]: http://www.prometec.net/bluetooth-le/

title: HC 08 Module with Arduino Uno

Answers: 0


body:
I have a need to receive a specific confirmation packet after commanding my transmitting Xbee to stop sending normal packets.

My buffer still has normal packets in it when this happens, so next time I call readPacket(), I don't want to see them. So right before I call my stop command, I try to purge the incoming buffer like this:

    void burnSerial(void) {
      while (xbee.readPacket(20)) {
        xbee.getResponse().getRx16Response(rx16);
      } //read all available responses
        // only do this when not in a constant stream of responses or it may hang.

      while (Serial.available()) { Serial.read(); }
      //burn whatever may be in serial buffer
    }

But this doesn't work. The next time I call `xbee.readPacket()`, I see tons of normal packets before I finally see my confirmation packet. Why don't these functions do anything for me at all?

title: How to purge incoming Xbee packets from the buffer?

Answers: 1

body:
It means there's a lot of latency between your issuing a command and getting a confirmation of the command's effect. When you send the command, it's best that you wait and read packets *until* you find the confirmation and *then* you return from the function or do whatever else you want to do. There is no need for a separate `burnSerial()` function, nor should you blindly discard data. So basically, the sequence of operations should be:

 - Send the command
 - Read packets until you find the 'confirmation' identification marker
 - Return or exit

This assumes that your transmitter only sends confirmation *after* it has halted the stream.


body:
I'm doing a project for university and I am struggling to code and set up a rotary encoder that can control hot-cold variations. Much like the idea of communicating temperature selected by turning a dial. I would either like to control a single strip of RGB LEDs or a single bulb (changing and fading between colours at the same time).

I would like to have the dial turn from 0 - 180 degrees and relate to intense blue changing to intense red and all the colours in between as increments.

I have an Arduino Uno.

Thank you!

title: How to control cold to hot (blue to red gradient) RBG LED strip/bulb with a rotary encoder?

Answers: 2

body: Well as I understand you want to use a rotary encoder ? Rotary encoder can turn freely. Which you can read via arduino easily with a library. You can count a number(let's say x) from 0 up to 255, and write that number to one of the color. For the other color write 255-x so when blue is fading down the red is increasing. But I suggest you to use a potentiometer which has a limited turn (about 270 degrees). Connect it to arduino's one of the analog read pins. It will give you a 10 bit value which is between 0-1023 . You can scale this down to 0-255 range with map function. [Example:  "x = map(x,0,1023,0,255);" ] after that just follow the same process as before.

body: http://playground.arduino.cc/Main/RotaryEncoders is where the rotarty encoder libraries are. From there you can use PWM on the outputs as said. There are also some addressable RGB strips/modules that incorporate a driver IC such as adafruit neopixels where you can just write values for colour and brightness to the IC fairly simply, depending on your level of electronics knowledge.


body: I am a newbie and I would like to build my own minimalistic ATmega32U4 based arduino compatible board. Can anyone please tell me which parts resistors/capacitors (and maybe one status led) I need to connect it over usb to my computer? Thanks in advance.

title: Minimal Arduino using ATmega32U4

Answers: 2

body:
Building your own may be worthwhile from a learning point of view, but makes minimal sense otherwise. You can buy Arduino clones (legal) from China for under $US5 each - good enough quality, assembled, working.
You cannot build one for that.

A DIY minimalist Arduino requires a running processor - see datasheet for the processor of choice as Ignacio says.Probably decoupling capacitors and maybe one or two resistors and maybe 1 or 2 small capacitors. If you cannot derive the needed information from a datasheet you do not know enough to sensibly do it by yourself. There are many on-web ~= minimalist implementations to copy.

If you want onboard USB you'd usually use a USB-serial converter but this can be done by "bit bashing" if you truly want a minimalist implementation>

BUT - just buy one and use the large amount of time gained to learn related things of more immediate use.

body:
Several Arduinos and Arduino-compatible boards use the ATmega32U4.
Many of them have published open-source plans that show exactly what components are used and how they are connected. They may not be the absolute minimal number of components, but it seems clear that you don't need *more* components than a known-working board:

* 1 ATmega32u4
* 1 16 MHz crystal
* 2 22pF ceramic caps (for crystal)
* 1 uF decoupling cap
* 1 pushbutton
* 1 10 KOhm pull-up resistor (for pushbutton)
* 1 LED
* 1 220 Ohm resistor (for LED)
* 1 USB socket
* 2 22 Ohm resistors (between USB socket and ATmega32u4)

Alas, there are two unnecessarily difficult hurdles between newbies and getting a new ATmega32u4 device connected over USB to a computer:

* The ATmega32u4 and nearly every other device that communicates over USB is only available in SMT packages with pins at 0.8 mm pitch or even closer together.
Most people find packages with pins at 2.54 mm pitch easier to handle and plug into a breadboard.

* Installing a bootloader into any new processor chip is often tricky.

As Russel already pointed out, you can save a lot of time by starting out with an Arduino or Arduino-compatible board that already has the chip soldered on and the bootloader programmed in, bypassing the above unnecessarily difficult hurdles.

A few Arduinos and Arduino-compatibles (with links to schematics, etc.) that use the ATmega32u4:

* [Bootloading an ATmega32u4 with Arduino][1]
* [Teensy 2.0 (ATmega32u4 USB dev board)][2]
* [Arduino Leonardo][3]; [Arduino Leonardo][4]
* [Arduino MICRO][5]
* [SparkFun Pro Micro (Arduino-compatible)][6]
* [FLORA - Wearable electronic platform: Arduino-compatible][7]
* [Adafruit Feather 32u4 Basic Proto][8]
* [Installing Arduino Bootloader on an ATmega32u4][9]; [Installing Arduino Bootloader on an ATmega32u4][10]

  [1]: http://murchlabs.com/monday-experiment-bootloading-an-atmega32u4-with-arduino/
  [2]: https://www.adafruit.com/products/199
  [3]: https://www.arduino.cc/en/Main/ArduinoBoardLeonardo
  [4]: https://www.adafruit.com/product/849
  [5]: https://www.arduino.cc/en/Main/ArduinoBoardMicro
  [6]: https://www.sparkfun.com/products/12640
  [7]: https://www.adafruit.com/product/659
  [8]: https://www.adafruit.com/products/2771
  [9]: http://electronut.in/bootloader-atmega32u4/
  [10]: http://forum.arduino.cc/index.php?topic=121371.0


body:
I am having trouble figuring out the pinout of my 6 - pin USBasp Chinese clone that I got off eBay.
**BEFORE YOU TELL ME TO LOOK AT THE PINOUT DIAGRAMS,** I can tell you that my version of the usbasp has no way of telling which way is up and which ways is down. Images:
[![ ][1]][1]

[![ ][2]][2]

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

title: Help with usbasp pinout

Answers: 1

body:
 Look at the following pinout diagram (from [telecnatron.com](http://telecnatron.com/reference/pinouts/avr-isp/index.html)):

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

The right-hand diagram above shows the USBASP-board pin-header pin assignments, when you are looking into the pin-header.  The header shell will have a triangle marking pin 1.  Note that pin 1 is on the same side of the connector as the key (the ridge on the cable connectors, the slot on the pin-header shell).  Each socket on the cable also will have a triangle marking pin 1.

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


body:
I am using an ATTINY88 for a project that requires to turn on an LED. Right now I am using pin PA1(ADC7/PCINT25). I noted, however, that when the pin is ON, I get about half the voltage that is connected to Vcc. I checked the voltage in other pins and they are close to Vcc. Will anyone know, what could be the reason for this?

I figure this pin has an internal resistor enable, but I am not certain.

title: digitalPin giving lower voltage than Vcc

Answers: 1

body:
You should connect the AVCC pin to VCC. From the datasheet (emphasis
mine):

> AVCC is the supply voltage pin for the A/D converter **and
> a selection of I/O pins**. This pin should be externally connected to
> VCC **even if the ADC is not used**. [...]
>
> The following pins receive their supply voltage from AVCC:
> PC7, PC[5:0] and (in 32-lead pack- ages) **PA[1:0]**. All other I/O
> pins take their supply voltage from VCC.


body:
I have a device in which a user connects their mobile device to an arduino uno via a HM-10 bluetooth transponder.  I want to be able to calculate the approximate distance between the user and the transponder by hopefully using the RSSI methodology:

     d = 10 ^ ((TxPower - RSSI) / 20)

**My goal** is for the user to send a connection request to the HM-10, the uno to then calculate the distance, and if greater than x meters away, reject the request.  I realize RSSI based distance is an estimate at best but that is fine for my purposes.

With that in mind, I have two questions:

    1.) Is an HM-10 able to capture the RSSI strength of a mobile device to
        calculate distance?
    2.) Can it do so WITHOUT connecting first based on the
        initial request of the mobile device?

title: Find RSSI of Mobile Device Without Connecting

Answers: 1

body:
You have two questions, but what makes you think you can't find these out?

When you want to know what a device can do (and thus can't do) you should check the devices' datasheet. I believe it is [this file][1].

Bluetooth (and gsm) devices often work by sending AT commands. For example: "AT+PIO" to set/query GPIO pins of the module.
You can send "AT+RSSI?" to get a response on the RSSI value.

----------

Not everything can be mentioned in the datasheet though. If you can't find any sources on it, it's most likely not a feature.

The only way to add a "validation function" within the bluetooth connection code, would be to re-write the firmware of the device.

But, you could:

 1. Connect (with everyone using the right pin)
 2. Check their RSSI
 3. Disconnect if it doesn't match your criteria

I'm not sure if this module can have multiple connections, I didn't really see a way to disconnect a single connection. If not, you could even toggle the power to the module to "disconnect" the client(s).

  [1]: ftp://imall.iteadstudio.com/Modules/IM130614001_Serial_Port_BLE_Module_Master_Slave_HM-10/DS_IM130614001_Serial_Port_BLE_Module_Master_Slave_HM-10.pdf


body:
I'm using the Arduino sketch for LED stroboscope found here: http://mehax.blogspot.co.uk/2011/02/arduino-stroboscope.html.

Also below, I've inserted the loop part where this calculations are made:

    void loop() {
    // this while is a workaround for timer limitations using micros vs millis
    sensorValue = analogRead(analogInPin);   //take potentiometer reading
    hold = sensorValue*55 + 400;             //add some time to scale and for code execution
    microsCurrent = micros();                // collect current time
    if (microsCurrent > microsPrev + hold){  //set up timing loop
    frequency = 1000000/(microsCurrent - microsPrev);
    microsPrev = microsPrev + hold;            //set up millis for delay stuff

    //set all 6 LEDs high (they were already plugged in)
    digitalWrite(3,HIGH);
    digitalWrite(5,HIGH);
    digitalWrite(6,HIGH);
    digitalWrite(9,HIGH);
    digitalWrite(10,HIGH);
    digitalWrite(11,HIGH);
    delayMicroseconds(.02*hold);  //leave LEDs on long enough to see

    //set all LEDs low
    digitalWrite(3,LOW);
    digitalWrite(5,LOW);
    digitalWrite(6,LOW);
    digitalWrite(9,LOW);
    digitalWrite(10,LOW);
    digitalWrite(11,LOW);

    if(millis() > millisSerial + 200){
      millisSerial=millis();    //reset timer
      holdFrequency = 1000000/hold;
      //do some math to find values
      rpm = frequency * 60;

I want to use this code in my project, but I don't really understand how this code calculates the stobing frequency.

So, I have following questions:

 1. Why "hold" variable is calculated in the given way?
 2. Why "microsCurrent", "microsPrev" and all other timings are executed?
 3. How "frequency is calculated"?
 4. What is "hold frequency" variable?

Sorry, I'm very new to Arduino and don't know much coding.
Will appreciate very much your help!

title: Strobe Frequency Calculation, how its done?

Answers: 1

body:
> Why "hold" variable is calculated in the given way?

`hold` stores the intended delay between the strobe pulses, i.e. the
stroboscope period. It is computed as an affine function of the
potentiometer cursor position because... well, that's the simplest way
to make it user-adjustable. 400 µs is the shortest period that
(according to the program author) one may reasonably want to set.

> Why "microsCurrent", "microsPrev" and all other timings are executed?

See the [Blink Without
Delay](https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay) Arduino
tutorial.

> How "frequency is calculated"?

From the code:

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

    frequency = 1000000/(microsCurrent - microsPrev);

The frequency is the inverse of the period. The period is the time
elapsed between this strobe and the previous one. The numerator is a
conversion factor to get the frequency in hertz from a period in
microseconds.

> What is "hold frequency" variable?

It's the intended frequency (inverse of the intended period),
disregarding the timing jitter that makes the actual instantaneous
frequency slightly different.


body: I just got my ESP8266, but I am unable to program it. Since it can't be connected to via USB, I was wondering if I can program it using an Arduino or perhaps use it as a shield for an Arduino Nano. I haven't been able to find a good guide online. Any help is greatly appreciated.

title: Is it possible to program an ESP8266 12F using an Arduino Nano?

Answers: 2

body:
> Is it possible to program an ESP8266 12F using an Arduino Nano?

Yes, but it is much easier to use a FTDI for USB-to-Serial adaptation. Two buttons are also needed to activate the ESP8266 programming mode.

Cheers!

body:
Yes, you can program it with Arduino but its a bit complex that way. You will need a separate Linear Regulator with Adjustable Output to get it hooked up with the Arduino.
 Its way better to have an FTDI adapter to program it.

But if you still want to know, there is a tutorial below,

Upload Bareminimum sketch so that no program is running on the Arduino.

[![Circuit Diagram][1]][1]

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


body:
I'd like the double number 200.00 shown as `200.00` on my LCD screen.

For instance, when I pass just a number (`int`) like 40 to the LCD, it uses it as an ASCII code to show a character on the display.

Now I want to send a `double` to it and it should be displayed as a double.

    #include <Wire.h>

    void setup() {
       Wire.begin(0x63);
    }

    double f;
    void loop() {

      f = 200.00;

      Wire.beginTransmission(0x63);
      Wire.write(byte(0x00));
      Wire.write(4); //HIDE CURSOR
      Wire.write(12); //CLEAR SCREEN
      Wire.write(13); //CURSOR 2nd LINE
      Wire.write("Frequenz: ");
      Wire.write(f); //<- How to do this?
      Wire.write("Hz");
      Wire.endTransmission();
    }

title: Arduino Wire.h send double to lcd

Answers: 2

body: Use `Wire.print()`, instead of `Wire.write()` which is intended only to output single bytes or byte arrays.

body:
The Arduino [Wire][1] class does only support [write()][2] of byte, string and vector of bytes. To write a double it must first be converted to a string. This can be done with the standard C library function [dtostrf()][3].

    double f;

    void loop() {
      char buf[10];

      f = 200.00;

      Wire.beginTransmission(0x63);
      Wire.write(byte(0x00));
      Wire.write(4); //HIDE CURSOR
      Wire.write(12); //CLEAR SCREEN
      Wire.write(13); //CURSOR 2nd LINE
      Wire.write("Frequenz: ");
      Wire.write(dtostrf(f, 0, 2, buf));
      Wire.write("Hz");
      Wire.endTransmission();
    }

The class inherits from [Print][4] (via [Stream][5]) so that the overloaded member function [print()][6] for double can be used. In that case:

    double f;

    void loop() {
      f = 200.00;

      Wire.beginTransmission(0x63);
      Wire.write(byte(0x00));
      Wire.write(4); //HIDE CURSOR
      Wire.write(12); //CLEAR SCREEN
      Wire.write(13); //CURSOR 2nd LINE
      Wire.write("Frequenz: ");
      Wire.print(f);
      Wire.write("Hz");
      Wire.endTransmission();
    }

Please note that the maximum number of bytes to write (between beginTransmission and endTransmission) is [limited to 32][7] in the standard configuration of the Arduino core.

Cheers!

  [1]: https://www.arduino.cc/en/Reference/Wire
  [2]: https://www.arduino.cc/en/Reference/WireWrite
  [3]: http://www.atmel.com/webdoc/AVRLibcReferenceManual/group__avr__stdlib_1ga060c998e77fb5fc0d3168b3ce8771d42.html
  [4]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/Print.h
  [5]: https://www.arduino.cc/en/Reference/Stream
  [6]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/Print.h#L67
  [7]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/libraries/Wire/src/Wire.h#L28


body:
This is similar to:
https://arduino.stackexchange.com/questions/22319/is-this-function-subject-to-memory-fragmentation

I am trying to get my head around Memory fragmentation in Arduino's and embedded systems in general.

Currently I have a function in a `__lcdAux__` Class which is responsible for doing basic operation on the lcd.
One of the members of the class is a char array `double2StrBuff1` which is used with `__dtostrf()__` to create a double which is then passed to `sprintf`. So the following function (`__lcdAux::UpdatePosition__`) is responsible for updating the position on the lcd.

    void lcdAux::UpdatePosition(double MtXPosLengthUnits) {
     lcd->setCursor(0, 2);
     dtostrf(MtXPosLengthUnits, 0,3, double2StrBuff1);
     sprintf(lcdBuff, "X: %s", double2StrBuff1);
     lcd->print(lcdBuff);
    }

Currently, I am under the impression that by defining once the class as a global variable and then using it throughout the program, then the char array is allocated only once memory space. Therefore by using it afterwards no memory fragmentation occurs.

However, I read that functions allocate space on the stack which is immediately recoved when the function is exited. Therefore I am curious if the following declaration is any different in terms of memory fragmentation.

    void lcdAux::UpdatePosition(double MtXPosLengthUnits) {
     lcd->setCursor(0, 2);
        char double2StrBuff1[10];
     dtostrf(MtXPosLengthUnits, 0,3, double2StrBuff1);
     sprintf(lcdBuff, "X: %s", double2StrBuff1);
     lcd->print(lcdBuff);
    }

To sum up:

- by putting  the declaration for variable `__char double2StrBuff1[10];__`  inside the function, is the memory allocated from the stack and therefore recovered upon exiting the function (therefore there is no need to declarate a member variable on the class level),

OR

- is the fact that `__double2StrBuff1__` is a pointer means that the pointer is allocated in the stack but the values are located in the heap (therefore what I am doing makes sense)?

PS: Because some might point out that  `__"X: %s"__` is worse in terms of memory usage and fragmentation, I'll state the following. Instead of the format string `__"X:%s"__` I use a `_PROGMEM` const `char_ array` and `__strcpy_P()_`, but to simplify the question I replaced it with the literal string , since I feel that is another problem.

title: Understanding memory fragmentation due to char arrays in functions

Answers: 2

body:
> by putting the declaration for variable char double2StrBuff1[10];
> inside the function, is the memory allocated from the stack and
> therefore recovered upon exiting the function

This is correct.

> is the fact that double2StrBuff1 is a pointer means that the pointer
> is allocated in the stack but the values are located in the heap
> (therefore what I am doing makes sense)?

No, `double2StrBuff1` is not a pointer, it's an array. In C and C++,
when you use an array identifier, it decays to a pointer in many
situations. However, for the purpose of memory allocation, an array is
_very different_ from a pointer.

Heap allocation only happens when using `malloc()` and `new`.

body:
The examples in the question above use 1) global and 2) local aka stack allocation and do not give heap fragmentation. The heap is not involved.

Below is a version that may give heap fragmentation (though a very low risk):

    void lcdAux::UpdatePosition(double MtXPosLengthUnits) {
        lcd->setCursor(0, 2);
        char* double2StrBuff1 = (char*) malloc(10);
        dtostrf(MtXPosLengthUnits, 0,3, double2StrBuff1);
        sprintf(lcdBuff, "X: %s", double2StrBuff1);
        lcd->print(lcdBuff);
        free(double2StrBuff1);
    }

Please not that heap allocation is very slow compared to stack allocation.

C/C++ does not have any implicit heap allocations (in the language). A local array in a function is allocated on the stack and removed when the function returns. The only library functions that can generate stack fragmentation are [setjmp and longjmp][1] if used to create a [spaghetti stack][2].

  [1]: http://www.nongnu.org/avr-libc/user-manual/group__setjmp.html
  [2]: http://c2.com/cgi/wiki?SpaghettiStack


body:
So my problem is this, I have an Arduino Uno with an Adafruit Motor Shield (1.0) and an HC-06 Bluetooth Module and I want to use them at the same time, the problem is that the Motor Shield uses all the ports that I need for the HC-06 (TX, RX, GND and VCC). In addition to all that, my project needs to be light weight (It's a quadcopter). Is there any way that I could use both of them at the same time?

Thanks in advance!

title: Motor Shield and HC-06 Bluetooth Module competing for pins

Answers: 2

body:
The motor shield doesn't actually use the TX and RX pins. Though as a shield it will go into all the arduino pins.

You could either solder some wires to the TX and RX pins, or use something like the [proto shield](https://www.adafruit.com/product/2077) to sandwich in the middle of it, and connect the BT module onto this shield.

You could also remove all the male headers from the motor shield, and replace them with [stacking headers](https://www.adafruit.com/products/85)

body: Ok so i had the same problem but i found like the easiest solution. So what i did was scrape the wire end to the copper using a knife or a wire cutter. And then place it in the Arduino holes and then squeeze the motor shield on top of it. Works like a charm!


body:
I was connecting L293d Motor Driver IC with an Arduino Due Board. May be due to wrong connections, but when I made the grounds common, the Arduino LED goes off and Atmel IC heats up. When I reconnect my Due board with my PC anytime, the LED turns on and slowly dims to off and Atmel IC fries up.

I wanted to repair it. What should I do?

I have checked the input voltage of the **AMS1117 3.3V regular IC** as 3.8 V, while the output is 2.2 V. If I externally give 5 volt at input again, the input voltages drops. The regulator is loading.

*I thought of replacing the regular IC?
Will that work?*

Also I externally powered the Board with 3.3V by its pin labeled "3.3V" . The LEDs glow on and did not go off. But the Atmel Microcontroller IC becomes very hot.

What should I do?

title: Arduino Due ( Atmel Microcontroller) IC Heat up and led goes off

Answers: 1

body:
Motor driver boards exist to allow an MCU to *control* a motor without having to supply its power. If you try to power motors from the Arduino as well, they draw too much current and things get hot or damaged.

The 3.3v pin is only for supplying modest amounts of current at 3.3v *from* a 5v Arduino. You can not back-power the board with it. I don't know what happens if you try, but I bet it isn't good...


body:
I'm building web based remote control system for esp8266. In arduino IDE, using the ESP libraries. To, send data to the server, I'm using http post.
For some settings, I need to transfer 30 or so, different values over a single post request.  And assign it to different type of variables.

 so, from this:
    192.168.1.101/testpost?lenght=10&1=100&2=true&3=1800&4=125

 i need this:

 uint8_t brightness = 100;
 bool randomOrder = true;
 uint16_t Delay = 1800;
 uint8_t Position = 125;

This is the relevant code. Basically, my idea is, to send the lenght of the array (will be different each time.) in the first argument.
Than create a for loop that put every value in a array into variable pointers. But, since lots of different type variables going on, i'm not sure how to do that.

    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>
    #include <ESP8266mDNS.h>

    //values i need to set in a single post.
 uint8_t settings0;
 bool brightness;
 uint16_t randomOrder;
 uint8_t Delay;

    void setup {
 //relevant code that handels post request.
    server.on("/testpost", HTTP_POST, []() {

 String ZeroValue = server.arg("lenght");

 int lenght = ZeroValue.toInt();

 //this doesnt really work, but its a starting idea.
 int* SettingsArray[4] = {&settings0, &brightness, &randomOrder, &Delay};

 for( int i = 0; i < lenght; i++) {

   String PresetSettings = server.arg(i);
   SettingsArray[i] = PresetSettings.toInt();
  }
 });
    }

Ultimately, I can just do that, but I'm wondering if there is a more elegant solution.

 brightness = SettingsArray[1];
 randomOrder = SettingsArray[2];
 Delay = SettingsArray[3];
 Position = SettingsArray[4];

title: Best way to assign value to lot of variables

Answers: 1

body:
The WebServer class supports [argument lookup by name][1]. This should allow HTTP argument parsing that does not require length and/or specific order:

    192.168.1.101/testpost?brightness=100&randomOrder=true&delay=1800&position=125

And parse with:

    brightness = server.arg("brightness").toInt();
    randomOrder = server.arg("randomOrder").toInt();
    Delay = server.arg("delay").toInt();
    Position = server.arg("position").toInt();

Please note that some value will require cast (and there might be a need for special handling of "true" and "false"). For further robustness each argument name needs to be checked that it is available.

    String arg = server.arg("argName");
    val = (arg.length() == 0 ? defaultVal : arg.toInt());

Or simply:

    String arg = server.arg("argName");
    if (arg.length() != 0) val = arg.toInt();

Cheers!

  [1]: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WebServer/src/ESP8266WebServer.h#L93


body: I have a 12V addressable RGB strip that I want to control with an Arduino, the chips are ws2811s, is there a way to do this as the Arduino is 5V and 3.3V?

title: Controlling a digital 12V addressable RGB led strip with Arduino?

Answers: 1

body:
<s>The only signal you need to worry about is DIN (data in) which is normally 5V from an Arduino. Use that to switch a MOSFET or transistor to convert the digital pulses to 12V. In other words, the Arduino switches the transistor, the transistor outputs 0 or 12 V.</s>

---

Judging by [this link](http://doityourselfchristmas.com/forums/showthread.php?23588-WS2811-5050-Pixels-at-12v-Signaling-at-5v) you still just send 5V digital switching to the strip.

> The data signal never needs to be 12 volts. The 12 volt pixels all drop the voltage down to about 5 volts to operate the chip. Usually just a resistor and a zener diode, sometimes just a resistor.

In other words, connect the "power" pin to +12V, and the ground pin to Gnd from your power supply.

Connect the Din (data in) to your Arduino pin directly. Of course, *also connect the Arduino ground to the ground pin*.

---

Also see [this Youtube video](https://www.youtube.com/watch?v=pu1kzJGMZyA). On the comments he says:

> These 12v WS2811 "pixels" still use 5v signalling. You simply connect the 12v source power directly to the strip, tie the ground to the arduino and then treat them as if they were a 5v strip.


body:
I am a beginner in the Arduino world. I made some basic projects of the book that comes with the starter kit (it's was borrowed by a friend of mine) and also I used a humidity, a temperature sensors and a LCD display.

I want to buy an Arduino Uno for measure **room temperature, humidity, carbon monoxide, carbon dioxin and maybe a couple more variables. I will to use 4 sensors, 1 buzzer, 1 LCD display and 1 ESP8266 serial WIFI wireless module**.

After this work I will add for functionalities but as I have a lot of components I am not sure if the Arduino Uno can supports them because it has a limited quantity of pins.

Do I need an Arduino with more pins? what if I use all these pins and I need more? Can the Arduino Uno be expanded with more pins?

As the Arduino Uno is a very small computer, can its processor support all these components and their operations?

title: How many sensors can be supported by a single Arduino unit?

Answers: 4

body:
I think you want to know how many sensors 1 Arduino can support.  But just in case, I am answering both interpretations of the title of your question:

 1. How many different types of sensors can an Arduino support?:

With the correct software and hardware, the Aruidno can interface with almost any kind of sensor.  The exceptions include but are not limited to sensors which produce more data than an Arduino can process (such as a video camera) or sensors that require fast responses (such a time of flight laser distance sensors (LIDAR)).

 2. How many sensors can an Arduino support at the same time?:

This depends on what processor resources are needed.  If the sensor needs the ADC there 6 channels on most Arduinos.  If you need more, there are hardware solutions.  But many here have suggested to simply add a 2nd Arduino.

To specifically address your laundry list:

> room temperature

Thermistor connected to ADC.  But most are not linear, so you will have to create a look up table.

> humidity

I think there is a SPI module on the market to do this.

> carbon monoxide

These sensors usually require an amplifier.  And change with age & temperature.  So a lot of software here as well as hardware.

> carbon dioxin

Not sure about this one.

> buzzer

Self osculating? Then you only need a logic output.

> 1 LCD display

Alpha & numeric? Most have 4 or 8 pin Hitachi interfaces.  But you can look for a SPI or serial port LCD so as to conserve on Arduino pins.

> ESP8266

This is just a serial device.  You will need the Ardino's serial port.

I'll leave it up to you to make a detailed assessment of the necessary processor resources.  Because you need to first pick out the specific hardware you will be using.

That's half the battle.  The other half is verifying the libraries for all these sensors and communication devices will not interfere with one another.  That I will leave up to you as it is not an easy task to wade through all the code for all the different libraries you will be using.  And, again, until you pick out exactly what sensors and devices you will be using it is impossible to even start analyzing as we wouldn't know which libraries to look at.

body:
The question itself is a bit broad, but I'll try and provide some insight here.

The number of sensors that can be supported, and the number of pins they require, will depend on what sort of interface they use.

 - If your sensor has an **analog** interface, you will need an analog input pin for each sensor.
 - If your sensor has an **I2C** interface, you can have multiple devices sharing the same pins (a bus) provided that they have different I2C addresses (often configurable with jumpers on the device).
 - If your sensor has an **SPI** interface, you can have multiple devices using the same pins (a bus), except that each will need a _chip select_ PIN connected to a digital I/O pin on your Arduino so that it can 'select' each device.
 - If your sensor has a **serial** interface, you can generally only have one device.

To add complexity to the problem, you can get expansion modules for the Arduino that will give you extra analog pins or other communication interfaces.

With the long list of sensors you have above, you may also be hard-pressed for program space, as most sensors will need code and/or libraries to interface with them. The Arduinos with more pins (such as the MEGA) also have more program space.

I would encourage you to do some further research on the sensors you want to use, and finding out what interface they use, and what Arduino libraries are available for them. This way, you can fully understand the requirements and limitations of any parts you want to use.

Further reading:

 - https://www.arduino.cc/en/Reference/Wire (I2C interface)
 - https://www.arduino.cc/en/Reference/SPI (SPI interface)
 - https://www.arduino.cc/en/Reference/Serial (Serial interface)
 - https://www.arduino.cc/en/Guide/Libraries (Using libraries)
 - https://www.arduino.cc/en/Tutorial/HomePage (Arduino tutorial)

body:
An Uno has more than enough pins for the devices you described.

 - A DHT22 Relative Humidity and Temperature sensor needs only one digital pin for both variables.
 - An MQ-7 Carbon Monoxide sensor needs one analog pin.
 - An MG-811 Carbon Dioxide sensor needs one analog pin (and an amplifier).
 - A Piezo buzzer needs one PWM pin.
 - The LCD with a Hitachi interface needs four digital pins.
 - The ESP module needs two digital pins.

That's 7 digital pins, one of which needs to be a PWM pin, and 2 analog pins. I did not make any choices about best or cheapest devices, just ones I either knew about or could find quickly by searching. But with this pin requirement doesn't come close to exhausting the available pins on an Uno so there's plenty of capacity left unassigned for you to make other choices that might require different interfaces or more pins.

body: Look at the MUX Shield, I just used one to add 48 Inputs to a MEGA making it capable of having 98 Inputs or Outputs


body:
I am a beginner who would like to buy an Arduino Yún (58 dollars).

It is retired so will I have any problem?

Else I can buy an Arduino Uno and an Arduino Yún Shield. But in this case I don't understand the difference between an **Arduino Uno + Arduino Yún Shield** and an **Arduino Uno + ESP8266 serial WIFI wireless module**.

Arduino Yún Shield: I can't find the price. I only found an Iduino.
[![Arduino Yún Shield][1]][1]

ESP8266 serial WIFI wireless module: 7 dollars.
[![WiFi Module - ESP8266][2]][2]

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

title: Should I buy a retired Arduino?

Answers: 3

body:
It is retired so will I have any problem?

It depends on what you want to do with your arduino. If you need a project that requires future support then dont buy a retired board. If you just want to do basic beginners stuff (like blinking LEDs, controlling motors, sending serial information wired or with an add on shield to send wireless information)-then any arduino can do these basic projects and probably at a cheaper price than 58 dollars.

body:
When a board is retired, it may:
- get no support (never had support from Arduino zelf though)
- not be readily available.

Which may or may nog be a problem.
The biggest problemen with retired boards is that they often didn't sell very well.

So they may:
- target niche applications.
- not have a lot of people post tutorials on it.
- not have/get elaborate answers on Arduino.se

I believe you should only get something that fits your needs.
Usually you van get away with an Uno, and since there are millions if (beginner) tutorials, i'd pick that as my first Arduino.

If you want to do anything more "pc-like" like USB, camera or a "server", my first pick would be a raspberry pi.
Also, since there are hundreds of tutorials.
You can choose to do it with a yún, and it may work, but you should check if there are tutorials/documentation for whatever you'd like to do with it.

body:
The question of the Arduino Yun being retired can be answered here:
http://www.arduino.org/forums/yun/retriered-boards-894?p=3495&hilit=Retired#p3495
At least regarding Arduino.org the answer is no. The Yun is **not** retired.


body:
*<sup>**Question completely rewritten**</sup>*

Trying to assess an Arduino project feasibility. New to Arduino... but did a lot of controller programming (assembly), Roboteq (C) and Phidgets (C++) , using various kinds of motors and sensors ; and reading the Arduino documentation makes me feel confident interfacing and programming shouldn't be an issue.

However, before investing time (and some money) in the project, I thought it'd be better to ask here if Arduino is the right choice, considering

- a non-latching [Hall sensor](https://en.wikipedia.org/wiki/Hall_effect_sensor) is to be connected to Analog 0, `analogRead()` to return a [0,1023] value, used as a proximity sensor. This should be straight forward.

Question →

- while the Arduino runs my program, and is still connected to the PC (USB), is it possible to synchronously or asynchronously send commands from the PC to the Arduino. I.e. can the Arduino poll if there is something coming from USB (synchronous), or is there a way for the PC via USB to have Arduino do something (asynchronously)?

Thank you.

title: Arduino project feasibility

Answers: 1

body:
It's perfectly doable. As Chris Stratton puts it, it's all about
implementing _non-blocking_ serial communication:

* whenever you receive a character, you store it in a buffer
* whenever you have a complete command in the buffer, you process it and
  reset the buffer

For a line-oriented protocol, it may look something like:

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

    /* Process incoming characters if any. */
    while (Serial.available()) {
        static char buffer[BUF_LENGTH];  // incoming command
        static int length = 0;           // command length

        int data = Serial.read();
        if (data == '\r') {              // complete command
            buffer[length] = '\0';       // terminate the string
            if (length)
                exec_command(buffer);    // process
            length = 0;                  // reset buffer
        }
        else if (length < BUF_LENGTH - 1)
            buffer[length++] = data;     // buffer incoming character
    }

For a more complete example, you may want to take a look at this [simple
Arduino command line interpreter][interpreter]. You connect a terminal
emulator to the Arduino at 9600/8N1, type the "help" command and it
displays:

    mode <pin> <mode>: pinMode()
    read <pin>: digitalRead()
    aread <pin>: analogRead()
    write <pin> <value>: digitalWrite()
    awrite <pin> <value>: analogWrite()
    echo <value>: set echo off (0) or on (1)

You can use it as a template, replace existing commands or add new ones
(the interpreter is just a long `if ... else if ...`) and – since
it's all non-blocking – add whatever you want to `loop()`.

[interpreter]: https://gist.github.com/edgar-bonet/607b387260388be77e96


body:
I am looking for a more elegant way to write a function that performs timer-based tasks as in the case of the code below, which essentially collects 5 sample values from a microphone module over a given period of time and then computes their average. It is important that it does not use the `delay()` function because other tasks are supposed to run in the background which should not be affected by the delay.

      int sensorPin = A0;
      int ledPin = 13; //  pin for the LED
      int sensorValue = 0; // variable to store the value coming from the sensor
      unsigned long timer;
      int interv = 50;
      unsigned long sampleArray[] = {0, 0, 0, 0 , 0};
      unsigned long millisaver;

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

      }

      void loop ()
      {

        if (millis() > 2000) {
          if (millis() < 2050) {
            millisaver = millis();
            timer = (int) millisaver;
            Serial.println(timer);
          }
          if ( millis() > timer && millis() < timer + interv ) {
            sampleArray[0] = sensorValue = analogRead (sensorPin);
          }
          else if ( millis() > timer+interv && millis() < timer + interv*2 ) {
            sampleArray[1] = sensorValue = analogRead (sensorPin);
          }
          else if ( millis() > timer+interv*2 && millis() < timer + interv*3 ) {
            sampleArray[2] = sensorValue = analogRead (sensorPin);

          }
          else if ( millis() > timer+interv*3 && millis() < timer + interv*4 ) {
            sampleArray[3] = sensorValue = analogRead (sensorPin);

          }
          else if ( millis() > timer+interv*4 && millis() < timer + interv*5 ) {
            sampleArray[4] = sensorValue = analogRead (sensorPin);
          }
          else if ( millis() > timer+interv*5) {
            unsigned long averageVal = (sampleArray[0] + sampleArray[1] + sampleArray[2] +sampleArray[3] + sampleArray[4])/5 ;
            Serial.println(averageVal);
            millisaver = millis();
            timer = (int) millisaver;
          }
        }
      }

title: A more elegant way to deal with timers without using delay()?

Answers: 3

body:
You need to make a function which is pretty much completely self contained. Within the function should be a counter so it knows which sample it is on, and a timestamp to know when it should next run. The function should also inform the caller when it has a full sample set to process.

I haven't tested this (don't know if it even compiles) but something like this might work:

    bool getSample(uint8_t pin, unsigned long *samples) {
        static uint32_t ts = millis();
        static uint8_t sampleNumber = 0;

        if (millis() - ts >= 50) {
            ts += 50;
            samples[sampleNumber++] = analogRead(pin);
            if (sampleNumber == 5) {
                sampleNumber = 0;
                return true; // We have 5 samples
            }
        }
        return false; // We don't have 5 samples yet.
    }

    // ... later ...

    if (getSample(sensorPin, sampleArray)) {
        // Process Samples
    }

body:
For excact timing there is feature called ADC Auto Trigger mode. For example millis() are usually counted by timer 0 overflow (on AVR based Arduinos) every 1024us (I suppose it's because of PWM - otherwise it could be set exactly to 1ms). So if you don't mind that little offset, you can configure
ADC with Timer 0 Overflow and use every 20 measure only.
But don't forget that analogRead on another pin changes ADC channel and you will get something else if you don't check it.

As an auto trigger source can be used one of these:

* Free Running Mode
* Analog Comparator
* External Interrupt 0
* Timer/Counter 0 Compare Match A
* Timer/Counter 0 Overflow
* Timer/Counter 1 Compare Match B
* Timer/Counter 1 Overflow
* Timer/Counter 1 Capture Event

For ATMega328 it can be something like this:

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

        // ADC setup is done by arduino framework, but it's possible to change it slightly (for ATMega328) :
        ADCSRB  = _BV(ADTS2); // ADTS2..0 = 100, Timer 0 overflow as trigger source
        ADCSRA |= _BV(ADATE); // enable auto trigger mode
        ADCSRA |= _BV(ADIF); // reset conversion interrupt flag (by writing log 1)

        analogRead(A0); // dummy read to set correct channel and to start auto trigger mode
    }

    int8_t sample_count = 0;
    int8_t sample_index = 0;
    uint16_t  samples[] = {0, 0, 0, 0, 0};
    uint16_t sample_sum = 0;

    void loop() {
        if (ADCSRA & _BV(ADIF)) {
            ADCSRA |= _BV(ADIF); // reset ADIF flag by writing logic 1 into it (mentioned in datasheet)
            if (++sample_count == 20) {
                sample_count = 0; // reset sample_count, as we wan't every 20th

                sample_sum -= samples[sample_index];
                samples[sample_index] = ADC; // read value
                sample_sum += samples[sample_index];

                if (++sample_index == 5) { // reset index and count and send average
                    sample_index = 0;
                    Serial.println(sample_sum);
                }
            }
        }
    }

body:
You didn't say what you want to do with those samples. If you want to
estimate the level of sound intensity, your whole approach is completely
wrong. First, your sampling rate (20 Hz) is way too low: you should
sample at least at twice the frequency of interest, typically at
8 kHz or more. Then you have to subtract the DC offset added by the
microphone module, then square the result in order to get an
instantaneous intensity, then low-pass filter to get a usable intensity
reading. As Majenko said, if you average (or low-pass filter) the
samples _before_ squaring, you would detect zero sound.

I've written a sound meter program for an Arduino Uno that does exactly
that, and it's available as a GitHub Gist:
[sound-meter.ino](https://gist.github.com/edgar-bonet/e693799f58a545ca89a2).
It uses the auto-trigger mode as explained by KIIV, but with free
running mode instead of a timer. This gives 9.6 kHz sampling rate.


body:
I'm working on Linux Mint 18 Sarah (earlier Ubuntu 16.04 LTS) system. I've installed Arduino IDE using command `sudo apt-get install arduino` and I've added me dialout group using `sudo usermod -aG dialout $(whoami)`. This is results of executing `groups` command:

    hubert@hubert-SATELLITE-C660D ~ $ groups
    dialout adm cdrom sudo dip plugdev lpadmin sambashare hubert

When I try upload following code to Arduino Leonardo:
<!-- language-all: lang-cpp -->

    /*
      Blink
      Turns on an LED on for one second, then off for one second, repeatedly.

      This example code is in the public domain.
     */

    // Pin 13 has an LED connected on most Arduino boards.
    // give it a name:
    int led = 13;

    // the setup routine runs once when you press reset:
    void setup() {
      // initialize the digital pin as an output.
      pinMode(led, OUTPUT);
    }

    // the loop routine runs over and over again forever:
    void loop() {
      digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(500);               // wait for a second
      digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
      delay(500);               // wait for a second
    }
orange LED marked with L letter on my board blinks and next I get following error:

    Wielkość binarna szkicu: 4 736 bajtów (maksymalnie: 28 672 bajtów)
    processing.app.debug.RunnerException: Couldn’t find a Leonardo on the selected port. Check that you have the correct port selected.  If it is correct, try pressing the board's reset button after initiating the upload.
     at processing.app.debug.AvrdudeUploader.uploadViaBootloader(AvrdudeUploader.java:153)
     at processing.app.debug.AvrdudeUploader.uploadUsingPreferences(AvrdudeUploader.java:67)
     at processing.app.Sketch.upload(Sketch.java:1671)
     at processing.app.Sketch.exportApplet(Sketch.java:1627)
     at processing.app.Sketch.exportApplet(Sketch.java:1599)
     at processing.app.Editor$DefaultExportHandler.run(Editor.java:2380)
     at java.lang.Thread.run(Thread.java:745)

On my IDE Arduino shows on `/dev/ttyACM0` serial port. When I try running this IDE on root privileges, I get the same error. On root privileges serial port is changing from `/dev/ttyACM0` to `/dev/ttyACM1`, from `/dev/ttyACM1` to `/dev/ttyACM2` etc. I tried different USB cabels and reset Arduino but these ways nothing help. On Windows 7 my Arduino works and Arduino IDE uploads code without problems. Can anybody help me?

title: Arduino Leonardo isn't detected by Linux Mint on serial port /dev/ttyACM0

Answers: 0


body:
I'm trying to provide analog control to a Bluetooth controlled car, via Arduino. I have joystick app (as the pot).
It send values between 0 to 255
So I'm thinking... Whether this flow down here  will work?

Joystick app --> Bluetooth Rx --> DAC --> Vs pin of L293D. Or motor?

Is Arduino required at all? Or is the serial word enough to translate into voltage via DAC?

title: Can I use a DAC with an L293D driver?

Answers: 1

body:
No, you cannot. A DAC cannot provide enough current to either directly drive a motor or to power a motor driver (which is basically driving the motor directly through a switch anyway).

A motor driver requires a PWM signal to rapidly switch a high current source on and off to set the motor speed.

You *could* feed the DAC output into the input of a voltage-to-PWM converter chip which would then feed the motor driver's EN pin, but that is pretty pointless when you could just use a small microcontroller to receive the digital speed value and directly generate a PWM signal.

After all, that is the kind of job that small microcontrollers are designed for...


body:
**Question:**
Is there a way to collect any data (e.g. MAC addresses, installed devices, driver versions, etc.) from a PC by simply connecting an Arduino via USB to it, so that this PC can be clearly identified?

**Background:**
Basically, I`m using an Arduino to send some text to a computer by emulating a keyboard, but I don´t want the text to be sent to any computer I connect the Arduino with. That is why I want the PC to be identified first.

*To be clear: this should be done without having to install programs on the PC in the first place.*

title: Identify connected PC per Arduino

Answers: 1

body: No you cannot. Arduino communicates to pc via UART so there must be a host which can send or receive the data. You have to install software on the host computer which can send and receive data to the com port to which arduino is connected to.