body:
I'm working on a project where I need my arduino to detect the value of encoder at the instant the reading of the joystick change to 128.  When the joystick is at rest, the reading is 128 which also means, my robot will hold its position/brake. Values above or below 128 correspond to the motor moving forward or backward.

I actually want to record the encoder value exactly at the first instant my arduino reads 128, so that I can apply PID position control so that my robot can brake or hold its position against gravity. The first instant when the joystick reads 128, that is the encoder value that I'd like to set as the Setpoint.

Here's some explanations for implementing PID in Arduino.
[http://playground.arduino.cc/Code/PIDLibraryConstructor][1]

For instance the joystick readings go from 140, 137, 131, [128], 128, 128, 133, 139, 131, [128], 128 and at the same time, the encoder gives out corresponding values. I need the encoder values at the Joystick value of 128 in the square bracket, [] in the example above.

If I use the code below, it will just run the statements in {} whenever it sees 128, which is not what I want. FYI, the motor sometimes tend to backdrive, and this gives different encoder value also at 128. What I only need is the first encoder value at the first reading of 128 whenever I encounter it.

    void loop()
    {

      int pwmSpeed;

      int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);

      Input = encoder0Pos;

      if (Y_axis == 128)
      {

        Setpoint = encoder0Pos;
        myPID.Compute();
        analogWrite(pwm, Output);

      }

      else if (Y_axis > 128)
      {
        pwmSpeed = Y_axis;
        digitalWrite(dir,HIGH);           // set DIR pin HIGH or LOW
        analogWrite(pwm, pwmSpeed);            //analogWrite(pin, value)
      }
      else
      {
        pwmSpeed = abs(Y_axis-255);
        digitalWrite(dir, LOW);
        analogWrite(pwm, pwmSpeed);

      }

    }

Thanks.

//New edited code is shown below:

What do you think of the code? Did I do it correctly? I will test it once I get back to the lab.

If 128 is detected, encoder value is stored in Setpoint and then Pid.compute() is executed for as long as 128 is detected. For this duration, Pid.compute() will compute the error = Setpoint - Input and use Pid formula to calculate the Output that can be found in the analogWrite(pwm, Output). Motor will work to maintain its position at Setpoint.

However if other than 128 is encountered, it will just execute the 'else if' and 'else' statement to move the robot forward or backward.

    global g_detect128 = false;

    void setup()
        {
    //any code here
        }

    void loop()
    {

      int pwmSpeed;
      int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);

      Input = encoder0Pos;

     if (!g_detect128 && Y_axis == 128)
        {
        Setpoint = encoder0Pos;
        g_detect128 = true;
        }

      if (Y_axis == 128)
      {

        myPID.Compute();
        analogWrite(pwm, Output);

      }

      else if (Y_axis > 128)
      {
        pwmSpeed = Y_axis;
        digitalWrite(dir,HIGH);           // set DIR pin HIGH or LOW
        analogWrite(pwm, pwmSpeed);            //analogWrite(pin, value)
      }
      else
      {
        pwmSpeed = abs(Y_axis-255);
        digitalWrite(dir, LOW);
        analogWrite(pwm, pwmSpeed);

      }

     if(Y_axis != 128)
        {
        g_detect128 = false;
        }

    }

  [1]: http://playground.arduino.cc/Code/PIDLibraryConstructor

title: Arduino: Record value of the encoder only once at the instant the PS2 joystick reads 128 (when at rest)

Answers: 1

body:
If you only want to catch this event once - when it first hits 128, you just need a global variable to flag when you've seen it:

    boolean g_bSeen128 = false;

    void setup()
    {
        // ... whatever
    }

    void loop()
    {
        // ... your existing code

        // catch first time we see 128
        if (!g_bSeen128 && Y_axis == 128)
        {
            // ... do whatever you need here. e.g.
            Setpoint = encoder0Pos;
            myPID.Compute();
            analogWrite(pwm, Output);

            // stop the event being caught next time
            g_bSeen128 = true;
        }

        // from comments below - to just ignore consecutive 128's, add this:
        if (Y_axis != 128) g_bSeen128 = false;

        // ... your existing code

    }

If you only want to do something if the input changes, no matter what it is, you can keep track of the last input:

    int g_nLastInput = -1;

    void setup()
    {
        // ... whatever
    }

    void loop()
    {
        // get input
        int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);

        // if input has changed ...
        if (Y_axis != g_nLastInput)
        {
            // ... save latest input
            g_nLastInput = Y_axis;

            // now process the change, e.g.
            if (Y_axis == 128)
            {
                // ... do something special for 128
            }
            else
            {
                // ... do something else for other inputs
            }
        }
    }

I'm not sure what you're trying to do with the PWM when you get inputs either side of 128, it seems to me that you might want to go in one direction if the input is less than 128 and go in the other direction if it's greater than 128. In either case, the magnitude of your PWM speed should just reflect how far you are from 128 in either direction. So subtracting 128 from your input will give a delta that is +/- 128 and we can scale its absolute value to 0..255 for the PWM setting.

If that's correct, an alternative way of coding your original logic might be like this:

    void loop()
    {
        // get input
        int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);

        Input = encoder0Pos;

        // if input has changed ...
        if (Y_axis != g_nLastInput)
        {
            // ... save latest input
            g_nLastInput = Y_axis;

            // now process the change
            int nDelta = Y_axis - 128;

            if (nDelta == 0)
            {
                // i.e. Y_axis is 128
                Setpoint = encoder0Pos;
                myPID.Compute();
                analogWrite(pwm, Output);
            }
            else
            {
                // choose direction
                digitalWrite(dir, (nDelta > 0) ? HIGH : LOW);

                // set PWM speed scaled to 0..255
                analogWrite(pwm, abs(nDelta) * 2);
            }
        }
    }


body:
I am having Issue while connecting ESP8266 with Arduino Mega. It always says "Module have no response."

Please check and correct me if I am wrong anywhere.

I am using below code and and wiring diagram is

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

