message:
How much time does the Arduino need to call a Function or to read a Variable?

How much **time** does an Arduino Uno or Mega need **to only call a function**. And how does the time change if this function is inside a Class, for example inside a Library?

The same thing for a variable. How much time does a micro-controller need **to read a declared variable**?

How to determine this values? Is there a mathematic formula? Can we predetermine this type of delays and other similar micro-controller related delays?

body:
It is hard to give a general answer, as it depends on the specifics of
your code and on how the compiler compiles it:

> How much time does an Arduino Uno or Mega need to only call a function.

This can involve a number of things:

* the caller puts the arguments on some predefined CPU registers, unless
  they are already there from a previous operation (the compiler tries
  to optimize the code so that this happens whenever possible)
* the caller issues the `call` instruction to do the actual function
  call
* the callee pushes some CPU registers into the stack in order to use
  them without clobbering the caller's data
* the callee does its job
* the callee pops the previously pushed registers
* the callee issues the `ret` (meaning return) instruction
* the caller finds the return value in some CPU registers

On the Uno, the `call` and `ret` instructions cost 4 CPU cycles
each (0.25 µs). On the Mega, it's 5 cycles (0.3125 µs)
each. `push` and `pop` are 2 cycles each, and you need one such
pair for every 8-bit register you need to save.

> And how does the time change if this function is inside a Class, for
> example inside a Library?

The only difference is that a class method receives an extra hidden
parameter called `this`. Except if it's a virtual method, which is more
expensive because it involves some pointer dereferencing.

> How much time does a micro-controller need to read a declared
> variable?

“Reading” generally means transferring the contents of the variable to
some CPU registers. Local variable are usually allocated to CPU
registers in the first place, so there is no need to read them. Global
(and local static) variables are stored in RAM, and reading them takes
2 cycles per byte (e.g. 4 cycles for a 16-bit `int`).

> How to determine this values?

Disassemble the code generated by the compiler. Then look up the
instructions in the [instruction set manual][]: it documents the number
of clock cycles needed by each instruction.

[instruction set manual]: http://www.atmel.com/images/Atmel-0856-AVR-Instruction-Set-Manual.pdf


sender: user

sender: assistant

body:
> How much time does an Arduino Uno or Mega need to only call a function.

Why do you want to know? This sounds like an [X-Y problem](http://xyproblem.info/).

It will vary, depending on a lot of things.

* The number of arguments, because the more arguments the more work involved. Plus if an argument involves copying it might invoke a copy constructor.

* Whether or not the compiler in-lines the function. If it is in-lined (copied into the other function) then there is less work, for example the compiler doesn't need to generate `call` and `ret` instructions.

* What the function does. The more things a function does, the more registers the compiler may have to `push` and then `pop` afterwards to save the state of registers which had useful information in them, outside the called function.

* The size of the arguments. Longer arguments take longer to copy onto the stack, or put into registers. For example, `long` arguments will take longer than `char` arguments.

---

> How much time does a micro-controller need to read a declared variable?

Again, it varies. It depends on the variable size, and whether or not it is already in a register. If the variable happens to be in a register at the time, you could argue it takes zero time to read it.

---

> How to determine this values?

The sensible thing to do is to time some test code. Here's an example from another thread:

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

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();

      unsigned long start, finish;

      start = micros ();
      for (byte i = 0; i < 100; i++)
        digitalWrite (13, HIGH);
      finish = micros ();

      Serial.print ("Time taken to do digitalWrites: ");
      Serial.println (finish - start);
      Serial.flush ();

      }  // end of setup

    void loop ()
      {
      }  // end of loop

In the middle of the code there I time doing digitalWrite 100 times. By dividing the resulting output by 100, I can work out how long each digitalWrite takes.

---

You don't normally need to know how long, exactly, it takes to read variables, and call functions. Either your code works at an acceptable speed, or it doesn't.

Trying to answer this question on test code may give meaningless results. For example, in my test code the compiler may have in-lined the digitalWrite call. But if I use digitalWrite in many places it will no longer in-line it, which means the timing figures are now incorrect.

---

> The Questions is how much time the millis() and micros() functions need to finish their work, so the measurement is accurate.

If that was what you wanted to know, it would have been better to ask that exact question. That saves us waffling on about copy constructors and so on.

I tested with the code below, which calls `micros()` and saves the results to a variable `foo`. I made it volatile so that the compiler wouldn't be tempted to optimize away the saving altogether (because it isn't used anywhere else).

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

    void setup ()
      {
      pinMode (13, OUTPUT);
      PORTB = 0;
      }  // end of setup

    volatile unsigned long foo;

    void loop ()
      {
      PINB = bit (PB5);   // toggle D13
      foo = micros ();
      PINB = bit (PB5);   // toggle D13
      }  // end of loop

I measured 3.380 µs on my oscilloscope for the time when D13 is high. That would be 54 clock cycles. A couple (only) would be the time taken to toggle D13. Thus you can probably reckon `micros()` in general as taking 3.38 µs.

