message:
Arduino Delivering less power

I connected 4x716 Coreless DC Motors on pin 13,12,11,10 and 1xGY-521 to  Arduino Pro Mini 328, 5v but speed of propellers is not enough to produce enough torque to lift the quad whereas when i connect then  directly to 3.3v LiPo battery the quad has lift but because of no flight control it moves randomly.

I checked the voltage of pin 13,12... they have output as 0.5-0.6v, I think this is the reason quad is not lifting.

I am using following code

    // MPU-6050 Short Example Sketch
    // By Arduino User JohnChi
    // August 17, 2014
    // Public Domain
    #include<Wire.h>
    const int MPU=0x68;  // I2C address of the MPU-6050
    int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;

    int p1 = 13;
    int p2 = 12;
    int p3 = 11;
    int p4 = 10;

    void setup(){
      Wire.begin();
      Wire.beginTransmission(MPU);
      Wire.write(0x6B);  // PWR_MGMT_1 register
      Wire.write(0);     // set to zero (wakes up the MPU-6050)
      Wire.endTransmission(true);
        pinMode(p1, OUTPUT);
      pinMode(p2, OUTPUT);
      pinMode(p3, OUTPUT);
      pinMode(p4, OUTPUT);
      digitalWrite(p1, 0);
      analogWrite(p2, 0);
      analogWrite(p3, 0);
      analogWrite(p4, 0);

      Serial.begin(9600);
    }
    void loop(){
      Wire.beginTransmission(MPU);
      Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
      Wire.endTransmission(false);
      Wire.requestFrom(MPU,14,true);  // request a total of 14 registers
      AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
      AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
      AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
      Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
      GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
      GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
      GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
      Serial.print("AcX = "); Serial.print(AcX);
      Serial.print(" | AcY = "); Serial.print(AcY);
      Serial.print(" | AcZ = "); Serial.print(AcZ);
      Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53);  //equation for temperature in degrees C from datasheet
      Serial.print(" | GyX = "); Serial.print(GyX);
      Serial.print(" | GyY = "); Serial.print(GyY);
      Serial.print(" | GyZ = "); Serial.println(GyZ);

       digitalWrite(p1, HIGH);
      analogWrite(p2, 250);
      analogWrite(p3, 255);
      analogWrite(p4, 255);

      delay(333);
    }

body:
Atmega328 output pins are rated at 40 mA absolute-maximum current, and the 328's total current through Vcc and ground pins is 200 mA absolute max.  Eg, see table 29.1 in the Atmega328 specs.

Although [some sources](http://www.quadkopters.com/product/diy-kit/716-coreless-dc-motor-high-speed-x-4/) rate a high-speed 716 coreless dc motor at 40 mA, [other sources](http://www.seeedstudio.com/depot/37V-50000RPM-Small-Coreless-Motor-716-p-1884.html) rate it at 100 mA.  In either case, it exceeds normal I/O pin capability. You should use FETs or other drivers between Arduino output pins and the motors rather than trying to drive the motors directly from digital output pins.

*Edit:* Regarding the comment, “But most projects i've seen don't use any drivers, Why so ?” I replied:
> Perhaps they are using slightly higher voltage to the Pro Mini, eg 3.7 V up to 5 V, which after accounting for voltage drop in the i/o pin circuits may deliver enough voltage to the motors. Note that a driverless circuit ie direct drive from the i/o pins operates the 328 out of its safe operating area (SOA), but it may be close enough to the safe area to usually work.

For example, some of the 716-based quadcopter pages I looked at say they used 4.2 V LiPo batteries.  Also note, 716 seems to be a fairly generic motor designation; it refers to the motor's 7 mm diameter and 16 mm length.  As a generic designation it has been used for several different motors, some of which produce less power.  For example, in [thread #1710948](http://www.rcgroups.com/forums/showthread.php?t=1710948&page=35) on rcgroups.com, people refer to different RPMs, less lift, etc. for various motors, and the importance of shaving grams off of the copter's weight to allow it to fly.

Another item that matters when drawing high current from an Atmega328 is which ports are used; and for some devices, it matters whether drive is high-side or low-side, ie whether current is sourced or sunk.  The Atmega328 spec sheet (Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf) says “Each output buffer has symmetrical drive characteristics with both high sink and source capability”, but for several kinds of drivers less voltage is lost with low-side drive than with high-side.  Ie, you could try connecting the motor's V+ lead to Vcc and its V- lead to the i/o pin, and inverting the on-off logic in the sketch. (I don't know if this will make any difference at all in how well things work.)

Regarding which ports are used, the footnotes to Table 30-1, “Common DC characteristics”, spell out various combinations of ports where total current draw must not exceed a limit (100 mA in some cases, 150 mA in others).  On the Uno and Pro-Mini, digital outputs marked 10 through 13 (as used for motor control in the question's sketch) are port B Atmega pins, with a footnoted total-current limit for the group.  If you move two of the motor drives to outputs marked 2...4 or D2...D4, then a different total-current limit will apply.  (Again, I don't know if this will make any difference at all in how well things work.)  Refer to Table 30-1 footnotes for details.

As noted in Gerben's comment, having [flyback-diodes](https://en.wikipedia.org/wiki/Flyback_diode) for the motor circuits is a good idea. This consists of placing power diodes across the motors, cathode to V+, anode to V-, to prevent energy stored in the motor's inductance from producing extreme i/o pin voltages each time the motor is turned off.

