message:
millis() not working properly

I'm doing a little project that, on a press of a button, will light up three LEDs and then will turn off the LEDs in different times. I'm using the `millis()` function to control the time that each LED will be on.

On the first time that I press the button, everything works fine. But the problem starts when I press the button for the second time.

If I press the button soon after the loop ends, something goes wrong and the behavior of the LED become a mess (just one or two LEDs light up in weird times). But, if I wait about 2 seconds before pressing the button for the second time, everything goes right.

Here's my code:

    const int ledPin1 =  11;
      const int ledPin2 =  12;
      const int ledPin3 =  13;
      const int buttonPin = 2;

      int buttonState = 0;
      long previousMillis1 = 0;
      long previousMillis2 = 0;
      long previousMillis3 = 0;

      int state = 0;

      void setup()
      {
        pinMode(ledPin1, OUTPUT);
        pinMode(ledPin2, OUTPUT);
        pinMode(ledPin3, OUTPUT);
        pinMode(buttonPin, INPUT);

        Serial.begin(9600);
      }

      void loop()
      {

           buttonState = digitalRead(buttonPin);

           if (buttonState == HIGH) {
            state = 1;
           }

           if (state == 1)
           {
            taskExecute(3000, 2000, 4000);
           }
      }

      void taskExecute(int tMotor1, int tMotor2, int tMotor3)
      {

        int ledState1 = HIGH;
        int ledState2 = HIGH;
        int ledState3 = HIGH;

        digitalWrite(ledPin1, ledState1);
        digitalWrite(ledPin2, ledState2);
        digitalWrite(ledPin3, ledState3);

        do
        {
          unsigned long currentMillis = millis();

          if(currentMillis - previousMillis1 > tMotor1)
          {
            previousMillis1 = currentMillis;

            if (ledState1 == HIGH)
              ledState1 = LOW;

            digitalWrite(ledPin1, ledState1);
          }

          if(currentMillis - previousMillis2 > tMotor2)
          {
            previousMillis2 = currentMillis;

            if (ledState2 == HIGH)
              ledState2 = LOW;

            digitalWrite(ledPin2, ledState2);
          }

          if(currentMillis - previousMillis3 > tMotor3)
          {
            previousMillis3 = currentMillis;

            if (ledState3 == HIGH)
              ledState3 = LOW;

            digitalWrite(ledPin3, ledState3);
          }
        } while (ledState1 == HIGH || ledState2 == HIGH || ledState3 == HIGH);
        state = 0;
      }

Other strange thing that happens is that sometimes the time that i've been set in millis for the led get on become a little different. Example: when I press the button, the LED 1 needs to light up for 3 seconds, but he lights up just 2.5 seconds.

What i'm doing wrong? Thanks!!

body:
The variables `previousMillis` (1-3) are not properly initialised.  So if you wait a while before pressing the button, that delay time becomes part of the time that the LED is illuminated for.

If your `taskExecute()` function sets them before the loop, this will fix that:

    void taskExecute(int tMotor1, int tMotor2, int tMotor3)
    {
        int ledState1 = HIGH;
        int ledState2 = HIGH;
        int ledState3 = HIGH;

        digitalWrite(ledPin1, ledState1);
        digitalWrite(ledPin2, ledState2);
        digitalWrite(ledPin3, ledState3);

        unsigned long time_now = millis();
        previousMillis1 = time_now;
        previousMillis2 = time_now;
        previousMillis3 = time_now;

        do
        {
            ...
        } while (ledState1 == HIGH || ledState2 == HIGH || ledState3 == HIGH);
        state = 0;
    }

On a coding-style note - I did not initially see the resetting of the global variable `state=0` at the end of the `taskExecute()` function.  It might be better to move this up to underneath the initial call to `taskExecute()` so all the `state` handling is in one place.


sender: user

message:
How to limit the number of message that an Arduino sends to a phone without terminating it

I just stayed on `delay()` since that is the only thing I know but the thing is `delay()` cannot be interrupted. What I'm trying to achieve with this code is:

 1. When the soilSensor detects moisture it would send a text message to a number only ONCE without terminating the program even if in the next loop the soilSensor is still detecting moisture.

 2. The soilSensor's delay is `delay(60000)` and we would still wait for while to finish the delay but what if in the middle of the soilSensor's `delay(60000)` there is a movement for just about 5 seconds? What to do so that the tiltSensor can overlap the soilSensor's delay and sends a message to a number?

I want this program to run forever. Please help me! I needed this ASAP!

    #include <SoftwareSerial.h>
    SoftwareSerial SIM900(7, 8);
    int led=22;

    void setup()
    {
      Serial.begin(9600);
      SIM900.begin(19200);
      pinMode(led, OUTPUT);
      delay(1000);
    }

    void sendSMS1()
    {
      SIM900.println("AT + CMGS = \"+************\"");
      delay(100);
      Serial.println("Water Detected");
      delay(100);
      SIM900.println("Water Detected");
      delay(100);
      SIM900.println((char)26);
      delay(100);
      SIM900.println();
      delay(100);
    }

    void sendSMS2()
    {
      SIM900.println("AT + CMGS = \"+************\"");
      delay(100);
      Serial.println("Movement Detected");
      delay(100);
      SIM900.println("Movement Detected");
      delay(100);
      SIM900.println((char)26);
      delay(100);
      SIM900.println();
      delay(100);
    }

    void loop()
    {
      int soilSensor = analogRead(A0);
      int tiltSensor = analogRead(A1);

      if(soilSensor >= 10)
      {
        digitalWrite(22, HIGH);
        Serial.println(soilSensor);
        sendSMS1();
        delay(60000);
      }
      else
      {
        digitalWrite(22, LOW);
        delay(60000);
      }

      if (tiltSensor >= 100)
      {
        digitalWrite(led, HIGH);
        Serial.println(tiltSensor);
        sendSMS2();
        delay(60000);
      }
      else
      {
        digitalWrite(led, LOW);
        Serial.println(tiltSensor);
        delay(60000);
      }
    }

sender: assistant

body:
You use millis() to keep track of time and also prevent blocking. Replicating your program logic:

    long soil_timer = 0;
    long tilt_timer = 0;
    char soil_flag = 1;
    char tilt_flag = 1;

    void loop() {
        int soilSensor = analogRead(A0);
        int tiltSensor = analogRead(A1);

      if (soil_flag == 1) {
        if (soilSensor >= 10) {
          digitalWrite(22, HIGH);
          Serial.println(soilSensor);
          sendSMS1();
        }
       else {
          digitalWrite(22, LOW);
        }
        soil_timer = millis();
        soil_flag = 0;
      }

      if (tilt_flag == 1) {
        if (tiltSensor >= 100) {
           digitalWrite(led, HIGH);
           Serial.println(tiltSensor);
           sendSMS2();
        }
        else {
           digitalWrite(led, LOW);
           Serial.println(tiltSensor);
        }
        tilt_flag = 0;
        tilt_timer = millis();
      }
      if (millis() - soil_timer >= 60000){
         soil_flag = 1;
      }
      if (millis() - tilt_timer >= 60000){
         tilt_flag = 1;
      }
    }


message:
How to change Multiple variable values through Serial Monitor

