body:
I have two DS18B20 temperature sensors connected via a OneWire bus to an arduino. I noticed that these sensors get hot, when permanently powered and decided to just turn them on for measurment.

First attempt: Define a pin as output and feed the sensors. Because I received only one value (first sensor on bus), I assumed that the current delivered may not be high enough and utilized a transistor (+resistor) as switch for the main 5V line to feed the sensors from the mains (as before). The result is the same. I only get the value of the first sensor. When I connect the sensors directly, I get both values.

I tried up to 4 seconds delay after switching the bus on and again after reading the values (before switching the bus off again), with no luck. Only the first sensor answers.

Do I have a timing or a current problem here?

**UPDATE**

Wiring (working): Two DS18B20 in parrallel with a 4,7k resisor between `DATA` and `VIN`. One Arduino pin used, Sensors directly powered by power-supply (same as arduino)

Wiring (not working): Broke the `VIN` line and added a transistor as switch between power-supply and sensors `VIN`. Used a second pin and a resistor to power up the line.

The transistor is a `TC124E` (npn) logic level transistor. I have the feeling, that this boy is not providing enough current to the sensors, which in addidtion have five meter cables attached...

**UPDATE II**
It is not the current. I replaced the transistor with a mosfet (70T03H) and the result is exactly the same: When switched, only one sensor answers . When I connect the gate directly to a +5V line, I get both values as expected.

Kinda think, that the switching of the pin irritates the bus or the specific device.

**UPDATE III (Solution)**

I tracked this down to a mixture of

* Different resolution settings on the sensors
* my code not waiting long enough to get the sensor with the higher resolution to setup (on-to-read time). Giving the bus slightly more time to setup before any reading is accepted, solved my problem.

title: Weird OneWire bus problem

Answers: 1

body:
If you were trying to wire your bus in parasitic mode, here is what I am using:

    OneWire Bus in parasitic mode:

    +------------+     +5v            +---------+     +---------+
    |    MCU     |      |             | DS18b20 |     | DS18b20 |
    |            |  R_pu = 4.7K       | g  d +5 |     | g  d +5 |
    | Strong-    |      |             +-o--o--o-+     +-o--o--o-+
    | Pullup   > o------o               |  |  |         |  |  |
    |            |      |               +--|--+         +--|--+
    |            |      |               |  |            |  |
    |    Data <> o------o---------------|--o------------|--o------ - - -
    |            |                      |               |
    +------------+                      V               V

I run at least three sensors this way on an approximately 6 meter bus, completely reliably.


body:
My task is to use a port extender (MCP23s17) to drive a touch keypad for which I have to define names of pins so that I can call those names in arguments of a function.

I have searched for different methods to define "PORT EXTENDER" pin but could not find any satisfactory results. Kindly help me handle the situation.

i have used the following libraries downloaded from Arduino playground
1. CapacitiveSensor.h
2. MCP23S17.h
Now I have to use MCP23S17 Pin in the following function

    #define key1 2
    #define key2 4
    CapacitiveSensor cs_4_2=Capacitivesensor(key2,key1);  //capacitive sensor is connected to pin 4 and 2

key1 and key2 are Arduino's pins. I want some method by which I can refer key1 and key2 to the port extender's (MSP23S17) pin. The above answers are surely helpful but they doesn't fulfill my requirement.

Thanks in Advance
Sorry for English.

title: How can I define a port extender MCP23s17 pin in Arduino

Answers: 3

body:
If you use this [arduino library](http://playground.arduino.cc/Main/MCP23S17#pinMode):

    #define LED_PIN 15

    mcp.pinMode(LED_PIN, LOW); //set led pin on the MCP23S17 to an OUTPUT

    mcp.digitalWrite(LED_PIN, LOW)

body:
If you are using [my library](https://github.com/MajenkoLibraries/MCP23S17) you can do something like:

    MCP23S17 expander1(&SPI, 10);

    #define LED_PIN expander1, 15

    void setPin(MCP23S17 &expander, int pin, bool level) {
        expander.digitalWrite(pin, level);
    }

    // ... later ...

    setPin(LED_PIN, HIGH);

body:
There is also the [Adafruit][1] Library, all do similar things, just in a slightly different way. I use this one, it just depends on which method you are most comfortable with and what your requirements are. Try them all and find out.

    void setup() {
      Serial.begin(9600);  // debugging
      mcp.begin();      // use default address 0

          for(int i = 0; i < 6; i++) {
            mcp.pinMode(trafficLights1[i], OUTPUT);
          }
           for(int i = 0; i < 6; i++) {
            mcp.pinMode(trafficLights2[i], OUTPUT);
           }
            for(int i = 0; i < 5; i++) {
            mcp.pinMode(trafficLights3[i], OUTPUT);
            }
      for (int P=0;P<16;P++) {
        mcp.pullUp(P, HIGH);  // turn on a 100K pullup internally
        mcp.digitalWrite(P,LOW);
     }
          mcp.digitalWrite(11, HIGH);
    }

  [1]: https://github.com/adafruit/Adafruit-MCP23017-Arduino-Library


body: It seems like the majority of Arduino applications are written without using classes / objects. Is there a reason for this? Does is slow down the Arduino or somehow present undesirable behavior?

title: OOP vs procedural programming on arduino

Answers: 1

body:
Your assumption is quite wrong:

* The majority of libraries use OOP.
* The majority of in-built device drivers use OOP.
* The core is filled with many OOP helper objects and classes.
* 99.99% of all sketches use those OOP objects.

The sketches themselves may not be written as a class or set of classes for a number of reasons:

1. There is no point
2. The programmer doesn't know how

When a sketch is just stitching together calls to objects defined through libraries and making a few decisions there is little point in making the sketch itself an object. It's just a waste of time.  In general if the sketch gets too complex to manage it gets broken down into smaller units - i.e., libraries - which are very often written as classes.

The moment you do `Serial.begin(9600);` you are using OOP.


body:
I am uploading a test sketch(Blink) to my new Zero(with Wifi101 shield) and when I press Upload in the IDE, the Console says the following:

Arduino: 1.6.10 (Linux), Board: "Arduino/Genuino Zero (Programming Port)"

    Open On-Chip Debugger 0.9.0-gd4b7679 (2014-10-03-00:26)
    Licensed under GNU GPL v2
    For bug reports, read
     http://openocd.org/doc/doxygen/bugs.html
    debug_level: 0
    adapter speed: 500 kHz
    adapter_nsrst_delay: 100
    cortex_m reset_config sysresetreq
    Error: unable to find CMSIS-DAP device
    Error: No Valid JTAG Interface Configured.
    Error: No Valid JTAG Interface Configured.

I am using the Zero programming port.

title: Arduino zero Error: unable to find CMSIS-DAP device

Answers: 1

body:
I had exactly the same error with the same board. Running the IDE as root solved the problem. So, Chris was right pointing out a permission issue.

I found more information here : http://bitofahack.com/post/1437909576

Then I added the file `/etc/udev/rules.d/98-openocd.rules` :

    ACTION!="add|change", GOTO="openocd_rules_end"
    SUBSYSTEM!="usb|tty|hidraw", GOTO="openocd_rules_end"
    ATTRS{product}=="*CMSIS-DAP*", MODE="664", GROUP="plugdev"
    LABEL="openocd_rules_end"

I then ensured that I was member of group `plugdev`.

`udev` looks for changes in his rules directory so you don't have
to restart it.

I plugged the board again and it worked.

Note that you can force udev to read the rule files again by entering :

    sudo udevadm control --reload

I had to do this because I first made a mistake in the rule file.

Hope this helps.


body:
Just this general question.As the titles says.

How does Arduino decide when to go into flashing mode and normal mode?

Is it by connecting certain pins to ground,so it's a hardware check or does it have to do with the code?

Other similar arduino like products such as the esp8266 work the same way as long as they use the same chip?

Answers: 1

body:
It first runs the bootloader. If there is no data coming into the serial connection within a certain amount, i.e. it's not being programmed, it will exit the bootloader and start the actual sketch.

In the UNO you will notice a 3 second delay between providing power, and your sketch starting.


body:
I'm about identify myself stupid, howcome I couldn' t figure out how to split a string into substring using arduino, even after 10 days of searching. The number is fact... So, As Mr.Arduino.cc says: *string*.substring() is just can be used as conditional phrase with loops like if. and there is no method such strtok() like in C can help me with this. So guys, I' m bagging you for help, please!

    if (ks > 255 * 60)
                {
                        vek.print("Bu yazı, ", 25, 0);
                        vek.printNumI(255*60, 25, 8);
                        vek.print("karakterd-", 25, 16);
                        vek.print("en uzun ol", 25, 24);
                        vek.print("dugundan", 25, 32);
                        vek.print("gosterlemz", 25, 40);
                }

    for (byte i = 0; i <= ss ; i ++)
                {
                        for (byte j = 0; j <= 6; j++)
                        {
                                int ilk_kar = j * 10 + i * 60;
                                int son_kar = ilk_kar + 10;

                                String yaz=readString.strtok(ilk_kar,son_kar);

                                vek.print(yaz, 25, j);

                                if (analogRead(A5) == 1023)
                                {
                                        continue;
                                }
                                else
                                {
                                        break;
                                }
                        }
                }
        }
    }