My Code:

    //#include <SoftwareSerial.h>
       //use mega Serial 2 for serial monitor; Serial 1 on pins 19 (RX) and 18 (TX);// Serial2 on pins 17 (RX) and 16 (TX), Serial3 on pins 15 (RX) and 14 (TX).
       #define SSID "SopraSteria"
       #define PASS "1234567890"
       #define DST_IP "220.181.111.85" //baidu.com
       //SoftwareSerial dbgSerial(10, 11); // RX, TX
       void setup()
       {
         // Open serial communications and wait for port to open:
         //serial 2 is to esp8266
         Serial2.begin(115200);//9600 (mine), 57600, 115200
         Serial2.setTimeout(2000);

         //serial 0 is to usb
         Serial.begin(115200);

         while(!Serial);
         while(!Serial2);

         //dbgSerial.begin(9600); //can't be faster than 19200 for softserial
         //dbgSerial.println("ESP8266 Demo");
         Serial.println("ESP8266 Demo on Mega2560");

        while(Serial2.available()>0)
        Serial2.read();

         delay(1000);
           //test if the module is ready
         Serial2.println("AT+RST");
         //delay(1000);
         //delay(1000);
         Serial.println("Resetting module");
         Serial2.flush();
         //Serial.println(Serial2.read());
         //if(Serial2.find("ready"))
         if(Serial2.find("Ready")||Serial2.find("ready"))
         {
           //dbgSerial.println("Module is ready");
           Serial.println("Module is ready");
         }
         else
         {
           //dbgSerial.println("Module have no response.");
           Serial.println("Module have no response.");
           //while(1);
         }
         delay(1000);
         //connect to the wifi
         boolean connected=false;
         for(int i=0;i<5;i++)
         {
           if(connectWiFi())
           {
             connected = true;
             break;
           }
         }
         if (!connected){
          //while(1);
          Serial.println("Not Connected.");
         }
         delay(1000);
         //print the ip addr

       Serial2.println("AT+CIFSR");
         Serial.println("ip address:");
         while (Serial2.available())
         Serial.write(Serial2.read());

         //set the single connection mode
         Serial2.println("AT+CIPMUX=0");
       }
       void loop()
       {
        //connectWiFi();
         String cmd = "AT+CIPSTART=\"TCP\",\"";
         cmd += DST_IP;
         cmd += "\",80";
         Serial2.println(cmd);
         Serial.println(cmd);
         Serial.println(cmd);
         if(Serial2.find("Error")) return;
         cmd = "GET / HTTP/1.0\r\n\r\n";
         Serial2.print("AT+CIPSEND=");
         Serial2.println(cmd.length());
         if(Serial2.find(">"))
         {
           //dbgSerial.print(">");
           Serial.print(">");
           }else
           {
             Serial2.println("AT+CIPCLOSE");
             //dbgSerial.println("connect timeout");
             Serial.println("connect timeout");
             delay(1000);
             return;
           }
           Serial2.print(cmd);
           delay(2000);
           //Serial.find("+IPD");
           while (Serial2.available())
           {
             char c = Serial2.read();
             //dbgSerial.write(c);
             Serial.write(c);
             //if(c=='\r') dbgSerial.print('\n');
             if(c=='\r') Serial.print('\n');
           }
           //dbgSerial.println("====");
           Serial.println("====");
           delay(1000);
         }
         boolean connectWiFi()
         {
           Serial2.println("AT+CWMODE=1");
           String cmd="AT+CWJAP=\"";
           cmd+=SSID;
           cmd+="\",\"";
           cmd+=PASS;
           cmd+="\"";
           //dbgSerial.println(cmd);
           Serial2.println(cmd);
           Serial.println(cmd);
           delay(2000);
           if(Serial2.find("OK"))
           {
             //dbgSerial.println("OK, Connected to WiFi.");
             Serial.println("OK, Connected to WiFi.");
             return true;
             }else
             {
               //dbgSerial.println("Can not connect to the WiFi.");
               Serial.println("Can not connect to the WiFi.");
               return false;
             }
           }

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

title: Issue while connecting ESP8266 with Arduino Mega. It always says “Module have no response.”

Answers: 3

body: As shown in the Fritzing diagram, you have connected the ESP8266 to the Mega's Serial1 pins (18 and 19), but in the program, you try to interact with Serial2 (pins 16 an 17). For this to work, your wiring and your program must match.

body:
I took your code as a starting point and got it to work with some small modifications. I am providing my version below for your review. I had to add a bunch of delays. I am also communicating with the ESP8266 at 19200 baud.