I am trying ... with minimal success to change/Check and also run voids through the serial monitor .the code i  put i am having probles is that when i am try to send a value larger than 9 the value assigns a diffrent number Ex i set to 200 but arduino sets it as 512.. i got around it deviding the value by 1.6 and got me the new number and only works upto 90 , but i am tryn to see how it should be done correctly...

    const uint16_t inputLength = 512;
    int ss = 0;
    int bHold = 0;

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

     void loop() {
      if ( Serial.available() > 0 )
      {
        static char input[inputLength];
        static uint16_t i;
        char c = Serial.read();

        if ( c != '\r' && c != '\n' && i < inputLength - 1)
          input[i++] = c;

        else
        {
          input[i] = '\0';
          i = 0;

          uint16_t array[80];
          uint16_t j = 0;

          if ( !strncmp(input, "ss", 2) )
          {
            char* p = input + 2;
            while ( (p = strchr(p, ' ')) != NULL )
              array[j++] = strtol(p, &p, 10); //< changed from 16

            for ( uint8_t i = 0; i < j; i++ )
            {
              ss = array[i];
              Serial.println(ss);
            }
          }

          if ( !strncmp(input, "bHold", 5) )
          {
            char* p = input + 5;
            while ( (p = strchr(p, ' ')) != NULL )
              array[j++] = strtol(p, &p, 10);   //< changed from 16

            for ( uint8_t i = 0; i < j; i++ )
            {
             bHold = array[i];
            // bHold=bHold /1.6;
             Serial.println(bHold);
            }
          }

          if ( !strncmp(input, "Whos There", 10) )
          {
            Serial.print("me");
          }
          if ( !strncmp(input, "hello", 5) )
          {
            Serial.print("hi");
          }
          if ( !strncmp(input, "sa", 2) )
          {
            Serial.print("  ss= ");
            Serial.print(ss);

            Serial.print("  bHold= ");
            Serial.print(bHold);

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

Thank you for any tips you can give...

EDIT: I am trying to pass a new value with command on the serial monitor "ss 500"..so that in the arsuino ss = 500. but in this case it makes it equal to 1280.

EDIT2: Chaged the strol to 10...works perfectly ...Thank you TisteAndii!!!!

body: You are setting the input string's base to 16 instead of 10 in your `strtol` conversions, which is why you are getting 1280 when you expect 500.


message:
Connect function generator to Arduino

How do I connect a function generator that generates an analog signal to an Arduino Uno?

I don't know how to begin, so could you also tell me the settings for the function generator, e.g. its amplitude, frequency, etc, that won't damage my Arduino?

I plan to visualize the output on Processing.

[![Agilent 33220A Function Generator][1]][1]
<sub>(source: [sonoma.edu](https://www.sonoma.edu/users/m/marivani/es110/images/fg_big.jpg))</sub>

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

body:
> I don't know how to begin, so could you also tell me the settings for the function generator, e.g. its amplitude, frequency, etc, that won't damage my Arduino?

That is not an Arduino question. That is a question about how to operate the function generator. Please check the users manual. You need to set the voltage output (DC + AC) so that it matches the Arduino.

An analog signal should go to an analog pin on the Arduino (not pin 8). It is also important to connect GND.

Cheers!


body:
Looking at the [Agilent 33220A 20 MHz Waveform Generator User's Guide][1], I can see that the Function Generator has a USB port. If you have, or can get hold of, a [USB *Host* shield][2] for the Arduino, you should be able to link the two together physically. Then, using the [USB Host Library for Arduino][3], you could get the two talking to each other.

Alternatively, if you fancy a bit more hard work, then you could get a MAX3421E, and wired it up yourself as an interface, but I wouldn't recommended it.

Note: If you have an Arduino Due (I know that you say that you have an Uno, but just in case) then you could use the [USBHost library][4] to connect the two directly, without the need for a USB Host shield.

Regarding, getting the two to talk together, that may not be exactly easy. From the manual I can see that the PC software can auto-configure the function generator, however, for receiving data it may not be so easy. You appear to have to send a **GTL** command to get the data sent to the USB (p251, and onwards, of the manual). Good Luck! :-)

  [1]: http://cp.literature.agilent.com/litweb/pdf/33220-90002.pdf
  [2]: https://www.arduino.cc/en/Main/ArduinoUSBHostShield
  [3]: https://github.com/felis/USB_Host_Shield_2.0
  [4]: https://www.arduino.cc/en/Reference/USBHost


body:
## Confirm with an oscilloscope

When I connect my function generator I <s>usually</s> always make sure that the output is in the range 0 to 5V, with my oscilloscope. The default is probably more like ±2.5V - but I don't have an Agilent so you would have to check. Press the `Ampl` button to check. (Mine reads 5VPP).

[![Default operation][1]][1]

You can see from the above image that we indeed have (roughly) 5VPP - and that there is a -2.56V component, which will damage the Arduino, being negative.

---

## Add an offset

So press the `Offset` button and add a 2.5V DC offset. Now the voltage jumps 2.5V and is between 0 and 5V:

[![With 2.5V offset][2]][2]

The scope confirms that the minimum is 80mV and the maximum is 4.96V, which is in range for an Arduino pin (assuming you are running an Arduino at 5V, which is not always the case).

Now you should be safe to experiment with different frequencies and wave-forms. Just leave the Amplitude and Offset alone. :)

---

## Extra precautions

You could feed the function generator through an input protection circuit, just in case you absent mindedly forget to carry out the appropriate steps.

[![Input protection][3]][3]

The zener diode will conduct negative voltages to ground (dissipated through the 1k resistor) and will also limit positive voltages to around 5.1V.

  [1]: https://i.stack.imgur.com/Jn5AO.png
  [2]: https://i.stack.imgur.com/kk2e1.png
  [3]: https://i.stack.imgur.com/Pm0WV.png


message:
Why is there a clock in my arduino?

Of course I know it is usefull to control the time of a delay, but any other use?

With a 16Mhz clock, each line of my program will take 1/16000000 second, right?

even a very very big line will only take 1/16000000 of a second ?

With a 8MHz clock, each line will take the double of the time, right?
So the whole "main loop"  will take the double time too, right?

body:
> Why is there a clock in my arduino?

Because that is how computers and microcontrollers, etc, work.

> With a 16mhz clock, each line of my program will take 1/16000000 second, right?

No.

> even a very very big line will only take 1/16000000 of a second ?

No.

The clock defines at what speed the *machine code instructions* are fetched from memory and executed. Most instructions take 1 clock cycle, but some take more.

One line of C code may be compiled into any number of assembly instructions, which then get converted into machine code (raw numbers).  That could be anywhere from 1 assembly instruction to thousands of assembly instructions, depending on what the line does.

> With a 8mhz clock, each line will take the double of the time, right? So the whole "main loop" will take the double time too, right?

Every operation in the chip is governed by the clock. If the clock is half the speed the chip is running at half the speed, so every operation will take twice as long, yes.


body:
Not answered in @Majenko's post: Yes, with a 8MHz clock, each line will take the double of the time. Unless the line waits for something that is not clock driven - e.g. external input.

In addition to @Majenko's answer, a CPU has a clock to ensure the instructions are complete, before the next step starts. A CPU is made out of lots of transistors (I found a reference that indicated the AtMega was in the range of low millions, give-or-take an order of magnitude).

During a cycle, the electricity flows through the chip, turning transistors on/off, the results of which will turn more transistors on/off, and so forth down the line. While this is happening, some parts of the chip have a "wrong" value - you can think of this as being half-way through a calculation (you've added the one's column and the 10s column, and are about to start on the 100s column). You don't want this to affect the outside world, so (for example) your output pins are latched - held at whatever value they are - until the instruction is complete. How long it takes to complete an instruction varies, but the manufacturer works out the slowest instruction under the worst circumstances.

For the AtMega (which is the chip on the Arduino), Atmel (who designed the chip) has declared this is 1/20,000,000 of a second - this is 20MHz.

Note that not all microprocessors run all their instructions at 1 instruction per cycle - some instructions might take 1, or 2, or 10 cycles. Pipelining makes things even more complicated - a processor might do some of the work (e.g. fetch the next instruction) in one cycle, execute it in the next - but while it is executing instruction 1, it can also fetch the next instruction. To do this, it might need to take a guess at what instruction comes next (in the case of the machine-code equivalent of a "goto" - such is used for loops), and if it guesses wrong, it has to cope with that; throw away the instruction it retrieved and retrieve the next one, losing a cycle.

The Wikipedia page on [instruction pipelining][1] shows an example of a RISC chip pipelining in 5 stages - instruction fetch, instruction decode, execute, memory access, and write-back. So, you can have 5 instructions at some stage of execution, overlapping. Until the "writeback" phase, the instructions have no real effect. You can think of this as an assembly line - it takes 7 minutes to put a widget together, but it can be broken down into 5 stages, the longest stage taking 2 minutes. Once every two minutes, each partly completed widget is moved by the assembly line to the next station. You get one widget out every two minutes - The "clock" can only tick as fast as the slowest step. If you push the widget out any faster, the "bottleneck" will get more and more widgets queued up.

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


message:
How to get the MAC address of an Ethernet shield, if it is not printed on it?

Help me to find out how to connect an Ethernet shield over the internet using a LAN cable. I have tried many times but I'm not getting a MAC and IP address.

body:
If you do not have a MAC address then you have to make one up.  There are a couple of rules and regulations about what a MAC address can be, but most of the time you can just make one up:

1. It must be unique on *your* network
2. There are a set of prefixes that are reserved for special purposes:
  * The lowest bit of the first byte must be 0
  * The second bit of the first byte must be 1

You can read more about it here: https://en.wikipedia.org/wiki/MAC_address

Once you have provided a MAC address and physically connected it to the network then you need an IP address and netmask.  There are two ways you can get the IP address and netmask:

1. Through DHCP - For example your home internet router would provide the IP address for you.
2. By allocating your own. This must be within the range of your network's IP addresses, typically something like 192.168.0.x where x is between 1 and 255.  The IP address must be unique on your network.

The netmask, again, can be given by DHCP, otherwise you will have to enter the netmask of your network, typically 255.255.255.0

Then to access the internet itself you need to provide (or be provided with through DHCP) the address of the internet gateway and possibly a DNS server address. On a home network they are typically the address of the router, which may well be 192.168.0.1 or something similar.


message:
esp8266-01 and arduino UNO communicating over i2c

i am not able to communicate over i2c with my esp-01 as master and UNO as slave. i get special characters sent back to esp, but my esp is sending correctly...
output on my esp-01
[![output on my esp-01][1]][1]
output on my UNO is
[![output on my UNO][2]][2]

  [1]: https://i.stack.imgur.com/iBFZA.png
  [2]: https://i.stack.imgur.com/LkRcZ.png

connections are esp-01 gpio-0 to uno A4 and gpio-2 to uno A5
is it because i am not using a level shifter or any mistake in my code..?

here is my esp master code

    #include <Wire.h>
    #define I2CAddressESPWifi 6
    int x=32;

    void setup()
    {
      Serial.begin(115200);
      Wire.begin(0,2);//Change to Wire.begin() for non ESP.
    }

    void loop()
    {
      Wire.beginTransmission(I2CAddressESPWifi);
      Wire.write(x);
      Wire.endTransmission();
      x++;
      delay(1);//Required. Not sure why!

      Wire.requestFrom(I2CAddressESPWifi,10);
      Serial.print("Request Return:[");
      while (Wire.available())
      {
        delay(100);
        char c = Wire.read();
        Serial.print(c);
      }
      Serial.println("]");
      delay(500);
    }

and here is my Uno slave code

    #include <Wire.h>
    #define I2CAddressESPWifi 6

    void setup()
    {
      Serial.begin(115200);
      Wire.begin(I2CAddressESPWifi);
      Wire.onReceive(espWifiReceiveEvent);
      Wire.onRequest(espWifiRequestEvent);
    }

    void loop()
    {
      delay(1);
    }

    void espWifiReceiveEvent(int count)
    {
      Serial.print("Received[");
      while (Wire.available())
      {
        char c = Wire.read();
        Serial.print(c);
      }
      Serial.println("]");
    }

    void espWifiRequestEvent()
    {
      String ts = getTime();
      Serial.print("Sending:[");
      Serial.print(ts.c_str());
      Serial.println("]");
      Wire.write(ts.c_str());
    }

    String getTime(){
      int sec = millis() / 1000;
      int min = sec / 60;
      int hr = min / 60;
      String ts = "U:";
      if (hr<10) ts+="0";
      ts += hr;
      ts +=":";
      if ((min`)<10) ts+="0";
      ts += min % 60;
      ts +=":";
      if ((sec`)<10) ts+="0";
      ts += sec % 60;
      return(ts);
    }

body: Perhaps the `Serial.print()`s in the slave's request event function are causing too much delay (clock stretching?). You should make the `Wire.write()` the second statement in that function right after the `getTime` call. Or you could use `Wire.write("Hello")` as the only statement in the function, so you can narrow down the problem.


message:
Serial.print() is slower than it should be

I'm trying to use Arduino as a DAQ but the `Serial.print()` is not working as fast as I expected. How many bits are sent if you are using a int, because if I use a `uint8_t`, it's taking the same amount of time? How I could improve the speed of the `Serial.print()`? I'm already working at 115200 baud.

body:
By not using `Serial.print`?

`Serial.print` will format the number as a string of ASCII characters. The number of characters depends on the size of the number. Yes, that is very wasteful.

If you are sending values between 0 and 255 (`uint8_t`) you can just send the raw value as a single ASCII character, since there are 256 of those.

    Serial.write(myVal);

For anything greater than 255, i.e., you want to send an `int` or `uint16_t` then you will have to come up with some better way. You can't send one byte for the full value, so you would have to send it as two bytes:

    Serial.write((myVal >> 8) & 0xFF);
    Serial.write(myVal & 0xFF);

HOWEVER... how do you know which byte coming in is which? It's very very easy to get out of sync and not get the right values when you read the data in.  So you need some way of "packetizing" the data so that you know "This is a correct set of values".  Just how you do that is entirely up to you - do you just wrap each pair of bytes in a special set of other bytes? Nah - that becomes as wasteful as `Serial.print`. Instead it's better to buffer up a batch of values and send them as a block with just a few extra bytes to define the packet.

One example of doing that is my [ICSC library](https://github.com/MajenkoLibraries/ICSC/). Take a look at it and you can see how you can craft a packet to send lots of data as one stream of data.


body:
`Serial.print` sends the ASCII representation of the data. So:

    uint8_t data8 = 102;
    uint32_t data32 = 102;
    char datastring[] = "102";
    Serial.print(each_of_the_previous_data);

each of these are sent exactly in the same way, i.e. three bytes ('1', '0', '2', so 0x31 0x30 0x32).

This, as you noticed, is highly inefficient. What I suggest you is to send them in binary mode, so

    uint8_t *convertToByteArrayLittleEndian(uint8_t *buffer, int32_t val)
    {
     uint8_t i;
     for (i = 0; i < 4; i++)
     {
      buffer[i] = val & 0xFF;
      val = val >> 8;
     }
     return buffer;
    }
    uint8_t *convertToByteArrayBigEndian(uint8_t *buffer, int32_t val)
    {
     uint8_t i;
     for (i = 0; i < 4; i++)
     {
      buffer[3-i] = val & 0xFF;
      val = val >> 8;
     }
     return buffer;
    }

    uint8_t supportArray[4];
    uint8_t data8 = 102;
    uint32_t data32 = 102;
    char datastring[] = "102";
    Serial.write(data8); // Sends 0x64 = 100
    Serial.print(convertToByteArrayLittleEndian(supportArray,data32),4); // Sends 0x64 0x00 0x00 0x00
    Serial.print(convertToByteArrayBigEndian(supportArray,data32),4); // Sends 0x00 0x00 0x00 0x64
    Serial.print(datastring); // Sends 0x31 0x30 0x32

I had to use an helper function to convert from int to byte array, since Serial.write does not support directly an int. You can choose if you want to send the data in big endian or little endian format.

As you can see, in binary mode the amount of data exchanged varies.

Just three more things.

1) you probably can go higher in frequency (maybe 1Mbit/s) with the serial. Just try it out

2) If you decide to use binary mode, maybe you will need some synchronization (i.e. a start byte) to ensure you are not listening a stream from a "middle" point. There are various techniques (prevent use of some bits in the stream, use some forbidden values and escape it)...

3) If you want to go faster, I suggest you to switch peripheral. For instance use SPI (of course you won't be able to use a common USB-UART interface, but you can create a native USB dongle with an SPI interface to get the connection)

EDIT:

According to other info from the OP:

The data is 10 bits. Let's split it into two 5bits data, so we can use the upper 3 bits for sending sync info (to understand which byte comes first). The required rate is 6kHz.

I made some calculations, and it looks like that you can use this code:

    #include "TimerOne.h"

    bool timerHasBeenTriggered = false;

    void setup()
    {
     Timer1.initialize(167);         // initialize timer1, and set a 6kHz frequency
     Timer1.attachInterrupt(callback);
     Serial.begin(#HIGHER_THAN_115200#);
    }

    void callback()
    {
     timerHasBeenTriggered = true;
    }

    void loop()
    {
     int16_t val = analogRead(ANALOG_PIN); // takes 104us
     Serial.write((val & 0x1F) | 0xA0); // Send lower 5 bits, upper 3 set to 101
     Serial.write((val >> 5) & 0x1F); // Send lower 5 bits, upper 3 set to 000
     while (!timerHasBeenTriggered);
     timerHasBeenTriggered = false;
    }

Here the loop has an execution time of around 104us (serial calls just store the values in a queue). The vast majority of the time is spent acquiring from a channel.

I used a timer to trigger the next acquisition so it can be more precise (and the millis() function is useless, since you want to trigger it 6 times per millisecond).

From the PC you will receive two bytes. The first one is in the form `0b101XXXXX`, the second `0b000YYYYY`. You will only have to

1. wait for a byte starting with 101
2. save the other 5 bits (XXXXX)
3. get the next byte and check it starts with 000
4. the data will be just the concatenation of the two 5-bits chunks: YYYYYXXXXX

Note that the limiting factor of the timing is the analogRead function. If you want to go faster (or to acquire from multiple channels) you will need to change the ADC clock prescaler. This, however, will make your ADC frequency higher than 200kHz, which is not recommended (you will get less precise data).


body:
>  I need a sample rate of 6 kHz

OK, so that means you need to sample and send every 1/6000 seconds (167 µs).

I have a [lengthy discussion about the ADC hardware](http://www.gammon.com.au/adc). Amongst other things is a table of conversion times for the different ADC prescalers, assuming a 16 MHz clock:

    Prescaler
        2    * 13 * 1/16E6  = 0.000001625 (  1.625 µs)
        4    * 13 * 1/16E6  = 0.00000325  (  3.25  µs)
        8    * 13 * 1/16E6  = 0.0000065   (  6.5   µs)
       16    * 13 * 1/16E6  = 0.000013    ( 13     µs)
       32    * 13 * 1/16E6  = 0.000026    ( 26     µs)
       64    * 13 * 1/16E6  = 0.000052    ( 52     µs)
      128    * 13 * 1/16E6  = 0.000104    (104     µs)

If you go for maximum resolution (10 bits) you need a prescaler of 128, which takes 104 µs. The number of conversions you can do a second (taking the inverse of the above) is:

    Prescaler  Conversions/sec
      2           615,385
      4           307,692
      8           153,846
     16            76,923
     32            38,462
     64            19,231
    128             9,615

---

You also need to take into account the transmission time. At 115200 baud you can transmit one byte every 1/11520 seconds (86.8 µs) so therefore two bytes (16 bits) would take 173.6 µs.

If you sample then transmit you will therefore take, per sample:

    104 + 174 = 278 µs

This is too slow if you want to achieve it inside 167 µs.

---

You can sample asynchronously (in the background) so you transmit one sample while taking the next one, but you are still limited by the transmission speed of serial, so it would still take 174 µs per sample.

In fact, fiddling with the prescaler isn't really the issue here because the serial transmission time is the limiting factor.

Forget about the ADC and how it works for the moment. At 115200 baud you can't transmit 2 x 6000 bytes per second. That is simply because the maximum is 11520 bytes per second.


body:
If your signal of interest is of short-enough duration, you might get by by collecting the data into memory, then dumping it at whatever speed you can. If you're using an Uno or other AtMega328 based Arduino, the RAM size, and therefore, your buffer, will be quite limited. Storing the first value as int and subsequent values as one-byte differences can help.

An on-board memory device, like an [FRAM][1], could buffer 8K or 32K bytes (or half as many ints).

Or the same differences technique can be used to send one-byte binary differences and improve your sample transmission rate. It's easy to get out of sync, though. This won't be too reliable for continuous or long data streams.

Otherwise, you're just baud-bound. How fast can you drive the serial output and the receiver still be able to keep up? You're pushing the edges of what the device can do. It's an interesting problem and possibly fun to solve, but I'm reminded of the old adage about alligators and needing to drain the swamp! :)

  [1]: https://www.adafruit.com/index.php?q=FRAM&main_page=adasearch


body:
Some benchmarking of Serial.print() and comparing to clib functions (itoa/ltoa) might give some insight. First, printing int and long int with DEC base using Arduino core Print functions (Arduino IDE 1.6.7, Arduino Mega2560).

    Serial.print(12345, DEC): 240 us
    Serial.print(12345678L, DEC): 388 us

Second, use HEX base.

    Serial.print(0x1234, HEX): 204 us
    Serial.print(0x12345678L, HEX): 384 us

Third, use the AVR clib functions to convert number to a string and then print the string. 10 and 16 base.

    Serial.print(itoa(12345, buf, 10)): 104 us
    Serial.print(ltoa(12345678L, buf, 10)): 240 us

    Serial.print(itoa(0x1234, buf, 16)): 80 us
    Serial.print(ltoa(0x12345678L, buf, 16)): 240 us

Cheers!

----------

Below is the test sketch:

    void setup()
    {
      uint32_t start, stop, us;
      char buf[16];
      Serial.begin(9600);

      start = micros();
      Serial.print(12345, DEC);
      stop = micros();
      us = stop - start;
      Serial.println();
      Serial.print(F("Serial.print(12345, DEC): "));
      Serial.print(us);
      Serial.println(F(" us"));
      Serial.flush();

      start = micros();
      Serial.print(12345678L, DEC);
      stop = micros();
      us = stop - start;
      Serial.println();
      Serial.print(F("Serial.print(12345678L, DEC): "));
      Serial.print(us);
      Serial.println(F(" us"));
      Serial.flush();

      start = micros();
      Serial.print(0x1234, HEX);
      stop = micros();
      us = stop - start;
      Serial.println();
      Serial.print(F("Serial.print(0x1234, HEX): "));
      Serial.print(us);
      Serial.println(F(" us"));
      Serial.flush();

      start = micros();
      Serial.print(0x12345678L, HEX);
      stop = micros();
      us = stop - start;
      Serial.println();
      Serial.print(F("Serial.print(0x12345678L, HEX): "));
      Serial.print(us);
      Serial.println(F(" us"));
      Serial.flush();

      start = micros();
      Serial.print(itoa(12345, buf, 10));
      stop = micros();
      us = stop - start;
      Serial.println();
      Serial.print(F("Serial.print(itoa(12345, buf, 10)): "));
      Serial.print(us);
      Serial.println(F(" us"));
      Serial.flush();

      start = micros();
      Serial.print(ltoa(12345678L, buf, 10));
      stop = micros();
      us = stop - start;
      Serial.println();
      Serial.print(F("Serial.print(ltoa(12345678L, buf, 10)): "));
      Serial.print(us);
      Serial.println(F(" us"));
      Serial.flush();

      start = micros();
      Serial.print(itoa(0x1234, buf, 16));
      stop = micros();
      us = stop - start;
      Serial.println();
      Serial.print(F("Serial.print(itoa(0x1234, buf, 16)): "));
      Serial.print(us);
      Serial.println(F(" us"));
      Serial.flush();

      start = micros();
      Serial.print(ltoa(0x12345678L, buf, 16));
      stop = micros();
      us = stop - start;
      Serial.println();
      Serial.print(F("Serial.print(ltoa(0x12345678L, buf, 16)): "));
      Serial.print(us);
      Serial.println(F(" us"));
      Serial.flush();

    }

    void loop()
    {
    }

The clib itoa/ltoa are regarded to be relative slow and there are proposals to improve performance. Please see, for instance, this [bug report][1].

  [1]: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=627899


message:
NewliquidCrystal example HelloWorld_i2c just flickers

I've bought a cheap I2C LCD display (specs in the end of this question).

I can't make it print. I've tested with two displays of same model, so nothing is broken.

I am using the NewliquidCrystal 1.3.4 library, ie not the "normal" LiquidCrystal library. I'm trying with the I2C example called HelloWorld_i2c ([link to example code][1]). I've only changed the address from 0x37 to 0x27.

It compiles fine, but the result is only that the display flickers.

What is wrong and how do I fix it?

Super simple example flickers too
---

Well, this one gives just one blink.

 #include <Wire.h>
 #include <LiquidCrystal_I2C.h>
 LiquidCrystal_I2C lcd(0x27);  // Set the LCD I2C address
 void setup()
 {
   lcd.begin(16,2);               // initialize the lcd
   lcd.home ();                   // go home
   lcd.print("Hello, ARDUINO ");
 }
 void loop()
 {
 }

Pictures
---

In the light it shows that the writing to the display is randomly jumping around.

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

In the dark, it shows that the background light flickers:

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

Details about the LCD display
---

Text on the backside

 YwRobot Arduino
 QAPASS
 LCM1602 IIC V1

Text on the chip

 TLPCF85747
 HA
 T62281
 A N 1
 I L knM988223

  [1]: https://bitbucket.org/fmalpartida/new-liquidcrystal/raw/20245cfb111aadad288f73102fcf353356a89651/examples/HelloWorld_i2c/HelloWorld_i2c.pde
  [2]: https://i.stack.imgur.com/cybkA.gif
  [3]: https://i.stack.imgur.com/Hd20P.gif

body:
I was able to make the example run as intended, by using a different constructor call:

    LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

I am not able to tell you, what these parameters and values mean. However, the documentation for this constructor is shown below ([source][1]).

 /*!
     @method
     @abstract   Class constructor.
     @discussion Initializes class variables and defines the I2C address of the
     LCD. The constructor does not initialize the LCD.

     @param      lcd_Addr[in] I2C address of the IO expansion module. For I2CLCDextraIO,
     the address can be configured using the on board jumpers.
     @param      En[in] LCD En (Enable) pin connected to the IO extender module
     @param      Rw[in] LCD Rw (Read/write) pin connected to the IO extender module
     @param      Rs[in] LCD Rs (Reset) pin connected to the IO extender module
     @param      d0[in] LCD data 0 pin map on IO extender module
     @param      d1[in] LCD data 1 pin map on IO extender module
     @param      d2[in] LCD data 2 pin map on IO extender module
     @param      d3[in] LCD data 3 pin map on IO extender module
     */
    LiquidCrystal_I2C( uint8_t lcd_Addr, uint8_t En, uint8_t Rw, uint8_t Rs,
                      uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3 )
 ;

  [1]: https://github.com/marcmerlin/NewLiquidCrystal/blob/master/LiquidCrystal_I2C.h#L100


body: Try to pull the I2C sensor at the back of the LCD board, you can see that it is shorted to the SMD mounted on the back,  just pull it a little so that it won't touch and short the conductors. This has happened to me, try it if this works.


message:
How to control nokia 5110 display using esp-01

I am working on a smart device using esp-01 to pull data from internet and display on Nokia 5110 LCD display, and send back the resistive touch inputs to my server and display those on my lcd I am using an Arduino UNO as a secondary device that talks to esp-01, my display and the resistive touch panel. As the esp-01 has got a system on chip, I can program it and do most of the thing my UNO is doing, but because of lack of ports I am using UNO (as far as i know that's the only limitation.. I dont exactly know how is the analog pins on UNO different from the gpio pins on esp) is there any ways if I can do the whole task using only my esp-01 by eliminating UNO. If its only about the less gpio pins on esp-01, will I be able to eliminate UNO by using higher esp such as esp-07 or esp-12E? if not, could you suggest a best way of bi-directional communication between esp and UNO? (so that esp can sent the display info to uno and based on that info, uno can send the resistive touch inputs to esp)

body: Yes, you can use a NodeMCU ESP12E board for example as a standalone microcontroller, you actually don't need an Arduino in your case.


body:
The ESP-12 (don't know about other versions) does have one ADC pin.
https://github.com/esp8266/Arduino/blob/master/doc/reference.md#analog-input

I don't know how much your pins display needs. If this is more than one, then you will need a seperate ADC. There are many available as a single chip, but you could also use an arduino as you're doing now.


message:
Addressing EACH of the 3x3x3 LEDs separately

I read a few 3x3x3 LED tutorials, e.g. let us take this one:

http://www.instructables.com/id/Making-an-Arduino-3X3-LED-Cube-in-Less-Than-30-Min/?ALLSTEPS

As far as I understand, you can address any of the 3x3 _light columns_:

    *  *  *       1  2  3
    *  *  *       4  5  6
    *  *  *       7  8  9

and each of the three vertical layers:

    top
    middle
    bottom

But can I address each of the 27 leds separately? In other words, can I light up:

    1+  2   3         bottom layer
    4   5+  6
    7   8   9

    1   2+  3         middle layer
    4+  5   6
    7   8   9

body:
No, the three transistors are there to select the layer you want to control. At every moment only ONE layer can be on. But if you switch through controlling these layers fast enough, you can create the illusion of having multiple leds on even across layers. THis is because the human eyes are just not capable of seeing lights flashing at a high rate.

TL;DR
No you can't address them individually, but you can create the illusion that you can.


body:
3 * 3 * 3 = 27

**The easy/overkill way**

You could do this by assigning a pin to every LED (on an arduino Mega)

**The overkill way**

Use shift registers, almost any arduino will do.
The shift register will set it's outputs according to the amount of high/low signals being clocked in.
In theory, you can address an infinite amount of LED's (only limited by space, time or funds).

**Breaking it down**

You can break it down, so that you control each layer at once.
Effectively you only drive 9 LED's (1 layer).
And attach a transistor to the negative side of the layer.
This way you can choose a LED with the positive side, and a layer with the negative (per layer) control.

Switching these layers rapidly, will make the changes invisible to the eye. So it seems that the LED's are on all the time.

**To infinity**

Combine the overkill way (shift registers) with breaking it down (to reduce cost/size) and you'll be able to create a (somewhat) scalable design.

There are an awfull lot of tutorials, I suggest you choose one you can understand, try to make a smaller cube, and scale up from there!

***Scaling issues***

 - You'll need a better powersupply for each series of LED's you add.
 - Costs.
 - Processing time, the arduino might not be able to clock the signals fast enough, making it visible for eyes. (depends on the amount of LED's)

Be sure to check/measure/calculate these things along the project.


message:
Arduino UNO Rx/Tx speaks to itself

I'm trying to make my chinese arduino (which use a chinese CH340G chip) speaks to itself via serial.
I have wired rx/tx together.

Then, I run the arduino IDE and go to the serial monitor.

When I write a message, the arduino should respond with the exact same message, right ? Actually, when I write a message, the arduino doesn't respond anything...

body:
After some research I found the below schematics of an Arduino UNO with CH340G. A loop-back is not possible as there is a voltage divider (1K ohm, i.e. RX/TX LED) resistors on the RX and TX line.

[![UNO with CH340G][1]][1]

Tested on a Chinese Arduino Uno clone (VISduino) with CH340G and just as you wrote a loop-back does not work. Tested also an Arduino Mega 2560 clone with CH340G and a Duemilanove clone with FTDI. Both these work just fine.

Cheers!

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


body:
There is no problem doing a loopback on an Arduino Uno, but you cannot
use the serial monitor at the same time. I wrote the following test
program, which works as expected:

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

    const int LED_PIN = 13;

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

    void loop() {
        uint8_t data = random();
        Serial.write(data);
        while (!Serial.available()) { /* wait */ }
        if (Serial.read() == data) {

            // Two short pulses = success
            digitalWrite(LED_PIN, HIGH);
            delay(100);
            digitalWrite(LED_PIN, LOW);
            delay(100);
            digitalWrite(LED_PIN, HIGH);
            delay(100);
            digitalWrite(LED_PIN, LOW);
            delay(700);
        } else {

            // One long pulse = failure
            digitalWrite(LED_PIN, HIGH);
            delay(500);
            digitalWrite(LED_PIN, LOW);
            delay(500);
        }
    }

There are, however, two caveats with this naive program:

1. the loopback wire has to be removed before uploading
2. after connecting the wire, the Arduino has to be reset to get out of
the while loop.


body:
As Mikael Patel pointed out in his answer, you have set up a voltage divider. Mikael has thoughtfully provided a schematic of the clone Uno, where the relevant part is here:

[![Clone schematic][1]][1]

---

## Equivalent circuit

If you jumper together pins D0 and D1 (Rx and Tx) on the Uno effectively you have made this circuit:

[![Loop-back voltage divider][2]][2]

---

## Testing

If I set up this with a function generator, I get this result:

[![Loop-back scope results][3]][3]

You can see that for a square-wave input of 0 to 5V, we only get an output of 2.16 to 5V.

---

## What is LOW?

Now looking at the datasheet for the DC characteristics we see:

[![DC characteristics][4]][4]

For an input to register as LOW it has to be no higher than `0.3 * Vcc = 0.3 * 5`. Thus the voltage cannot be higher than 1.5V. Since we are measuring 2.16V, that will not count as a LOW.

Now admittedly that is for the Atmega328P and not the CH340G, but it will probably have similar characteristics.

I found a datasheet for the CH340G, and that shows even stricter requirements for a LOW signal:

[![CH340G datasheet][5]][5]

---

## Official Uno

Comparing to the official Uno circuit:

[![Uno schematic][6]][6]

You will note there that the indicator LEDs are on a different circuit, and thus do not form a voltage divider.

---

## The Maths

The clone Uno circuit above can be re-arranged like this:

[![Re-arranged circuit][7]][7]

Given that the LEDs have a voltage drop of 1.86V (measured in practice, and about right for the red LEDs I am using) then effectively we have the resistors R1 and R2 connected to 3.14V.

Since they are in parallel they are effectively 500 ohms.

Now using the formula for voltage dividers:

    1000 / (1000 + 500) * (5 - 1.86) = 2.09V

This is close enough to the observed result. I didn't check each resistor to make sure it was exactly in spec.

I don't think R4 affects the results because it is effectively "floating".

  [1]: https://i.stack.imgur.com/YKHdw.png
  [2]: https://i.stack.imgur.com/oM9IO.png
  [3]: https://i.stack.imgur.com/2j648.png
  [4]: https://i.stack.imgur.com/sNI3Y.png
  [5]: https://i.stack.imgur.com/FBn9B.png
  [6]: https://i.stack.imgur.com/Oj1bl.png
  [7]: https://i.stack.imgur.com/Hv5FO.png


message:
Arduino Due with Atmel Studio 7

I was trying to switch to Atmel Studio for programming my Due project since it became more and more complex.
I managed to use the Arduino Importer Wizard to load a blink.ino file and included all the requested libraries more or less my hand that were marked as missing during compiling.
Now the compiling kind of works, but I still get this error:

    Error  (inkerScript): No such file or directory ECU arm-none-eabi-g++.exe 0

The `(inkerScript):` part is no typo. It is really like this in the console.
Taking a look in the Toolchain Options I have these settings (which I am not able to edit):
[![Linker Options][1]][1]

Going into the Miscellaneous Part of the Options I can edit these fields:
[![Miscellaneous Options][2]][2]

By editing the Linker Flags field, I can change the error message from `(inkerScript): No such file or directory` to e.g. `HelloWorld: No such file or directory`.

Is there anything wrong with my options? What is the correct setting for "Linker Flags" and what are they doing?

Unfortunately I am not a pro with C++ Compiling / Linker Errors / Settings.

Thanks.

  [1]: https://i.stack.imgur.com/Jx8rV.png
  [2]: https://i.stack.imgur.com/GJijt.png

body:
I just encountered this.  After looking at other examples in the compiler command line options, it looks like it should be $(LinkerScript) instead of ($LinkerScript).

In Atmel Studio, go to project properties, toolchain, ARM/GNU Linker, Miscellaneous to find the option to change.


message:
Arduino Yun & nRF24L01+ -> Linino crashing

I'm trying to hook up a nRF24L01+ wireless transmitter to an Arduino Yun Mini on SPI, but I'm having a hard time. After a few minutes Linino crashes and becomes completetly inaccessible - until I upload a new sketch to the Arduino.

I connected the SPI pins (MOSI, MISO and SCK) to the corrensponding pins of the Yun. I connected CE to pin 3 and CSN to pin 2. I'm using the RF24 library found here: [https://github.com/TMRh20/RF24][1]

The following little code is enough to make Linino crash:

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

    RF24 radio(3,2);

    void setup() {
      radio.begin();
    }

    void loop() {

    }

What am I doing wrong here? Any ideas? Any help is greatly appreciated!
  [1]: https://github.com/TMRh20/RF24

body:
I finally managed to get it running. It really seems to be a problem with radio interference. I failed to hook up an external WLAN antenna to the Arduino Yun mini but I found a very useful workaround with a usb adapter here:
[http://www.lucadentella.it/en/2014/11/08/yun-adattatore-wifi-usb/][1]

This workaround is possible with an Arduino Yun mini as well but you'll need the Arduino Yun Linux OS from here:
[https://www.arduino.cc/en/Main/Software][2]

because the necessary packages are not available for the Linino system that comes with the Yun mini. Then, you can connect the WiFi adapter to USB+, USB-, 5V and GND of the Yun mini and you're good to go.

  [1]: http://www.lucadentella.it/en/2014/11/08/yun-adattatore-wifi-usb/
  [2]: https://www.arduino.cc/en/Main/Software


message:
Using Arduino microcontrollers without board

I am new into Arduino. So if I program the microcontroller using the Arduino board and once it is doing what I want can I just take the microcontroller out of the board and use the microcontroller itself? If so could you please guide me to some tutorials on how to use it?

body:
I have a post about a [breadboard Arduino](http://www.gammon.com.au/breadboard) - in that I demonstrate the minimal amount of parts you need to use the controller (which is not much).

Example of wiring it up:

[![Minimal Arduino][1]][1]

If you want to use an external crystal or resonator you can add that to the board like this:

[![Crystal on board][2]][2]

8 MHz crystal shown, but you could use 16 MHz. Or change the fuses and use the internal oscillator.

---

Schematic showing how you could (if you wanted) add an ICSP header and an FTDI header:

[![Simplified Arduino schematic][3]][3]

  [1]: https://i.stack.imgur.com/bJdmz.jpg
  [2]: https://i.stack.imgur.com/DHOaY.jpg
  [3]: https://i.stack.imgur.com/XHxrG.png


message:
i2c address instead of assigning pins

I found this sketch online and would like to reuse it. I do have a dot-matrix-display, that is accessable through an i2c with the address 0x70. How do I change the code to be able to use the hardware address instead of the `Data`, `Load` and `CLK` pins?

    #include <DS1307RTC.h>
    #include <Time.h>
    #include <Wire.h>
    #include "LedControl.h"

    //Pin definition constants
    const int mDataIn=12, mLoad=11, mClk=10;  //Max7219 LED matrix

    int h1, h2, m1, m2, s1, s2; // Each digit
    int tChange; //Scratch used during change time via pushbutton

    // Matrix library instance
    LedControl lc=LedControl(mDataIn, mClk, mLoad,1); //Pin assignments and number of matrices (1)

    void setup() {

      // Notify Arduimo that the RTC is the external time provider
      setSyncProvider(RTC.get);

      //Initialize the MAX72XX in power-saving mode.
      lc.shutdown(0,false);
      lc.setIntensity(0,1); // Set brightness to a low value
      lc.clearDisplay(0); // Clear the display
      delay(100); // Wait after initializing display

      Serial.begin(9600);
    }

    void loop() {

      //Isolate hours, minutes, seconds, one digit to each LED matrix column.
      h1=n1(hour());
      h2=n2(hour());
      m1=n1(minute());
      m2=n2(minute());
      s1=n1(second());
      s2=n2(second());

      // Cast as (change integer to) byte, write to LED row.
      // (Row runs from pin to pin on model used.)
      lc.setRow(0,7,byte(h1));
      lc.setRow(0,6,byte(h2));
      lc.setRow(0,4,byte(m1));
      lc.setRow(0,3,byte(m2));
      lc.setRow(0,1,byte(s1));
      lc.setRow(0,0,byte(s2));
      }

      int n1(int num) {  // Function to isolate first digit of 2-digit integer
        num = num / 10; //Integer division by 10 (discard remainder)
        return num;
      }

      int n2(int num) {  // Function to isolate second digit of 2-digit integer
        num = num % 10; //Modulo division by 10 (keep remainder only)
        return num;
      }

body:
>  How do I change the code to be able to use the hardware address instead of the Data, Load and CLK pins?

That is not possible as this is two totally different LED drivers. MAX72XX uses a protocol with those signals, while the dot-matrix LED display uses I2C.

You can always port the library to the dot-matrix. Or rewrite the sketch with the dot-matrix library.

Cheers!


message:
Does lowering arduino analog reference increase precision in measuring low voltage?

The definition for Analog Reference is as follows: The reference voltage used for analog input (i.e. the value used as the top of the input range).

By default you have analog reference of 5V. So the precision of analogRead is 5 / 1023 = 0.0048875.

Now what happens if I lower the analog reference to let's say 1V. Does that mean that the precision now is 1 / 1023 (and the arduino can't measure voltages higher than 1V) or it is the same precision as before with the only difference being the fact that the arduino can't measure voltages higher than 1V anymore?

body:
The former, i.e precision would now be 1/1023 but the accuracy of the AD converter is 4 / 1024 or 1 part in 256  i.e. 0.25%.

Also be aware that the internal reference voltages themselves are not very accurate :

DEFAULT: depends on your computer power supply USB2  Vbus = 4.4V - 5.25V, Vint 1 = 1.1V  actually 1.0 -- 1.2V, Vint 2 = 2.56V  actually 2.4 -- 2.8V


body: The A/D simply gives a binary value between 0 and 1023. That value is evenly divided between reference and ground. Since it is a successive approximation register that starts counting at zero and counts up in consistent steps until the reference voltage is reached, that count is saved and presented as the reading. If your input voltage is in that range you will get a reading on the number of steps from zero where it matched (0 to 1023). If measuring higher voltages you simply use a resistor divider and multiply the reading by that ration.


message:
What is this temperature sensor module? (LM358, 103)

I got this sensor some time ago because I wanted to play with measuring the temperature. I don't remember how I got it or if it has a name.

I've Googled around, and obviously is has the following

 1. LM358 op amp
 2. "103" thermistor

When googling for help I mostly find stuff about how to use the LM358 which is way above my skill level.

What is this and how do use it? :)

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

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

body:
Connect VCC to +5V, GND to GND, then S to A0.

Do an analogRead() of A0 and then convert that to temperature using the Steinhart-Hart equation, inserting the three values A B and C which you don't know because you have no documentation for the thermistor.


body:
"103" is standard resistor (and other component) numbering - the first two digits specify a value and the third is a power-of-ten multiplier:

    1 0 3 = 10 * 10^3 = 10K

    4 7 2 = 47 * 10^2 = 4.7K

For devices that are typically measured in *thousandths*, *millionths* or smaller (like a capacitor) then the third digit is a *minus* power-of-ten:

    1 0 6 = 10 * 10^-6 = 1u

That black disc labelled '103' is a [thermistor](https://en.wikipedia.org/wiki/Thermistor) - a temperature-controlled resistor. It is most likely NTC, or negative-temperature coeffiecient, thus the resistance decreases as the temperature increases. This is contrary to typical physics where an increase in the temperature of a generic conductive material results in an increase in its electrical resistance.

The LM358 is included to *buffer* the thermistor from the Arduino/microcontroller. In simple terms, this means that the effective resistance of the analogue input pin does not have to be taken into consideration when converting the voltage measured to into a value for the temperature.

Without a better picture of both sides of the board, or better yet a circuit diagram, it is not possible to determine what the voltage on pin `S` will be for a given temperature. However, it seems that the thermistor is in series with another 10K resistor (`R3`, marked '103' of course) such that an increase in temperature results in an increase in voltage. At roughly 20 degrees Celsius (it depends on the manufacturer and their specifications) the resistance of the thermistor will be 10K, thus the voltage at `S` will be `Vcc/2`. Calculating the voltage for different temperatures requires you to know the temperature coefficient, which can be found from the datasheet or by measuring the resistance at various known temperatures and plugging those values into an equation.


message:
Edit variables through Serial?

Hello in a previous question i was able to set variables through if statements

  <!-- language: c -->

      const uint16_t inputLength = 512;
    int ss = 0;
    int bHold = 0;

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

     void loop() {
      if ( Serial.available() > 0 )
      {
        static char input[inputLength];
        static uint16_t i;
        char c = Serial.read();

        if ( c != '\r' && c != '\n' && i < inputLength - 1)
          input[i++] = c;

        else
        {
          input[i] = '\0';
          i = 0;

          uint16_t array[80];
          uint16_t j = 0;

          if ( !strncmp(input, "ss", 2) )
          {
            char* p = input + 2;
            while ( (p = strchr(p, ' ')) != NULL )
              array[j++] = strtol(p, &p, 10); //

            for ( uint8_t i = 0; i < j; i++ )
            {
              ss = array[i];
              Serial.println(ss);
            }
          }

          if ( !strncmp(input, "bHold", 5) )
          {
            char* p = input + 5;
            while ( (p = strchr(p, ' ')) != NULL )
              array[j++] = strtol(p, &p, 10);

            for ( uint8_t i = 0; i < j; i++ )
            {
             bHold = array[i];
             Serial.println(bHold);
            }
          }

          if ( !strncmp(input, "Whos There", 10) )
          {
            Serial.print("me");
          }
          if ( !strncmp(input, "hello", 5) )
          {
            Serial.print("hi");
          }
          if ( !strncmp(input, "sa", 2) )
          {
            Serial.print("  ss= ");
            Serial.print(ss);

            Serial.print("  bHold= ");
            Serial.print(bHold);

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

if works! but if i keep adding variables i have to keep adding if statements and this will get longer. so then i went with code like this that allows me to set all variables at once

  <!-- language: c -->

    #define INPUT_SIZE 30

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

    }
    void loop()
    {

      while (Serial.available() > 0) {

        int _mode = Serial.parseInt();
        int _ss = Serial.parseInt();
        int _bHold = Serial.parseInt();

        if (Serial.read() == '\n') {
          ss = _ss;
          bHold = _bHold;
          mode = _mode;

        }
      }

    }

this works awesome! but i have to set all variables at once. my question is is there a way i can simply input a command like ss = 10 press enter then bHold = 30 and not have to input any other variable?
thanks i advance. please point me in right direction  Maybe make a function?

body:
Somewhere along the line you have to tell your program how to map names to actual variables. Once you have compiled your program it forgets the names of the variables - those only exist in the source code.

So you have to have some other manual list of those variable names - be that in the form of `if(...)` statements, or an array of structs with the name in them, or whatever.

There's no getting away from it - you need that manual mapping in some form or other.

The closest you could get would be to set up some kind of *hash* system using structs and linked lists, whereby you could set any key/value pair, but then of course your program would still have to know to look for certain keys in the hash to do things with them, so that would be pretty pointless since you've just moved the variable mapping from one place to another.


body:
You can store variables on the fly in a simple array or linked list.
A linked list would probably be better, but for now we'll just use an array.

    const int MAX_VARS = 10;
    const int NAME_SIZE = 16;

    typedef _var
    {
        char  name[NAME_SIZE];
        int   value;
    } Var;

    Var variables[MAX_VARS];
    unsigned int var_count = 0;

    void loop()
    {
        char *command = getSerialInput(); // get a line of input from the serial stream

        // parse the command "set varname=value"
        if (strncmp(command, "set ", 4) == 0)
        {
            char *new_name = command + 4; // skip the 'set '

            char *ptr = strchr(command,'='); // find the equals character
            if (ptr != NULL)
            {
                 *ptr = '\0';              // Break the string in half about the '='
                 char *new_value = ptr+1;  // Everything after the equals is the value

                 // Now we have a parsed variable name, and value
                 // Have we already stored this variable?
                 int i;
                 for (i=0; i<var_count; i++)
                 {
                     if (strcmp(variables[i].name, new_name) == 0)
                     {
                         // Found an existing copy - update it
                         variables[i].value = new_value;
                         break;
                     }
                 }

                 // Did we find the variable already?  No - add a new one
                 if (i == var_count && i< MAX_VARS)
                 {
                     strncpy(variables[i].name, new_name, NAME_SIZE);
                     variables[i].name[NAME_SIZE-1] = '\0'; // fix any strncpy() overflow
                     variables[i].value = new_value;
                     var_count += 1;
                 }
                 else if (i == MAX_VARS)
                 {
                     Serial.println("Out of variable slots");
                 }
            }
        }
        // parse the command "get varname"
        else if (strncmp(command, "get ", 4) == 0)
        {
             char *new_name = command+4;
             int i;
             for (i=0; i<var_count; i++)
             {
                 if (strcmp(variables[i].name, new_name) == 0)
                 {
                     // Found an existing copy - output it
                     Serial.println(value, DEC);
                     break;
                 }
             }

             // Did we find the variable already?  No - error
             if (i == var_count)
             {
                  Serial.print(new_name);
                  Serial.println(" - not found");
             }
        }
    }
    else
    {
        Serial.println("HELP: \"set <name>=<value>\" or \"get <name>\"");
    }

This would be better with dynamically allocated memory, so the programme only uses exactly what it needs.  But I wanted to show a way of storing a list of user input without complications.  Obviously this programme omits a lot of error checking too - like when you run out of array slots in `variables`; or when the user input is bad.


message:
Ideal power supply for ESP8266

What is the ideal power supply for this module? What do you use that works ok?

Will the [AMS1117][1] work?

  [1]: http://www.ebay.com/itm/5PCS-5V-to-3-3V-DC-DC-Step-Down-Power-Supply-Buck-Module-AMS1117-LDO-800MA-CM10-/321963058956?hash=item4af67e670c:g:6hcAAOSwo3pWfi4t

body:
Yes, that will work. However, ignore the entire description.

That is **NOT** a buck regulator - it is a low-dropout **linear** regulator.  Thus it will waste power as heat - the more current you draw the hotter it will get.

The '1117' range of regulators are pretty much ubiquitous. I use them in a wide range of products and situations where power consumption isn't critical (i.e., not battery based products).

For lower power requirements you want to get a *real* buck regulator. Something more like this: http://www.ebay.co.uk/itm/301842020065

**Note that it's an adjustable module, and you will need to first use a multimeter to adjust the output to 3.3V before you connect it up.**

Because they are adjustable they are a great thing to keep around since you can use them for all sorts of different situations.


message:
Why is my Arduino still working?

I read an article that said that shorting an IO pin to ground would destroy the pin.  I've done this before when I connected a buzzer to an IO pin and to ground without resistors, the buzzer is only 14 ohms so the current would be quite high through the pins.  Why is my Arduino still working,  and how should I know when to use resistors or what rating to use?

body:
You don't necessarily destroy the pin, but it won't do it any good. To work out the resistors use Ohm's Law. The continuous output of a pin should not exceed 20 mA, thus:

    V = I * R
    R = V / I
    R = 5 / 0.020
    R = 250

Thus 250 ohms, from the pin to ground, would allow a safe amount of current to flow.

As for the rating, that resistor would dissipate:

    W = V * I
    W = 5 * 0.020
    W = 0.1

Thus a resistor that could handle 100 mW would be required. More reasonably, a quarter watt resistor should be fine.


body:
The Arduino is tougher than it looks. ;-) Or maybe you were just lucky.

The exact point of failure of an IC is hard to predict, because of part
to part variations, and because it can depend on many uncontrolled
factors (duration of fault, temperature, voltages and currents on other
pins, part history...). Then, the _absolute maximum ratings_ are not the
predicted point of failure. They are rather a lower bound:

* The part _should not_ fail if you do not exceed the ratings
* it _may_ fail anywhere beyond those limits.

Time is, however, also a factor. The manufacturer says that operating
the part close to the limits for an extended period may shorten its
lifespan.


message:
Pin Mapping of nRF2401L01+ using Adafruit's nRF24L01+ library

I have an Arduino Uno and one of these nRF24L01+ from china (see image)
[![enter image description here][1]][1]

To use the module i wanted to use the library provided by Adafruit (http://playground.arduino.cc/InterfacingWithHardware/Nrf2401). My problem is, that they're using different names for some pins, because the library is designed for a different module with the following pin outs.

[![i.stack.imgur.com/2aT18.jpg][2]][2]

I don't know which PIN from the China module corresponds to the DAT and DR1 Pin on the Adafruit module.

So my questions are:

 1. Is it OK to use the library in conjunction with the china module?
 2. What are the DAT and DR1 PIN on the module from China ?

What I know so far:
- took a look into the library and into the documentation at playground.arduino.cc/InterfacingWithHardware/Nrf2401 and found out that the DR1 pin is for the available() function to check if data is available to be read.

  [1]: https://i.stack.imgur.com/YMLJG.jpg
  [2]: https://i.stack.imgur.com/2aT18.jpg

body:
    DR1 is MISO
    DAT is MOSI

Though I'd advice using the [RF24 library](https://github.com/tmrh20/RF24/), as it's a lot more recent than the one from 2009 you linked to.


message:
Multiplication, division. What is wrong?

const unsigned long C1 = 30 * 1000;
    const unsigned long C2 = (300 * 1000)/C1; // must be = 10

    void setup() {
      Serial.begin(57600);
      Serial.println("\n-------");
      Serial.print("C1 = "); Serial.println(C1);
      Serial.print("C2 = "); Serial.println(C2);

      unsigned long V1 = (300 * 1000)/C1;   // must be = 10
      Serial.print("V1 = "); Serial.println(V1);

      long V2 = (300 * 1000)/30000; // must be = 10
      Serial.print("V2 = "); Serial.println(V2);

      int V3 = (300 * 1000)/30000; // must be = 10
      Serial.print("V3 = "); Serial.println(V3);
    }

    void loop() {
    }

Arduino UNO printed in monitor console:

    C1 = 30000   (ok)
    C2 = 143164  (must be = 10)
    V1 = 143164  (must be = 10)
    V2 = 0       (must be = 10)
    V3 = 0       (must be = 10)

What is wrong?

body:
    300

and

    1000

are integers.

What

    long V2 = (300 * 1000)/30000;

really does is take the *integers* 300 and 1000 multiply them. This calculation overflows, and equals -27680. Dividing that by 30000 yields 0. What you added in your comment isn't a hack, it's the proper solution. By including the suffix L or UL you tell the compiler that you want longs, not ints.


body:
> What is wrong?

You are assuming that the expression is long int but it is actually int. The literals are int. You need to convince the compiler that the expression is actually long int. That can be done by cast:

    ((long) 30000)

or literal long integer syntax:

    30000L

The AVR GCC compiler uses int defined as 16-bit. Expression and literals are implict 16-bit.

More on the representation of C/C++ data types, expressions, and calling conventions can be found [here][1].

Cheers!

  [1]: https://gcc.gnu.org/wiki/avr-gcc


body:
A good practice with literal numbers which you want to divide and multiply is to always define them as `double`, and convert them to integer when they are used. This is often the case with frequency/period constants. This prevents most catastrophic overflow / rounding errors that integer math would have, while allowing you to use consistent units in your definitions.

     #define F_CPU 16000000.0   // in Hz
     #define F_TICK (1.0/F_CPU) // in seconds
     #define DELAY 0.001        // in seconds
     #define COUNT ((uint16)(DELAY/F_TICK))
     Serial.println(COUNT);

Of course, you can calculate the number of CPU ticks per millisecond using fixed-point math, for example by defining the frequency in MHz and the tick time in nanoseconds, but you'll have to scratch your head every time you need to convert a period to a frequency and vice versa, and you'll have to change units the moment your frequency will not be a multiple of MHz.


message:
Atmel AVR languages

Hello I recently purchased some atmel AVR chips. You can programme them in Arduino. I was wondering if it is possible to programme them in any other language except for C or Arduino. Also can you use just binary instead of C?

body:
You can program them in C or C++ through the avr-gcc compiler. Arduino uses C++ ([-std=gnu++11][1]) and automatically includes a few libraries, as well as generating forward declarations for anything in the top level .ino file automatically.

You can write AVR assembly and translate it to machine code using avr-as (a portion of avr-gcc)

There is nothing stopping you from just writing whatever bytes you want to program memory if you want to write machine code.

You can look through the [avr instruction set][2] if you are interested in those last two options.

  [1]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/platform.txt#L30
  [2]: http://www.atmel.com/images/atmel-0856-avr-instruction-set-manual.pdf


body:
> I was wondering if it is possible to programme them in any other language except for C or Arduino.

I have seen this question before. Here is a great answer with a lot of links:

https://stackoverflow.com/questions/6590161/programming-languages-targeting-arduino-avr

There are also a number of libraries/platforms/frameworks as the Arduino core to help you up from "bare metal".

Cheers!


message:
Controlling 3 stepper motors simultaneously

I have three stepper motors connected to the drv8825 drivers to an arduino uno.

I am using the example code below (from [here][1]), which works fine for moving multiple stepper motors at the same time BUT they all move for the same number of steps and in the same direction. I would like to tweak the code so that all of them move at the same time but each one for a different number of steps and in different directions. The motor with the least steps would probably have to wait for the motor with the most steps to finish its movement before going again.

    int dirPin = 8;
    int stepperPin = 7;
    int bdirPin = 6;
    int bstepperPin = 5;

    void setup() {
     pinMode(dirPin, OUTPUT);
     pinMode(stepperPin, OUTPUT);
     pinMode(bdirPin, OUTPUT);
     pinMode(bstepperPin, OUTPUT);
    }
     void step(boolean dir,int steps){
     digitalWrite(dirPin,dir);
     digitalWrite(bdirPin,dir);
     delay(50);
     for(int i=0;i<steps;i++){
     digitalWrite(stepperPin, HIGH);
     digitalWrite(bstepperPin, HIGH);
     delayMicroseconds(800);
     digitalWrite(stepperPin, LOW);
     digitalWrite(bstepperPin, LOW);
     delayMicroseconds(800);
     }
    }
    void loop(){
     step(true,1600);
     delay(500);
     step(false,1600*5);
     delay(500);
    }

Thank you in advance for your help!

  [1]: http://www.geeetech.com/wiki/index.php/DRV8825_Motor_Driver_Board

body:
You need a struct for each stepper with a timestamp, a position and rate of change and a loop that updates the postion based on rate which is the change in position over some time:

    struct stepper {
      unsigned long timestamp;
      int position;
      int rate;
    };

    // init steppers array

    while (keepGoing()) {
      unsigned long now = millis();
      int si;

      delay(10);

      for (si = 0; si < 3; si++) {
        struct stepper *stepper = &steppers[si];

        if (steppers[si].timestamp > now) {
           steppers[si].position += steppers[si].rate;
           steppers[si].timestamp = now + 100;
        }
      }

This is a back-of-a-napkin sketch of course. It is only supposed to illustrate how you can update any number of things concurrently.

The important thing is that you only call delay once. And presumably it would be only a very short delay compared to the unit of time for the rate. In the above example it would adjust the stepper position every 100ms. You would need to experiment with the timing to find a good behavior given the speed of the stepper, speed of the code and maximum permitted rate.

Beware that there is a lot to think about beyond this. For example, you should initialize the timstamps with different timestamps so that the motors are not all running at the same instant and thus *try* to minimize the total power consumed by the motors at any particular time.

Note that I have never played around with stepper motors but this type of loop is a common programming idiom for handling things concurrently.


body:
You would first have to provide all the necessary information to your
`step()` function: direction and number of steps for _each_ motor. Then
you just have to stop the loop at different points for each motor. You
do this by running the loop up to the number of steps of whichever motor
needs to run for longer, and making the steps of each motor conditional
on the loop index, as follows:

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

    void step(boolean dir0, int steps0,
              boolean dir1, int steps1,
              boolean dir2, int steps2) {
        digitalWrite(dir0Pin, dir0);
        digitalWrite(dir1Pin, dir1);
        digitalWrite(dir2Pin, dir2);
        delay(50);
        int max_steps = max(max(steps0, steps1), steps2);
        for (int i = 0; i < max_steps; i++) {
            if (i < steps0) digitalWrite(stepper0Pin, HIGH);
            if (i < steps1) digitalWrite(stepper1Pin, HIGH);
            if (i < steps2) digitalWrite(stepper2Pin, HIGH);
            delayMicroseconds(800);
            if (i < steps0) digitalWrite(stepper0Pin, LOW);
            if (i < steps1) digitalWrite(stepper1Pin, LOW);
            if (i < steps2) digitalWrite(stepper2Pin, LOW);
            delayMicroseconds(800);
        }
    }

It would be more elegant to put the data for all the motors in an array,
and you would probably want to do so if you have more than three motors.


body:
I have two ideas:

- I don't have personal experience working with the [AccelStepper Library](http://www.airspayce.com/mikem/arduino/AccelStepper/), but I believe it implements a class that allows you to work with multiple steppers.
- I plan on controlling two steppers for a project of my own (a self-balancing robot implemented with an STM32 processor), and I plan on using hardware timer interrupts to control the speed of my motors. A quick [google search](https://www.google.com/search?num=20&q=arduino+timer+interrupts) shows that a similar approach is possible with Arduino. You can probably use `Timer0`, as 1ms is fairly fast for a single step. This has several benefits...
 - The refresh function will run on set intervals, (allowing you to control the speed very precisely.
 - It will run with the correct timing, even if there is a function in `loop()` that is taking a long time.

**Note: do NOT put any `delay` statements in your interrupt handlers.** If you do this, it will probably prevent other interrupts from occurring and cause some API functions (such as `millis` or `micros`) to misbehave. In addition, the execution of anything in `loop` is halted while the interrupt is being handled, meaning that you would effectively stop everything until the interrupt is done. See the caveat in Arduino reference page for `delay`.


message:
Quick start on Arduino for experienced embedded programmer?

I'd like catch up the Arduino concepts (programming & IDE). There are excellent online tutorials available for Arduino but all of them which I saw are made for those who didn't have embedded/electronics background. Going through them is heavily time consuming as I'm already familiar with the embedded programming other than Arduino or Raspberry Pi.

Does any one know any quick reference materials for Arduino which excludes electronic/embedded basics which is meant for experienced embedded programmer? That could be a big time saver for me.

Thanks in advance!

body:
As far as I know, there is no tutorials about using Arduino's for, e.g. "multi-tasking, real time response". That is not the focus of the Arduino community.

The Arduino UNO development board is built around Atmel's [ATmega328][1]. The [Summary datasheet][2] gives an overview of its hardware capabilities on the first page. If you are familiar with MCU development, that should give you a feel for its hardware capabilities. The complete [ATmega8/168/328 datasheet][3] is over 600 pages, and describes every feature, with all registers in detail.

The Arduino IDE uses gcc under the covers. So you likely already know how to use that. When you download and install the Arduino IDE, gcc and gnu binutils for AVR will be installed too.

The Arduino IDE has all of the Atmel header files, so much of the code in the datasheet should compile, link and upload.

The IDE is really designed for beginners. It is to easy to use, but has very few features beyond basic editing, compiling and loading. It does support a serial-monitor to see text printed by the uploaded application, but it doesn't support a debugger like GDB out-of-the-packet.

However, it doesn't prevent you writing C++ code and header files, and it will build the whole collection of files.

Because the IDE lets you create and edit C++ directly, you can install the IDE on any of the three main platforms, and get started very quickly.

You will probably want to visit [AVRFreaks][4] who tend to focus at a lower level than Arduino.

There is also [AVR LibC library][5] which points you at the documentation for the AVR upload tool, avrdude, and debugger.

Summary: Install Arduino IDE, do a couple of quick projects to get a feel for the system. Then start writing C++ as normal. Install [AVR LibC library][5] for a more traditional library, and visit [AVRFreaks][4] forums for more technical help and information.

  [1]: http://www.atmel.com/devices/atmega328.aspx
  [2]: http://www.atmel.com/Images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Summary.pdf
  [3]: http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf
  [4]: http://www.avrfreaks.net/
  [5]: http://www.nongnu.org/avr-libc/


body:
> But I suppose to debug an existing Arduino project (which my friend gave to me because the developer left from his small electronic company) developed for GSM based remote motor control product. They haven't used Arduino board but used Arduino IDE/library for coding. Flashed the hex output from Arduino on their custom board with Atmel processor. So I need to go through the existing Arduino code and help them to solve the issue that they are facing.

This is maybe one of the worst type of projects to get involved in. Code that needs debugging on a platform that you have not used before. Code that you might not know the status of and where the requirements are loose.

I would recommend starting by getting all the details on the table. Understand the intended software architecture, estimate memory foot-print, and processing, etc - if the product is feasible. There might be a reason for the developer ditching this project?

AVR is small scale embedded and that implies a very different implementation strategy. There is no operating system and much of the code is bare metal.

The Arduino core is a platform (library) that abstracts a small set of basic hardware functions. It was originally intended for Media/Design Students.
To help reduce the threshold when getting started the IDE has build support, i.e. pre-processing, such as an implicit add of the Arduino header file (Arduino.h) and generation of forward declarations for functions in a sketch. The IDE does not use make/makefiles. Source code is C/C++ (AVR GCC) and if necessary AVR assembly.

The quick reference for the Arduino core function can be found [here][1]. There is also a list of [libraries][2]. Some are packaged with the Arduino IDE/core while others need to be installed. There is a library manager in the IDE to download and install some of the libraries. New libraries are added more or less daily right now.

Depending on the code you will have to read more about the libraries used and/or internal AVR hardware (registers, functions, etc).

Cheers!

  [1]: https://www.arduino.cc/en/Reference/HomePage
  [2]: https://www.arduino.cc/en/Reference/Libraries


message:
Ublox GPS with Arduino Mega 2560 not working

Recently I bought a GPS module ([ublox neo-6M-0-001][1]) for my Arduino Mega 2560. I connected Vcc and Gnd (LED at GPS module glows blue and sometimes blinking).

GPS module RX port is connected to the Arduino's TX3, Port 14.
GPS module TX port is connected to the Arduino's RX3, Port 15.

As a first step I just want to print the serial data received from the GPS module:

    #include "SoftwareSerial.h"

    SoftwareSerial mySerial(15, 14); // RX, TX

    void setup() {
      Serial.begin(9600);
      Serial.println("uBlox Neo 6M Test");
      mySerial.begin(9600);
    }

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

Saldy, there is no data received from the GPS module. According to [the datasheet][2] the baud rate 9600 seems to be correct.

Do I need to configure the GPS module somehow before it delivers data? Do I need to buy an external antenna?

Thanks for your help.

  [1]: http://www.ebay.de/itm/311397889516
  [2]: http://arduino-ua.com/docs/NEO-6_DataSheet.pdf

body:
The Arduino Mega 2560 has three additional hardware serial ports. Why not use one of them instead? [Serial1][1] on pins 19 (RX) and 18 (TX).

    void setup()
    {
      Serial.begin(9600);
      Serial.println("uBlox Neo 6M Test");
      Serial1.begin(9600);
    }

    void loop() // run over and over
    {
      if (Serial1.available())
         Serial.write(Serial1.read());
    }

Cheers!

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


message:
Arduino & ARM - Replacement for avr-libc?

There is very cool [avr-libc library][1] that provides direct access for all functions of AVR microcontrollers. I'm writing a project for **Arduino Due** and I want to use timers and ISRs directly. Is there a library like `avr-libc` for ARM Cortex M3?

  [1]: http://www.nongnu.org/avr-libc/user-manual/modules.html

body:
I think `newlib` is the one you want.
[howto][1]

  [1]: https://balau82.wordpress.com/2010/12/16/using-newlib-in-arm-bare-metal-programs/


body:
I found the official library here: http://www.atmel.com/tools/atmel-arm-toolchain.aspx

**UPDATE:**

I have finally understood understand how **exactly** Arduino accesses specific ARM features. It includes `sam.h` file which in turn contains [Cortex Microcontroller Software Interface Standard][1]. With this cool interface anyone can use so many cool features:

 - Timers
 - Advanced interrupts
 - Power saving mode
 - SIMD instructions
 - And many other

  [1]: http://asf.atmel.com/docs/latest/cmsis.html


message:
Simultaneously reading data from multiple serial ports

I have three sensors latched on to three different Arduino devices.

The respective Arduino devices are connected on to an Arduino Mega on Serial1, Serial2 and Serial3.

The data from each device component (i.e., an Arduino with an accompanying sensor) were sent in data packets with different starter byte headers ('$' , '/' & '#' ) accompanying the buffered data from each individual device component onto the Mega on the Tx/Rx lines.

My question here is, how can I simultaneously read out all the data from the different serial ports on the Arduino mega sketch?

body:
> My question here is how can I simultaneously read out all the data from the different serial ports on the arduino mega sketch.

As you are using several serial ports data can already be received simultaneously. Each serial software class (Serial1, Serial2, Serial3) has an internal buffer where data is stored until it is read.

You only need to read the data before the internal buffers are filled and there is a risk for over-flow. Check that data is available and read as usual per serial port. Avoid any blocking calls to avoid buffer over-flow.

Cheers!


body:
The easiest and most overlooked way to read ANY hardware serial ( Serialx) is to utilize Arduino IDE main() function layout and let the serialEventx do the work.

Here is much simplified layout of IDE main () function.

main()
{
Setup()
for(;;)
{
loop()
serialEventx()
}
}

However using serialEvent requires much different approach to your program flow - the loop() cannot have any logic which would introduce a delay.
Your program must process the serialEvent FIRST, loop() processing is secondary.


body:
I had my arduino mega receiving the data from Serial2 and Serial3, by adopting a sketch that was developed by @Majenko in answer to the post https://arduino.stackexchange.com/questions/19818/processing-serial-data. The sketch below outputs data to the serial monitor. The NEW problem I have now is trying to develop a python sketch that would seperate the data from the buffers into two different csv files, with each csv files representing the data from each of the two sensors.

        static char buffer[20];
        int count =0;

        void setup()
       {
        Serial.begin(115200);
        Serial2.begin(115200);
        Serial3.begin(115200);
        delay(50);

        }

        void loop(){

    if (Serial.available()){  //Slide the window
       for(count=0; count<10; count++){
          buffer[count] = Serial.read();
          //Add the new character
          buffer[9] = Serial.read();

          //Check the framing window
       if((buffer[0] == '$') && (buffer[9] == 0xAC)){
         //Calculate the checksum
          uint16_t cs = 0;
       for (uint16_t i = 2; i < 8; i++){
        cs += buffer[i];
        }
        //if the checksum matches....
        if(cs == buffer[8]){
          //Send the byte to serial port three
          Serial2.write(buffer, count);
      }
      }

     }
    }

     if (Serial2.available()){
        for(count=0; count<10; count++){
          buffer[count] = Serial2.read();
          //Send the byte to serial port three
          Serial.write(buffer, count);
         }
     }

     if (Serial.available()){  //Slide the window
       for(count=11; count<20; count++){
          buffer[count] = Serial.read();
          //Add the new character
          buffer[19] = Serial.read();

          //Check the framing window
       if((buffer[11] == '+') && (buffer[19] == 0xAE)){
         //Calculate the checksum
          uint16_t cs2 = 0;
       for (uint16_t i = 6; i < 18; i++){
        cs2 += buffer[i];
        }
        //if the checksum matches....
        if(cs2 == buffer[18]){
          //Send the byte to serial port three
          Serial3.write(buffer, count);
      }
      }

     }
    }

     if (Serial3.available()){
        for(count=11; count<20; count++){
          buffer[count] = Serial3.read();
          //Send the byte to serial port three
          Serial.write(buffer, count);
         }
     }
   }


message:
Why the 4.7 K Ω resistor in this pitch follower sketch?

I am reading *Arduino for Dummies*, and I am blocked at the pitch follower exercise. It consists in making a piezo vary with a light sensor. I can't see the point of the resistor (and why 4.7?) in this sketch:

[![http://media.wiley.com/Lux/98/381398.image0.jpg][1]][1]

Any help for a dummy is appreciated! :-)

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

body:
*Arduino measures Voltages on pins A0 to A5; but the LDR is a variable resistor (varying with Light). So we need to convert the varying resistance to a voltage that the Arduino can measure.*

For more details see [here][1].

Cheers!

  [1]: http://www.instructables.com/id/How-to-Use-a-Light-Dependent-Resistor-LDR/


body:
The resistor couples with the LDR to form a *voltage divider*. The voltage at the point where the resistor and LDR join will vary depending on the ratio of the two resistances - the resistance of the LDR and the 4700 ohm resistor.

The value of 4700 is chosen to allow a reasonable range of voltages when in a ratio with the LDR, and the best value depends on the resistance range of the LDR.


message:
Is Teensy compatible with the Arduino keyboard library?

I am thinking about buying some Teensy micro-controllers, but I want to know if the [teensy][1] are compatible with the [arduino keyboard library.][2]

  [1]: https://www.adafruit.com/?q=teensy&
  [2]: https://www.arduino.cc/en/Reference/MouseKeyboard

body:
It looks like the Teensy designer uses the standard Arduino mouse and keyboard library:

https://www.pjrc.com/teensy/td_keyboard.html

On another note, I'm sure Teensy is a fine product, but I prefer other open hardware solutions like Pro Micro which can be had on [AliExpress.com for  under $4 ea.][1]

  [1]: http://www.aliexpress.com/w/wholesale-arduino-pro-micro.html?spm=2114.01010208.0.334.k7qlR1&site=glo&SearchText=arduino pro micro&g=y&SortType=price_asc&groupsort=1


message:
RGB LED Resistance

In tutorials I've seen, people connect every LED of a RGB LED to a resistance. I understand the purpose, but could we simply put the same resitance once, if we connect it to the common cathode or annode?

Example:

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

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

body: The problem with one resistor in common anode/cathode is that when you activate more than one colour of the RGB LED, you will have additional current flowing through the one resistor which will cause increased voltage drop across the one resistor due to ohms law which will cause less forward voltage across the LED and likely extinguish it or at least make it much less bright.


message:
ATTiny84 blink mystery

Novice mode, please.

I programmed my ATTiny84 using Arduino Ethernet (Arduino IDE 1.6.7) using [https://github.com/damellis/attiny branch][1] - `1 MHz internal oscillator` mode. I uploaded ISP sketch to Arduino with all cables disconnected (first I did it with all of them connected but Arduino didn't seem to mind), connected the whole setup using 10 uF capacitor and the sketch got sent into ATTiny84 without problems.

Blink sketch is using atttiny84's digital pin 7 (that is physical leg No. 6) set to 1 s blink rate.

But, when I connect an yellow LED, it won't blink. I'm not yet good enough with my oscilloscope (don't know how to hook it up) but my multimeter is showing something weird - voltage is slowly rising on DP7 (I measured against ground) - over approx. 5-6 seconds to 400 mV, then immediately jumps to 1V (not sure about this, could be measurement bug) and then right to 0V.

Blink sketch:

    int led = 7;

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

    // the loop routine runs over and over again forever:
    void loop() {
      digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);               // wait for a second
      digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);               // wait for a second
    }

I'm clueless. Please confer.
Thank you.

Images of my setup:
[![enter image description here][2]][2]

  [1]: https://github.com/damellis/attiny branch
  [2]: https://i.stack.imgur.com/uCfvn.jpg

body:
I solved my own problem. Wiring was completely OK, so was flashing.

The problem was RESET pin (4th physical pin). As soon as I disconnected it after flashing, LED started blinking. If someone knows why, I'd appreciate some info.


message:
How to stop Arduino from reseting after serial connection lost

If I connect to an Arduino Uno via a serial console to read debugging statements and then disconnect, the Arduino appears to reset. How do I stop this from happening?

I'm trying to program an Arduino to receive a "shutdown" signal from a Raspberry Pi via serial, which will make the Arduino cut the RPi's power. However, this will also cut the serial connection, and if it causes the Arduino to reset, it'll reactivate power.

body:
There is a link on the Uno marked RESET-EN which links the Atmega16U2 (or 8U2) which handles incoming serial data to the main chip, the Atmega328P. If you cut that link (eg. with a knife) then it won't reset. However uploading new sketches will be harder because you will have to manually press the Reset button when the IDE starts to upload a new sketch.

---

Board:

[![RESET_EN link][1]][1]

---

Schematic:

[![Schematic][2]][2]

---

One thing that people do is put a 10 µF capacitor between RESET and GND. That holds enough current to "weather" the reset pulse, and that stops the board resetting. You can always remove the capacitor to reprogram the board.

  [1]: https://i.stack.imgur.com/9S21W.jpg
  [2]: https://i.stack.imgur.com/CY6Lk.png


body:
I found the solution to my problem was this [answer][1], which works for me on both a normal laptop and Raspberry Pi without having to modify any Arduino hardware.

  [1]: https://raspberrypi.stackexchange.com/a/31298/29103


message:
RePaper 2.7" eInk Display with Arduino Due

I got a RePaper 2.7' eInk display that unfortunately doesn't support Arduino Mega because of its limited SRAM capacity (8k bytes). I am porting the library to Arduino Due because of its sufficient RAM capacity (96 KB in two banks: 64KB and 32KB).

I am using the thread [rePaper - 2.7" Graphic eInk Dev Board Headers ](https://forums.adafruit.com/viewtopic.php?f=22&t=47571) and I've done all the modifications.

Has anyone successfully ported the library to Arduino Due? Also, does anyone have a library for Dynamic Printing for this display?

body:
You're trying to port the library from the Due to the Mega? If the library is large a "port" just isn't going to happen because relatively minor modifications to the code are very unlikely to shrink the size significantly; you'll need a complete rewrite.

My suggestion is to start by studying the data sheet for the device and the code for the existing Due driver to get an idea of how it works. Then sit down and write some sketches for your Mega that make something happen on the display (perhaps just clearing it, turning on and off a few specific pixels, the like) to verify your understanding. Once you've done that, you can start to consider the design of your driver.

Because of the vastly different memory limitations it's likely that your driver will look and work very differently from the Due driver. For example, a 264 x 176 x 1 bit frame buffer would use almost 6K of RAM (most of the RAM in a Mega 2560 and far more than in an Uno), so you're not going to want to have one. I don't know if the Due driver has a frame buffer (I'm just using this as an example of a typical difference you might encounter), but if it does, and that's used for doing certain kinds of things, you'll need to do them in a different way or not do them at all.

This is not a simple project, but it's a great one and will teach you a lot about microcontroller programming!