Error: sketch_aug22a.ino: In function ‘void loop()’:
sketch_aug22a.ino:83:56: error: ‘class String’ has no member named ‘strtok’

What am I supposed to do?

Thanks, already...

title: How to split a string into substring Arduino

Answers: 1

body:
Import the *string.h* library by adding `#include <string.h>` on top of your sketch, in order to use the `strtok()` function.
Checkout the usage example of `strtok()` here: http://www.cplusplus.com/reference/cstring/strtok/?kw=strtok


body:
We are using an Arduino Nano for simple serial comms to fire a relay from a Windows 10 PC.

Initial issue we had was windows not recognizing the device (COM Port) when the pc is powered off (as per this link: [Arduino Nano - USB not present after reboot][1] ) so we powered the arduino nano over a 5V pin and now when Windows starts up the device is recognized.

However, as I'm learning with these chips, nothing is ever that simple. Now the relay that we are firing does not work with external power, but if you unplug the external power then the relay does fire (powered over USB)

The units are at a mine and at the moment and I believe that the problem is that the serial chip is now not responding as per this - from the official Arduino Nano page:

*The FTDI FT232RL chip on the Nano is only powered if the board is being powered over USB. As a result, when running on external (non-USB) power, the 3.3V output (which is supplied by the FTDI chip) is not available and the RX and TX LEDs will flicker if digital pins 0 or 1 are high.*

Note - I included the above from another question but this no longer appears on the official arduino nano page (can't past link as it's my first post)

The question is how can we get the digital pins on the arduino nano to fire using an external power source and input from a Windows PC?

Thanks

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

  [1]: https://electronics.stackexchange.com/questions/74123/arduino-nano-usb-not-present-after-rebootn
  [2]: https://i.stack.imgur.com/zhH2X.png

title: Arduino nano digital pins not working with external power source

Answers: 2

body:
I think you may need to back up and start over again.

Rather than changing the power supply, you need to fix the problem that made you think you needed to change power supplies.