I have not optimized the timing yet but I was able to run this code for 24 hours straight with no issues. I am using Pins 6 and 7 on the Arduino for COMM to the ESP8266.

    #include <SoftwareSerial.h>
    #define SSID "YOURSSID"
    #define PASS "YOURPW"
    #define DST_IP "220.181.111.85"

    SoftwareSerial Serial2(6, 7); // RX, TX

    void setup() {

    // Open serial communications w ESP8266
    Serial2.begin(19200);
    Serial2.setTimeout(5000);

    // serial 0 is to usb
    Serial.begin(115200);
    while(!Serial);
    while(!Serial2);

    Serial.println("ESP8266 Demo on Mega2560");

    while (Serial2.available() > 0)
    Serial2.read();
    delay(1000);
    while (Serial2.available() > 0)
    Serial2.read();

    //test if the module is ready
    Serial.println("RESETTING ESP8266 WIFI CHIP");
    Serial2.write("AT+RST\r\n");
    delay(2500);
    while (Serial2.available() > 0)
    Serial.write(Serial2.read());

    delay(2500);
    while (Serial2.available() > 0)
    Serial.write(Serial2.read());
    Serial.println("");

    //  connect to the wifi
    boolean connected=false;
    for(int i=0;i<5;i++) {
    if(connectWiFi())
    {
    connected = true;
    break;
    }
    }

    if (!connected){
    Serial.println("Not Connected.");
    }

    Serial2.println("AT+CIFSR");
    delay(2000);
    while (Serial2.available())
    Serial.write(Serial2.read());
    delay(2000);
    while (Serial2.available())
    Serial.write(Serial2.read());

    //  set the single connection mode
    Serial2.println("AT+CIPMUX=0");
    delay(2000);
    while (Serial2.available())
    Serial.write(Serial2.read());
    delay(2000);
    while (Serial2.available())
    Serial.write(Serial2.read());
    }

    void loop() {

    String cmd = "AT+CIPSTART=\"TCP\",\"";
    cmd += DST_IP;
    cmd += "\",80";
    Serial2.println(cmd);
    Serial.println(cmd);
    delay(5000);

    if(Serial2.find("Error")) return;

    cmd="GET / HTTP/1.0\r\n\r\n";
    Serial2.print("AT+CIPSEND=");
    Serial2.println(cmd.length());
    delay(2000);

    if(Serial2.find(">"))      {
    Serial.print(">");
    }
    else {
    Serial2.println("AT+CIPCLOSE");
    Serial.println("connect timeout");
    delay(2000);
    return;
    }
    Serial2.print(cmd);
    delay(2500);

    while (Serial2.available()) {
    char c = Serial2.read();
    Serial.write(c);;
    if(c=='\r') Serial.print('\n');
    delay(5);
    }

    Serial.println("");
    Serial.println("====");
    delay(2000);
    }

    boolean connectWiFi() {

    String cmd;
    int iIP;

    iIP = 0;
    Serial2.println("AT+CWMODE=1");
    delay(5000);
    while (Serial2.available())
    Serial.write(Serial2.read());

    cmd="AT+CWJAP=\"";
    cmd+=SSID;
    cmd+="\",\"";
    cmd+=PASS;
    cmd+="\"";

    Serial2.println(cmd);

    delay(2000);
    Serial.println("Line 1");
    while (Serial2.available() > 0)
    Serial.write(Serial2.read());

    delay(2000);
    Serial.println("Line 2");
    while (Serial2.available() > 0)
    Serial.write(Serial2.read());
    if (Serial2.find("OK")) {
    Serial.println("WIFI OK was received!");
    iIP = 1;
    }

    if( iIP == 1 ) {
    Serial.println("OK, Connected to WiFi.");
    return true;
    }
    else  {
    Serial.println("Can not connect to the WiFi.");
    return false;
    }

    }

body:
Your transmitter and receiver pins need to be crossed, rx->tx and tx->rx. As a mnemonic, the two ends of the antenna point to the board edge with the receiver pin and it is that pin that needs the voltage divider. While you're at it, it would be a good idea to tie the RST pin high, as well as the CH_PD. I use one 10K pullup for both.

Recent versions of these boards are shipped with their baud rates set to 115200. Since you're using a hardware UART on the Mega board, you can send/receive to it at that rate.

*Note to readers using a software UART (SoftwareSerial): First thing, change the board's baud rate to 9600 and communicate with it at that rate. You can use SoftwareSerial to make the change as it sends at 115200 reasonably reliably, but its receive function can't keep up at that rate).*

You can confirm your connections and baud rate with:

`EspSerial.println("AT");`