Changing it to call `millis()` instead, it only takes 1.760 µs (28 clock cycles). This is probably because all `millis()` does is return a variable which has already been calculated (in the timer ISR).

Test done on an Arduino Uno running at 16 MHz.


message:
How to change Arduino Nano MODEL_ID

I'm working on a project using a set of different Arduino Nano connected to a Raspberry Pi through USB.
Now my question is: *"how can I, from the Pi's point of view, differentiate all of those Arduino and associate them with their respective tty?"*

I found some part of my answer in [this question][1]. The answering guy proposes to manually change the Arduino `MODEL_ID` when compiling and to use it afterwork to identify the device. The problem is that I don't know how to achieve that.

I tried to edit the `boards.txt` file to add a new board configuration with custom `vid.x` and `pid.x` (why all those 4 different values?) but after selecting my board and uploading, the `MODEL_ID` still stays the same:

    ID_MODEL_FROM_DATABASE=HL-340 USB-Serial adapter
    ID_MODEL_ID=7523

Can't I just specify somehow the `USB_PID` macro to the compiler command line?

  [1]: https://arduino.stackexchange.com/questions/14600/how-to-differentiate-between-2-micros-on-linux?newreg=c19dc2b8ae03419c8bb5e132fc41bbb3

body:
> How to change Arduino Nano MODEL_ID?

The [Arduino Nano][1] used a special USB-Serial adapter (FTDI FT232RL). You can [change the ID][2] but this requires some special hacking. Please see the provided links.

Cheers!

  [1]: https://www.arduino.cc/en/Main/ArduinoBoardNano
  [2]: http://www.alauda.ro/2013/11/changing-ftdi-descriptors/


body:
Finally find the solution =)

You don't have to change the ID vendor or ID product: it is possible to attribute a permanent name with devpath (where the device is plugged)
The only downside of using the devpath is that the devices will always have to stay plugged into the same physical port.

Answer here:[PersistentUSBDevices][1] / [Alternative filtering via Devpath][2]

  [1]: https://www.domoticz.com/wiki/PersistentUSBDevices
  [2]: https://www.domoticz.com/wiki/PersistentUSBDevices#Alternative_filtering_via_Devpath


message:
How to use Serial Monitor without Arduino board?

I want to use Arduino(atmega8) on breadboard using USBASP programmer and want to use Serial Monitor without using any Arduino board as ISP programmer.
My questions: 1. Is such thing possible?
2. How do I do that?

body:
> How to use Serial Monitor without Arduino board?

Yes that is possible. Connect to the RX/TX pins on the breadboard chip. Remember these are 5V. You will need an Serial-USB or RS232 adapter to connect your development machine. Please see this [blog post][1] for some inspiration.

Cheers!

  [1]: http://cosa-arduino.blogspot.se/2013/04/programming-attinyx5.html


message:
How do I know if bootloader flash was successful?

I just bought a raw Atmega328p microcontroller. I am attempting to flash it with the Arduino bootloader.