Following a link in a comment on the [question you linked](https://electronics.stackexchange.com/questions/74123/arduino-nano-usb-not-present-after-rebootn)  to leads to [this thread on the Arduino forums.](http://forum.arduino.cc/index.php?topic=23025.0)

The suggestion there is that a particular pin on the FTDI chip on the Nano isn't connected as it should be.

To be exact, the Test pin ([pin 26 on the FT232RL chip](https://www.arduino.cc/en/uploads/Main/ArduinoNano30Schematic.pdf)) needs to be grounded to fix the original problem you were having with communications with the Nano.

The description there fits your description.  The Nano can't talk to the PC if the Nano is connected to the PC at power on.  The same thing happens with the circuit referenced in that Arduino forum thread, but they are using another embedded system instead of a PC.

If you fix that, then you won't need to use an external 5V supply.

To back up the conclusion from the Arduino forum, here's an excerpt from page 8 (pin descriptions) of the [FT232RL datasheet:](http://www.ftdichip.com/Support/Documents/DataSheets/ICs/DS_FT232R.pdf)

> 26 TEST   Input  Puts the device into IC test mode. Must be tied to GND
> for normal operation, otherwise the device will appear to fail

You need to connect pins 25 (ground) and pin 26 (Test.)

Excerpt from the Nano schematic:
[![enter image description here][1]][1]

Pins 25 (ground) and 26 (Test) are right next to one another, so easy to fix.

You need to put a blob of solder on the red marked spot in this picture:
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/XaPqA.png
  [2]: https://i.stack.imgur.com/ovzQJ.png

body:
I accepted the answer from JRE as I believe this is the best answer. For certain reasons we weren't able to do this so I've posted this as a workaround.

We ended up splitting the USB input to the arduino nano by using a Y cable. We used the one end for the power to the device and the other end for comms from the PC (with power disabled). This solved our issue as the chip now received power and responded to comms and the USB driver also initialised correctly on Windows when starting up.

If you are unable to solder the chip then this is a workaround that we have used.


body:
I have this strange problem. My TMP 36 sensor works fine when it is the only thing connected to my Arduino Uno board. The voltage measurements, and thus the temperature, are accurate and consistent. However, when I attach an LCD screen to the Uno and have a program print the TMP's measurements to the screen, the values become inconsistent, and can change up to 10 degrees F from one reading to another. (I have the sensor take a measurement every second.) This does not happen when the LCD screen is not plugged in. I decided to remove separate connectors from the screen and see when the measurements became consistent again. I tried this once and found that a ground wire that goes to connection 5 on the screen caused to value to change when I repeatedly inserted and removed it from a ground pin. The TPM values were changing even when there was nothing else connected to the LCD (it wasn't on) except for the ground wire. I don't understand how this is possible, and I don't know if this is a hardware or software issue.

I rewired the LCD screen starting with sensor wires, then ground wires, and then the two 5V connections, with one of them having a 220 ohm resistor. I did this while the circuit was powered, and watched the values for any large changes. The first change was a few seconds after I wired the last 5V wire. The sensor measured 80 degrees F and then 85 degrees F one second later. It then went to 81 for a few seconds, then 87. The values continued to change, but not by as much as previous times. By the way, the temperature in the area that the Arduino is in is about 82 degrees F.

TMP values do not change by more than 3 degrees F when the LCD is not connected to the screen. I don't understand what could be causing this. Has anyone else had this problem before, or know the cause?

Here is [the layout][1].

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(12,11,5,4,3,2);
    const int sensorPin = A5;
    const float baselineTemp = 20.0;

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

    void loop() {
      int sensorVal = analogRead(sensorPin);
      Serial.print("Sensor value: ");
      Serial.print(sensorVal);
      float voltage = (sensorVal / 1024.0) * 5.0;
      Serial.print(", volts: ");
      Serial.print(voltage);
      Serial.print(", degrees C: ");
      float temperature = (voltage - .5) * 100;
      Serial.print(temperature);
      Serial.print(", degrees F: ");
      float fahrenheit = (temperature * 1.8 + 32);
      Serial.println(fahrenheit);
      delay(1000);
      lcd.begin(16,2);
      lcd.print(fahrenheit);
      lcd.print(" degrees F");
      float averageTemp;
      if(temperature < baselineTemp) {
        lcd.setCursor(0,1);
        lcd.print("Below room temp");
      }
    }

  [1]: http://fritzing.org/projects/tmp-and-lcd

title: Why do my temperature sensor values become inconsistent when additional hardware is added to the board?

Answers: 5

body: Don't take power for LCD from Uno pins. Connect LCD power to separate power source.

body: I don't see +5v -> Aref (and Aref -> bypass capacitor -> Gnd). Necessary, if you are using the power supply voltage as a reference, as you appear to be.

body:
For an analog sensor like the TMP36, the Arduino uses the 5V as reference. If the 5V changes (but the TMP36 voltage stays the same), the Arduino thinks that the temperature has changed. The value returned by analogRead() increases. That is why the temperature seems to raise if the 5V is lowered.

The TMP36 (with resistor) outputs a certain voltage. That is different from 'ratiometric' sensors, they output a voltage relative to the 5V, and changes to the 5V have no effect on the result. A 'ratiometric' sensor is for example a wheatstone bridge, or a LDR with resistor.

With the TMP36, you need a good voltage reference to read the actual voltage. The internal voltage reference can be used. Perhaps an extra voltage divider is needed. Or use a power supply to the power barrel jack and let the onboard voltage regulator create a fixed voltage of 5V which can be used as reference.

When using digital temperature sensors, like the DS18B20, all these problems are gone instantly.

The 5V should never be connected to AREF. It is already internally connected to VCC at default, and when the internal voltage reference is selected, the AREF pin changes the voltage. In that case, an internal shortcut is created when AREF is connected to 5V. There is no need to add 100nF to AREF, since the Arduino Uno has already 100nF to AREF and GND.

A breadboard can have bad contacts. Since the current of the LCD uses the same GND and +5V wires, it can have influence on the TMP36. It is better to use seperate wires as already mentioned by Chris Stratton. To reduce noise you could take a number of analogRead() values and use the average. For an analog temperature sensor it is common practice to average a number of samples.

body: Try powering your circuit using a 9V battery. I have also had this problem and it worked when I used a separate power supply. It seems to be an electrical noise caused by your computer USB. The answer posted by JRobert should be necessary if you want to power from the computer.

body: I had this issue and put a 0.1 µF capacitor across the sensor and got much reduced noise (to within half a degree which is really +- one tick).


body:
I am wanting to POST some data from Arduino to WebService (written in .NET), intending to save some temperature data to MS SQL Server.

My code in arduino is:

    void PostarDados(String dados, String chamador) {
      if (client.connect("mysite.com.br",80)) {
        client.println(chamador);
        client.println(F("Host: mysite.com.br"));
        client.println(F("Content-Type: application/x-www-form-urlencoded"));
        client.print(F("Content-Length: "));
        client.println(dados.length());
        client.println();
        client.println(dados);
      }
      if (client.connected()) client.stop();
    }

When sending to Serial instead of client, I am obtaining the following text:

    POST /webservice.asmx/SetValoresTempUmidade HTTP/1.1
    Host: mysite.com.br
    Content-Type: application/x-www-form-urlencoded
    Content-Length: 39

    Chave=1&Temperatura=23.30&Umidade=42.20

I have enabled HTTP POST in web.config to make HTTP POST possible (I can successfully invoke webservice from browser):

      <location path="Webservice.asmx">
        <system.web>
          <webServices>
            <protocols>
              <add name="HttpGet"/>
              <add name="HttpPost"/>
            </protocols>
          </webServices>
        </system.web>
      </location>
      <system.webServer>
        <httpProtocol>
          <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Headers" value="Content-Type" />
          </customHeaders>
        </httpProtocol>
      </system.webServer>
    </configuration>

I have also set `ScriptMethod` to my webservice functions:

    <WebMethod()> <ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)>
    Public Sub SetValoresTempUmidade(Chave As Integer, ByVal Temperatura As Double, ByVal Umidade As Double)
        Dim ctx As New DataClassesDataContext
        Try
            Dim A As New TBL_DADO
            A.CHAVE_INICIO = Chave
            A.DATA = Now
            A.TEMPERATURA = Temperatura
            A.UMIDADE = Umidade
            ctx.TBL_DADOs.InsertOnSubmit(A)
            ctx.SubmitChanges()
        Catch ex As Exception
        End Try
    End Sub

Finally, I am trying to get some response from server using the following code (not receiving anything):

    while (client.connected()) {
      while (client.available()) {
       buffer[counter++] = client.read();
      }
    }

Explained that, I have two questions:

 1. What am I doing wrong?
 2.  How could I debug this?

title: HTTP Post not working

Answers: 1

body:
Using

    byte server[] = {XX, XX, XX, XX}; //IP
    if (client.connect(server,80)) {

instead of

    if (client.connect("mysite.com.br",80)) {

worked


body: i want to use multiple capacitive touch keypads with arduino uno but number of IO ports are not enough. So I decided to use MSP23S17 port extender. Now i have to find some methods to sense the touch keypad without using its library. Can anyone tell me if there is any way to do the task.

title: how to use capacitive touch keypad without using CapacitiveSensor.h Library

Answers: 1

body: Here's one: Microchip mtch6102, though it might be a little more complex than you're looking for.  All the others I found with a quick search were surface mount or single button controllers.  You might be able to multiplex a single button controller like the Atmel AT42QT1011, but I don't know what the settling or reset times are.  It may take to long to change pads, reset the chip, then wait for settling/calibration time (if any).


body:
I'm using a max7219 like this one [max7219][1]. When I first tested my circuit, I used an 8x8 display and the code worked just fine. Now, after I modified the code and changed the display with the chained one, the text is showing only on the first matrix. I've seen someone that had another problem with the same matrix module, only that in his case the same text was printed on all the matrixes [unsolved problem][2], in the end he didn't find a solution. Below, I'll attach my code. Please help me find the problem.

    //Pin connected to ST_CP of 74HC595
    int latchPin = 6;
    //Pin connected to SH_CP of 74HC595
    int clockPin = 7;
    ////Pin connected to DS of 74HC595
    int dataPin = 5;

    int period = 30;

    byte rotl(byte n, byte b)
    {
      return (n << b) | (n >> (8 - b));
    }

    byte X[] {

    0x80,
    0x80,
    0x80,   //L
    0x80,
    0x80,
    0x80,
    0x80,
    0xFF,

    /*0x10,
    0x00,
    0x10, //I
    0x10,
    0x10,
    0x10,
    0x10,
    0x10,

    0XF0,
    0x90,
    0x80, //C
    0x80,
    0x80,
    0x80,
    0x90,
    0xF0,

    0xF0,
    0x09,
    0x09,
    0x09,
    0x09,
    0x09, //A
    0x09,
    0xF0*/

    };

    void setup() {
      //set pins to output so you can control the shift register
      pinMode(latchPin, OUTPUT);
      pinMode(clockPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
    }

    void loop()
    {
      for (int i = 0; i < 8; i++)
      {
        X[i] = rotl(X[i], 1);
      }
      for(int i = period;i>0;i--)
      {
        displayX();
      }

    }

    void DisplayMatrix(byte numCol, byte numLine)
    {
      byte numberToDisplay1 = numCol;
      byte numberToDisplay2 = numLine;

      digitalWrite(latchPin, LOW);
      shiftOut(dataPin, clockPin, MSBFIRST, numberToDisplay1);
      shiftOut(dataPin, clockPin, MSBFIRST, numberToDisplay2);
      digitalWrite(latchPin, HIGH);
      delay(1);

    }

    void displayX()
    {
       DisplayMatrix(X[0],1);
       DisplayMatrix(X[1],2);
       DisplayMatrix(X[2],4);
       DisplayMatrix(X[3],8);
       DisplayMatrix(X[4],16);
       DisplayMatrix(X[5],32);
       DisplayMatrix(X[6],64);
       DisplayMatrix(X[7],128);
    }

  [1]: http://www.aliexpress.com/item/MAX7219-Dot-Matrix-Module-For-Arduino-Microcontroller-4-In-One-Display-with-5P-Line/32637207300.html?spm=2114.30010308.3.1.1iTpoC&ws_ab_test=searchweb201556_10,searchweb201602_5_10057_10056_10055_10049_10017_10059_10058_10060_10061_10062_412_10063,searchweb201603_7&btsid=7c7446b0-8328-4abd-b0d9-6d20abc0b98a
  [2]: http://forum.arduino.cc/index.php?topic=402935.0

title: max7219 chained display showing text only on the first display

Answers: 1

body:
Communicating with more than one MAX7219 chip when cascaded involves sending data to all the chips at once. You have to treat the cascaded sequence of chips as a single entity - an entire display in its own right.

With one chip you send an 8-bit register value followed by an 8-bit data value. To use two chips you have to send twice that - an 8-bit register and 8-bit data for the second chip, followed by an 8-bit register and 8-bit data for the first chip.

The chips have a "NO-OP" register (0x00) which can be used to ensure that nothing is done on that chip if you don't want to change anything.

So setting line 3 to 0x55 on the first display, and line 5 to 0xAA on the second display you would send the sequence `\ 0x05,0xAA,0x03,0x55 /` as a single transaction (lower CS `\` before, raise it `/` afterwards).

If you only wanted to set line 2 on the second display to 0x69 you would send the sequence: `\ 0x02,0x69,0x00,0x00 /`

For three chips you need to send three blocks of 8+8 values. For four chips, 4 blocks of 8+8. Etc.

Note that it is important to send enough data for *all* the chips - you can't shortcut and only send data for the first display if that is all you want to talk to, since whatever is currently in the first display's shift register will get sent out to successive chips, and you will get the display duplication as seen in the other question.


body:
I am having an Arduino Uno and a C2042A LCD with I2C shield on it. Because the VirtualWire library does not work for me. I tried only the wire library but it's still not working:

My code:

    #include <Wire.h>

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

    void loop() {
      Wire.write(4);
    }

I just read on [this website][1] which commands you have to use but it doesn't do anything. What is my fault, how to solve it?

  [1]: http://www.robot-electronics.co.uk/htm/Lcd03tech.htm

title: Arduino Wire.h library: how to communicate with an LCD?

Answers: 3

body: The documentation under the link you posted says: "The I2C display is located on the I2C bus at an address of 0XC6.", not the address you have used in your code.

body:
SOLVED!

I forgot to write `beginTransmission()`. Here's my code:

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

    #include <Wire.h>

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

    void loop() {
      Wire.beginTransmission(0x63);
      Wire.write(byte(0x00));
      Wire.write("Temperatur:");
      Wire.endTransmission();
    }

body:
You can't begin writing unless you first initialize it like with Serial.begin

In this case you don't show Wire.beginTransmission.

Perhaps it is in the code you didn't show us, but it is required.


body:
Can uncompressed MP3 audio data be sent from Arduino board, by SPI, to Adafruit Music Maker shield instead of from the SD card on the Music Maker?

Instead of using SD card on Music Maker board, I want to send the compressed MP3 data from a Particle Photon board on the Particle shield shield, by SPI, to the VS1053B codec chip on Music Maker board, and then to amplifier for speakers.

Particle Shield Shield is attached to Particle Photon board, which has STM32F205RGY6 120Mhz ARM Cortex M3.

Particle Photon board uses its WiFi to receive uncompressed MP3.

title: Can MP3 be sent to SPI of Adafruit Music Maker Arduino shield instead of from its SD card?

Answers: 1

body:
As far as I can see the SD card on the shield isn't read by the VS1053 directly, but by the arduino, which sends it to the VS1053.

So as far as I can see, you should be able to do what you want.


body:
I want Arduino to receive MP3 by WiFi (from iPhone), and then send to Music Maker codec and amplifier.

I want to use Arduino IDE and library software from Adafruit for the Music Maker, so I need an Arduino board 100% compatible with the library for Music Maker.

title: Is Adafruit Arduino Feather M0 WiFi compatible with Adafruit Music Maker shield?

Answers: 1

body: No, it is not.  Adafruit Feather boards are only compatible with Feather 'wings' and not Arduino shields.


body:
I have code but I don't know how to send SMS from my Mobile
I mean what the message I can send to switch the Led?
To switch On or Off.
I use SIm900
and use this code

    #include <SoftwareSerial.h>

     char inchar; // Will hold the incoming character from the GSM shield
     SoftwareSerial SIM900(7, 8);

     int led = 10;

     void setup()
     {
       Serial.begin(19200);
       // set up the digital pins to control
       pinMode(led, OUTPUT);
       digitalWrite(led, LOW);

       // wake up the GSM shield
       SIM900.begin(19200);
       delay(20000); // give time to log on to network.
       SIM900.print("AT+CMGF=1\r"); // set SMS mode to text
       delay(100);
       SIM900.print("AT+CNMI=2,2,0,0,0\r");
       // blurt out contents of new SMS upon receipt to the GSM shield's serial out
       delay(100);
       Serial.println("Ready...");
     }

     void loop()
     {
       //If a character comes in from the cellular module...
       if(SIM900.available() >0)
       {
         inchar=SIM900.read();
         if (inchar=='#')
         {
           delay(10);

           inchar=SIM900.read();
           if (inchar=='a')
           {
             delay(10);
             inchar=SIM900.read();
             if (inchar=='0')
             {
               digitalWrite(led, LOW);
             }
             else if (inchar=='1')
             {
               digitalWrite(led, HIGH);
             }
             delay(10);
             // SIM900.println("AT+CMGD=1,4"); // delete all SMS
           }
         }
       }
     }

title: What SMS can send to switch LED?

Answers: 1

body: The code appears to be looking for an SMS that says `#a0` or `#a1`. The logic doesn't look very robust, though. It reads a character, then waits 10ms and tries to read another. What does `SIM900.read()` do if there is no next character? Will it return something? Or wait until there is another? If it waits, the code can get out of sync with incoming, badly-formed commands.


body:
I am trying to get 2-Arduinos passing data. The Master will request the data and the Slave send it. But, the length of the string the Slave will send is unknown each cycle.

I found some things here on writing strings with I2C but it seems it is limited to 32 bytes no matter what the Master requests. How can I get the full string sent each time?

Master makes request for string that could be about 180 bytes max - ever.

    Wire.requestFrom(8,200);  // I2C-ID = 8, Length = 200
    while (Wire.available())
    {char c = Wire.read();
    cmdInStr.concat(c);
    }

Slave sends

    int len = cmdOutStr.length()+1;
    char ascii_num[len];
    for (int i=0; i<len; ++i)
    { Wire.write(ascii_num[i]);
    }

title: Arduino I2C long string

Answers: 2

body:
There is no maximum length for sending/receiving in I2C. It is the Wire library `BUFFER_LENGTH 32` macro, causing this limitation.

You can either copy some code from Wire library and implement your own `requestFrom` function which will store data directly to your `cmdInStr` string buffer or you can change Wire.h to have bigger `BUFFER_LENGTH`.

Or another way is to extend Wire.h like this:

    #ifndef BUFFER_LENGTH
    #define BUFFER_LENGTH 32
    #endif

and in your sketch:

    #define BUFFER_LENGTH 180
    #include <Wire.h>

All depends on your preferences, but implementing own requestFrom and storing it directly into your `cmdInStr` buffer will be little bit more efficient than copying it into Wire buffer and then into your own buffer again.

And do you really need all these data in one string, isn't it possible to proceed it on the fly?

body:
You can only send and receive fixed length amounts of data with I2C. The master has to know how much to request from the slave - or the slave to accept from the master.

There's a number of ways around it though:

1. Splitting / joining.

The trick here is to split the data into packets and re-assemble it at the remote end.

For instance, you split your string into 16-byte chunks. Then you send each chunk separately. Prefixed to each chunk (so the chunk becomes 17 bytes) is a byte telling the remote end how many characters are in this chunk.  Any spare space in a chunk is padded with something (0x00 for instance) so it remains 17 bytes long in total.

2. two-stage transaction

In this method you first make a transaction which tells the remote end how many characters to receive in the next transaction, or retrieves the number of characters that need to be received from the remote end. The second transaction then receives (or sends) that specific number of characters.

If your strings are longer than the internal I2C buffer (32 bytes) then method 1 is probably the best way.

You can also combine the two methods so both ends know how much to expect to be transferred in total as well as how much of each packet is valid data. The sum of the second should match the first.


body:
When I try to upload any sketch to my arduino uno r3, the code compiles, the board resets and the RX light blinks 3 or 4 times.I have nothing from the TX light.

The uploading progress bar in the IDE stucks at it's end for a period and then gives me "avrdude: stk500_recv(): programmer is not responding" 10 times.

I've done the loopback test and it works well so, what should i do ?

thanks for help.

title: "avrdude: stk500_recv(): programmer is not responding" when uploading sketch

Answers: 1

body:
> yes, it has worked before. ... uncorrect bootloader or something,,...

Does the last program you successfully uploaded write anything to the serial port? If you just run the Arduino (no upload attempt) with the Arduino IDE's serial terminal open, can you see that output? It's pretty hard to damage the boot-loader without actually writing a new, bad one to the chip.

If the current program seems to running but not writing to serial when it should, a likely cause of upload failure is the code in 16U2 processor (or the chip itself) that handles the USB to serial conversion; it's the square 32-pin chip between the 16 MHz crystal and USB connector. Its firmware can be re-loaded - search here for how to do that. If the chip itself is damaged it is probably not worth attempting a repair.

Update: Is the +5v pin on the power header (left edge of the board, if the USB connector is pointing up) reading 5v? You'd expect the output pins to read 0v, 5v, or be noisy if they are floating. A steady 1v sounds strange. At this point it would be worth trying this board on another computer, and another board on your computer, and see which one fails.


body:
I made a big search about how to Format Numbers with the Arduino. I want to **format unsigned Longs into a String** in this format: "*23,854,972*".

The most of the snippets I found work **only with the standard C / C++ Libraries**. They **dont work on the Arduino** until I should put some STL libraries on the Arduino, which I want to prevent. It would be too bit of a overhead to import these only for this task. Also these Libraries will of course use some additional Flash and SRAM.

For my Application it is very important that the solution uses the minimum Flash, SRAM and is **fast**.

Even if a solution does not use STL or works only with the native Arduino Libraries, I would need help to decide which one is **more effective** in the sense of speed.

Incoming Number: 23854972
Arduino Program Output: 23,854,972

title: The most effective way to format numbers on Arduino

Answers: 2

body:
> The most effective way to format numbers on Arduino

If "effective way" is minimum effort you could hack the avr-libc source code for [ltoa][1] and do something like below:

    char *ultos_recursive(unsigned long val, char *s, unsigned radix, int pos)
    {
      int c;

      if (val >= radix)
        s = ultos_recursive(val / radix, s, radix, pos+1);
      c = val % radix;
      c += (c < 10 ? '0' : 'a' - 10);
      *s++ = c;
      if (pos % 3 == 0) *s++ = ',';
      return s;
    }

    char *ltos(long val, char *s, int radix)
    {
      if (radix < 2 || radix > 36) {
        s[0] = 0;
      } else {
        char *p = s;
        if (radix == 10 && val < 0) {
          val = -val;
          *p++ = '-';
        }
        p = ultos_recursive(val, p, radix, 0) - 1;
        *p = 0;
      }
      return s;
    }

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

      char buf[32];
      Serial.println(ltos(12345678, buf, 10));
      Serial.println(ltos(-12345678, buf, 10));
    }

    void loop()
    {
    }

Gives the output:

    12,345,678
    -12,345,678

Cheers!

PS: Please see the table driven, non-recursive, number conversion in [Cosa][2] ([source][3] and [benchmark][4]) for a lean and faster implementation.

  [1]: https://github.com/vancegroup-mirrors/avr-libc/blob/master/avr-libc/tests/simulate/stdlib/ltoa-2.c
  [2]: https://github.com/mikaelpatel/Cosa
  [3]: https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/IOStream_dtoa.cpp
  [4]: https://github.com/mikaelpatel/Cosa/tree/master/examples/Benchmarks/CosaBenchmarkUART

body:
Here is my try at it: The usual way to write a number in decimal is to
get the digits from right to left with a loop that looks something like

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

    digit = '0' + val % 10;
    val /= 10;

The following function does exactly this, with the addition of adding
commas at the correct positions:

    /*
     * Format an unsigned long (32 bits) into a string in the format
     * "23,854,972".
     *
     * The provided buffer must be at least 14 bytes long. The number will
     * be right-adjusted in the buffer. Returns a pointer to the first
     * digit.
     */
    char *ultoa(unsigned long val, char *s)
    {
        char *p = s + 13;
        *p = '\0';
        do {
            if ((p - s) % 4 == 2)
                *--p = ',';
            *--p = '0' + val % 10;
            val /= 10;
        } while (val);
        return p;
    }

Note that the string is right adjusted in the buffer, and the unused
characters are not touched. This means you can get a right adjusted
string by:

* pre-filling the string with spaces (for padding)
* calling the function above
* using the original buffer as the right adjusted string

Otherwise you would use the returned pointer to have a string with no
padding.

Here is a simple test program:

    unsigned long vals[] = {0, 1, 2, 9, 10, 999, 1000, 0xffffffff};
    const int COUNT = sizeof vals / sizeof vals[0];

    void setup()
    {
        Serial.begin(9600);
        char buffer[14];
        for (int i = 0; i < COUNT; i++) {
            unsigned long val = vals[i];
            Serial.print(val);
            Serial.write('\t');
            Serial.println(ultoa(val, buffer));
        }
    }

    void loop() {}


body:
I need to split up code which I've already developed for one micro into two different Arduinos connected by serial. The "remote" micro is directly connected to a 20x4 character LCD and the main micro will be sending it a command set to print, move cursor, etc.

My plan was to make functions that used existing code such as
lcd.print("This or that");
to replace the lcd library on the main micro and send command bytes and data bytes up to the remote micro. Seems pretty straightforward.

Then I discovered that apparently lcd.print cannot be a function name. Fine, so I changed it to lcd_print(). So far, so good. But in the existing library, lcd.print accepts strings, bytes, just about anything any length. For example:
lcd_print("any string of any length");
lcd_print(a_2d_array [x] [y]);
lcd_print(this_byte);
lcd_print(this_integer);

Now it's getting over my head. I know I can painstakingly turn a single function into many different functions, but wouldn't it be nice to replicate the functionality of the Arduino LCD library with a single command:

lcd.print();

Then all I have to do is create the function and keep the existing code and send the bytes up to the slave micro. Wouldn't that be nice! I appreciate any thoughts. Thanks.

title: Sending LCD commands to a slave micro

Answers: 1

body:
Just inherit `Print` class and implement `virtual size_t write(uint8_t);` and you can use all kinds of print/println that Print implements. See [Print Class @arduino.cc][1].

It implements these methods for you:

    size_t print(const __FlashStringHelper *);
    size_t print(const String &);
    size_t print(const char[]);
    size_t print(char);
    size_t print(unsigned char, int = DEC);
    size_t print(int, int = DEC);
    size_t print(unsigned int, int = DEC);
    size_t print(long, int = DEC);
    size_t print(unsigned long, int = DEC);
    size_t print(double, int = 2);
    size_t print(const Printable&);

    size_t println(const __FlashStringHelper *);
    size_t println(const String &s);
    size_t println(const char[]);
    size_t println(char);
    size_t println(unsigned char, int = DEC);
    size_t println(int, int = DEC);
    size_t println(unsigned int, int = DEC);
    size_t println(long, int = DEC);
    size_t println(unsigned long, int = DEC);
    size_t println(double, int = 2);
    size_t println(const Printable&);
    size_t println(void);

However you have to implement 2D array print if you really need this, I don't see why do you need it but whatever (you can print each line separately). It just saves you time with implementing everything else.

And for std::ostream like approach I like this (works with anything inherited from Print class):

    template <class T> inline Print & operator<<(Print & p, const T & val) {
      p.print(val);
      return p;
    }

    // ...

    void loop() {
      float variableA = 221.23;
      String variableB = "Some string";
      Serial << F("flash string to save some ram: ") << variableA << F(" / ") << variableB << "\n";
    }

Then you can implement some commands interface.

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


body:
Schematic:

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

I am making some light fixtures controlled by an Arduino UNO. Each fixture will host two approx. 1 meter long analog RGB LED strips with a current draw at full power of ~1.2 A per meter. I have a 12 V power supply that I will wire directly to the strips, with the RGB channels wired to the Ardiino PWM pins via NPN MOSFET (note in the schematic I've only shown one color channel for simplicity, but there would of course be three transistors hooked up to three PWM pins). The Arduino itself will be powered by USB.

My main difficulty in wiring the system is that for so much current I need fairly thick wire. The pads on the LED strips are delicate and I have several times damaged them by mechanical stress from the wire while soldering. The thick wire also crowds the narrow space between the pads creating a risk of a short. Therefore my first question is (bear with me, I'm pretty new to this):

1) How should I wire the LED strips?

My thought is to wire up the strips in parallel with thinner, more flexible wires. This brings up two sub-questions:

1a) How should I join the thinner wires to the thick wire coming from the power supply?

1b) At the junction between the wires leaving the lights and running to the transistor, does the wire need to become thick again? (I think the answer is yes – the current should be the same as coming out of the power supply.)

I also am unsure about the ground.

2) Does the wire coming from transistor to ground need to be joined to the ground pin on the Arduino or can it run directly to the ground terminal of the power supply?

Sub-question:
2a) Does the wire coming from transistor to ground need to be thick?

I don't really understand how transistors work (basically my understanding is that the Arduino uses a small amount of current over the PWM pins to somehow control how much current is allowed to flow through the rest of the circuit.

I've drawn a schematic showing how I think maybe this system needs to be wired up. Do I need to make changes?

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

title: Wiring LED strips in parallel & ground

Answers: 2

body:
I think you are overestimating the size of wire required to attach to the LED strips, I have connected a lot of single color LED strip (in excess of 1mtr) with the wire that was already attach and it was reasonably light gauge.
Look at this [Example][1] on Ebay and you can see what i mean.

I am note an Electrical Engineer so i don't know the method to calculate the minimum wire gauge, but if in doubt contact the manufacturers and ask them or search on the web.

As for the Transistor mounting/wiring you would mount that on a small circuit board with terminal block fitted for ease. Any power/connecting wire should not be less that used to the LED strip.

Also you will need a current limiting resistor attached to the Base pin on your transistors. You will have to work out the value of that based on the spec sheet.

There is a bit of learning required first, once you have researched the above you will have you exact answers.

  [1]: http://www.ebay.com.au/itm/NEW-2835SMD-300-LED-Flexible-Strip-Light-Ribbon-Lamp-Lighting-COOL-White-DC12V-/302050174238?hash=item465397e51e:g:P7sAAOSwRQlXeyVB

body:
It's all a question of *losses*.

Wire is basically a resistor. The thinner and longer the wire the higher the resistance. Current flowing through a resistor causes a voltage drop across the resistor.

Long thin wires with large amounts of current through them will basically mean you get less than your 12V at the LED strips. The question has to be: how much less a voltage is tolerable?

Each strip takes 1.2A. Take for example 24AWG wire. That has a resistance of 0.0842Ω per meter. With 1.2A flowing through a meter of that you get 0.10104V dropped across the wire. That turns your 12V into 11.9V.

Conversely, a meter of 14AWG wire has a resistance of 0.00829Ω - so you would lose 0.009948V over that length.

Now you want two strips - which is double the current, and thus double the voltage drop. On 14AWG you would lose about 0.02V over a meter. Not really enough to worry about. But you can't connect 14AWG to the LED strips. You can connect thinner wire (say 24AWG as above) to them. But that looses too much voltage. Well - *over a meter it loses too much voltage*. But what about over, say, 10cm? That's a 10th the length of before, and so a 10th the voltage loss: 0.01V.

So what is to stop you having a short length of thin wire connected to the LED strips, which then connects to a longer length of thick wire? Answer: absolutely nothing.

And how do you join them together? Well, I find the best way is with solder. Insert the thin wire (stripped) into the end of the fat wire (stripped) and twist them together (axially) then flood the joint with solder.

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

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


body:
I am working with two servomotors and both are having the same problem: right after i connect them to the arduino and upload the code, they do as the code says for a really small amount of time (0.1s maybe), and then they simply stop. If i keep connecting and reconnecting it again the servo answer to the code for a really small amount of time and then stop, as I said before.

    #include <Servo.h>

    #define SERVO 6 // Porta Digital 6 PWM

    Servo s; // Variável Servo
    int pos; // Posição Servo

    void setup ()
    {
      s.attach(SERVO);
      Serial.begin(9600);
      s.write(0); // Inicia motor posição zero
    }

    void loop()
    {
      for(pos = 0; pos < 90; pos++)
      {
        s.write(pos);
      delay(15);
      }
    delay(1000);
      for(pos = 90; pos >= 0; pos--)
      {
        s.write(pos);
        delay(15);
      }
    }

I am using the code above, and it looks totally fine. Does anyone know what might be causing this problem?

title: Servomotor losing its connection right after being connected to Arduino

Answers: 1

body:
Your code is correct. Check the following:

 - Arduino works from 5V, but most servos need 6V.
 - Even if your servo works from 5V, don't ever connect your servo power directly to Arduino pins. These pins are not able to provide adequate power for servo.
 - Check that grounds of both power supply for Arduino and power supply for servo are connected together.


body:
I want to use loop() iterations counter to execute some tasks periodically or tasks like debouncing. My other sketch is running every loop() at least 20 ms, and if i am using 5 ms time to wait to
debounce a button, it will still be at least 20 ms waiting, also cpu will have to compare two not zero values, which is a bit slower.
I think it is more difficult for cpu than just incrementing and decrementing one variable and comparing it to 0. So i came up with pattern like that:

    boolean onOff=1; // arduino led state. My task here is LED blinking.
    byte loopCounter=2; // number of iterations made by loop(). Set as little variable as possible to save ram and cpu time.
    //Code will be executed every "loopCounter" iteration of loop().
    void setup() {
      pinMode(13, OUTPUT);
    }

    void loop() {
          if (--loopCounter == 0) { //comparing with 0 should be a bit faster and easier for Arduino to process. Correct me if i am wrong.
            loopCounter=2; // That digit sets how often your code will be executed. Every 2(3,4... set your own value) iterations of loop().
            digitalWrite(13, onOff= !onOff); // the task itself.
            }
    }
It may be more convenient in some ways than millis() and micros() patterns. Also i do want want to use hardware timers for timing.
It may be convenient in cases, when you don't care when exactly task will be done, you just want it to be done ASAP (as soon as possible), but
not during that particular iteration of loop(). Basicly you can use it as a timer if you know how it takes one iteration to be done.
So, if your sketch runs 1 iteration of loop() for 1 ms, and you need some action to be done every 1 sec, 1ms*1000 == 1 sec. So you
need it to be done every 1000 iterations.

 1. So, is that really can save some ram and cpu time?
 2. Is comparing with zero is faster for arduino than comparing with not
    zero?
 3. Are millis() and micros() timing patterns using more operations
    (setting value to variable, computing the difference between 2
    values and than comparing it to a period you have set) instead of
    decrementing and comparing to zero with my pattern?
 4. Any side-effects of using my pattern? I can only think of very
    unaccurate timing and delays more than you think if your sketch done
    smth more than usual, because of button push for example or some
    sensor changed value.

 Thank you!

title: Faster and lighter approximate timing code without using timer

Answers: 1

body:
Personally I wouldn't be putting too much effort into optimizing away your timers. `millis()` is pretty fast - the work needed to calculate the result is done in the background *anyway* (by interrupts). I tried some test code:

<!-- 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 ();

      start = micros ();
      volatile unsigned long now;
      for (byte i = 0; i < 100; i++)
        now = millis ();
      finish = micros ();

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

      }  // end of setup

    void loop ()
      {

      }  // end of loop