You should receive `OK' in reply.


body:
I wants to do in Arduino countdown that shows how many days, hours and minutes remaining to Friday 12:00.
In my program I used a function in php `strtotime('next friday')` which thus could calculate differential timestamp and show how much time is left until Friday 12:00.

Is there a function `strtotime('next friday')` in Arduino?
I have RTC which gives me just the current date and time, but does not show the current day of the week.

**EDIT:
I have a solution**

We have day of week. We multiplied by 86400.

We have an hour. We multiply by 3600.

We have a minute. We multiplied by 60.

Add everything.

Subtract this from 604800.

`nextFriday  = 604800-((dayofweek * 86400)+(now.hour()*3600)+(now.minute()*60)+now.second());`

Important, Friday is the number of the week "0". Friday = 0; Saturday = 1; etc...

title: How to count the time until the next day of the week?

Answers: 2

body:
The key to working with time is to have a known "base" time to calculate everything relative to.  This is called the *epoch*.  Different systems use different epochs, and each has advantages and disadvantages.

I generally use the UNIX epoch in my programming (chiefly because I am a UNIX nut), which is the first of January, 1970 (01/01/1970).  This is year, month, day, hour, minute and second 0.

From that you can then calculate the number of seconds between the epoch and any other time you choose as long as it is later than the epoch.

To calculate the day of the week for any given date you first need to know the day of the week for the epoch (for UNIX that's a Thursday) then work out how many days there are between the epoch and the target time.

Calculating real times in terms of seconds can be somewhat tricky due to leap years and daylight savings, but there are plenty of algorithms in the public domain, and many RTC libraries include functions to convert to/from epoch times.

For instance, the [Arduino Time Library](http://playground.arduino.cc/code/time) has functions to calculate weekdays, and to convert to "time_t" format (seconds since epoch) which can be used to work out differences in times.  For instance, if you know that it's Tuesday and you want next Friday then you know that Friday is 3 days in the future - so you can get the current time in seconds from the epoch then add to that 3 days' worth of seconds (3 × 60 × 60 × 24) to that time to get the same time of day next Friday.

body:
<!-- language-all: lang-C++ -->
There are generic examples, e.g. [Determination of the day of the week - Wikipedia](https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week).

> In the C language expressions below, **y**, **m** and **d** are, respectively, integer variables representing the year (e.g., 1988), month (1-12) and day of the month (1-31).

            (d+=m<3?y--:y-2,23*m/9+d+4+y/4-y/100+y/400)%7

Also see [StackOverflow - C Program to find day of week given date](https://stackoverflow.com/questions/6054016/c-program-to-find-day-of-week-given-date).


body:
I'm trying to use my 30A ACS712 on my OSD (it has ATMEGA16L).

But it is very unstable, 0 amps goes from 450 to 445, but that isn't that bad, but when I put 10A of current through it jumps from 440 to 380.

I already searched on google and tried to add filter cap between acc and gnd, but it didn't help and acs712 and osd have different power supply than the load.

Any help is welcome.

title: ACS712 inacurrate reading. Wild jumping

Answers: 1

body:
This is not a simple chip to use.  These parts of the data sheet may help you understand what is happening.  It is internally an analog device and needs clean power.  I would highly recommend you download the Allegro data sheet, it has a lot of information that will help you.  Below is a short section of the data sheet, The first paragraph should give you a hint that the output voltage will be about 2.5V with a 5V unipolar power supply.

"Quiescent output voltage (VIOUT(Q)). The output of the device
when the primary current is zero. For a unipolar supply voltage,
it nominally remains at VCC⁄ 2. Thus, VCC = 5 V translates into
VIOUT(Q) = 2.5 V. Variation in VIOUT(Q) can be attributed to the
resolution of the Allegro linear IC quiescent voltage trim and
thermal drift.

Electrical offset voltage (VOE). The deviation of the device output
from its ideal quiescent value of VCC / 2 due to nonmagnetic
causes. To convert this voltage to amperes, divide by the device
sensitivity, Sens.

Accuracy (ETOT). The accuracy represents the maximum deviation
of the actual output from its ideal value. This is also known
as the total output error. The accuracy is illustrated graphically in
the output voltage versus current chart at right."

I realize this does not answer your question but it does give you a good starting point to resolve your problem.  Hopefully you or a buddy has some analog experience, that will help a lot.  Oh Yes clean power supplies are imperative for this to work.


body:
I'm using an Arduino Yun to read from a data file, which will then populate a data structure. The `file.read()` function "*returns: The next byte (or character), or -1 if none is available.*"

This functionality is identical to the `SD.read()` function in the SD card library.

The data file will never have any value that exceeds 1 byte with all numbers in the range 0-255. If I print these numbers as a long string in the data file, each character is read as a byte. So I need to call `file.read()` 3 times to read in a single 0-255 value. And then do some additional processing to construct the final 8-bit value for storing.

I could reduce this to 2 calls by printing the Hex code in the data file, but this isn't much of an improvement.

**Is there a way to encode a full byte in a single character?**

**Effectively , is there a particular way I can format my data file so that I can read in an `8-bit unsigned` value in a single call to `file.read()`?**

title: Encoding an entire Byte for File Reading

Answers: 2

body:
This is a fragment (untested) of how you can do it:

    char datafile[512];
    int ch;
    int index = 0;

    while ((ch = file.read()) != -1) {
      datafile[i] = (char)ch;
      if (++i == 512)
        break;
    }

body:
There's two parts to what you want to do, writing the file in the right form, and reading that format file.

The format of file is known as *raw binary*. Every byte in the file can store a separate value between 0 and 255, or between -128 and 127, dependin on how you interpret the data.  At the end of the day, every byte in a file is just a collection of 8 bits yielding 2^8 = 256 combinations. What those combinations actually mean is more of a human thing than a machine thing.

We, as humans, have decided upon three main representations of those bytes: *unsigned* numbers from 0 to 255, *signed* numbers from -128 to 127 (lookup two's complement) and finally ASCII characters.

ASCII characters are more of a lookup table placed over one of the other two representations. Some systems use unsigned bytes and some signed bytes for the basis of that lookup tabe.

Writing text into the file results in looking up the corresponding byte values for each character in that text and placing those values in the file. When you read the file the reverse is done - the byte values are read and you look them up in the ASCII table to find the corresponding letters.

To store just numbers between 0 and 255 it is far more efficient to bypass that ASCII table and store the values directly as bytes. How you do that is entirely dependent on what language you are writing your software in. Since you haven't mentioned what that language is I can't advise you on that front' only give some examples in languages I know.

Such as in C you would store your data in an array of *unsigned char* or *uint8_t*. You then use the `write()` function to write raw data to the file.

In Perl you might use the `pack()` function to store your values as bytes in a string then write that string to a file.

When reading the data you are presented with a raw value. That may be given to you as a signed or an unsigned value depending on the underlying system. I don't know what the yun is off hand. Converting from whatever is handed to you by thr `file.read()` function to what you expect it to be though is a very simple matter, and is called *casting*.

    int in = file.read();
    uint8_t bval = (uint8_t)in;

The bit in brackets is the *cast* which converts the value in the integer *in* into a uint8_t (Unsigned INTeger 8-bit Type) which corresponds to whatever you wrote as an unsigned char or uint8_t at the other end.


body:
I'm looking to create a USB device that would  be basically a HID keyboard. I am able to do that with Uno. I flash new firmware with a HID keyboard descriptor and on the arduino side I loop and check for button presses. Based on butotn presses I send the report.

What I would like to add to this is option to send some data from a PC and based on that data do something (like turn an LED on.)

Here is an example:

    loop() {
      check_and_send_buttons();
      uint8_t inputByte = get_input(); //new
      handle_input(inputByte); //new
    }

I'm on Linux and I tried sending some data via hidrawX but that did not work out.
Any ideas?

I'm willing to also write new device driver for Linux if needed.

title: Uno as a composite USB HID keyboard

Answers: 1

body:
On UNO R3 the HID protocol is handled by the secondary AVR present on the board. Which is the one talking to the PC. So what you should modify is the code implementing the USB protocol on the secondary AVR.

The main (328p) AVR interacts with it through the serial port.

You do not need to alter the Linux driver, since it already supports the driving of the usual LEDs (CAPS, Num Lock, Scroll Lock), if these are enough for you.

So, to recap:

 1) enhance the HID implementation to understand LED status commands coming from the PC

 2) report such changes over serial

 3) on the primary AVR, monitor for such messages coming over serial port from the secondary AVR and use them to drive the LEDs.


body:
I'm preparing this kit on eBay to create the following instructable - http://www.instructables.com/id/4x4x4-RGB-LED-Cube/
But I have doubts about 0.1uF and 22pF capacitors since the once on eBay are 50v. Also MOSFETs - instructable uses IRF9531 but the ones I found on eBay are IRF9540N.
Is the equipment I added on eBay compatible with instructable?

title: Verify RGB Led Cube equipment

Answers: 2

body:
Capacitor ratings don't really matter in your case, as you are using only 5 volt. Only their values (F) do.

Though the crystal you selected has an indication it needs 20pF load capacitors, not 22pF. 22pF is probably still fine. (Also note the ±20% accuracy, so between 17.6 and 26.4pF)

The IRF9531 and IRF9540N have the same pinout. They are also pretty similar in specs. The IRF9540N is slightly better even.

Note that the ATMega328p doesn't have the bootloader pre-installed. It's not that hard to do yourself though.

The EEPROM you selected is an SMD version. Kind of hard to work with if you are still a beginner. Better use a [DIP version](http://www.ebay.com/itm/2PCS-AT24C256-10PU-2-7-DIP-8-24C256-PU27-2-Wire-Serial-EEPROM-GOOD-QUALIITY-/311362511891?hash=item487ea6e413) instead (that one is a bit more expensive, but 4 times the size)

I'd suggest you add an [USB to Serials Adapter](http://www.ebay.com/itm/FT232RL-FTDI-Serials-Adapter-Module-Mini-Port-f-Arduino-USB-TTL-3-3V-5-5V-/311406775045?hash=item48814a4b05) to the list, so you don't need the Arduino Uno every time you want to reprogram it, and use the Uno for something more useful.

body:
For a crystal with 20pF load capacitance you need 40pF capacitors.

The formula used is:

* Cx1 = Cx2 = 2(CL - Cpara)

CL is 20pF and Cpara is the parasitic capacitance of the circuitry involved. Under most amateur circumstances that can be ignored.


body: I'm supplying power to Arduino via PC USB.

title: Can both the 3.3V and 5V pins on the Arduino be used at once for power?

Answers: 1

body:
Yes.

Here's a block diagram of how the Arduino power is arranged:

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

As you can see the USB power is fed through a FET (P-channel MOSFET) to isolate it when there is external power applied (as decided by the comparator *COMP*).  External power is fed through a 5V regulator and is fed to the same point as the USB power.  Thus you get the same 5V at the same point regardless of if you have USB or Barrel Jack power.  From there the 5V (wherever it comes from) is fed into a 3.3V regulator.  The 5V pin on the Arduino is connected directly to the 5V point where the USB and the 5V regulated input are connected. The 3.3V pin is connected directly to the output of the 3.3V regulator.

So no matter what input power arrangement you use - barrel jack, USB power, battery connected to the V IN pin (not shown, but connects to the barrel jack), or regulated 5V into the 5V pin, you get access to the same 5V and 3.3V power on the 5V and 3.3V power pins.

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


body:
I'm trying to get a ESP8266 board with 2x4 pins to work. I'm connecting it to an Olimexino 32u4 (Leonardo-compatible), configured to use 3.3V. This simple snippet I use to transfer everything to the PC (CH_PD is connected to D8, /RST to D9):

    void setup() {
      pinMode(8, OUTPUT);
      pinMode(9, OUTPUT);
      digitalWrite(8, LOW);
      digitalWrite(9, LOW);
      delay(2000);
      // initialize both serial ports:
      Serial.begin(9600);
      Serial1.begin(115200);
      delay(10000);
      digitalWrite(9, HIGH);
      digitalWrite(8, HIGH);
    }

    void loop() {
      // read from port 1, send to port 0:
      if (Serial1.available()) {
        int inByte = Serial1.read();
        Serial.write(inByte);
      }

      // read from port 0, send to port 1:
      if (Serial.available()) {
        int inByte = Serial.read();
        Serial1.write(inByte);
      }
    }

When launching, I see following output:

    <"random" bytes>
    Ai-Thinker Technology Co. Ltd.

    invalid

Performing a reset shows more:

    AT+RST

    OK

     ets Jan  8 2013,rst cause:2, boot mode:(3,6)

    load 0x40100000, len 1396, room 16
    tail 4
    chksum 0x89
    load 0x3ffe8000, len 776, room 4
    tail 4
    chksum 0xe8
    load 0x3ffe8308, len 540, room 4
    tail 8
    chksum 0xc0
    csum 0xc0

    2nd boot version : 1.4(b1)
      SPI Speed      : 40MHz
      SPI Mode       : QIO
      SPI Flash Size & Map: 8Mbit(512KB+512KB)
    jump to run user1 @ 1000

    ŒÂÕ�MEM CHECK FAIL!!!
    äsl�‚rô
    Ai-Thinker Technology Co. Ltd.

    invalid

The mode is set to station:

    AT+CWMODE?

    +CWMODE:1

    OK

Listing the access points works fine:

    AT+CWLAP

    +CWLAP:(3,"ap-1",-91,"01:23:45:67:89:ab",1)
    +CWLAP:(3,"ap-2",-88,"cd:ef:01:23:45:67",2)
    +CWLAP:(3,"ap-3",-74,"89:ab:cd:ef:01:23",11)

    OK

But logging in to my Fritzbox router fails (WPA2):

    AT+CWJAP="ap-2","mypassword"
    WIFI CONNECTED
    +CWJAP:1

    FAIL
    WIFI DISCONNECT

First I thought the reason is the low signal, but even moving directly beside the Fritzbox shows the same result (though with higher signal value in `AT+CWLAP`).

I've tried nearly everything, e.g. `AT+CWMODE=3`, `AT+RST`, `AT+RESTORE`). Nothing changes. When using a wrong password, I'm getting no "WIFI CONNECTED" messages at all.

Could it be a power problem (that the Olimexino can't provide up to 200mA at the 3.3V line?

Connecting from my smartphone to the ESP8266 in one of its access point modes (2 or 3) works fine. If there were power problems, wouldn't then the access point mode fails as well?

title: ESP8266 failure to connect to router

Answers: 4

body:
It looks like the ESP8266 could not obtain the IP address over DHCP (it was enabled in the ESP8266, but the Fritzbox was configured for a limited range only .200 - .209). When setting the IP explicitly:

    AT+CIPSTA="192.168.92.82","192.168.92.254","255.255.255.0"

    OK
and then trying to connect, it worked:

    AT+CWJAP="ap-2","mypassword"
    WIFI CONNECTED
    WIFI GOT IP

    OK
Pinging also works now: :)

    AT+PING="arduino.stackexchange.com"

    +39

    OK

body:
In my case when I try to connect to my router, I get the following output:

    AT+CWJAP="myssid","mypassword"
    WIFI CONNECTED
    +CWJAP:1

    FAIL
    WIFI DISCONNECT

The reason is that the ESP8266 I have is setup with DHCP disabled by default. To enable it you can try the following:

    AT+CWDHCP=1,1

If that works, you will get this message:

    OK
    WIFI GOT IP

body: I had many headaches related with this CWJAP:1 error and few others like Ok in return for change IP number command but actually the IP number still the same as before !!! The solution: The AT+RESTORE command to bring the ESP8266 back to the factory defaults... When not logical things happens for unknow reason probably is due to some internal register has dirty values inside and only a AT+RESTORE can normalize them...

body:
I had this same problem and spent an embarrassing number of hours trying to fix it before coming across this post.

I did a `AT+RESTORE` followed by `AT+UART_DEF=9600,8,1,0,0` since, as expected, my module expected communication on 115200 after the restore.

Then... as if by magic, everything works now...

    AT+CWJAP="ssis","pwd"
    WIFI CONNECTED
    WIFI GOT IP

    !

I really don't know what was wrong that the `RESTORE` fixed... I must have screwed up the module by experimenting with various commands somehow.


body:
I just changed the router for my webserver and I'm having trouble to connect my arduino with the LAN.
I'm using a router which uses Zhone technology, and I've been working with NetGear for a while without problems.
The procedure I've done so far is:

 1. Connect the arduino with the ethernet and run the DhcpAdressPrinter example
 2. Once I got the adress, in my case 192.168.1.125 I run the WebServer example, using the IP assigned by the DHCP.
 3. In the serial monitor, I see it has started the program with the correct IP.

Problem: WHEN PUTTING THE IP INTO A BROWSER, NOTHING CHARGES

More info:

 - In my router page (192.168.1.1) I can see that each ethernet port has
   assigned a MAC adress, I don't really understand why.
 - I also can see that the arduino has been successfully added to the DHCP with the IP assigned and the MAC adress that I wrote on the code
 - Finally, add that I've read in another website that sometimes the problem is due to the fact that the router just let the access to some specific MAC adress, but i'm not sure.

Any help will be apreciated! Thanks!

title: Connect my arduino with ethernet shield to new router

Answers: 1

body:
Finally, I was capable to solve it by just creating a port forwarding with the IP that was assigned by the DCHP.
It looks like my router for security reasons don't let you comunicate with other devices within the lan, so it's necessary to open a port and access the device through it!


body:
 I'm using a DOGM163 Display. It works in a DEMO sketch provided by the manufacturer but not in my sketch. This is strange, because I am using the same library specific commands as in the example.

I think of the following possibilities:

 1. Something inside the other libraries I use in my sketch is hindering the dogm from working (perhaps by fiddling around with the ports connected to the display).

 2. I've got a power problem which surfaces when doing more than just that demo.

 3. Timing is botched.

 4. Something with my wiring is wrong. Perhaps in conjunction with 1).

I'm using:

    #include <Arduino.h>
    #include "newsched.h"
    #include "dplan.h"
    #include <EEPROM.h>
    #include <PinChangeInt.h>
    #include <dogm_7036.h>
    #include <SPI.h>
    #include <OneWire.h>
    #include "lampcontrol.h"

Power seems to be ok, as I'm receiving all debug messages via serial correctly.

The display is sharing its port with a port expander and a SD-port. But removing the SD-port doesn't change the problem.

**Update (Part1)**
Here comes the code, which works:

[http://pastebin.com/eXUVzeV8][1]

This is a slightly modified manufacturer example. But it does what it should do. It displays the demo text.

Here comes, what doesn't work:

[Main sketch][2]
[newsched.h][3]
[newsched.cpp][4]
[display.h][5]
[display.cpp][6]
[menu.h][7]
[menu.cpp][8]

The other source files, 19 in total!, can be posted on request, but as you can see from newsched.cpp I already disabled most of the code to narrow down the error.

What exactly means "not work"? Not work means, the display seems to be turned off. The LED backlight is on, but you cannot see the grey character boxes (due to display bias), which appear in the working code sample.

**Update 2**
Schematic: [![Schematic][9]][9]

  [1]: http://pastebin.com/eXUVzeV8
  [2]: http://pastebin.com/MCsyDUXL
  [3]: http://pastebin.com/1xSNGhCs
  [4]: http://pastebin.com/UCPuyG08
  [5]: http://pastebin.com/cKCErjHR
  [6]: http://pastebin.com/dvVWdJAK
  [7]: http://pastebin.com/278UYXGu
  [8]: http://pastebin.com/PhYikzBP
  [9]: https://i.stack.imgur.com/PcBLd.jpg

title: Display unresponsive in one sketch, while working in another

Answers: 0


body:
I'm quite new to Arduino. I have build a number of projects successfully, like potentiometers, serial communication, DAC, sensors, motors etc.

I use a laptop to power my Arduino project and Atmel Studio to program and upload to the Arduino. I have created a project with 2 motors and I have successfully used a separate power supply (a transformer) to power the motors.

Now I want to continue my experiments but I'm afraid of the possibility to cause any problem to my laptop.

When I made the circuit with the 2 power sources (laptop for the Arduino, transformer for the motors) I had to connect the 2 grounds together.

So my question is that:

*Can someone explain me or point me to some information about power electronics so to be absolutely sure that I won't cause any problem to the laptop?*

Should I use optocouplers, or diodes etc? Is there a way to avoid the 2 grounds connection? What is the reason to connect both grounds (of the 2 power supplies) in the first place?

title: safety for power electronics

Answers: 1

body:
Connecting the grounds together is required since without that there would be no circuit for the current to flow through.  Take this simple block diagram for instance:

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

In the top diagram there are two complete circuits - the green one (Arduino's 5V power) and the blue one (device's 12V power).  The communication between the Arduino and the Device can't happen because there is no circuit (red).

In the bottom diagram the red circuit has been completed by joining the grounds together.  That means that the current has some way to get back to where it came from (which current always *has* to do) so the signals you send can actually get through.

To avoid having to connect the grounds together you need something called *Galvanic Isolation*.  This involves using some method that is not electricity to connect the two circuits together.  That could be using light in the form of an opto-coupler, or magnetism in the form of a transformer, or even something even more physical like a relay.  In that situation you have an arrangement like this:

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

The ground connection that was part of the red circuit above has now been sliced in half (red and orange now) and the isolation device is responsible for passing the signal from one side to the other.

Galvanic isolation is highly desirable when:

* You are controlling a different *type* of current (e.g., using DC to switch AC)
* You are working with voltages considerably higher than your drive voltage (e.g., switching mains)
* You have different ground potentials (e.g., you have a long distance connection)

  [1]: https://i.stack.imgur.com/0uyFv.png
  [2]: https://i.stack.imgur.com/G9hvY.png


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

I'm trying to connect Arduino with MySQL database on my online server.

I manage my project to work on WampServer locally on localhost, but when I try to move everything online I have problem... on the serial monitor I get the message that the server is connected and my sensor readings, but I can't put them in to my database on my online sever.

Here is my code:

---

**dbconnect.php**

    <?php
    $MyUsername = "*******";  // enter your username for mysql
    $MyPassword = "*******%";  // enter your password for mysql
    $MyHostname = "*************";      // this is usually "localhost" unless your database resides on a different server

    $dbh = mysql_pconnect($MyHostname , $MyUsername, $MyPassword);
    $selected = mysql_select_db("tanjamayaarduino",$dbh);
    ?>

---

**add_data.php**

    <?php
        // Connect to MySQL
        include("dbconnect.php");

        // Prepare the SQL statement
        $SQL = "INSERT INTO tanjamayaarduino.temperature (sensor ,celsius, light, moisture1, moisture2) VALUES ('".$_GET["serial"]."', '".$_GET["temperature"]."','".$_GET["light"]."','".$_GET["moisture1"]."','".$_GET["moisture2"]."')";

        // Execute SQL statement
        mysql_query($SQL);

        // Go to the review_data.php (optional)
        header("Location: review_data.php");
    ?>

---

**Arduino code**

    #include<Ethernet.h>
    #include<SPI.h>
    const int temperaturePin = A3;    //LM35 Temperature sensor
    const int lightPin = A2;          //LDR photoresistor sensor
    const int moisture1Pin = A4;          //Moisture1 sensor
    const int moisture2Pin = A5;          //Moisture2 sensor

    // **** ETHERNET SETTING ****
    // Arduino Uno pins: 10 = CS, 11 = MOSI, 12 = MISO, 13 = SCK
    // Ethernet MAC address - must be unique on your network - MAC Reads T4A001 in hex (unique in your network)
    byte mac[] = { 0x90, 0xA2, 0xDA, 0x0F, 0x3A, 0xDC };
    // For the rest we use DHCP (IP address and such)
    IPAddress ip(192, 168, 2, 121);
    EthernetClient client;
    //IPAddress server(192, 168, 2, 100); // IP Adres (or name) of server to dump data to
    // IP Adres (or name) of server to dump data to  (godaddy baza server 37.148.204.140) (User: tanjamayaarduino@188.121.42.33) (goddady glavna adresa na hostingot 188.121.46.1)
    //IPAddress server(188, 121, 46, 1);
    char server[] = "188.121.46.1";

    int  interval = 5000; // Wait between dumps

    void setup() {

      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }
      if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
        // no point in carrying on, so do nothing forevermore:
        // try to congifure using IP address instead of DHCP:
        Ethernet.begin(mac, ip);
      }

      Serial.println("Tweaking4All.com - Temperature Drone - v2.0");
      Serial.println("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-\n");
      Serial.print("IP Address        : ");
      Serial.println(Ethernet.localIP());
      Serial.print("Subnet Mask       : ");
      Serial.println(Ethernet.subnetMask());
      Serial.print("Default Gateway IP: ");
      Serial.println(Ethernet.gatewayIP());
      Serial.print("DNS Server IP     : ");
      Serial.println(Ethernet.dnsServerIP());
    }

    void loop() {
      // if you get a connection, report back via serial:
      if (client.connect(server, 80)==1) {
        float tem = getTemp();
        Serial.println( tem );
        float lig = getLight();
        Serial.println( lig );
        float mois1 = getMoisture1();
        Serial.println( mois1 );
        float mois2 = getMoisture2();
        Serial.println( mois2 );

        Serial.println("-> Connected");
        if (client.connected()) {
          // Make a HTTP request:
          client.print( "GET /advertacs/test/arproekt/add_data.php?");
          Serial.println("-> add_data");
          client.print("serial=");
          client.print( "TempSensor" );
          client.print("&&");
          client.print("temperature=");
          client.print( tem);
          Serial.println("-> add_temp");
          client.print("&&");
          client.print("light=");
          client.print( lig);
          Serial.println("-> add_light");
          client.print("&&");
          client.print("moisture1=");
          client.print( mois1);
          Serial.println("-> add_mois1");
          client.print("&&");
          client.print("moisture2=");
          client.print( mois2);
          Serial.println("-> add_moi2");

          client.println( " HTTP/1.1");
          client.println( "Host:" );
          client.println(server);
          client.println( "Connection: close" );
          client.println();
          client.println();
          client.stop();
        }
      }
      else {
        // you didn't get a connection to the server:
        Serial.println("--> connection failed/n");
      }

      delay(interval);
    }
    float getTemp() {
      float temperatureC = (5.0 * analogRead(temperaturePin) * 100.0) / 1024; //converting from a 0 to 1023 digital range to 0 to 5 volts (each 1 reading equals ~ 5 millivolts
      return temperatureC;
    }
    float getLight() {
      float light;
      light = analogRead(lightPin) ;
      return light;
    }

    float getMoisture1() {
      float moisture1;
      moisture1 = analogRead(moisture1Pin) ;
      return moisture1;
    }
    float getMoisture2() {
      float moisture2;
      moisture2 = analogRead(moisture2Pin) ;
      return moisture2;
    }

title: Connect Arduino to MySQL database online problem

Answers: 2

body:
There are two basic things wrong with your code.  First is the formatting of your headers - you have mistakenly used `client.println` for sending the first part of the Host: header, so it becomes split onto two lines:

    client.println( "Host:" );
    client.println(server);

Secondly you are using the server's IP address instead of the actual host name in the Host: header. That means the server can't work out which website you are wanting to talk to and just rejects your request.

You need to have something more like:

    client.print("Host: ");
    client.println(servername);

where `servername` is the *name* of the server (`www.website.com`) *not* the IP address.  You can put it all in one line if you don't ever want to change the website name, since it makes it slightly harder to find and edit:

    client.println("Host: www.mywebsite.com");

body:
First of all, are you now connected to SQL? If so, and it still doesn't work... Have you tried to escape your `"`, so instead of:

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

    $SQL = "... VALUES ('".$_GET["serial"]."', '".$_GET["temperature"]."',...')";