The process seemed relatively straightforward as I had just followed the posted tutorial (https://www.arduino.cc/en/Tutorial/ArduinoISP).

Everything seemed to go fine and I even got a message after the second attempt with a message of 'Burning Bootloader Done'. I am targeting the device as if it were an Arduino Pro Mini.

I then moved onto program the chip with an Arduino sketch via the FTDI programmer. However, the sketch upload fails. It says that it is out of sync. I verify that everything is wired up correctly, yet it still fails. I then remove power to the Atmega328p chip (just to see if I get a different error) yet I still get the out of sync error.

This has me questioning whether or not the bootloader was even flashed in the first place. So how do I know if the bootloader actually was successful? A couple things to note:

- When I power on the Atmega328p, the PB6 output starts blinking immediately. I would assume that if there were a bootloader, there would be a moment of pause until the regular program starts. Should I expect to see a pause if the bootloader is on the chip?

- If the bootloader is on the chip, should I even expect to see the Atemga328ps default heartbeat?

- When I flash the chip with the bootloader, it says that it could take up to a minute to finish. However, it only takes 6 seconds until it states 'Bootloader Finished Burning'. This seems like it's happening too fast.

If we determine that the problem is due to something else (i.e. not the bootloader), I will begin a new discussion. However, right now I'm just curious how I know if the bootloader is actually on the device.

body:
See [my page about burning bootloaders](http://www.gammon.com.au/bootloader).

The sketch there has a "verify" option so you can check if the bootloader was burned.

See my post https://arduino.stackexchange.com/questions/15936/what-happens-when-code-is-uploaded-using-the-bootloader.

With Optiboot installed you expect to see three flashes:

[![Optiboot start][1]][1]

As for your other problems, see https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board.

You may well not have set the fuses correctly.

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


message:
Why does the current drop through a multiplexer?

I am trying to control 64 leds through a number of 8:1 analog multiplexers. The input is from pin 11 on the Arduino which is giving 40mA (maximum) and it is pulsed at 38kHz. Then I use other pins to select one of 64 leds to control. For testing, I am just trying one of those leds. The problem is that the current across the led is just 2mA, which means it is very dim. Using a multimeter, the current after the first multiplexer seems to be 4mA and after the second just 2mA. How can I get the current to increase? Thanks in advance!

body:
Analog multiplexers are not a good design choice for switching digital signals.

You should instead choose a digital solution. Maybe the 74HC138 would be a better choice? That's a 3-to-8 decoder with 3 enable inputs.

You could use 9 of them to reduce pin usage on the Arduino, or 8 of them if you have pins to spare.

One of the enables on the first-stage can be a "mater enable" - or tie one of the enables of all 8 of the second-stage together for a "master enable". Another enable to all the 8 second-stage muxes can be the PWM signal. The third is driven by the Arduino or the first stage as a MUX selector.

Something like this arrangement:

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

Note that the outputs are *active low*, so you would connect the anode of your LEDs to +5V and the cathode, through a suitable resistor, to the output.

Another option would be to use a set of shift registers that have an *output enable* pin. Drive that pin with the PWM signal and you can have any combination of LEDs enabled at once.

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


message:
Absolute noob looking for troubleshooting help

My 10-year-old son went to a "Robotics Camp" and came home with a non-functional Arduino robot. I figured it shouldn't be too much trouble to get it working. He swears he had it operating at the camp, but our best efforts notwithstanding, we were unable to reproduce his successes at home to any degree at all. Currently we seem to have an ungainly, $400 paperweight.

I'm a .Net web-developer by day, but I'm completely uninitiated when it comes to Arduino. I did enough research to learn how to upload a basic sketch- the "Blink" sketch- to our board an verify that the board is functional. Upon uploading the Blink sketch we got a flashing red LED. I was able to go into the sketch and modify the the variable values and see the results in the duration of the LED flash after uploading the sketch again. So I'm confident that we have a good connection to the PC and a functioning Arduino board.

But beyond that I'm stumped. When I attempt to upload the program that my son brought home, the robot does nothing. I can see a red LED blink a few times on the Arduino, but other that that, nothing happens.

Here's some photos of our setup:

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

Here's the sketch that my son brought home:

    /***************************************************
      This is an example for our Adafruit 16-channel PWM & Servo driver
      Servo test - this will drive 16 servos, one after the other

      Pick one up today in the adafruit shop!
      ------> http://www.adafruit.com/products/815

      These displays use I2C to communicate, 2 pins are required to
      interface. For Arduino UNOs, thats SCL -> Analog 5, SDA -> Analog 4

      Adafruit invests time and resources providing this open source code,
      please support Adafruit and open-source hardware by purchasing
      products from Adafruit!

      Written by Limor Fried/Ladyada for Adafruit Industries.
      BSD license, all text above must be included in any redistribution
     ****************************************************/

    #include <Wire.h>
    #include <Adafruit_PWMServoDriver.h>
    #include <QueueList.h>

    // called this way, it uses the default address 0x40
    Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
    // you can also call it with a different address you want
    //Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver(0x41);

    // Depending on your servo make, the pulse width min and max may vary, you
    // want these to be as small/large as possible without hitting the hard stop
    // for max range. You'll have to tweak them as necessary to match the servos you
    // have!
    #define SERVOMIN  300//150 // this is the 'minimum' pulse length count (out of 4096)
    #define SERVOMAX  400//600 // this is the 'maximum' pulse length count (out of 4096)

    uint16_t servoMins[] = {160, 200, 500, 150, 150, 150, 0};
    uint16_t servoMaxs[] = {600, 600, 700, 600, 600, 600, 0};
    uint16_t servoHomes[] = {380, 400, 300, 340, 375, 375, 0};

    enum GroupType {WithPrevious, NewGroup};

    #define PAUSE_COMMAND 6
    #define NUM_TRANSITIONS (PAUSE_COMMAND+1)

    unsigned long currentTime;

    class transition
    {
      private:
        unsigned long startTime;
        unsigned long totalTime;
        uint16_t pulseLenStart;
        uint16_t pulseLenEnd;
        uint16_t currentPulseLen;
        int id;
        bool transitioning;

      public:
        void init(int id, uint16_t current)
        {
          this->id = id;
          currentPulseLen = current;
          totalTime = 0;
          startTime = 0;
          pulseLenStart = current;
          pulseLenEnd = current;
          transitioning = false;

        }

        uint16_t calculate(unsigned long currentTime)
        {
          float t = 1.0f;
          if (totalTime > 1e-3f)
            t = (currentTime - startTime) / (float)totalTime;
          t = (t > 1.0f) ? 1.0f : t;
          currentPulseLen = (uint16_t)(((float)pulseLenEnd - (float)pulseLenStart) * t + pulseLenStart);
    /*      if (transitioning)
          {
            Serial.println("transitioning");
            Serial.println(id);
            Serial.println(t);
            Serial.println(currentTime);
            Serial.println(startTime);
            Serial.println(totalTime);
            Serial.println(pulseLenStart);
            Serial.println(pulseLenEnd);
            Serial.println(currentPulseLen);
          }
    */
          if (t >= 1.0f)
            transitioning = false;
          return currentPulseLen;
        }

        void createTransition (uint16_t pulseLen, unsigned long time)
        {
    /*      Serial.println("create Transition:");
          Serial.println(id);
          Serial.println(pulseLen);
          Serial.println(time);
    */
          pulseLenStart = currentPulseLen;
          pulseLenEnd = pulseLen;
          totalTime = time;
          startTime = currentTime;
          transitioning = true;
        }

        bool isTransitioning()
        {
          return transitioning;
        }
    };

    transition transitions[NUM_TRANSITIONS];

    struct Command
    {
      uint16_t pulseLen;
      unsigned long totalTime;
      int commandType;
      GroupType groupType;

      void execute()
      {
        transitions[commandType].createTransition(pulseLen, totalTime);
      }
    };
    QueueList<Command> commandQueue;

    void program ();
    void restoreHomePositions (double seconds);

    void setup()
    {
      pwm.begin();

      Serial.begin(9600);
      Serial.println("Hello world");

      pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz updates

      for (int servoNum =0; servoNum < NUM_TRANSITIONS; servoNum++)
      {
        //pwm.setPWM(servoNum, 0, servoHomes[servoNum]);
        transitions[servoNum].init(servoNum, servoHomes[servoNum]);
      }

      restoreHomePositions (0);
      program();
      restoreHomePositions (.75);

      yield();
    }

    void processCommandQueue();

    void loop()
    {
      currentTime = millis();

      processCommandQueue();

      for (int servoNum = 0; servoNum < NUM_TRANSITIONS; servoNum++)
      {
        if (transitions[servoNum].isTransitioning())
        {
          uint16_t pulselen = transitions[servoNum].calculate(currentTime);
          if (servoNum != PAUSE_COMMAND)
          {
            pwm.setPWM(servoNum, 0, pulselen);
            Serial.println("setPWM");
            Serial.println(servoNum);
            Serial.println(pulselen);
          }
        }
      }
    }

    bool isTransitioning()
    {
      for (int servoNum = 0; servoNum < NUM_TRANSITIONS; servoNum++)
      {
        if (transitions[servoNum].isTransitioning())
          return true;
      }
      return false;
    }

    int frame = 0;
    void processCommandQueue()
    {
      if (!commandQueue.isEmpty())
      {
        Serial.println("Frame");
        Serial.println(frame);
        frame++;
      }
      if (!commandQueue.isEmpty() && !isTransitioning())
      {
        do
        {
          Command top = commandQueue.pop();
          top.execute();
        }
        while (!commandQueue.isEmpty() && commandQueue.peek().groupType == WithPrevious);
      }
    }

    void move (int commandType, uint16_t pulseLen, double seconds, GroupType groupType = NewGroup)
    {
      Command command;
      command.groupType = groupType;
      command.commandType = commandType;
      command.pulseLen = pulseLen;
      command.totalTime = (unsigned long)(seconds * 1000);
      Serial.println("Command:");
      Serial.println(groupType == NewGroup ? "NewGroup" : "WithPrevious");
      Serial.println(commandType);
      Serial.println(pulseLen);
      Serial.println(command.totalTime);
      commandQueue.push (command);
    }

    void rotateWrist (int percent, double seconds, GroupType groupType = NewGroup)
    {
      percent = percent < -100 ? -100 : percent;
      percent = percent > 100 ? 100 : percent;
      uint16_t pulseLen = map (percent, -100, 100, servoMins[5], servoMaxs[5]);
      move (5, pulseLen, seconds, groupType);
    }

    void bendWrist (int percent, double seconds, GroupType groupType = NewGroup)
    {
      percent = percent < -100 ? -100 : percent;
      percent = percent > 100 ? 100 : percent;
      uint16_t pulseLen = map (percent, -100, 100, servoMins[4], servoMaxs[4]);
      move (4, pulseLen, seconds, groupType);
    }

    void rotateForeArm (int percent, double seconds, GroupType groupType = NewGroup)
    {
      percent = percent < -100 ? -100 : percent;
      percent = percent > 100 ? 100 : percent;
      uint16_t pulseLen = map (percent, -100, 100, servoMins[3], servoMaxs[3]);
      move (3, pulseLen, seconds, groupType);
    }

    void bendForeArm (int percent, double seconds, GroupType groupType = NewGroup)
    {
      percent = percent < -100 ? -100 : percent;
      percent = percent > 100 ? 100 : percent;
      uint16_t pulseLen = map (percent, -100, 100, servoMins[2], servoMaxs[2]);
      move (2, pulseLen, seconds, groupType);
    }

    void bendUpperArm (int percent, double seconds, GroupType groupType = NewGroup)
    {
      percent = percent < -100 ? -100 : percent;
      percent = percent > 100 ? 100 : percent;
      uint16_t pulseLen = map (percent, -100, 100, servoMins[1], servoMaxs[1]);
      move (1, pulseLen, seconds, groupType);
    }

    void rotateRobot (int percent, double seconds, GroupType groupType = NewGroup)
    {
      percent = percent < -100 ? -100 : percent;
      percent = percent > 100 ? 100 : percent;
      uint16_t pulseLen = map (percent, -100, 100, servoMins[0], servoMaxs[0]);
      move (0, pulseLen, seconds, groupType);
    }

    void pause (double seconds)
    {
      move (PAUSE_COMMAND, 0, seconds, NewGroup);
    }

    void restoreHomePositions (double seconds)
    {
      rotateRobot (0, seconds, NewGroup);
      bendUpperArm (0, seconds, WithPrevious);
      bendForeArm (0, seconds, WithPrevious);
      rotateForeArm (0, seconds, WithPrevious);
      bendWrist (0, seconds, WithPrevious);
      rotateWrist (0, seconds, WithPrevious);

    }

    //This is where the program goes!

    void program ()
    {
        //Available commands
      /*rotateWrist (where, seconds, groupType)
      bendWrist (where, seconds, groupType)
      rotateForeArm (where, seconds, groupType)
      bendForeArm (where, seconds, groupType)
      bendUpperArm (where, seconds, groupType)
      rotateRobot (where, seconds, groupType)
      pause (seconds)*/

      //example 1 -- rotates the wrist servo 100% over 2 seconds,
      //starting a new transition group.
      rotateWrist (100, 2);
      //example 2 -- bends the upper arm and the forearm at the same time
      //moving both 45% over 1.5 seconds.
      bendUpperArm (45, 1.5);
      bendForeArm (45, 1.5, WithPrevious);
      bendForeArm(45, 1.7, WithPrevious);

    }

      //To start a new group, the groupType should be either NewGroup or left blank
      //Any call after that set to WithPrevious will start the transition at the
      //same time as the first transition in the group.
      //As soon as a new call is made with a NewGroup groupType, a new transition group is m
    // End of your program

  [1]: https://i.stack.imgur.com/gFLrZ.jpg
  [2]: https://i.stack.imgur.com/4KcaR.jpg
  [3]: https://i.stack.imgur.com/JVyBn.jpg
  [4]: https://i.stack.imgur.com/AjGsX.jpg
  [5]: https://i.stack.imgur.com/O7xyU.jpg

body:
I'm not familiar with the breadboard in your images. You didn't mention if you're familiar with how to use a breadboard and from what I can see I'm not even sure why its being used. It looks to me like you could just connect the jumper wires directly to the pins on the Arduino.

Was the Arduino ever unplugged from the breadboard after it was known to work properly?

Due to the angle of the photo it is hard to see which pins the wires are connected to. Can you identify which Arduino pins the six wires are connected to?


body:
Please consider the following to assist in your understanding of the Arduino and of the servo operation. I recently "instructed" a summer camp of teens to construct the MeArm robot arm, using inexpensive servos and an Arduino.

The servos you have will operate without the servo driver, enabling you to isolate the problem. Consider to connect the signal wire for each servo to an assigned pin on the Arduino and test each servo with the built-in Sweep sketch. Your off-board power for the servos should share the ground with the Arduino, while the +V would connect to the power lead for the breadboard and hence to the servos.

Pins 6, 9, 10, 11 are PWM capable and you can modify in the Sweep sketch to operate each one independently as a way of testing the base "kit."

The code for Sweep is simplistic, while the servo driver has a good bit of "middle-man" calculations to accomplish more refined control.

Example from the summer camp:

[in setup]
claw.attach(9);
inout.attach(10);
updown.attach(11);
rightleft.attach(6);

[in loop]
 - the following was placed in a for-loop:
claw.write(pos);

... and more code including delays and limits to pos to prevent servo chatter/slam.

This will likely show you that your servos are working (or not) and enable a better understanding of the basics, while perhaps increasing your chances of understanding the more complex and flexible servo board library of code.


message:
WizNet W5100 not connecting to modern switches and routers

I have an Arduino data collector with a W5100 module (see bottom of picture). Simple fixed IP connection:

     byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
     byte ip[] = { 192, 168, 1, 242 };
     Ethernet.begin(mac,ip);

This works with my old routers (Asus WL500, TP-Link MR3420), but fails to connect when plugged in a gigabit switch or my new router (D-Link DWR-116). The connection LED on the new devices does not lit up or blinks slowly, showing repeated connection attempts. So the W5100 fails to make the physical connection.

I made it work by adding my 10-year old Surecom switch to the mix, but wonder what the problem could be. Is there some cable configuration that is used by the W5100 but have been removed from these new network devices? (Not sure if the cable is cross or straight, trying another cable is messy, the whole thing is built in the wall.)

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

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

body:
I think your problem is due to the MAC address that is being loading into the W5100.  Try setting the 2 low order bits of the first byte to 0.

These bits define whether the MAC address is unicast or multicast and whether it is private or universal.  Some switches appear to block ARP requests if these bits are set incorrectly.

I changed the first byte of the MAC address from x'47' to x'44' and things started working.


body:
I just made a setup on my Dell PowerConnect and it starts to accept the W5100.
I had to change the port speed to 10M and it starts working. The 100M and 1000M was not accepting the w5100.
Before, I had a CISCO wifi 10/100M wired connection between it and w5100 and it connects fine, but this isn't the main network on my company.


body:
sounds like a mac address issue.
I googled for Tp-Link MAC address bytes and it worked perfectly. (it is first 4 bytes)


message:
Can i supply the AREF pin with an Analog pin from the same board?

I guess its a dumb question but couldnt find anything about it online. I know its possible to supply the AREF pin with 3.3 V to increase the ADC resolution.

For the project i am working on the analog voltage i will be reading will be between 0 and 2.2 and the increased resolution is a must.

I know i can use another board that has a 12 bit resolution but i really would like to make do with Uno. So i wonder if i can set an analog pin to output 2.3 V and feed it to the Aref pin.

If thats not possible please let me know why, so i can increase my knowledge

body: The output voltage of the "analog outputs" (which are actually PWM) are dependent on supply voltage and so are not a good choice where precision is required. Consider using either an integrated voltage reference (e.g. TL431) or a constant-current source feeding a zener diode instead.


body:
With an input voltage between 0 and 2.2 V, you can use a 2:1 voltage divider to cut the voltage in half.  In your code, use [`analogReference(INTERNAL)`](https://www.arduino.cc/en/Reference/AnalogReference) to set the analog reference voltage to 1.1 V.  The 1.1 V internal reference voltage is created by a bandgap circuit so is reasonably accurate.

To make the [voltage divider](https://en.wikipedia.org/wiki/Voltage_divider), put two equal resistors (eg 10KΩ each) in series; connect one end of the series to your input voltage, the other end to ground, and the mid-point to an analog input pin.


message:
Arduino MPU6050 Control 2 Servo

I'm new to gyroscope and accelerometer and am working on my project to control servo with Arduino Uno R3 based on the reading from InvenSense MPU6050 6DOF gyroscope and accelerometer. I've found the a same sheet of code from different websites.

Website 1_http://www.projehocam.com/wp-content/uploads/mpu6050-2-servo.txt

Website 2_http://www.instructables.com/files/orig/FLY/GZAL/IDIN48PC/FLYGZALIDIN48PC.ino

And from this part of the code, I couldn't understand the servo.write part...

        #ifdef OUTPUT_READABLE_YAWPITCHROLL
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            Serial.print("ypr\t");
            Serial.print(ypr[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(ypr[1] * 180/M_PI);
            myservoY.write(int(ypr[1] * -180/M_PI)+90);   // Rotation around Y
            Serial.print("\t");
            Serial.println(ypr[2] * 180/M_PI);
            myservoX.write(int(ypr[2] * 180/M_PI)+90);   // Rotation around X
        #endif

Why is the operation (int(ypr[1] * -180/M_PI)+90) ??

body:
`ypr` contains the Yaw, Pitch and Roll. It is provided in radians.

Servo.write takes degrees.

Multiplying radians by 180/PI converts it to degrees.  Adding 90 centralises it around the 90 degree point (half way) of the servo.


message:
externally powering the Arduino questions

I have several questions on externally powering the Arduino Uno

   - I have a 7.2V power source that is 6 rechargeable AA batteries together, 1.2V and 1300mA each. If i use a 4.70 and 1.5 ohm resistors together to give 1.16 amps, can I power the arduino with this?

- Can I power a servo off the Arduino 5V rail If i place a 470uF or more capacitor alongside it?

- Will anything heat or blow up or am I just being paranoid like always?

body:
I am guessing that you are thinking of dividing down the battery voltage from 7.2V down to 7.2*(4.7)/(4.7+1.5) = 5.5V. This is generally a bad idea for a few reasons.

1. The battery voltage will not be a constant 7.2V. When they are fully charged it could be even higher. As they discharge they could drop significantly and your Arduino POR (power-on-reset) circuit would potentially shut the board down before the batteries are fully discharged

2. The batterys' internal resistance would probably drop the output voltage considerably once the resistors try to draw 1A of current. It might even collapse the voltage to some unusable value.

3. Even if the battery internal resistance is very low and even if the Arduino is not drawing much power (or even off) you will always be drawing ~1A of current from the batteries. This will rapidly drain your batteries and will also heat them up from their internal resistance. Not to mention your external resistors better be able to handle > 5W or so. Conclusion: lots of unnecessary heat and power loss.

To answer your other question, assuming the servo is low power and the Arduino power supply is up, you could power it from the Arduino 5V supply (not your batteries).

If you need to use batteries to power an Arduino, I would highly recommend a power regulator to produce a stable output voltage to power your Arduino.


body:
Your typical Arduino has a built-in 5V regulator. Just plug the batteries into the barrel jack - that is what it is for.

If you don't have a barrel jack on your Arduino (it's one of the little ones?) then you will need a *voltage regulator*. For battery usage you want a switching "buck" regulator.

You can find them cheaply enough under the name "UBEC" (Universal Battery Elimination Circuit) and are used for model aircraft etc.


body:
You can connect the batteries fine into Vin or the barrel jack, however you will run into the issue that your battery voltage will sag. This will vary on what chemistry batteries you are using, NiMh voltage discharge sits on a bit of a plateau around 1.2V typically, alkaline has more of a gentle curve downwards and then drops off quite sharply around or below 1V.

The reason this is an issue is highlighted on the Arduino Uno page itself:

> Input Voltage (recommended)   7-12V
>
>Input Voltage (limit)  6-20V

and

> The board can operate on an external supply from 6 to 20 volts. If supplied with less than 7V, however, the 5V pin may supply less than five volts and the board may become unstable. If using more than 12V, the voltage regulator may overheat and damage the board. The recommended range is 7 to 12 volts.

The issue here is the dropout of the onboard regulator.

The solution is to use your own external regulator and connect it to the 5VDC pin.

You can use:

1. An external swithcmode DC-DC converter, you would be ideally after a buck boost. DC-DC converters are available from ICs for a full ground up DIY design to available on board modules and daughterboards and fully assembled circuits. Regarding the other answer a BEC or UBEC may not be suitable as typically they are buck converters and have higher minimum output voltages than that required by the OP, some however with careful selection may be alright to use.

Adafruit off the shelf buck-boost module:
https://www.adafruit.com/products/2190

2. An external linear LDO regulator, ideally with as low dropout as possible. You will need to pick this part to suit your input voltage range, this may be difficult as extremely low dropout parts are typically low current and not suitable if wanting to drive a servo. Something like a REG103 for example may work, depending on the dropout an LDO linear regulator may work down to around 5.2~5.3VDC minimum, which should be okay for most of the capacity of the batteries.

3. A premade shield, some may work for you, some to give you an idea of what is required.

DC-DC converter for battery shield:
https://www.wayneandlayne.com/projects/battery-booster-shield/

Adafruit has a lithium battery shield such as does Sparkfun (not enough rep for more links)

Itead has a AAA battery shield also.

Options here will depend on your design ability and assembly skills as to if you can DIY or need off the shelf.

Your servo will be fine connected to the external regulator as long as the option you use is rated to supply enough current.


body:
This question has been answered on electronics.stackexchange, e.g. [How to provide separate voltages from a common power source](https://electronics.stackexchange.com/questions/252742/how-to-provide-separate-voltages-from-a-common-power-source/252793)

Daniel V has explained the main issues.

The 'killer' for most people is the resistors are always across the battery, and so they alone will take over 1A from the battery pack continuously, and hence run it flat in just over an hour. Further, they need to dissipate over 5W of heat, so they aren't that cheap either.

A NiMh rechargeable battery will have a voltage of about 1.4V when it's fully charged, dropping to under 1V before it is exhausted. So that would mean the resistor network needs to output 5V or less with an input voltage from 6x1.4V=8.2V down to under 6x1V=6V.

So the resistor ratio would need to handle 8.2V in and produce 5V out, and then 6V in would produce 3.66V. My reading of the ATmega sec is it might struggle to run at 16MHz at that 3.66V input voltage.

You might try to make a resistor-based voltage divider more efficient by increasing the total resistance.

However, as explained on the electronics.stackexchange, the load presented by the ATmega on an Arduino varies dynamically, from microsecond to microsecond, so it is very hard to choose resistors which would maintain the voltage within a reasonable operating range, while the current passing through the Arduino varies so much.

An Arduino has an on-board voltage regulator.

However, the typical 5V regulator on generic Arduino's have a drop-out voltage of 2V, i.e. the input voltage needs to be 7V or more. That means most of that battery pack capacity will provide less than 7V, so the voltage will start to drop.

You *might* be lucky and the on-board regulator will 'track' the input voltage down. That means it will fail below 5V as its input drops below 7V. You would need to test your Arduino; there is no guarantee that the regulator on the board does this. Further, it might struggle to run at 16MHz as the voltage approaches 4V.

So, if this is just a one-off hobby project, it might be reasonable to try that. However, if other people are going to use it, it might be too risky.

The ATmega can be run with anything between 5V and 1.8V if the clock is slow enough. Also you'd need to either modify the electronics, or change the bootloader of the Arduino to ensure it runs at a much lower clock frequency. So it is possible to run at a lower voltage than 5V, by changing the bootloader, but it seems like a strange exercise. Then a resistor divider (which wastes a lot of energy), or the on-board regulator could be used.

Instead, look at a Low-Drop-Out (LDO) voltage regulator. There are parts which will regulate anything from 8.4V down to 6V, or less, down to 5V. An Arduino alone uses well under 100mA, it is the electronics it is driving which uses the majority of an Arduino's specified 500mA.

So you look for a voltage regulator, which will take 9V in (as a safety margin) with a drop-out voltage of 0.7V (lots at this spec), 5V out, and 250mA or better. Most electronics distributors have a product selector which will help you find this, and you may find small ready-made modules which do exactly this (but not an LM111xx).

You don't post a link to the servo you're using.

Low-cost servo's typically take a lot of current as they move. I've measured some using a proper bench power-supply unit (bench PSU). They typically take well over 1A for periods long enough for me to see it happen. So the power supply would likely need to supply more than 1A for short periods, i.e. 10's of milliseconds. You will need quite a substantial capacitor to handle that.

Depending on the servo, you might be better to use 4xNiMh to power the servo directly, without any intermediate regulation, and a more modest capacitor. The ground (-) of that power supply needs to be connected to the GND of the Arduino so that the servo signal from the Arduino will drive the servo correctly.

In that case, you might use a low-cost (ebay) DC-DC step up (boost) switching regulator to provide the 5V to the Arduino. Their are lots available which are intended to power USB devices at 5V.


message:
How to serially communicate arduino uno to PIC18f4550?

I am new in PIC programming

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

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

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

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

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

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

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

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

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


message:
Arduino Nano stuck on uploading

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

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

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

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

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

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

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

> Did I burn my board?

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

Cheers!

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


message:
EthernetUdp2 does not name a type

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

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

    #include<SPI.h>

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

    }

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

    }

and it is giving the following Error :

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

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

    Error compiling.

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

after Enabling Show verbose output I got :

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

    Build options changed, rebuilding all

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

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

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

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

    Error compiling.

any Help please

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

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

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

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

          // Public members...

    };

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

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

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

    #include<SPI.h>

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

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

    }

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

    }


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

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

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

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


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

avrdude:

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

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

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


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

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

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

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

Any ideas?

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

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

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


body: Save the variables you need to EEPROM.


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

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


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


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

Here is the image of Ethernet shield near RJ45 socket:

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

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

Is this true?

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

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

**UPDATE**

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

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

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

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

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

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

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

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


message:
Controlling 12v DC LED strips using Arduino UNO

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

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

And can I use PWM?

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

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

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

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

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


message:
How to insert a power button on Arduino Nano

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

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

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

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

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


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

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

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


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

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

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

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

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

Here is the source code of the transmitter:

 #include <Manchester.h>

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

 uint16_t transmit_data = 2761;

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

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

And this is the code on the receiver:

 #include "Manchester.h"

 #define RX_PIN 4
 #define BUFFER_SIZE 22

 uint8_t buffer[BUFFER_SIZE];

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

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

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

 #include <Manchester.h>

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

 uint16_t transmit_data = 2761;
 int lastTransmit = 0;

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

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

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

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

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

    uint8_t receivedSize = 0;

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

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


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

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

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

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

What can be the reason?

**UPDATE**

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

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

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

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

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

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

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

    void loop() {

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

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

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

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

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

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

The situation is the same:

https://youtu.be/vypaNOxZ5KI

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

**UPDATE 2**

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

**UPDATE 3**

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

**UPDATE 4**

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

**UPDATE 5**

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

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

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

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

So this is the debug procedure I would advice:

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

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

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

Possible faults i can currently think of:

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

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


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

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

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


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


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

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

Restoring the Serial messages didn't change the behaviour.

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

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

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


message:
Uploading .hex to ATTiny13 using Arduino

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

I got here by:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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


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

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

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

I have an Arduino Uno.

Thank you!

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


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


message:
Minimal Arduino using ATmega32U4

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

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

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

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

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


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

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

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

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

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

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

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

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

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


message:
Help with usbasp pinout

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

[![ ][2]][2]

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

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

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

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

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


message:
digitalPin giving lower voltage than Vcc

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

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

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

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


message:
Find RSSI of Mobile Device Without Connecting

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

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

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

With that in mind, I have two questions:

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

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

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

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

----------

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

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

But, you could:

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

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

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


message:
Strobe Frequency Calculation, how its done?

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

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

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

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

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

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

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

So, I have following questions:

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

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

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

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

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

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

> How "frequency is calculated"?

From the code:

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

    frequency = 1000000/(microsCurrent - microsPrev);

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

> What is "hold frequency" variable?

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


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

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

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

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

Cheers!


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

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

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

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

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


message:
Arduino Wire.h send double to lcd

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

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

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

    #include <Wire.h>

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

    double f;
    void loop() {

      f = 200.00;

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

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


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

    double f;

    void loop() {
      char buf[10];

      f = 200.00;

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

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

    double f;

    void loop() {
      f = 200.00;

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

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

Cheers!

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


message:
Understanding memory fragmentation due to char arrays in functions

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

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

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

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

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

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

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

To sum up:

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

OR

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

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

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

This is correct.

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

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

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


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

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

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

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

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

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


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

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

Thanks in advance!

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

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

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


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


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

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

I wanted to repair it. What should I do?

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

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

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

What should I do?

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

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


message:
Best way to assign value to lot of variables

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

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

 i need this:

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

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

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

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

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

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

 int lenght = ZeroValue.toInt();

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

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

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

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

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

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

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

And parse with:

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

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

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

Or simply:

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

Cheers!

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