<!-- language: lang-none -->

Results:

    Time taken to do digitalWrites: 520
    Time taken to do millis: 188

You can see that the `digitalWrite()` (which you weren't worried about) takes 5.2 µs, whereas calling `millis()` (which you *were* worried about) takes 1.88 µs.

---

> Are millis() and micros() timing patterns using more operations (setting value to variable, computing the difference between 2 values and than comparing it to a period you have set) instead of decrementing and comparing to zero with my pattern?

Yes, just adding one to a variable and then comparing will be faster. Whether it is worth the effort is debatable.


body:
we have an error after compiling the code in arduinouno that is displayed as
error: 'power_usi_disable' was not declared in this scope   in Board: "Arduino/Genuino Uno".how to rectify this error. please reply us fast

title: No power_usi_disable() on Arduino Uno

Answers: 1

body:
The Arduino Uno does not have a USI peripheral. Thus, you cannot disable
the power of the (non-existent) USI, and there is no
`power_usi_disable()` function.

Solution: remove the call to `power_usi_disable()` from your code.

**Update**: To answer your _new_ question in the comment, `WDTCR` is the
Watchdog Timer Control Register on some AVR chips. On the Uno it is
called `WDTCSR`, because it is a control and status register.

Looks to me like you have downloaded from somewhere a program you do not
understand. That program was written for an ATtiny chip and you are
trying to compile it as-is for an Arduino Uno, which is based on an
(incompatible) ATmega328P. That's not the way to do it: you have to
understand the program and rewrite all the ATtiny specific stuff to fit
the Uno.


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

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

Answers: 2

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

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.


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

title: How to change Arduino Nano MODEL_ID

Answers: 2

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


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

title: How to use Serial Monitor without Arduino board?

Answers: 1

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


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

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

Answers: 1

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


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

title: Why does the current drop through a multiplexer?

Answers: 1

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


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

title: Absolute noob looking for troubleshooting help

Answers: 2

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.


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

title: WizNet W5100 not connecting to modern switches and routers

Answers: 3

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)