doing something like:

    $SQL = "... VALUES ('\".$_GET[\"serial\"].\"', '\".$_GET[\"temperature\"].\"',...')";

If it still doesn't work, once you send to SQL with your code, print on screen what you are effectively sending, copy it with your mouse, paste it in your phpadmin-sql console and execute it. There you should see any helpful tips on what is really happening.
Hope this helps!


body:
I'm not sure if this is more of an C++ question, but I've looked up both and still have no idea.

I have a sketch which controls 6 stepper motors using the AccelStepper library and in order to shorten the code, I would like to simply loop over them, or pass them to a function individually. They are all initialised with different parameters and then placed in an array.

However I get the error "conversion from ‘SomeClass()’ to non-scalar type ‘SomeClass’ requested" or "conversion from ‘SomeClass (*)()’ to non-scalar type ‘SomeClass’ requested" depending on what I try.

I've got experience with C and Java, not much C++ and I thought it would be a straightforward array of pointers, but I can't get the right combination.

I've made a cut down version that I try to compile with gcc to demonstrate either approach. I've removed all attempts at pointers with & or * to explain what I want:

    SomeClass classA();
    SomeClass classB();

    // error: conversion from ‘SomeClass()’ to non-scalar type ‘SomeClass’ requested
    SomeClass things[2] = {classA, classB};

    int init(class SomeClass thing) {
     std::cout << "Setting up thing ";
     thing.setFoo(100);
    }

    int main() {

     for (int i=0; i < 2; i++) {
      things[i].setFoo(100);
     }

     // could not convert ‘classA’ from ‘SomeClass (*)()’ to ‘SomeClass’
     init(classA);

       return 0;
    }