*Edit 2:* Regarding “which diode, FET to use and where [to] learn about them”, [electronics-tutorials.ws](http://www.electronics-tutorials.ws/transistor/tran_7.html) is an accurate and helpful presentation about FET digital circuits.  In particular, see the section called “An example of using the MOSFET as a switch”.

Which FETs to consider depends in part on your electronic-circuits fabrication skills.  Note that surface mount devices (SMD parts) usually weigh less than other versions of parts, which is important for a lightweight quadcopter.  However, some people find SMD parts difficult to work with.  In my opinion, the main difficulty is holding parts in their proper places while soldering them, due to small size.  (Eg, a SOT-23 SMD transistor package is on the order of 3mm x 2mm x 1mm, and a diode may be half as big.)  If you have good soldering skills and a way to hold parts in place while soldering, you should be ok, either using a printed circuit board or air-wiring parts using wire-wrap wire (ie, 30 AWG wire, about 0.25mm diameter).

Some typical logic-level-input SMD FETs are shown in [mouser.com's online catalog](http://www.mouser.com/Search/Refine.aspx?N=1323043&Keyword=logic+level+mosfet&Ns=Pricing|0&FS=True).  Note that in that list, RDS_on decreases a bunch as unit price increases slightly.  For example, the [FDN359BN](http://www.mouser.com/ProductDetail/Fairchild-Semiconductor/FDN359BN_F095/?qs=sGAEpiMZZMshyDBzk1/Wiwbr802GNVlLdK7ZHbmE8eQ=) would have under 0.1 ohm resistance when operated with Vcc = 3.7 V and currents < 100 mA.  Voltage drop running a 40 mA motor should be about 4 millivolts.

Some typical SMD Schottky diodes also are shown in [mouser.com's online catalog](http://www.mouser.com/Semiconductors/Discrete-Semiconductors/Diodes-Rectifiers/Schottky-Diodes-Rectifiers/_/N-ax1mj?P=1yzxl0uZ1yrhh8nZ1z0z5meZ1z0xoywZ1z0sou6Z1yzolw2Z1z0z5mmZ1yzteijZ1z0j8z5Z1yztawsZ1z0z4y2Z1yx5tfjZ1yrgsggZ1z0z7utZ1z0z458Z1yzolt6Z1yzsp1rZ1yzsbarZ1yuythpZ1yzspgbZ1z0z4yl).  I think even the cheapest of these would work ok.  Of course you'll need to adapt all these suggestions to your own skills, sources of parts supply, and budget.


sender: user

message:
To know the state of USB (Serial) connection (connected or not connected)

if (Serial.available()) {
            digitalWrite(7, HIGH);
    } else {
            digitalWrite(7, LOW);
    }

It doesn't seem to be so simple.
My testing LED turns on when the USB connection with another program is established, but it doesn't turn off (LOW) when that program exits.

sender: assistant

body:
The problem here is twofold.

Firstly, on Arduinos that don't have a direct USB connection, (i.e., boards like the Uno, Mega, etc that use a separate chip to manage the USB connection) you have no way of knowing if the USB is open or not.  That information simply isn't there. The main chip just receives UART serial data (*not* USB data) as it arrives and that is that.

Secondly, even on the boards that have a direct USB connection (Leonardo, etc) there is no *proper* way to know if the port has been opened or not.  The CDC/ACM protocol simply doesn't have that kind of information (a bit short sighted of them really).  The closest you can do is monitor the DTR and/or RTS signals that are encapsulated in the USB data stream.  It is down to the host operating system (and maybe even your own program) to exert those signals properly, so isn't foolproof even then.

To check the status of those lines in your sketch you can examine the *boolean operator* of the `Serial` object:

    if (Serial) {
      // I am connected
    } else {
      // I am not connected
    }

But as I say that can only work on boards like the Leonard - the other indirect boards think they are always connected, since there is no such thing as a *connection* in UART terminology, only data.


body:
<!-- language-all: lang-C++ -->

> How about having the other program send data to Arduino and Arduino knowing the connection is lost when new data isn't received? I have no idea what Arduino code would do that but just an idea.

That sounds simple enough.

    const unsigned long MESSAGE_TIMEOUT = 10UL * 1000;  // 10 seconds

    void setup ()
      {
      Serial.begin (115200);
      while (!Serial) ;  // wait for Serial to become active
      Serial.println ("Starting");

      }  // end of setup

    unsigned long lastMessage;

    void processInput ()
      {
      while (Serial.available ())
        {
        char c = Serial.read ();
        // do something with the data
        }  // end of while loop
      }  // end of processInput

    void loop ()
      {
      if (Serial.available ())
        {
        lastMessage = millis ();  // remember when we last got input
        processInput ();  // now handle the input
        }

      if (millis () - lastMessage >= MESSAGE_TIMEOUT)
        {
        // we don't seem to be receiving data
        }

      }  // end of loop


message:
How Add Piezo Buzz to Pong Sketch

I am junior high teacher teaching students how to program using Arduino. I know the basics of programing but the students wanted to program a game which is a little above my skill set. I am using the following sketch (http://www.itopen.it/arduino-pong-with-8x8-led-matrix-and-max7219/) to introduce them to programing games. Thanks to this site I understand most of the code. However I would like to add a line of code that will make a piezo buzzer buzz every time the "ball" hits the pad. I think the code should look something like the code bellow, but I am not sure if it is correct or where I would put it.

    #define buz 8 // number of pin buzzer connected to
         if (HIT_CENTER || HIT_RIGHT || HIT_LEFT) {
            digitalWrite(buz, HIGH);
            delay(100);
            digiralWrite(buz, LOW);
            }

Any help would be appreciated.

body:
The condition `HIT_CENTER || HIT_RIGHT || HIT_LEFT` will always be true.  (All three of those `HIT_` values are non-zero constants.)

Instead, you need to test if `getHit()` is non-zero.  (To see this, search the sketch for occurrences of `HIT_RIGHT` or `HIT_LEFT`.)

The sketch sets up an event timer (via `ball_timer = timer.every(BALL_DELAY, moveBall);` in `setup()`) so that ball position will update every 200 ms.  The `loop()` sequence is: Use `timer.update()` to service timer events.  Use `setPad()` to read the paddle position.  Use `drawGame()` to update the game picture. Somehow use `checkLoose()` to see if game is over.  Use `delay(GAME_DELAY)` to wait 10 ms.

Given that structure of `loop()`, throwing in a 100 ms delay to wait for a buzzer would mess up the game play.  You could turn on the buzzer and set up a timer event for turning it off, each time the ball hits the paddle.

More straightforwardly, since a 10 ms beep is likely to be adequately long, you could test for a hit just before `delay(GAME_DELAY)`, and always turn the buzzer off just after that delay.  In other words, before the delay say:
`if (getHit()) digitalWrite(buz, HIGH);` and after the delay say `digitalWrite(buz, LOW);`.

This supposes that writing HIGH to `buz` turns on the buzzer and that writing LOW turns it off.


body:
**Method 1:**
here is what i would have done is use this code snippet we can get the state of HIT,,,if it is not equal to HIT_NONE ,buzz it

     #define buz 8
     if(getHit()!=HIT_NONE){
        digitalWrite(buz, HIGH);
        delay(10);
        digitalWrite(buz, LOW);
        }

This is the simpler version where in delay is small,Beaware using delay will completely halt processor operation ,buttons ,joystick serial ports etc everything will be halted.

**Method 2:With Flexible Delay**

      #define buz 8
      unsigned long previousMillis = 0;
      const long interval = 200;   /////Specify the delay you want here
      void loop()
       {
         unsigned long currentMillis = millis();  //start timer
         /*
             Remaining Code Is Left As It Is
         */
       }

           ///////////Code Snippet Without Using Delay
       if(getHit()!=HIT_NONE){
       digitalWrite(buz, HIGH);
       if (currentMillis - previousMillis >= interval)
            {
                previousMillis = currentMillis;
                digitalWrite(buz, LOW);
            }
       }

But where to add these functions???
Use ***getHit()*** to implement ,,,just like below

      int getHit() {
      if(yball != 6 || xball < xpad || xball > xpad + PADSIZE){
        return HIT_NONE;          //returns in case of hit failure so no
                                  // buzzer ring
         }
            digitalWrite(buz, HIGH);    //If it has not returned yet makes
            delay(10);                  //sure that it is a successful hit
            digitalWrite(buz, LOW);     //buzzer ring
      if(xball == xpad + PADSIZE / 2){
        return HIT_CENTER;
         }
       return xball < xpad + PADSIZE / 2 ? HIT_LEFT : HIT_RIGHT;
     }

yet again u can replace those 3 lines with below one to be more flexible

    digitalWrite(buz, HIGH);
    if (currentMillis - previousMillis >= interval)
         {
             previousMillis = currentMillis;
             digitalWrite(buz, LOW);
         }
    }

hope this helps.


message:
make Arduino tell when the Python program stops reading from the Serial (crash, etc)

Here's the Arduino code:

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

      pinMode(7, INPUT_PULLUP);
    }

    void loop() {
        int val = digitalRead(7);
        if (val == HIGH) {
            Serial.print("1");
        } else {
            Serial.print("0");
        }
        Serial.println("");  // new line

    }

Python code:

    import time
    import serial

    # setup Arduino USB communication
    try:
     arduinoSerialData = serial.Serial('com3', 9600)

    except: # not connected/damaged
     pass

    while True:
     if arduinoSerialData.inWaiting() > 0:
      datastr = arduinoSerialData.readline()
      print datastr
      time.sleep(1)

WHat I want to add is, if Python program exits, or crashes, let the Arduino know somehow. More specifically turn on a LED in pin 8.

body:
There is no way to know if the connection has closed or not, you can only know if the connection *was* working at some point in the past.

Your communication protocol as shown is only *half duplex* (i.e., it's only one way - the Arduino sends to Python but never the other way around) which simplifies things somewhat.

There are a number of strategies you can employ in your case, and any number of them can be combined to create a system as robust (and complex) as you like.

First you would need to make your protocol *full duplex*.  This is, you need your Python program to be able to send information to the Arduino.  Since you aren't doing that at the moment the implementation of it can be in any way you like.

One method you can use is called [Keepalive](https://en.wikipedia.org/wiki/Keepalive).  In this system the Python program will periodically send an "I am here" message to the Arduino.  The Arduino receives these messages and remembers when the last one was (hint: use the `millis()` function).  If a message hasn't been received for more than a pre-defined timeout period the link is assumed to be dead.

Another method which is good if you are sending data very regularly from the Arduino to the Python program is to use a system of *acknowledgements*.  In this situation every bit of data sent to the Python program is followed by the Python replying with an "I got that" message.  If the Arduino doesn't get that response after sending its data within a certain timeout period (can be much shorter than for a keepalive timeout) then the link is assumed to be dead.

Wrapped around both these methods you can add an "I have arrived" and an "I am leaving" message.  These are sent by the Python program when it starts and just before it's about to exit so the Arduino knows when the link *should* be alive and when it *shouldn't*.  If it gets an "I am leaving" message then it knows that it shouldn't care whether it gets any acknowledgement or keepalive messages, so it doesn't need to think about timeouts. Only after it has received an "I have arrived" message should it start caring.

So for instance your protocol, with all these things implemented, might look like this (`>>` = message from Arduino to Python, `<<` is message from Python to Arduino):

    >> 1
    >> 1
    >> 1
    >> 0
    >> 0
    >> 1
    << A    - I have arrived
    >> 1
    << Y    - Yes, I got that
    >> 1
    << Y    - Yes, I got that
    >> 0
    << Y    - Yes, I got that
    << K    - keepalive - we know the link is alive and working.
    >> 0
    << Y    - Yes, I got that
    >> 1
    << Y    - Yes, I got that
    (Program crashes now.)
    >> 1
    *no Y received - assume connection is closed*
    >> 1
    ... etc ...

In this instance the 0 and 1 are what you are sending at the moment.  A is an "I have **A**rrived" message, Y is a "**Y**es I got that" message, K is a "**K**eepalive" message, and if the program had exited cleanly an L would have been an "I am **L**eaving" message.

Keeping the messages simple (single characters) means it's really easy for the Arduino to parse those messages and work out what is going on.

There is a certain amount of balancing act to be performed when implementing your system between how often you are sending data and how long you are willing to wait for a valid response or message to flag the connection closed.

Expanding your existing example program to incorporate these messages might look like:

    unsigned long lastKA = 0;
    unsigned long lastSent = 0;
    boolean isConnected = false;

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

      pinMode(7, INPUT_PULLUP);
    }

    void loop() {

        // Check the timeouts if we are connected
        if (isConnected) {

            // First check to see if the Keepalive timeout has passed
            if (millis() - laskKA > 5000) { // 5 second keepalive timeout)
                isConnected = false;
            }

            // If we have sent data...
            if (lastSent > 0) {
                // ... check that we got a response in time
                if (millis() - lastSent > 100) { // 100ms Y timeout
                    isConnected = false;
                }
            }

        }

        // If we are connected then send some data
        if (isConnected) {

            int val = digitalRead(7);
            if (val == HIGH) {
                Serial.print("1");
            } else {
                Serial.print("0");
            }
            Serial.println("");  // new line

            // and set the timer for the response
            lastSent = millis();
        }

        // Now process incoming messages.
        if (Serial.available()) {
            int c = Serial.read();

            // If the message is an A then turn on the connection and
            // treat it as a Keepalive as well.
            if (c == 'A') { // Arrived
                isConnected = true;
                lastKA = millis();

            // If it's a Leaving message then turn off the connection.
            } else if (c == 'L') { // Leaving
                isConnected = false;

            // If it's a Keepalive then reset the timer.
            } else if (c == 'K') { // Keepalive
                lastKA = millis();

            // A Y acknowledgement will disable the sent timer.
            } else if (c == 'Y') { // Yes
                lastSent = 0; // Cancel the sent timer
            }
        }
    }


message:
AnalogWrite custom voltage

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

I want to get a low voltage on output pin of Arduino mega. I have connected Pin 46 to A3, and wrote 120 value to 46 port. Expected was to get 2-3v on A3 input pin. Instead I always get 1023 values as input. Am I doing something wrong ?

    void setup(){
      Serial.begin(9600);
      pinMode(46, OUTPUT);
      pinMode(A3,INPUT);
      }

    void loop(){
      analogWrite(46,120);
      Serial.println(analogRead(A3));
      }

body:
The analog outputs aren't real analog outputs, they are PWM.

That means that they rapidly switch from OFF to ON and back to OFF again.  The analog value is the ration of OFF time to ON time, known as the *Duty Cycle*.

You can convert that rapid switching to a real voltage by passing the signal through a *low pass filter*.  The simplest form is the RC filter:

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

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


message:
Pyserial serial.write() doesn't work

I need to communicate with an Arduino. When I use `serial.readline()` to read what Arduino has to say it works fine. But when I use`serial.write('something')` doesn't seem to do anything.

Interesting thing is that if I write the same code in the console or command-line, it works as expected...

Using Python 2.7.

Python code:

    import serial
    import time

    arduinoSerialData = serial.Serial('com6', 9600)
    time.sleep(1)

    while True:
        arduinoSerialData.write('AAA')
        arduinoSerialData.flush()
        sleep(0.5)

Arduino code:

    void loop() {

    if (Serial.readString().startsWith("AAA")) {
        digitalWrite(7, LOW);
    } else {
        digitalWrite(7, HIGH);
    }

    delay(500);

Again, Python code runs fine from the console, so no idea why this happens.

body:
<!-- language-all: lang-C++ -->

Closely related to <https://arduino.stackexchange.com/questions/16207/know-the-state-of-usb-serial-connection-coonected-or-not-connected>

---

I would not be using `Serial.readString()` personally. How do you know where the string starts and ends? Just check for three "A" in a row.

Like this:

    const unsigned long MESSAGE_TIMEOUT = 10UL * 1000;  // 10 seconds
    const byte LED = 7;

    void setup ()
    {
      Serial.begin (115200);
      while (!Serial) ;  // wait for Serial to become active
      Serial.println ("Starting");
      pinMode (LED, OUTPUT);
    }  // end of setup

    unsigned long lastMessage;
    unsigned int countOfA;

    void processInput ()
    {
      while (Serial.available ())
      {
        char c = Serial.read ();
        if (c == 'A')
          countOfA++;
        else
          countOfA = 0;
        // do something with the data
      }  // end of while loop
    }  // end of processInput

    void loop ()
    {
      if (Serial.available ())
      {
        lastMessage = millis ();  // remember when we last got input
        processInput ();  // now handle the input
      }

      if (millis () - lastMessage >= MESSAGE_TIMEOUT)
      {
        countOfA = 0;
      }

      // warn if no keepalive received
      if (countOfA >= 3)
        digitalWrite(LED, LOW);
      else
        digitalWrite(LED, HIGH);

    }  // end of loop

Note that this will fail (ie. it will light the LED) if it gets something other than "A" which would include newlines, etc.

What it does it count the number of times it gets the letter "A". If it gets something else it resets the count. If 10 seconds elapse without receiving something, the count resets.


message:
Loading Leonardo bootloader to Atmega32U4 running at 8 MHz

I am currently using ATMega32U4 running at 16MHz using Leonardo. I can only supply 3.7V (I use LiPo batteries) and everything seems fine but this is not as per specs.

To run at 16 MHz, I have to supply 5V but I can't. I do not want to do any step-up. I am thinking of of using 8 MHz crystal so the processor will require only 3.3V, but I need to use a Leonardo.

Has anyone been successful in doing this?

body:
<strike>The bootloader does USB. I don't think you can do USB on the 32u4 on only 8mHz. </strike>

You can however set the system clock prescaler to divide the main clock by 2, making it run at 8mHz. The bootloader will however still run at 16mHz, but that's probably still fine (though out of spec).

> The AVR USB has a system clock prescaler, and the system clock can be divided by setting the “CLKPR – Clock Prescaler Register” on page 38. This feature can be used to decrease the sys- tem clock frequency and the power consumption when the requirement for processing power is low. This can be used with all clock source options, and it will affect the clock frequency of the CPU and all synchronous peripherals. clkI/O, clkADC, clkCPU, and clkFLASH are divided by a factor as shown in Table 6-10.

To divide the system clock by 2, set the CLKPS0 bit in the CLKPR register. The code for this would be something like this:

    void setup()
    {
      cli();
      CLKPR = _BV(CLKPCE);
      CLKPR = _BV(CLKPS0);
      sei();

      ...

just note that everything runs twice as slow. So `delay(1000)` will take 2 seconds. You'll have to update F_CPU somehow to fix this if this causes a problem.


message:
Sending a value from one arduino to another

I wonder if it is possible to send a value from one  arduino to another.

Basically, I have one arduino measuring let's say weight, but I want to display that value using an lcd in another arduino.
Is it possible to  send the value to a pin using analogwrite or digital write in the arduino doing the measurement and use analogread/digitalread at the other arduino making the display?

I do not know if this is possible but what is attractive is that one can have several arduino making weight measurements, all showing up in the display of just one central one...

body:
Yes it is possible,The answer provides one of the basic methods to do so

Connections

       Arduino1          Arduino2
         TX--------------->RX
         RX--------------->TX

Arduino1 Sketch:

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

    void loop() {
     ////read sensor data to a variable
     Serial.println(sensorDataVariable);
     delay(2000); //Not to flood serial port
    }

Arduino2 Sketch :

    int byteRead;
    void setup(){
     Serial.begin(9600);
     delay(2000);
    }

    void loop() {
      /* check if data has been sent from the computer: */
      while (Serial.available()) {
        /* read the most recent byte */
        byteRead = Serial.read(); //now byteRead will have latest sensor
                                  // data sent from Arduino1
      }
      //Write code to display the values to LCD
    }

hope this helps


body:
To tie multiple Arduinos together you need to come up with some kind of networking topology and some form of networking protocol.

Requirements are:

1. The Arduinos must not (electrically) interfere with each other
2. There must be some way to know which Arduino is sending what and where to

The two points could be addressed by having a separate connection for each Arduino but that ends up complicated, and there are only limited resources on an Arduino for creating such connections (you really need to use the hardware UART ports and the Uno has only 1. The Mega has 4).

A better solution is to use a *bus* system (also known as a *multi-drop network*).  There are a number of existing and well supported methods for doing this.  In the automotive system the [CAN Bus](https://en.wikipedia.org/wiki/CAN_bus) is used.  In industry the [RS-485](https://en.wikipedia.org/wiki/RS-485) system is heavily used.

Personally I prefer RS-485 since it is well established.  There are a number of standard protocols that run on RS-485, such as [MODBUS](https://en.wikipedia.org/wiki/Modbus), but for the Arduino world I wrote my own light weight protocol specially which is far simpler to get going with.  You can find out more here: https://github.com/MajenkoLibraries/ICSC


body:
You could have the LCD Arduino be an I2C master and all the weighing Arduinos be slaves. There's an example of master/slave communication and wiring here: https://www.arduino.cc/en/Tutorial/MasterReader.

I2C supports up to 128 devices and the wiring is very simple.


message:
how to detect 125khz tags with mfrc 522

I have just ordered MFRC 522 RFID reader from amzon, and I have also orders 5 RFID tags with keychains and a arduino uno board for my project, I have received RFID reader and tags and I have tested the tags with my Sony xperia NFC. The tags that I received with the readers are working fine but the key chain ones are not working. I think because of the frequency difference 13.56 MHz and 125 KHz. So, please tell will this key chain tags work with the Reader

body:
You are correct NFC is 13.56MHz the key chain ones you are referring to are most likely 125kHz The reader you have will only read 13.56MHz this is the NFC and HID cards. If you want to read the Key Chain ones you will need a reader like this one. [Weigand 26 Card Reader][1] Most Phones will not read the 125kHz

  [1]: http://www.amazon.com/gp/product/B0075DTXYY?psc=1&redirect=true&ref_=oh_aui_detailpage_o02_s00


body:
You can buy a 125 kHz reader from eBay for around $7. I got one like this:

[![RFID reader][1]][1]

You can communicate with it (listen to it) with a single serial pin (plus ground and power of course). I have a [post about that board](http://www.gammon.com.au/forum/?id=12849) which describes the connections.

---

> So, please tell will this key chain tags work with the Reader

No, the 125 kHz tags won't work with the 13.56 MHz reader. However you can work around this (if you want to) by using the 125 kHz tags with a different reader.

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


message:
Yun did not connect to WiFi after configuration and restart

When examined we find that Yun is still in master mode and 0% signal.

Any procedure known to solve this problem manually?

We can access Linux command under Mater mode AP-mode and print WiFi status

    /usr/bin/pretty-wifi-info.lua

We know procedure to change REST API access

  Method II:  config file

    opkg update
    opkg install nano
    nano /etc/config/arduino

    config arduino
            option password '775e9f944188a7bcb36e9ca5dc51672b44bcceeb7d56d89dfb914e$
            option wifi_reset_step 'clear'
            option secure_rest_api 'true'
    ...

  Merhod 1:  UCI API    need access to the Linux system by YSM program

PASSWORD

    uci set arduino.@arduino[0].secure_rest_api=true

OPEN:

    uci commit arduino

Is there any procedure manually to perform the configuration by hand for the mode:

 - change to client?
 - then restart?
 - from master mode where we have access to Linux command line?

This question has been left unanswered before in all forums examined.
Maybe someone knows the answer.

The problem lies in the Linux not in the hardware or routers or PC, as proven by testing.

body:
My wireless config is in the /etc/config/wireless, not in the /etc/config/arduino

How do you configure your Wifi ?
There is at least 4 methods  :
you can do this through OSJS, through LUCI, through ARDUINO IDE, or with UCI.


message:
Arduino as voltage monitor shorts to ground

I need to monitor voltages of several DC circuits in a generator's contact box.  Whenever the generator has an alarm, a LED is lit in the box and voltage on the line drops to zero.  I successfully get readings using analogRead(), but whenever I connect a line it shorts to ground (which is shared between the contact box and the Arduino) and triggers the contact box's alarm.  I need to devise a way to monitor voltages without triggering the alarm.

Each 5V line and ground from the generator has a bus bar termination point that connects to a point in the proprietary alarm box that houses the LEDs and buzzer. I connected Arduino ground to generator ground, then used A0-A7 on a Nano to connect to individual lines on the bus bar. Arduino VCC is connected to 5V regulated DC power.

body:
A voltmeter does not have a ground reference. An Arduino plugged into the USB port would have one. Conceivably a battery-powered Arduino might work, however a safer solution would be to use an opto-isolator to isolate the voltage being tested from the Arduino. Something like this:

[![Opto isolator][1]][1]

In this case you connect the "data pin" to the thing you are sensing. If it is at 5V then the LED will conduct (taking around 7 mA) and the transistor in the isolator will drive the Arduino pin `LOW`. If the data pin goes to zero volts, the transistor will not conduct, and the 1k resistor will pull the Arduino pin `HIGH`. Thus you can detect if the pin has changed voltage.

The 560 ohm resistor is a current-limiting resistor for the LED in the isolator. A 1k resistor would probably also work, reducing the current draw on the data pin to around 3.8 mA.

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


message:
Can we connect 4 4-digit 7 segment LED Displays to a single Arduino board?

Can we connect 4 4-digit 7 segment LED Displays to a single Arduino board ? Is it possible without another component in between ?

body:
You need 4*4+7 = 23 pins in common cathode configuration or 4 +7*4 = 32 in common anode and arduino uno only have 20 output/input pins so if you don't want to use any external component you are going to need an Arduino mega.

Anyway, the best idea is to use a max7219 matrix led driver. look for it in google.


body:
Actually, this is dependent on the datasheet. Assuming it's 7 segment + dot, it will require 8 independent pins to control each of the segment. All of segments are connected to a common anode/cathode which can be connected to a pullup/pulldown.

If we have 4 digit, that means we need 4*8=32 pins, which is a lot for any microcontroller. However, if you map out the internal circuit, you'll find that the segments are multiplexed. (You can do this by touching the pins with a wire connected to a pullup resistor, and another wire connected to ground.

Generally, you'll find that all the segment pins are multiplexed together in such a way that if all anodes/cathodes are enabled, all of the digits show the same display.

So how then can we make use of this information? Here's an idea:

How about turning on each of the digits one at a time (by controlling the common anode/cathode), but doing it quickly?

An example sequence would be as follows:
Set the segments for digit 1, enable the corresponding common anode/cathode for 5ms. Turn off.
Set the segments for digit 2, enable the corresponding common anode/cathode for 5ms. Turn off.
Do the same for digit 3 and then 4.
Repeat.

Controlling in this manner means you only need 8+4 pins=12 which is available on an arduino uno. Refreshing at 4*5=20ms will hardly be visible to our human perception, thanks to persistence of vision.

My answer is really just a starting point. If you spend some time, you can try to put in other smarts which are suited for your application, using even less pins. You should try this as an exercise. ;-)

Edit:
As a precaution, it's important to limit the current running through each of the LED segments so that they can live a long and happy life.

Assuming a forward voltage of 2V, adding a 1k resistor at the common anode limits the current to 3mA. This means adding resistors for all 4 anodes.

The same could work for common cathode displays, as long as the reverse breakdown voltage is not exceeded.

As with all things you find on the net, don't take my word for it. You should do the maths to check.


message:
Is it possible to create an electromagnetic wave using PWM?

What would be the simplest way of making an Arduino emit EM waves using PWM (or without)? Theoretically, oscillating a current through a wire would result in an electromagnetic wave, but I don't know if this is possible using an Arduino and if so, how?

body:
<!-- language-all: lang-C++ -->

I had a toy project a while ago that generated AM radio.

---

## Code

Code for Uno or any Atmega328 based boards:

    const byte ANTENNA = 9;

    void setup()
      {
      // set up Timer 1
      TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
      TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaler
      OCR1A =  9;       // compare A register value to 10 (zero relative)
      }  // end of setup

    void loop()
      {
      pinMode (ANTENNA, OUTPUT);
      delay (500);
      pinMode (ANTENNA, INPUT);
      delay (300);
      }  // end of loop

---

## Wiring

 Plug a wire into digital pin 9:

[![AM radio][1]][1]

---

## Theory

The 16 MHz clock is divided by 10 (that is, 1.6 MHz) and that is used to toggle pin 9 at that rate, giving a frequency of 800 kHz, since one toggle turns the output on, and second toggle turns it off.

Then by turning the output pin on and off slowly you effectively have "keyed" output.

Obviously this would not have a long range, but you could amplify the output signal.

---

> What does the timer code do?

It's a bit easier to understand if you look at the datasheet. I did a summary for Timer 1 (and the other two timers on the Atmega328) a while back.

## Timer 1

[![Timer 1 chart][2]][2]

The lines assigning to TCCR1A and TCCR1B set various bits as per the chart / datasheet. Then OCR1A is the value that the timer counts to, zero-relative, so it counts to 10.

The prescaler is set to 1, so each "tick" is 1/16000000 of a second (62.5 ns). Count 10 of them and you have 625 ns per tick. The timer is configured to toggle an output pin automatically. Since it takes two toggles (on and off) for one frequency "cycle" the period is 1.250 µs. The inverse of that is 800000. Thus the output frequency is 800000 Hz (800 kHz).

  [1]: https://i.stack.imgur.com/qHyEP.jpg
  [2]: https://i.stack.imgur.com/TflBq.png


message:
What is the I2C address of a sensor?

I have connected BMP180 sensor:

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

to Arduino and was able to read its values with appropriate samples (from [`Adafruit BMP085 Library`][2] and [`Adafruit BMP085 Unified`][3]).

Apparently, this sensor is sending information via [I2C bus][4].

However, I2C protocol assumes addresses of connected devices.

What are addresses in my case? How to know and/or change them?

Is it possible to connect several BMP180 to a single Arduino?

  [1]: https://i.stack.imgur.com/lWCYy.png
  [2]: https://github.com/adafruit/Adafruit-BMP085-Library
  [3]: https://github.com/adafruit/Adafruit_BMP085_Unified
  [4]: https://en.wikipedia.org/wiki/I²C

body:
Line 30 in [Adafruit_BMP085.h][1] clearly give you the address of sensor. Looks like the address is fixed meaning the only way you can connect several of these sensors is using a i2c multiplexer

  [1]: https://github.com/adafruit/Adafruit-BMP085-Library/blob/master/Adafruit_BMP085.h


body:
<!-- language-all: lang-C++ -->

From the datasheet:

> **4.2 Device and register address**
>
> The BMP085 module address is shown below. The LSB of the device address distinguishes between read (1) and write (0) operation, corresponding to address 0xEF (read) and 0xEE (write).

With the Wire library you divide that by 2 (because it handles the read/write bit) so the address for using with Wire is:

    0xEE / 2 = 0x77

Which is mentioned in the Adafruit library:

    #define BMP085_I2CADDR 0x77

> Is it possible to connect several BMP180 to a single Arduio?

You can certainly connect **two** of them. From the datasheet:

> There is an easy way to connect two BMP085 to the same I2C bus: You can use the XCLR input of BMP085 to set one BMP085 part silent while you communicate with the other BMP085 part via I2C and vice versa. The signals can be provided by two digital outputs of the microcontroller, or one digital output and one inverter.

If you have access to the XCLR input (the Adafruit board broke it out, I can't tell with the board in your photo) you could use that method. Otherwise do what some of the other answers suggested, and use an I2C multiplexer.


message:
Is it possible to make an arbitrary lake bottom generator?

I'm trying to generate an arbitrary lake bottom sonar returns using my Arduino.

I would like to seed a function with a "depth." This would be the starting depth. I would then like to randomize a set of parameters each time the function is called. **The output would look something like a time-truncated sine wave. The parameters would include:**

 1. Randomized Amplitude of waveform (which wouldn't vary too much)
 2. Randomized Period (or frequency) of waveform (also wouldn't vary too much)
 3. Randomized exit point. Say the period is 10 seconds but function ends at 7 seconds. This would allow for a changing in depth over time even if random.
 4. If possible, I would like to low pass filter the output to smooth any hard transitions.

Any suggestions on where to get started?

body:
A common method of generating realistic-ish 3d terrain is as follows:

Start with a square (as seen top-down), described by the lengths of it's side (all the same), and the height of each of the corners.

Divide each edge in half; for example, add a new point halfway between the north-west point and the north-east point; it's altitude will be the average of the altitude of the two existing points, plus or minus a random number.

Now add a point in the center of the existing square; it's altitude being the average of the north, east, west and south points you've just created, plus or minus a random number.

You now have 4 smaller squares. Repeat this process on the four smaller squares, then the smaller squares within that, and so forth.

You might want to manually do the first few points, tweaking it to get the shape you want, then leave the details to the algorithm. Your random number for the adjustments of the "middle point" heights should be proportionate to the length of the sides; for example, the random altitude adjustment might be a random number up to X% the length; then subtract half of X% of the length. Adjusting X% will give you an area that is more or less "pointy".


message:
What's wrong with my ESP8266?

After trying to upgrade firmware of ESP8266, it failed. I am not finding any response from it. It's just blinking a red LED.

What will I do now?

---

I had tried to upgrade the firmwire in different ways...but couldn't.The result is that i am not finding any wifi signal response in the network connection ...What's now?

body: The upgrade firmware on the ESP8266 is hardcoded. Attempting to reflash it with known good firmware should restore functionality.


body:
Make sure you have the correct firmware depending on the version of the board you have, the family seems quite big:
[esp8266 wiki][1]

  [1]: http://www.esp8266.com/wiki/doku.php?id=esp8266-module-family

There's nothing stopping you from experimenting and flashing different versions until you find the one that works.


body: Make sure that GPIO0 is not shorted to ground. Otherwise, try to reflash the firmware and when finished, leave GPIO0 floating to get out of firmware upgrading mode.


message:
Fog Machine - On Command

I work with a marching band, and we want to use fog machines for a particular part of the show. I know how to code/program in Arduino, however I am not great in the electrical and technical end. I own two fog machines, and the issue is that we need them to start fogging on command without delay (at least not a long delay, just not early and not late). We cannot exactly stop the show in the middle of a competition to say "wait, the fog is coming soon." We also need them to stop fogging on command.

I have read this article, [Motion Triggered Fog Machine][1] and it seems simple enough, however, I do not need or want it to work with a motion sensor. I suppose the easiest way you could help me is to either point me to a tutorial or tell me how to modify that tutorial to my own needs.

  [1]: http://www.instructables.com/id/Motion-Triggered-Fog-Machine/step1/The-Relay/

body:
Perhaps use a small wireless board like the NRF24L01 (available for around $1 each on eBay). Have one at the fogging machine, similar to the Instructable, but instead of a sensor, you turn the machine on and off when a command arrives. For example, send "0" to turn it off and "1" to turn it on. There are examples with the [NRF24L01 library](http://tmrh20.github.io/RF24/index.html).

[![NRF24L01 module][1]][1]

Then you have an Arduino in the wings nearby where you press a switch when you need to turn the fogging machine on (this would transmit the signal).

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


message:
Memory organisation of MIFARE 1K

I'm trying to use a MIFARE 1K RFID card with RC522 RFID reader/writer for my college project.
I'm trying to understand about memory organization of MIFARE 1K.A documentation() that supplied with a RFID Arduino library() says like this.
I will very appreciate if someone explain me this portion clearly.

> The MIFARE Classic 1K offers 1024 bytes of data storage, split into 16 sectors; each sector is protected by two different keys, called A and B. Each key can be
programmed to allow operations such as reading, writing, increasing valueblocks,
etc. MIFARE Classic 4K offers 4096 bytes split into forty sectors, of which 32 are same size as in the 1K with eight more that are quadruple size sectors. MIFARE Classic mini offers 320 bytes split into five sectors.
For each of these card types, **16 bytes per sector** are reserved for the keys and access conditions and can not normally be used for user data. Also, the very first 16 bytes contain the serial number of the card and certain other manufacturer data and are read only. That brings the net storage capacity of these cards down to 752 bytes for MIFARE Classic 1k, 3440 bytes for MIFARE Classic 4k, and 224 bytes for Mini. It uses an NXP proprietary security protocol (Crypto-1) for authentication and ciphering.

Accordind to above quote,

>For each of these card types, **16 bytes per sector** are reserved for the keys and access conditions and can not normally be used for user data.
> Blockquote

Explain how to divide 1024 bytes like this.It has 16 sectors.So,total memory should be 16*16=256 bytes.This is impossible. Please explain this.

body:
You're reading (and doing your sums) backwards.

You have 1024 bytes of data space.

That data space is split into 16 sectors, so 1024 / 16 = 64 bytes per sector.

Each sector has 16 bytes reserved for keys etc, so each sector has 64 - 16 = 48 bytes of user data space.

48 bytes of user data space per sector multiplied by 16 sectors is 768 bytes.

Incidentally 1024 - 768 = 256, which is what you were calculating before.  What you calculated was the amount of the 1024 bytes that is reserved *in total* for the keys and access controls.


body:
Divide 1024 bytes into 16 sectors -

    1024 bytes / 16 sectors = 64 bytes per sector

The first 16 bytes of each sector are used for 'management' and thus reserved. This leaves -

    64 - 16 = 48 bytes (per sector) for general storage


body: There is also an excellent graphic of the various mifare card layouts, that someone has put together: https://upload.wikimedia.org/wikipedia/commons/thumb/3/39/MiFare_Byte_Layout.png/220px-MiFare_Byte_Layout.png


message:
Esp8266 Arduino smart connect

Below i have an example of a temperature sensor.What i need to be able to set the username an password dynamically before connecting to my home router.It would ask me for the ssid and password for example.example. Ive seen a couple of posts about this with no definitive code to show how it would work.If anyone has experience with this could they comment here please.

    #include
    #include
    #include
    #define ONE_WIRE_BUS 8
    OneWire oneWire(ONE_WIRE_BUS);
    DallasTemperature sensors(&oneWire);

    #define SSID "[YOUR_SSID]"
    #define PASS "[YOUR_PASSWORD]"
    #define IP "184.106.153.149" // thingspeak.com
    String GET = "GET /update?key=[THINGSPEAK_KEY]&field1=";

    void setup()
    {
      Serial.begin(9600);
      sensors.begin();
      Serial.println("AT");
      delay(5000);
      if(Serial.find("OK")){
        connectWiFi();
      }
    }

    void loop(){
      sensors.requestTemperatures();
      float tempC = sensors.getTempCByIndex(0);
      tempC = DallasTemperature::toFahrenheit(tempC);
      char buffer[10];
      String tempF = dtostrf(tempC, 4, 1, buffer);
      updateTemp(tempF);
      delay(60000);
    }

    void updateTemp(String tenmpF){
      String cmd = "AT+CIPSTART=\"TCP\",\"";
      cmd += IP;
      cmd += "\",80";
      Serial.println(cmd);
      delay(2000);
      if(Serial.find("Error")){
        return;
      }
      cmd = GET;
      cmd += tenmpF;
      cmd += "\r\n";
      Serial.print("AT+CIPSEND=");
      Serial.println(cmd.length());
      if(Serial.find(">")){
        Serial.print(cmd);
      }else{
        Serial.println("AT+CIPCLOSE");
      }
    }

    boolean connectWiFi(){
      Serial.println("AT+CWMODE=1");
      delay(2000);
      String cmd="AT+CWJAP=\"";
      cmd+=SSID;
      cmd+="\",\"";
      cmd+=PASS;
      cmd+="\"";
      Serial.println(cmd);
      delay(5000);
      if(Serial.find("OK")){
        return true;
      }else{
        return false;
      }
    }

body:
The following code can do what you want ([source](https://gist.github.com/dogrocker/f998dde4dbac923c47c1)), all that is needed is to combine it with the sensor code. The default behaviour is to create an access point when it can't connect to the eeprom stored WiFi station but you can modify it to trigger with a button/jumper or any other way you prefer.

    #include <ESP8266WiFi.h>
    #include <ESP8266WebServer.h>
    #include <EEPROM.h>

    ESP8266WebServer server(80);

    const char* ssid = "test";
    const char* passphrase = "test";
    String st;
    String content;
    int statusCode;

    void setup() {
      Serial.begin(115200);
      EEPROM.begin(512);
      delay(10);
      Serial.println();
      Serial.println();
      Serial.println("Startup");
      // read eeprom for ssid and pass
      Serial.println("Reading EEPROM ssid");
      String esid;
      for (int i = 0; i < 32; ++i)
        {
          esid += char(EEPROM.read(i));
        }
      Serial.print("SSID: ");
      Serial.println(esid);
      Serial.println("Reading EEPROM pass");
      String epass = "";
      for (int i = 32; i < 96; ++i)
        {
          epass += char(EEPROM.read(i));
        }
      Serial.print("PASS: ");
      Serial.println(epass);
      if ( esid.length() > 1 ) {
          WiFi.begin(esid.c_str(), epass.c_str());
          if (testWifi()) {
            launchWeb(0);
            return;
          }
      }
      setupAP();
    }

    bool testWifi(void) {
      int c = 0;
      Serial.println("Waiting for Wifi to connect");
      while ( c < 20 ) {
        if (WiFi.status() == WL_CONNECTED) { return true; }
        delay(500);
        Serial.print(WiFi.status());
        c++;
      }
      Serial.println("");
      Serial.println("Connect timed out, opening AP");
      return false;
    }

    void launchWeb(int webtype) {
      Serial.println("");
      Serial.println("WiFi connected");
      Serial.print("Local IP: ");
      Serial.println(WiFi.localIP());
      Serial.print("SoftAP IP: ");
      Serial.println(WiFi.softAPIP());
      createWebServer(webtype);
      // Start the server
      server.begin();
      Serial.println("Server started");
    }

    void setupAP(void) {
      WiFi.mode(WIFI_STA);
      WiFi.disconnect();
      delay(100);
      int n = WiFi.scanNetworks();
      Serial.println("scan done");
      if (n == 0)
        Serial.println("no networks found");
      else
      {
        Serial.print(n);
        Serial.println(" networks found");
        for (int i = 0; i < n; ++i)
         {
          // Print SSID and RSSI for each network found
          Serial.print(i + 1);
          Serial.print(": ");
          Serial.print(WiFi.SSID(i));
          Serial.print(" (");
          Serial.print(WiFi.RSSI(i));
          Serial.print(")");
          Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*");
          delay(10);
         }
      }
      Serial.println("");
      st = "
";
      for (int i = 0; i < n; ++i)
        {
          // Print SSID and RSSI for each network found
          st += "
";
          st += WiFi.SSID(i);
          st += " (";
          st += WiFi.RSSI(i);
          st += ")";
          st += (WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*";
          st += "
";
        }
      st += "
";
      delay(100);
      WiFi.softAP(ssid, passphrase, 6);
      Serial.println("softap");
      launchWeb(1);
      Serial.println("over");
    }

    void createWebServer(int webtype)
    {
      if ( webtype == 1 ) {
        server.on("/", []() {
            IPAddress ip = WiFi.softAPIP();
            String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
            content = "<!DOCTYPE HTML>\r\nHello from ESP8266 at ";
            content += ipStr;
            content += "
";
            content += st;
            content += "
<form method='get' action='setting'>SSID: <input name='ssid' length=32><input name='pass' length=64><input type='submit'></form>";
            content += "";
            server.send(200, "text/html", content);
        });
        server.on("/setting", []() {
            String qsid = server.arg("ssid");
            String qpass = server.arg("pass");
            if (qsid.length() > 0 && qpass.length() > 0) {
              Serial.println("clearing eeprom");
              for (int i = 0; i < 96; ++i) { EEPROM.write(i, 0); }
              Serial.println(qsid);
              Serial.println("");
              Serial.println(qpass);
              Serial.println("");

              Serial.println("writing eeprom ssid:");
              for (int i = 0; i < qsid.length(); ++i)
                {
                  EEPROM.write(i, qsid[i]);
                  Serial.print("Wrote: ");
                  Serial.println(qsid[i]);
                }
              Serial.println("writing eeprom pass:");
              for (int i = 0; i < qpass.length(); ++i)
                {
                  EEPROM.write(32+i, qpass[i]);
                  Serial.print("Wrote: ");
                  Serial.println(qpass[i]);
                }
              EEPROM.commit();
              content = "{\"Success\":\"saved to eeprom... reset to boot into new wifi\"}";
              statusCode = 200;
            } else {
              content = "{\"Error\":\"404 not found\"}";
              statusCode = 404;
              Serial.println("Sending 404");
            }
            server.send(statusCode, "application/json", content);
        });
      } else if (webtype == 0) {
        server.on("/", []() {
          IPAddress ip = WiFi.localIP();
          String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
          server.send(200, "application/json", "{\"IP\":\"" + ipStr + "\"}");
        });
        server.on("/cleareeprom", []() {
          content = "<!DOCTYPE HTML>\r\n";
          content += "
Clearing the EEPROM
";
          server.send(200, "text/html", content);
          Serial.println("clearing eeprom");
          for (int i = 0; i < 96; ++i) { EEPROM.write(i, 0); }
          EEPROM.commit();
          WiFi.disconnect();
        });
      }
    }

    void loop() {
      server.handleClient();
    }

The configuration access point ssid and password are set in

    const char* ssid = "test";
    const char* passphrase = "test";

The default IP is 192.168.4.1. When you open it from a browser you see a screen which lists the available WiFi stations (ESP8266 scan result), the signal strength and an asterisk on locked stations. There are also two text boxes where you enter the ssid and password of the station you want to connect to and submit:

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

Note that there is a [link to a similar library](https://github.com/tzapu/WiFiManager) in the comments of the source link, that didn't work for me but you can try it.

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


body:
I have cobbled together, from the library examples, a program to log temperature and humidity to an MQTT server. The SSID/password, MQTT server and port, and the MQTT publish path can all be set at run time. Once they are set, the device will remember and re-use the settings next time it boots.

I am using the Arduino IDE to program an ESP8266-01. It, in turn, talks to a DHT11 sensor for temperature and humidity data.

The program is found at https://github.com/PabluskiNC/TempHumidityLogger

        #include <FS.h>                   //this needs to be first, or it all crashes and burns...

        #include "DHT.h"
        #define DHTPIN 2
        #define DHTTYPE DHT11
        DHT dht(DHTPIN, DHTTYPE);

        #include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino

        //needed for library
        #include <DNSServer.h>
        #include <ESP8266WebServer.h>
        #include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager

        #include <ArduinoJson.h>          //https://github.com/bblanchon/ArduinoJson

        #include <PubSubClient.h>
        WiFiClient espClient;
        PubSubClient client(espClient);
        long mqtt_lastMsg = 0;
        char mqtt_msg[50];
        int  mqtt_value = 0;

        //define your default values here, if there are different values in config.json, they are overwritten.
        char mqtt_server[40];
        char mqtt_port[6] = "1883";
        char mqtt_topic[34] = "OutTopic";

        //flag for saving data
        bool shouldSaveConfig = false;

        //callback notifying us of the need to save config
        void saveConfigCallback () {
          Serial.println("Should save config");
          shouldSaveConfig = true;
        }

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

          //clean FS, for testing
          //SPIFFS.format();

          //read configuration from FS json
          Serial.println("mounting FS...");

          if (SPIFFS.begin()) {
            Serial.println("mounted file system");
            if (SPIFFS.exists("/config.json")) {
              //file exists, reading and loading
              Serial.println("reading config file");
              File configFile = SPIFFS.open("/config.json", "r");
              if (configFile) {
                Serial.println("opened config file");
                size_t size = configFile.size();
                // Allocate a buffer to store contents of the file.
                std::unique_ptr<char[]> buf(new char[size]);

                configFile.readBytes(buf.get(), size);
                DynamicJsonBuffer jsonBuffer;
                JsonObject& json = jsonBuffer.parseObject(buf.get());
                json.printTo(Serial);
                if (json.success()) {
                  Serial.println("\nparsed json");

                  strcpy(mqtt_server, json["mqtt_server"]);
                  strcpy(mqtt_port, json["mqtt_port"]);
                  strcpy(mqtt_topic, json["mqtt_topic"]);

                } else {
                  Serial.println("failed to load json config");
                }
              }
            }
          } else {
            Serial.println("failed to mount FS");
          }
          //end read

          // The extra parameters to be configured (can be either global or just in the setup)
          // After connecting, parameter.getValue() will get you the configured value
          // id/name placeholder/prompt default length
          WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40);
          WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 5);
          WiFiManagerParameter custom_mqtt_topic("topic", "mqtt topic", mqtt_topic, 32);

          //WiFiManager
          //Local intialization. Once its business is done, there is no need to keep it around
          WiFiManager wifiManager;

          //set config save notify callback
          wifiManager.setSaveConfigCallback(saveConfigCallback);

          //set static ip
          //wifiManager.setSTAStaticIPConfig(IPAddress(10, 0, 1, 99), IPAddress(10, 0, 1, 1), IPAddress(255, 255, 255, 0));

          //add all your parameters here
          wifiManager.addParameter(&custom_mqtt_server);
          wifiManager.addParameter(&custom_mqtt_port);
          wifiManager.addParameter(&custom_mqtt_topic);

          //reset settings - for testing
          //wifiManager.resetSettings();

          //set minimu quality of signal so it ignores AP's under that quality
          //defaults to 8%
          //wifiManager.setMinimumSignalQuality();

          //sets timeout until configuration portal gets turned off
          //useful to make it all retry or go to sleep
          //in seconds
          //wifiManager.setTimeout(120);

          //fetches ssid and pass and tries to connect
          //if it does not connect it starts an access point with the specified name
          //here  "AutoConnectAP"
          //and goes into a blocking loop awaiting configuration
          if (!wifiManager.autoConnect("AutoConnectAP", "password")) {
            Serial.println("failed to connect and hit timeout");
            delay(3000);
            //reset and try again, or maybe put it to deep sleep
            ESP.reset();
            delay(5000);
          }

          //if you get here you have connected to the WiFi
          Serial.println("connected...yeey :)");

          //read updated parameters
          strcpy(mqtt_server, custom_mqtt_server.getValue());
          strcpy(mqtt_port, custom_mqtt_port.getValue());
          strcpy(mqtt_topic, custom_mqtt_topic.getValue());

          //save the custom parameters to FS
          if (shouldSaveConfig) {
            Serial.println("saving config");
            DynamicJsonBuffer jsonBuffer;
            JsonObject& json = jsonBuffer.createObject();
            json["mqtt_server"] = mqtt_server;
            json["mqtt_port"] = mqtt_port;
            json["mqtt_topic"] = mqtt_topic;

            File configFile = SPIFFS.open("/config.json", "w");
            if (!configFile) {
              Serial.println("failed to open config file for writing");
            }

            json.printTo(Serial);
            json.printTo(configFile);
            configFile.close();
            //end save
          }

          client.setServer(mqtt_server, stringToNumber(mqtt_port));
          client.setCallback(callback);
          Serial.println("local ip");
          Serial.println(WiFi.localIP());
          dht.begin();
        }

        int stringToNumber(String thisString) {
          int i, value, length;
          length = thisString.length();
          char blah[(length + 1)];
          for (i = 0; i < length; i++) {
            blah[i] = thisString.charAt(i);
          }
          blah[i] = 0;
          value = atoi(blah);
          return value;
        }

        void callback(char* topic, byte* payload, unsigned int length) {
          Serial.print("Message arrived [");
          Serial.print(topic);
          Serial.print("] ");
          for (int i = 0; i < length; i++) {
            Serial.print((char)payload[i]);
          }
          Serial.println();

          // Switch on the LED if an 1 was received as first character
          if ((char)payload[0] == '1') {
            digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
            // but actually the LED is on; this is because
            // it is acive low on the ESP-01)
          } else {
            digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
          }

        }

        void reconnect() {
          // Loop until we're reconnected
          while (!client.connected()) {
            Serial.print("Attempting MQTT connection...");
            Serial.print(mqtt_server);
            Serial.print(":");
            Serial.print(mqtt_port);
            Serial.print("...");
            // Attempt to connect
            if (client.connect("ESP8266Client")) {
              Serial.println("connected");
              // Once connected, publish an announcement...
              client.publish(mqtt_topic, "Reconnected");
              // ... and resubscribe
              //client.subscribe("inTopic");
            } else {
              Serial.print("failed, rc=");
              Serial.print(client.state());
              Serial.println(" try again in 5 seconds");
              // Wait 5 seconds before retrying
              delay(5000);
            }
          }
        }

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

          float h = dht.readHumidity();
          float t = dht.readTemperature();
          if (isnan(t) || isnan(h)) {
            Serial.println("Failed to read from DHT");
          } else {
            Serial.print("Temp:");
            Serial.print(t);
            Serial.print( "*C  Humidity:");
            Serial.print(h);
            Serial.println("%");
            if (!client.connected()) {
              reconnect();
            }
            client.loop();

            //long now = millis();
            //if (now - mqtt_lastMsg > 2000) {
            //  lastMsg = now;
            //  ++mqtt_value;
            char temp[7];
            dtostrf(t,4,2,temp); //convert float to char
            snprintf (mqtt_msg, 50, "%s C", temp);
            //  Serial.print("Publish message: ");
            //  Serial.println(msg);
            //  client.publish(mqtt_topic, msg);
            //}
            char pub_topic[34];
            strcpy(pub_topic,mqtt_topic);
            strcat(pub_topic,"/temperature");
            client.publish( pub_topic , mqtt_msg);
            Serial.print("Publish: ");
            Serial.print(pub_topic);
            Serial.print(" , ");
            Serial.println(mqtt_msg);

            dtostrf(h,4,2,temp); //convert float to char
            snprintf (mqtt_msg, 50, "%s %", temp);

            strcpy(pub_topic,mqtt_topic);
            strcat(pub_topic,"/humidity");
            client.publish(pub_topic,mqtt_msg);
            Serial.print("Publish: ");
            Serial.print(pub_topic);
            Serial.print(" , ");
            Serial.println(mqtt_msg);
          }
          delay(5000);
        }


message:
arduino creates strange files in SD card

I'm new to Arduino and electronics. I want to make a project including SD data-logger, but I had a problem. I would appreciate if someone show me where I made a mistake.

Firstly, circuit  was set up as in picture:

[![Hardware setup][1]][1]

I am using 8 Gb micro SDHC card with SD adapter. I formatted in FAT32. I can play audio files which are in appropriate format and read and the print contents of text files.

But when I want to create a new file, strange file is obtained in SD card as in pic:

[![Directory listing][2]][2]

So I reformat SD card. the code that is used while creating file is as this;

    // open a new file and immediately close it:
    Serial.println("Creating example.txt...");
    myFile = SD.open("example.txt", FILE_WRITE);
    myFile.close();

Somewhere I read SDHC card with more than 2 Gb capacity  is not supported in Arduino and I bought 2 Gb SD micro with SD adaptor.

But in this case aurduino does not detect SD card. please someone help me.

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

body:
I've had similar issues with large (> 1Gb) SD cards, I've had various different problems with different cards, some things that helped me debugging the problem:

 - make sure your wires are the same length and try to use **short wires**
 - make sure your power supply is sufficient, sd card readers can draw up to `150mA`
 - format the card in either `FAT16` or `FAT32` and never use "quick erase", try to use official tools (like https://www.sdcard.org/downloads/formatter_4/index.html)
 - make sure if you're the correct `BAUD rate` (9600) to talk to your card
 - filename support is pretty old so keep them short and don't use spaces or special characters
 - make sure the SD card is not in "**write lock**" mode, there's a small switch on the side of some SD cards that can prohibit writing (but will allow reading)


body:
I have faced this problem. Try

 - If you are using multiple devices with SPI communication ignore the others by keeping their slave select HIGH
 - Never forget `file.close()`


message:
Sets of Ultrasonic frequencies using arduino uno

Is it possible to create a set of ultrasonics frequencies using only the Arduino? What code to be used? And how am I going to do for it to work? For this project I need to focus in  the emitter side; all resources on Google are only on sensor and distance detector. I just want to use ultrasonic on other field just like for example on repelling rats. Thanks!

body:
There are three parts to this project, one of which you asked:

1.  I need to generate a frequency greater than 40 khz using arduino uno?

This one is easy: Yes. You can use the tone() library call. You can specify a frequency up to 8mhz. You can call this in the `void setup{}` part of your code, and (if you don't want to do anything else), leave the `void loop() {}` empty. You might want to generate an audible tone for a short period first, to show that it is working.

2. You need something to actually make the sound.

Depending on the frequency, most speakers won't do the trick, or will do it at a very low volume. Speakers are made to work with audible frequencies. Even then, some speakers (larger ones) are better at low frequencies; others (smaller ones) are better at higher audible frequencies. I think piezoelectric buzzers would give you a better response at higher frequencies. In any case, whatever you buy find out the frequency response for the specific part, find the frequency you intend to use along the bottom, then see what the volume (db) is for that frequency - this will give you an indication of how loud it will be. Remember that you won't be able to hear it.

The circuit is pretty trivial. Google piezo arduino

3. Efficacy:

From https://en.wikipedia.org/wiki/Electronic_pest_control#Effects_on_rodents

> Rodents adjust to the ultrasound (or any new sound) and eventually ignore it. At best, ultrasonic waves have only a partial or temporary effect on rodents. Numerous studies have rejected ultrasonic sound as a practical means of rodent control.Tests of commercial ultrasonic devices have indicated that rodents may be repelled from the immediate area of the ultrasound device for a few minutes to a few days, but they will nearly always return and resume normal activities. Other tests have shown that the degree of repellance depends on the frequency, intensity, and pre-existing condition of the rodent infestation. The intensity of such sounds must be so great that damage to humans or domestic animals would also be likely; commercial ultrasonic pest control devices do not produce sounds of such intensity.


body: Another answer to generating ultrasonic frequencies is to ditch the Arduino altogether - use a 555 timer circuit (for lower range frequency, probably up to low mHz), or a resonator. A quick search found a 2.4 gHz resonator for less than an Arduino. 555 timers can be tuned, resonators cannot. I think you could build a 555 square-wave generator for about $1-$2.


message:
SIM900 Shield read only sms headers without text

I enable messages about new SMS

    AT+CNMI=2,2,0,0,0

    OK
and when received sms, output like this.

    +CMT: "+79XXXXXXXXX","1","15/09/23,01:34:03+24"
    Test

But when I read message, output only before `<CR><LF>`
I don't see text of message.

    AT+CMGR=1

    +CMGR: "REC READ","+79XXXXXXXXX","1","15/09/23,00:34:17+24"

    AT+CMGL="ALL"

    +CMGL: 1,"REC READ","+79XXXXXXXXX","1","15/09/23,00:34:17+24"
    +CMGL: 2,"REC READ","+79XXXXXXXXX","1","15/09/23,01:34:03+24"

I use [following](https://gist.github.com/YokiToki/9d5e730c0c196ebaf3cf)  (via SoftwareSerial) code for test this.
`SMSGSM.GetSMS` and `SMSGSM.GetAuthorizedSMS` of [GSM GPRS GPS Shield Library](https://github.com/MarcoMartines/GSM-GPRS-GPS-Shield) receive only phone number without sms text.

I use this shield:
![_57](https://cloud.githubusercontent.com/assets/1845813/10030856/50090b88-6193-11e5-916b-5f58ac58e6d8.JPG)

    AT+GSV

    SIMCOM_Ltd
    SIMCOM_SIM900
    Revision:1137B05SIM900M64_ST_ENHAN

body:
Could you confirm that any of the commands sent over your `SoftwareSerial` are responding?

You probably need to add a `"\n"` (new line) at the end of your messages or just use `println()`.

Also, add your code to the question so we can be of better assistance.


body:
This is most likely a case of overrun SoftwareSerial buffer. You are reading too slowly from the modem, especially with the `Serial.print()`s in your code. You should look for SoftwareSerial.h in `C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\SoftwareSerial` if you're using Win 8 and above. Or just search your PC for it. Look for this line:

        #define _SS_MAX_RX_BUFF 64

Change 64 to 256 and save. If it solves your problem, try reducing 256 to 128 to see if it still works. The greater the size of the buffer, the lesser the amount of memory available to the rest of your program.

You could also try this, to interact with the module:

    #include <SoftwareSerial.h>

    SoftwareSerial SIM900(7,8);

    void setup() {
      Serial.begin(19200);
      SIM900.begin(19200);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      while (Serial.available() > 0){
        SIM900.write(Serial.read());
      }
      while (SIM900.available() > 0){
        Serial.write(SIM900.read());
      }
    }

It does the same thing as your code and doesn't require adjusting buffer size, though I still recommend you make the change if you will use other sketches.


message:
Two Leonardos on one USB hub - not working properly

I have two Arduino Leonardos here. They do different things, but basically they both emulate a keyboard. Here is an example:

    const byte SWITCH = 12;

    void setup ()
      {
      Keyboard.begin();
      pinMode (SWITCH, INPUT_PULLUP);
      }  // end of setup

    void loop ()
      {
      if (digitalRead (SWITCH) == LOW)
        {
        Keyboard.println ("foo");
        delay (2000);
        }
      }

Now I program a second Leonardo with the same code but send "bar" rather than "foo".

Now if I plug these into my PC (running Ubuntu 14.04) using different USB ports, everything works. When the switch is closed I see "foo" and "bar" being typed into whatever application is open.

However ...

If I plug them both into a D-Link 4-port USB hub (model DUB-1340) only the first one works. The other is ignored.

Doing `lsusb` shows this (along with other irrelevant devices):

    $ lsusb
    Bus 003 Device 040: ID 2341:8036 Arduino SA Leonardo (CDC ACM, HID)
    Bus 003 Device 039: ID 2341:8036 Arduino SA Leonardo (CDC ACM, HID)

This happens in both cases (if they are both in the USB hub or not).

---

## My question

Is this proper behaviour that two Leonardos on a USB hub fail to both work? (Perhaps you aren't supposed to plug two identical USB devices in at once).

Or, is this a bug in either:

* The Leonardo USB interface?
* My USB hub?

---

## Update

Further testing revealed that the setup worked OK when plugged into my Mac running OS/X.

Then I went back to Ubuntu and it worked as well! However a mouse that I had plugged into the USB hub now stopped working!

Further investigation reveals that the fourth port on my USB hub is faulty in some way. If I swap the mouse and the Leonardo the Leonardo works but not the mouse.

Following Majenko's suggestion:

> You can try running usb-devices from the usbutils package (should be already installed since lsusb is in the same package) and look for the two Leonardo blocks.

First one:

    T:  Bus=03 Lev=02 Prnt=50 Port=00 Cnt=01 Dev#= 66 Spd=12  MxCh= 0
    D:  Ver= 2.00 Cls=02(commc) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
    P:  Vendor=2341 ProdID=8036 Rev=01.00
    S:  Manufacturer=Arduino LLC
    S:  Product=Arduino Leonardo
    C:  #Ifs= 3 Cfg#= 1 Atr=80 MxPwr=500mA
    I:  If#= 0 Alt= 0 #EPs= 1 Cls=02(commc) Sub=02 Prot=00 Driver=cdc_acm
    I:  If#= 1 Alt= 0 #EPs= 2 Cls=0a(data ) Sub=00 Prot=00 Driver=cdc_acm
    I:  If#= 2 Alt= 0 #EPs= 1 Cls=03(HID  ) Sub=00 Prot=00 Driver=usbhid

Second one:

    T:  Bus=03 Lev=02 Prnt=50 Port=03 Cnt=04 Dev#= 72 Spd=12  MxCh= 0
    D:  Ver= 2.00 Cls=02(commc) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
    P:  Vendor=2341 ProdID=8036 Rev=01.00
    S:  Manufacturer=Arduino LLC
    S:  Product=Arduino Leonardo
    C:  #Ifs= 0 Cfg#= 0 Atr= MxPwr=
    cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bInterfaceNumber: No such file or directory
    cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bAlternateSetting: No such file or directory
    cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bNumEndpoints: No such file or directory
    cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bInterfaceClass: No such file or directory
    cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bInterfaceSubClass: No such file or directory
    cat: /sys/bus/usb/devices/usb3/3-3/3-3.4/3-*:?.*/bInterfaceProtocol: No such file or directory
    /usr/bin/usb-devices: line 79: printf: (none): invalid number
    I:  If#= 0 Alt= 0 #EPs= 0 Cls=() Sub= Prot= Driver=

---

## Tentative conclusion

Perhaps I somehow damaged that USB port by drawing too much current during testing at some earlier point.

Although ... now the mouse is working in the port where it was not working before, and the Leonardo has stopped working in the 3rd port, when it was previously not working in the 4th port.

Those error messages above must be relevant, but I don't know enough about it to say in what way.

body:
There is no reason I can think of that would stop it working as it should.

`lsusb` is showing both the devices, so they are being detected by the kernel.

You can try running `usb-devices` from the *usbutils* package (should be already installed since `lsusb` is in the same package) and look for the two Leonardo blocks. You should get two blocks like this:

    T:  Bus=01 Lev=03 Prnt=07 Port=00 Cnt=01 Dev#= 11 Spd=12  MxCh= 0
    D:  Ver= 2.00 Cls=00(>ifc ) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
    P:  Vendor=2341 ProdID=0036 Rev=01.00
    S:  Manufacturer=Arduino LLC
    S:  Product=USB IO Board
    C:  #Ifs= 3 Cfg#= 1 Atr=80 MxPwr=500mA
    I:  If#= 0 Alt= 0 #EPs= 1 Cls=02(commc) Sub=02 Prot=00 Driver=cdc_acm
    I:  If#= 1 Alt= 0 #EPs= 2 Cls=0a(data ) Sub=00 Prot=00 Driver=cdc_acm
    I:  If#= 2 Alt= 0 #EPs= 1 Cls=03(HID  ) Sub=00 Prot=00 Driver=usbhid

The important bit is the `I:` lines - they show the individual USB interfaces and what kernel driver has been associated with them.   For the keyboard, of course, it's the last entry, which is assigned to the `usbhid` driver.

Another good diagnostic is `dmesg -w`

Run that with both Leonardos disconnected.  Plug one in and it should show it registering as a USB device.  A few moments later you should get a pair of lines like:

    [ 2106.937086] input: Arduino LLC USB IO Board     as /devices/pci0000:00/0000:00:1a.7/usb1/1-1/1-1.4/1-1.4.1/1-1.4.1:1.2/0003:2341:0036.0006/input/input21
    [ 2106.990523] hid-generic 0003:2341:0036.0006: input,hidraw4: USB HID v1.01 Mouse [Arduino LLC USB IO Board    ] on usb-0000:00:1a.7-1.4.1/input2

That is the board being associated with an input device (in this case input 2).

Repeat it with the second Leonardo and see if the same appears, but this time with a higher input number (it would be 3 on mine if I had a second Leonardo).

The fact that the two Leonardos work together normally means that they should be working fine in any arrangement, so if the OS is seeing it all fine but the data isn't getting through, then my money is on the hub.  It looks quite a new hub, so it may have a few bugs in it that are yet to be ironed out.

USB devices are identified to the drivers using the VID and PID, but to the kernel the USB device is just a chain of bus/port numbers.  For instance my Leonardo above is identified as:

    1-1.4.1

That's USB bus 1, downstream port 1 (root hub - normally only has 1 port), which connects to a hub (the one built into the computer to drive multiple ports) which then has downstream port 4 connecting to a hub (on my desk) which then has downstream port 1 connecting to the device.  Nothing else can be connected to that same combination of downstream ports - it's physically impossible, so it's uniquely identified.


message:
TFT touch, 4bit data transfer

I followed instructions to get my TFT to work.

[![TFT photo][1]][1]

I want to use other pins on the Arduino Uno for other I/O, so how can I use 4-bit data transfer for the TFT touchscreen?

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

body: You read the datasheet for the chip that is on your TFT display (whatever that is) and find if it even supports a 4-bit mode.  It probably doesn't. I have a large number of TFT screens here and I don't recall any of them using parallel 4-bit.  It sounds like you actually want a TFT screen that works of SPI rather than a parallel interface.  Those *are* available, but by using SPI the screen updates are considerably slower.


message:
Waiting for an AT command to complete

I'm looking for a way to wait for a response from an AT command to return OK or CONNECTED or whatever the command returns when it's true.

I can check if the serial is available, but that means I have to manually guess what time between commands to give them time to connect or start.

Function:

    void ModemCommand(String command) {
      //Send command to modem
      mySerial.println(command);
      Serial.println(command);
      delay(100);
      while (!mySerial.available()) {
        //Wait for Response from modem
        Serial.println(F("No response yet"));
        delay(1000);
      }
      while (mySerial.available()) {
        Serial.write(mySerial.read());
        //Print response from modem
      }
      Serial.println("");
      //Linefeed after reponse
      delay(10);
    }

Code example:

    ModemCommand(F("ATE0"));
    //Turn on echo
    ModemCommand(F("AT+CFUN=1"));
    //Turn modem functions on
    waitSec(8,F("turning on Modem functions"));
    ModemCommand(F("AT+CGREG?"));
    //GSM attached?
    ModemCommand(F("AT+CSQ"));
    //Signal Quality
    ModemCommand(F("AT+CSTT=\"internet\""));
    //Set APN
    ModemCommand(F("AT+CIICR"));
    //Connect to APN GPRS
    waitSec(8,F("connecting to APN GPRS"));
    ModemCommand(F("AT+CIFSR"));
    //Get IP

Does anybody know how to do this?

body:
You would need to create a buffer which will populate over each loop so you dont block the main loop while waiting the all string.

When you get the string or your buffer is full, just check whatever is the response, and based on that you can make your decision.


body:
The most you can do is define a certain amount of time between received characters, after which you can decide that there's nothing more to be read from the modem. Of course, the time taken for processing is longer for certain commands (and some provide no response at all, until you've completed entering their payload, like TCPSEND, in which case you should simply use `mySerial.write()` to send said payload, and not your function), but once a response is ready and its first character is available, a timeout of 1 second between characters should be sufficient, for any reasonable baud rate. Something like this:

    #define TIMEOUT 1000

    void modem_command(String command){
      mySerial.println(command);
      Serial.println(command);
      while (mySerial.available() == 0);  // wait for first char

      unsigned long lastRead = millis();   // last time a char was available
      while (millis() - lastRead < TIMEOUT){
        while (mySerial.available()){
          Serial.write(mySerial.read());
          lastRead = millis();   // update the lastRead timestamp
        }
      }
      // No need for extra line feed since most responses contain them anyways
    }

Of course, you can always alter `TIMEOUT` based on your findings.


message:
Arduino due slow clock

To reduce the components amount I don't want to put the  32.768 kHz oscillator on my own Due.
Can I leave the corresponding XTAL inputs unconnected?

What is the main target of the slow clock?
What I can not do with the high clock but can do with the slow one?
Will I face to any issues if I don't use the low freq. oscillator?

body:
The slow clockr is primarily used for the real time clock (RTC) module inside the SAM3X chip.  It can also be routed to other places when you want a low speed clock source, but the only places it is actually *required* are the RTC and the watchdog.

The slow clock can be generated from an internal RC oscillator instead of requiring an external crystal, but the accuracy and stability of the RC oscillator is many orders of magnitude worse than a crystal.  Trying to use that for the RTC module will result in the clock drifting over time.  The watchdog won't really care if the clock isn't perfectly accurate.


body:
Atmel datasheet says:

**If the user does not need the crystal oscillator, the XIN32 and XOUT32 pins can be left unconnected**


message:
Light multiple RGB Led Strips from same 3 RGB PWM outputs

I need to control about 6 RGB Led Strips from an Arduino Board. The problem is that i need 3 PWM outputs for each led strip, but each will have probably the same colors. I was wondering if i could put two strips receiving a signal from the same PWM output, then i would have to use half the PWM outputs but send the same signal for each pair of strips.

The scheme i found is this one:

[![arduino schematic][1]][1]

And what i want is something like this:
[![enter image description here][2]][2]

Is this possible? What should i modify to make it work?

Thanks in advance.

  [1]: https://learn.adafruit.com/system/assets/assets/000/002/693/medium800/led_strips_ledstripbjt.gif?1396785837
  [2]: https://i.stack.imgur.com/yokZr.png

body:
You have few options:

 1. do as you represented in the drawing: it should work, as I expect the transistors to not load too much the input.

 2. add a [logic buffer][1] inbetween the arduino and the driver stage

 3. use other pins from the arduino for driving the additional strips and bitbang the PWM, instead of using the HW blocks

Whether the solution you propose (1) will work or not depends entirely on the max current that each PWM pin can output vs the total load from the 3 transistors it will have to drive.

  [1]: http://www.digikey.com/product-search/en/integrated-circuits-ics/logic-buffers-drivers-receivers-transceivers/2556308


message:
Arduino Analog Input Oscillating

I'm making a simple Infrared detector using a thermopile. I have a few extra capacitors than what that schematic says. I'm currently following another, but this is the gist.

Schematic and Breadboard- [![Breadboard and Schematic][1]][1]

**I can add breadboard picture if needed. I don't have 10 points in this Stack so I can't post more than 2.**

I'm using a 9V battery through a 24v - 5v regulator (had one around) to power my op amp and schematic. The signal from the OPAMP will be between 0-5V so voltage hasn't damaged the Arduino Uno. The final project will be something like: output > A then power green, A < output < B power yellow, B < output red.

The issue is that I'm getting an oscillating value from my Serial Monitor that goes from 0 to 1023 (or I have a conversion to change it back to output voltage. So 0V to 5V. See code).

It does this oscillation when I have the board connected to any of the AX pins (X=0-5) or nothing plugged in at all (I understand it will output weird numbers with the pin floating).

**I had a picture of the serial monitor but I don't have 10 points to add more than 2 pictures. Please see image below**

I know that the output from the OPAMP works because when I use a VoltMeter to read the output, it works fine. 0.3XXV when no flame, 5V when flame is directly on top of my theromopile. [![Serial Monitor and VM][2]][2]

Would anyone happen to have a suggestion to why the Arduino is acting this way? The volt meter reading is directly out of the Op amp pin 1. **no more than 2 links. AD822 op amp**

Here's my code before adding if statements for the LED's. It was incorrect.

    int TP=A2; // Assign Thermopile to pin A2
    int val; // Declare readValue Variable
    float Voltage; // Declare real world voltage variable - Float = in between variable
    int ledG = 11;
    int ledY = 12;
    int ledR = 13;

    void setup() {
     pinMode(TP,INPUT); // Declare Thermopile pin as input
     pinMode(ledG, OUTPUT);
     pinMode(ledR, OUTPUT);
     pinMode(ledY, OUTPUT);
     Serial.begin(9600); // Start your Serial Port
    }

    void loop() {
      val = analogRead(TP); // Read Thermopile pin and place value into readValue

      Voltage = (5./1023.)*val; // To do "floating point math" have a "." //after the number. If not, it will return real number (5/1023 = 0) according to Arduino

    Serial.println(Voltage); // Print readValue to Serial Monitor
      delay(100); // Delayed output to 1/4 a second
    }

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

body:
It seems you haven't connected the circuit ground to the Arduino ground.  This is essential to complete the circuit between your breadboard and the Arduino.  Without the ground connection the electrons that you send to the Arduino have no way of getting back again.

Here's a couple of diagrams that I drew for another question which deals with the Arduino driving a remote device, but the theory holds true no matter which way around it is.

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

In that diagram the red arrows (*not the aerial display team I hasten to add*) represent the connection between your breadboard circuit and the Arduino.  Without the ground connection there is no circuit, and a circuit is always needed for current to flow (and hence your signal).  With the ground connection the red arrows become a loop which allows the current to flow and transfer your signal.

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


message:
Is there a away to transmit sensor signal over RF without Arduino?

I would like to place analog sensor in a place, that is impractical to reach with a wire. But it looks like an overkill to use a separate small Arduino board to read and transmit sensor signal to main Arduino board at a close range (~1 m).

Is there a cheap practical way to setup such sensor signal broadcast over RF without using Arduino board? Something that could work for considerable duration with a small tablet like battery?

body:
You don't have to use a $30 Arduino. You can make a "breadboard" one for a few dollars, like this:

[![Breadboard Arduino][1]][1]

$5 for the chip and a couple of dollars for a couple of capacitors and resistors.

---

Add to that a NRF24L01 transceiver like this:

[![NRF24L01][2]][2]

Available from eBay for around $1 each. You need two, as you need to transmit from one and receive from another.

So the whole thing could be done for under $10.

---

> Something that could work for considerable duration with a small tablet like battery?

See [Power saving techniques for microprocessors](http://www.gammon.com.au/power)

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


body:
I would recommend investigating the ESP8266 modules.  Many people use them as a WiFi interface to an Arduino, but they are also capable of being used completely standalone.

You can pick up a cheap module and program it using a readily available USB to TTL UART adapter using the ESP8266 plugin to the Aduino IDE.

https://github.com/esp8266/Arduino

It's like having an Arduino and a WiFi interface all embedded in one chip, and the modules are tiny too - perfect for embedding in a project.

There are many different modules available, some with more pins than others for IO.  The best one is the NodeMCU since it has the programming interface built in (go for version 1.0 not version 0.9 since it has better IO options), but the higher end ESP8266 modules on carrier boards (ESP-12, etc) are as good, if a little harder to work with.


message:
Sending and receiving different types of data via I2C in Arduino

I have found a few good tutorials on how to send and receive data via I2C in connected arduinos. My limitation is now how to transmit different types of data like for instance, long, float, etc. Right now the communication via I2C using the wire library only allows transmission of numbers between 0 and 255. How can one transmit different types of numbers?.

In my code a master receives three types of data from the slave, and it send data of a fourth variable to the slave.

here is the code for the master

    #include <Wire.h>

    const int SLAVE_ADDRESS = 8; //Slave arduino ID
    int table[]={0,0,0}; //the data will be transmited via table as to allow different data to be transfer.
    void setup ()
    {
    Wire.begin ();
    Serial.begin (9600);  // start serial for output
    }  // end of setup
    void loop()
    {
    Wire.requestFrom(SLAVE_ADDRESS, 3);// request 3 bytes from slave device #8

    for(int i=0;i<3;i++)//organizes the data from the slave in the table
    {
    int c = Wire.read(); // receive a byte as character
    table[i]=c;
    }
    //displays the data
     Serial.print('\n');
       Serial.print(table[0]);
        Serial.print('\t');
       Serial.print(table[1]);
        Serial.print('\t');
       Serial.print(table[2]);
       Serial.print('\n');

    delay (500);

    // transmit just this variable to the slave
    int Work=1;
    Wire.beginTransmission (8);
    Wire.write (Work);
    Wire.endTransmission ();
    }

here is the code for the slave

    #include <Wire.h>
    int table[]={0,0,0};
    int Work=0;

    void setup() {
    Wire.begin(8);                // join i2c bus with address #8
    Wire.onRequest(requestEvent); // register event
    Wire.onReceive(receiveEvent); // register event
    }

    void loop() {
    int x=120;
    int y=1200;// gets converted to an strange # because is larger than 255
    int z=3;
      table[0]=x;
      table[1]=y;
      table[2]=z;
    }

    void requestEvent()
    {
      uint8_t Buffer[3];
      Buffer[0]=table[0];
      Buffer[1]=table[1];
      Buffer[2]=table[2];
      Wire.write(Buffer,3);
    }

    void receiveEvent(int howMany)
    {Work = Wire.read();}

body:
I believe that for your scenario, i.e. sending different types of variables, the EasyTransfer library (by Bill Porter) would be an elegant solution. The library can be found here: [https://github.com/madsci1016/Arduino-EasyTransfer][1]. There are implementations for serial, I2C, and VirtualWire and the examples provided are pretty self-explanatory.

The handling is very easy. After including the library, you create an EasyTransfer object, define a data structure that basically represents a "container" of your data and this can consist of different variables.

    struct RECEIVE_DATA_STRUCTURE{
      //put your variable definitions here for the data you want to receive
      //THIS MUST BE EXACTLY THE SAME ON THE OTHER ARDUINO
      int blinks;
      int pause;
    };

Once the "container" is filled, i.e. the variables are set on the sender side, they are sent with a simple command

      ET.sendData(I2C_SLAVE_ADDRESS);

On the receiver side, you define an identiacl data structureand receive the data by

    ET.receiveData();

Hope this helps.
[1]: https://github.com/madsci1016/Arduino-EasyTransfer