body:
Help please

I am trying to connect an Arduino Due via a SPI bus to a MAXIM31855 thermocouple sensing chip. I am using Arduino IDE version 1.6.11.
The problem I am having is that the code will only read the SPI bus once, it will not loop, regardless of how many times I call the function to read the SPI bus.

I have connected the clock and the MISO to the pin header just below the SAM processor chip its labeled SPI and I have connected the CS to pin 4.

Each time I press the reset button on the Due, the SPI will read once. I have confirmed this by using a Salae logic analyser. The Due doesn't lock up as other functions continue normally, it simply will not repeat the SPI read.

The 4 bytes that are returned from the Max are consistent with the specification for the chip as are the timing of the clk (4kHz) and the MISO logic levels (there is no MOSI in this MAX chip).

If anyone has a clue as to why this will not loop I would appreciate their input.

Cheers

    #include <SPI.h>
    //Give convenient names to the control pins

    #define slaveAPin 10
    // set up the speed, data order and data mode
    SPISettings settingsA(4000000, MSBFIRST, SPI_MODE1);

    void setup() {

      Serial.begin(9600);
      pinMode(slaveAPin,OUTPUT);
      SPI.begin(slaveAPin);

    }

    uint8_t  val1, val2, val3, val4;

    void loop() {
    // read four bytes from device A
     Serial.println(ReadTemp());
     delay(1000);

     }

    uint8_t ReadTemp(void)
    {
      SPI.beginTransaction(settingsA);
      digitalWrite (slaveAPin, LOW);
      // reading only, so data sent does not matter
      val1 = SPI.transfer(slaveAPin,0x00,SPI_CONTINUE);
      val2 = SPI.transfer(slaveAPin,0x00,SPI_CONTINUE);
      val3 = SPI.transfer(slaveAPin,0x00,SPI_CONTINUE);
      val4 = SPI.transfer(slaveAPin,0x00,SPI_LAST);
      digitalWrite (slaveAPin, HIGH);
      SPI.endTransaction();

      return val2;

    }

title: Arduino Due SPI will not loop

Answers: 0


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

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

Answers: 2

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.


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

title: Arduino MPU6050 Control 2 Servo

Answers: 1

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.


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

title: externally powering the Arduino questions

Answers: 4

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.