And just for completeness my class files which are simplified versions of the AccelStepper class:

SomeClass.h:

    #include <stdlib.h>

    class SomeClass
    {
    public:
        SomeClass();

        void    setFoo(float foo);
    };

SomeClass.cpp:

    #include <stdlib.h>
    #include <string>
    #include <iostream>
    #include "SomeClass.h"

    SomeClass::SomeClass()
    {
    }

    void SomeClass::setFoo(float foo)
    {
     std::cout << "foo ";
    }

I hope someone doesn't mind explaining what is probably really simple and obvious! :)

title: How to loop over objects or pass object to function?

Answers: 1

body:
There's a couple of fundamental errors in your sketch.  Mainly your construction of your class instances:

    SomeClass classA();
    SomeClass classB();

Those are taken as functions that return a SomeClass object, not SomeClass constructors.  Instead they should just read:

    SomeClass classA;
    SomeClass classB;

As for the rest, you are much better off using pointers to the classes - it makes passing them around so much easier.  For instance, your array would look like this:

    SomeClass *things[2] = {&classA, &classB};

That is an array of pointers to the objects.  It just stores the addresses that they are at, rather than duplicating the objects into new objects within the array.

Your loop would then run like this:

    for (int i=0; i < 2; i++) {
        things[i]->setFoo(100);
    }

Note the use of `->` instead of `.` because you are using a pointer to the object.

Similarly your `init()` function would be like this:

    int init(SomeClass *thing) {
        Serial.println("Setting up thing");
        thing->setFoo(100);
    }

    init(&classA);

However, if you're never going to use the contents of your array with it you could use a reference instead of a pointer:

    int init(SomeClass &thing) {
        Serial.println("Setting up thing");
        thing.setFoo(100);
    }

    init(classA);

That performs the same job as a pointer but leaves you with what looks like a real object rather than a pointer to the object - in fact it's just aliased the object name to a new one at the same address so you can still access it the same using `.`


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

title: Arduino Delivering less power

Answers: 1

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.


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

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

Answers: 2

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


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

title: How Add Piezo Buzz to Pong Sketch

Answers: 2

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.


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

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

Answers: 1

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
            }
        }
    }


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

title: AnalogWrite custom voltage

Answers: 1

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


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

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

Answers: 1

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.


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

title: Loading Leonardo bootloader to Atmega32U4 running at 8 MHz

Answers: 1

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.


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

title: Sending a value from one arduino to another

Answers: 3

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.


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

title: how to detect 125khz tags with mfrc 522

Answers: 2

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


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

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

Answers: 1

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.


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

title: Arduino as voltage monitor shorts to ground

Answers: 1

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


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

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

Answers: 2

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.


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

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

Answers: 1

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


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

title: What is the I2C address of a sensor?

Answers: 2

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.


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

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

Answers: 1

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


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

title: What's wrong with my ESP8266?

Answers: 3

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.


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

title: Fog Machine - On Command

Answers: 1

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