message:
data integrity when interrupts are too fast

I have an encoder that fires ~54000 interruptions per second.
This is way too fast for my arduino uno.
But I'm trying to see what I can get from it anyway. For science.

    unsigned long tickACount = 0;
    unsigned long tickBCount = 0;

    void myInterrupt(){
      tickACount++;
      tickBCount++;
    }

Then in my main loop, every second I print `tickACount` and `tickBCount`.
I can see my arduino is able to handle only about 2050 interrupts per second. No surprise here.

What surprises me, is that `tickACount` and `tickBCount` have different values! `tickBCount` is consistently higher that `tickACount`.

Ok now I switch them to volatile. And according to the documentation, volatile only makes sense for 8bit values. The counts will eventually overflow but it doesn't really matter. I just want to see if those two variables are still different.

    volatile uint8 tickACount = 0;
    volatile uint8 tickBCount = 0;

    void myInterrupt(){
      tickACount++;
      tickBCount++;
    }

The result is that the two values are still different.
Also, wrapping them into some `ATOMIC` macro does not help.

From what I read, interrupts cannot be interrupted.
And beside, if my interrupt was aborted midway, then `tickACount` would be higher than `tickBCount`, not the other way around.

Therefore, what can be the explanation for those two variables to be different?

Thank you for any idea!

body:
> 54000 interruptions per second [...] is way too fast for my arduino
> uno

Your test is probably flawed. My Uno does handle that interrupt rate
with no issues. See my test code below.

> my arduino is able to handle only about 2050 interrupts per second

You are probably doing something wrong, like blocking interrupts for too
long, or using a library that does so.

> What surprises me, is that `tickACount` and `tickBCount` have
> different values!

As previously stated in comments, this is not the case. Instead, the
counters have been incremented while you were printing them.

> And according to the documentation, volatile only makes sense for 8bit
> values.

Either the documentation is grossly wrong, or (most likely) you have
misread it.

> From what I read, interrupts cannot be interrupted.

This is indeed the default behavior. You could change it, by issuing
`interrupts()` within the interrupt handler, or by declaring an ISR as

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

    ISR(XXX_vect, ISR_NOBLOCK)
    {
        ...
    }

but that is seldom done.

Below is my test code. I used Timer 2 to generate a square wave on
pin 3, which is both a PWM pin (OC2B) and an interrupt pin (INT1).
The PWM frequency is about 54.054 kHz.

    const uint32_t PRINT_PERIOD = 1e6;  // print counts every second

    struct TickCounts {
        uint32_t tickA;
        uint32_t tickB;
    };

    volatile TickCounts rawCounts;

    void myInterrupt() {
        rawCounts.tickA++;
        rawCounts.tickB++;
    }

    // Atomically read both counts.
    static TickCounts getCounts() {
        TickCounts counts;
        noInterrupts();
        counts.tickA = rawCounts.tickA;
        counts.tickB = rawCounts.tickB;
        interrupts();
        return counts;
    }

    void setup() {
        // PWM at 54 kHz on OC2B = PD3 = INT1
        DDRD  |= _BV(PD3);    // pin PD3 as output
        OCR2A  = 37 - 1;      // period = 37 * 0.5 us = 18.5 us
        OCR2B  = 37/2 - 1;    // duty cycle ~ 50%
        TCCR2A = _BV(COM2B1)  // non-inverting PWM on OC2B
               | _BV(WGM20)   // mode 7: fast PWM, TOP = OCR2A
               | _BV(WGM21);  // ditto
        TCCR2B = _BV(WGM22)   // ditto
               | _BV(CS21);   // clock at F_CPU/8 = 2 MHz

        Serial.begin(9600);
        attachInterrupt(1, myInterrupt, RISING);
    }

    void loop() {
        static uint32_t last_time_printed;
        if (micros() - last_time_printed >= PRINT_PERIOD) {
            last_time_printed += PRINT_PERIOD;
            TickCounts counts = getCounts();
            Serial.print(counts.tickA);
            Serial.print(" ");
            Serial.println(counts.tickB);
        }
    }

And here is the output:

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

    54053 54053
    108107 108107
    162161 162161
    216215 216215
    270269 270269
    324324 324324
    378377 378377
    432431 432431
    486485 486485
    540539 540539
    ...


sender: user

message:
Ethernet nodemcu

I have a question that might be a #noob question but I am wondering if there is a board similar to the nodemcu in size that runs arduino code but instead can use ethernet to connect to the network instead of the wifi? I have already seen the connections to use one of the pins and such to connect that way but I am looking to see if there is a board that has the rj45 connection on it already.

sender: assistant

body:
I don't think you'll find a single off-the-shelf product.  The closest I have managed to come to it is a [Teensy 3.2](https://www.pjrc.com/store/teensy32.html) plus a [WIZ820io & Micro SD Card Adaptor](https://www.pjrc.com/store/wiz820_sd_adaptor.html) and a [WIZ850io module](http://www.wiznet.co.kr/product-item/wiz850io/), all stacked together.  Footprint-wise it's around the same as (or smaller than) many ESP8266-based boards - however it's considerably chunkier when all combined:

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

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


message:
PMS5003 Serial Output Data to SD Issues

I'm trying to save the output of an air quality sensor to a SD card, but I'm having a few issues.

The sensor I'm using is a Plantower PMS5003 which puts out its data via serial. I've heavily tweaked the example sketch from Adafruit ([here][1]) as I'd like to use the Low Power library to sleep the unit, take a sample and note the time, write it to SD, then return to sleep.

I am getting the timestamp written no issue, but the data is coming out repeated as below:

    22:13:10 - 34,55,61
    22:13:18 - 34,55,61
    22:13:27 - 34,55,61
    22:13:36 - 34,55,61
    22:13:44 - 34,55,61
    22:13:53 - 34,55,61
    22:14:1 - 34,55,61
    22:14:10 - 34,55,61
    22:14:18 - 34,55,61
    22:14:27 - 34,55,61
    22:14:35 - 34,55,61
    22:14:44 - 34,55,61

The 8s timer appears to be working fine, but the repetition of data has me confused. I've tried adding delays and the like in case it was a lack of data but when I run that example sketch it comes screaming in over serial.

I also ditched using the software serial as I couldn't get it to stop messing with the low power library, it wouldn't ever sleep.

That and any general advice on the sketch is appreciated, it seems like its not the best way to accomplish this.

    #include "LowPower.h"
    #include <SdFat.h>
    #include "RTClib.h"
    #include <Wire.h>

    SdFat SD;
    RTC_DS3231 rtc;

    File test;
    String tString = "";
    String sString = "";

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

      pinMode(10, OUTPUT);

      if (!rtc.begin()) while (1);

      if (!SD.begin(10)) while (1);
    }

    struct pms5003data {
      uint16_t framelen;
      uint16_t pm10_standard, pm25_standard, pm100_standard;
      uint16_t pm10_env, pm25_env, pm100_env;
      uint16_t particles_03um, particles_05um, particles_10um, particles_25um, particles_50um, particles_100um;
      uint16_t unused;
      uint16_t checksum;
    };

    struct pms5003data data;

    void loop() {
      //LowPower.idle(SLEEP_8S, ADC_OFF, TIMER2_OFF, TIMER1_OFF, TIMER0_OFF, SPI_OFF, USART0_OFF, TWI_OFF);
      LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);

      DateTime now = rtc.now();
      test = SD.open("test.txt", FILE_WRITE);

      tString = String(now.hour()) + ":" + String(now.minute()) + ":" + String(now.second()) + " - ";

      readPMSdata(&Serial);
      sString = String(data.pm10_standard) + "," + String(data.pm25_standard) + "," + String(data.pm100_standard);

    if (test) {
      test.print(tString);
      test.println(sString);
      test.close();

      delay(250);
    }
    }

    boolean readPMSdata(Stream *s) {
      if (! s->available()) {
        return false;
      }

      // Read a byte at a time until we get to the special '0x42' start-byte
      if (s->peek() != 0x42) {
        s->read();
        return false;
      }

      // Now read all 32 bytes
      if (s->available() < 32) {
        return false;
      }

      uint8_t buffer[32];
      uint16_t sum = 0;
      s->readBytes(buffer, 32);

      // get checksum ready
      for (uint8_t i = 0; i < 30; i++) {
        sum += buffer[i];
      }

      //debugging
      for (uint8_t i = 2; i < 32; i++) {
        Serial.print("0x"); Serial.print(buffer[i], HEX); Serial.print(", ");
      }
      Serial.println();

      // The data comes in endian'd, this solves it so it works on all platforms
      uint16_t buffer_u16[15];
      for (uint8_t i = 0; i < 15; i++) {
        buffer_u16[i] = buffer[2 + i * 2 + 1];
        buffer_u16[i] += (buffer[2 + i * 2] << 8);
      }

      // put it into a nice struct :)
      memcpy((void *)&data, (void *)buffer_u16, 30);

      if (sum != data.checksum) {
        Serial.println("Checksum failure");
        return false;
      }
      // success!
      return true;
    }

  [1]: https://learn.adafruit.com/pm25-air-quality-sensor/arduino-code

body:
There is a mismatch in the code.
The Arduino `loop` function assumes that `readPMSdata` needs to be called just once for valid data but the function `readPMSdata` itself assumes that it will be called over and over again until a enough bytes are received and are valid.

The solution is to let the Arduino `loop` call `readPMSdata` over and over again, until it has valid data. It returns `true` when it has valid data, so that can be used in a `if` statement.
This might cause troubles with the rest of the code in the `loop`. The `delay(250);` may no longer be used and I don't know the best place to go into sleep mode. Therefor I removed the powerdown.

    void loop() {
      if( readPMSdata(&Serial))        // call it many times to collect data
      {
        // there is valid data from the sensor
        DateTime now = rtc.now();
        test = SD.open("test.txt", FILE_WRITE);

        tString = String(now.hour()) + ":" + String(now.minute()) + ":" + String(now.second()) + " - ";

        sString = String(data.pm10_standard) + "," + String(data.pm25_standard) + "," + String(data.pm100_standard);

        if (test) {
          test.print(tString);
          test.println(sString);
          test.close();
      }
    }


message:
Can't create an array of type const char*

I have something being returned as a const char* and would like to save it to an array.

I've tried this:

    const char* book[amtBooks] = "";

and get this error:

    error: array must be initialized with a brace-enclosed initializer

body:
* `const char* book[amtBooks]` is an array of pointers.
* `""` is an array of chars (with only a NUL character).

You can initialize an array of chars with an array of chars:

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

    const char foo[] = "hello";

You can also initialize a pointer to char with an array of chars:

    const char *bar = "good bye";

this works because of the “decay to pointer” feature of C and C++.

But initializing an array of pointers with an array of chars simply does
not make sense. An array of pointers to char could be initialized as

    const char *book[] = {"hello", "good bye"};


message:
Reading names of files on sd card returning odd file names

When trying to read the file names from an sd card some are being returned with a ~1 and cutting off the full file name.

    Initializing SD card...initialization done.
    TEST.TXT  402
    UNTITL~1  0
    HELLOT~1  49
    DATALOG.TXT  562288
    ALONGN~1  0
    done!

Is there any way I get the full file name of each file?

The code for this is from here: [https://www.arduino.cc/en/Tutorial/Listfiles][1]

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

body:
That's the way the [FAT filesystem][1] works.

On the page you link to there's a link to a [page on SDCardNotes.][2]

> FAT file systems have a limitation when it comes to naming conventions. You must use the 8.3 format, so that file names look like “NAME001.EXT”, where “NAME001” is an 8 character or fewer string, and “EXT” is a 3 character extension. People commonly use the extensions .TXT and .LOG. It is possible to have a shorter file name (for example, mydata.txt, or time.log), but you cannot use longer file names.

When you wrote the files to the file system you were on an OS that supports longer filenames. When filenames are too long there's an 8.3 name created automatically with chunks of characters removed and replaced with `~`.

  [1]: https://en.wikipedia.org/wiki/8.3_filename
  [2]: https://www.arduino.cc/en/Reference/SDCardNotes


body:
You have long filenames on your SD card. The SD library is too primitive to know what they are.

I'd suggest switching to FatFS ([here is one implementation](https://github.com/gallegojm/Arduino-FatFs)) which has the option of using long filenames.


message:
Connecting Arduino Arduino to MOSFET

I want to use my Arduino Nano to control a 12V peristaltic pump via a BDX33c N-Channel MOSFET. The pump has a maximum current draw of 1,4 A. The Arduino (via VIN) and the pump are powered by a 12V supply. I connected the parts like shown in the schematic diagram.

[![Schematic Diagram][1]][1]

When I plugged the supply in, the Arduino voltage regulator and the Mosfet got really hot (I could not touch it longer than 1-2 seconds) and the RX-LED was on continously, even after turning it off and on again. The Arduino isn't recognized by my Computer anymore, so I assume it is dead.
What did I do wrong with my wiring?

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

body:
That little blue wire on your breadboard is shorting out the motor. You have most likely now blown the transistor and maybe your power supply. The 12V may also now have made its way into the Arduino through the dead transistor and nuked the rest of it.

Alternatively, the massive base currents imposed by the shorted ground connection may have burned out parts of the Arduino.


body:
> That little blue wire on your breadboard is shorting out the motor.

That is not the problem. That blue wire is actually correct. It connects the source to ground. (-ve)

Your drawing shows the Drain of the Mosfet connected to +12 volts and the Source connected to ground. (the -ve of the supply) If you didn't have the short (blue wire from Source to ground) it still would not have worked.

You can't put an N channel mosfet in the positive side of the supply and control it from a voltage lower than the positive supply. (something the previous answer didn't even mention)

You must have the source connected to ground (as you have) but the drain has to then connect directly to the motor, and the other side of the motor goes to the +12 connection. This would be the correct way, but there still is an important omission. You need to have a diode connected across the motor to control the flyback pulse when the mosfet turns off. Otherwise the voltage spike generated by the motor's inductance will destroy the mosfet switch.

Your blue wire on the breadboard is correct. What is wrong is the red wire to the center terminal of the mosfet. The red wire should be going to the motor. The Blue/yellow connection. The green wire should be going to the mosfet's center pin.And as I said before, there needs to be a diode across the motor, with the cathode (line on the body of the diode) connected to the +ve side of the motor connection.

This is a correct drawing as far as the mosfet and motor connections are concerned. This drawing shows 5 volts being brought to the breadboard to power the motor. In your case this should be the 12 volts from the power supply.

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

While the beadboard may be adequate for verifying the circuit, it may cause connection problems due to the significant current that the motor will draw. Even if you wired it up properly you may still have issues due to the poor connections.

EDIT:

I looked up the specs for the BDX33B and it is a darlington transistor and not a mosfet. But in the end, all that I said also applies whether it was a bipolar transistor or a mosfet. But you need to include a series resistor as shown in the drawing I provided. You can't drive it direct from a port pin as if it were a mosfet.

Another schematic.

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

  [1]: https://i.stack.imgur.com/hJfXO.png
  [2]: https://i.stack.imgur.com/uj6xS.png
This shows a darlington transistor like the one you listed, and a 12 volt power source.


message:
Does a pin (input pin Arduino) still float when connected to GPIO on RPI?

I am currently testing my application on an Arduino, and I experience floating pin issues. My program reads the pin status of input pins, which are configured as

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

    pinMode(5, INPUT);
    digitalWrite(5, HIGH);

but still they tend to float sometimes.

Will this be solved when I connect the pin directly to a GPIO pin on a RPI? Specifically when the application running on the RPI is not active yet (thus the GPIO pin will not actively high or low yet).

Both the PI and and Arduino will be powered at the same time, but the application on the Arduino will be active much faster than the application on the RPI.

So my concern is that while the RPI is still booting and loading the app, the Arduino might still 'suffer' from floating pins, which gives undesirable output to the things my Arduino controls.

Or, will the fact that the RPI and Arduino both have power, share the same ground, will result in a stable input on the Arduino?

PS: not an expert on electronics, hence the question. I can't test this yet as I don't have all the hardware of this project.

body:
You need to enable the internal pull-up resistors which are designed to prevent undefined input states on unconnected inputs.

Change

    pinMode(5, INPUT);

to

    pinMode(5, INPUT_PULLUP);

For more information on this see Arduino [digital pins](https://www.arduino.cc/en/Tutorial/DigitalPins).


body:
> Does a pin (input pin arduino) still float when connected to GPIO on RPI?

Yes. Connecting one floating pin to another floating pin doesn't make either one of them stop floating. If anything, the fact that there's now a long wire connecting them (and picking up RF) will probably make the behavior of the pins even less predictable.


message:
Calculate sensor unique address with a 8 position DIP Switch

I have a large amount of sensor boards that I need to be able to configure setting unique addresses. Each sensor is attached to it's own arduino, I'm using a 8 position DIP switch for setting the address.

I have tried diferent approaches. When I switch On and OFF I get random values. I understood that I would be able to get up to 255 possible positions, but without being able to get the proper byte data I would have to manually code each possibility, which seems wrong.

Schematic :

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

Code

    #include "DipSwitchI2C.h"

    DipSwitchI2C::DipSwitchI2C(int address)
    {
        _address = address;
    }

    void DipSwitchI2C::begin()
    {
     Wire.begin();
    }

    int DipSwitchI2C::read()
    {
     unsigned int address = 0;
     unsigned int value = 0;

     Wire.requestFrom(_address, 1);
      if (Wire.available())
     {
      value = Wire.read();
     }
     Wire.endTransmission();

        for (int i = 0; i < 8; i++)
        {
            address += (value & (1<<i)) > 0;
        }

     return address;
    }

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

body:
Assuming that your switches are on pins 2-9 on an UNO.  Change pins to match what you actually have.

    byte addressVal = 0;
    for(int i = 2: i<10; i++){
        addressVal <<= 1;
        addressVal += digitalRead(i);
    }

This will check each switch and add a 1 to the end of the byte.  On each iteration it shifts the contents of that byte 1 place to the left.  After it reads all the pins you have a byte with a value 0 to 255 depending on the states of the pins.


body:
As @jsotola noted the solution was simple:

    int DipSwitchI2C::read()
    {
     unsigned int address = 1;

     Wire.requestFrom(_address, 1);
     if (Wire.available())
     {
      address = Wire.read();
     }
     Wire.endTransmission();

     return address;
     }


message:
Do some variables not hold their value when a while loop is exited?

Sorry if i'm asking too many silly questions but i'm really stumped on this one. I understand if I set a variable inside a loop that that variable won't be within scope from the outside of the loop.

Usually I find that variables declared outside of a loop will be accessible inside the loop, modifiable within the loop, and hold their value when exiting the loop but in this case that doesn't seem to be happening.

There are books on the sd card.
I'm saving the name of each book to an array from within a while loop.
When the while loop is exited the array is still null.

How can I solve this? thanks

    int amtBooks = 5; //this gets set previously but im not going to show all the code

    // create an array the size of the amount of books
      char* book[amtBooks] = { NULL };

    // assign the name of each book to the array
      int bookNum = 0;
      while (true) {

        File entry =  root.openNextFile();
          if (! entry) {
            break; // no more files
          }

        book[bookNum] = entry.name();

        Serial.println(book[bookNum]); // <--------PRINTS FINE HERE

        bookNum ++;

      }

      root.close(); // close the stream

    Serial.println(book[0]); <---ONCE OUT OF THE WHILE LOOP NOTHING DISPLAYS?
    Serial.println(book[1]);

body:
You store a pointer to char array `name` in `File` variable `entry`. The `entry` goes out of scope (is deleted from stack) and your stored pointer points nowhere.

You need `char book[amtBooks][13] = {{0}};` and `strcpy(book[bookNum], entry.name());`


body:
> variables declared outside of a loop will be accessible inside the
> loop, modifiable within the loop, and hold their value when exiting
> the loop

This is correct.

> in this case that doesn't seem to be happening.

It is happening. The reason it looks like it doesn't is that
`book[bookNum]` is a pointer: the address of some data in memory. You
can check that the pointer _does_ hold its value by printing it:

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

    Serial.println((uintptr_t) book[bookNum]);

However, the statement you used:

    Serial.println(book[bookNum]);

has a different meaning. It doesn't print the value of the variable
(i.e. the pointer): it prints the characters that are stored at the
pointed-to address, up to and excluding the first NUL.

Your problem comes from the fact that when you declare

    File entry =  root.openNextFile();

you have a variable that is local to the loop. Then, when calling the
method

    entry.name()

you get a pointer to an array of characters that belongs to the `entry`
object. This pointer is only valid as long as the object is in scope. As
soon as it gets out of scope (at the end of each loop iteration), the
`entry` object is destroyed and all memory belonging to it is released.
At this point the pointer you saved is a “dangling” pointer: it points
to an area of memory that has already been deallocated.

The proper fix is to allocate yourself the memory you need to hold the
character arrays, as in:

    for (int bookNum = 0; bookNum < amtBooks; bookNum++) {
        File entry = root.openNextFile();
        if (!entry) break;
        const char *name = entry.name();
        book[bookNum] = (char *) malloc(strlen(name) + 1);
        strcpy(book[bookNum], name);
        Serial.println(book[bookNum]);
    }

If you know in advance the maximum length of a book name, you could
follow the advice of Jot and Juraj and statically allocate the maximum
space you may need. That would be safer in terms of memory management.


message:
What does this lines mean in RFID UID Card Reader Code?

I'm currently doing a project using RFID. I'm wondering how this lines of the code work. I know that this has something to do with getting the UID of a scanned/tapped card, but can someone please explain or elaborate to me each line, how it executes? Thank you very much.

      String ID = "";
      for (byte i = 0; i < 4; i ++) {
        ID += (rfid.uid.uidByte[i] < 0x10 ? "0" : "")
              + String(rfid.uid.uidByte[i], HEX)
              + (i != 3 ? ":" : "" );
      }

body:
The code formats UUID as a string of 4 hex bytes (each bytes a pair of hex digits) separated by colons.

    String ID = ""
Blank the string

    for (byte i = 0; i < 4; i ++){
Iterate over the four bytes of the UUID

      ID +=

Add the following to the string "ID"

    (rfid.uid.uidByte[i] < 0x10 ? "0" : "") +
If the hex number to be displayed is less than 0x10, add a leading '0' to the string 'ID'. This ensures the UUIDs are all aligned and all bytes within the UUID are displayed as two hex digits (even if only one is needed). It uses the ternary condition operator, which is a compact if/then/else that can only return one of two values (rather than executing chunks of code). See https://en.wikipedia.org/wiki/?: for more on the ternary condition operator.

     String(rfid.uid.uidByte[i], HEX) +

Add the UUID to the string 'ID' as HEX.

       (i != 3 ? ":" : "" );
Another instance of the ternary condition operator. This one adds a colon to the string 'ID' after the hex byte unless the index is 3 (ie the last one).

     }
End of for loop.
This means that the result is nn:nn:nn:nn instead of nn:nn:n:nn: (leave off trailing colon and differing numbers of hex digits).


message:
Stacking 3 of the same shields on top of each other and instructing them in sync

**Context:**
I have an audio track separated into individual channels grouped by frequency and speaker location. I need to play all three of these channels simultaneously and perform instructions like play, stop, repeat, skip across all channels to keep them in sync.

This is part of an outdoor installation so the solution must be modular and robust.

If possible, the most elegant solution I could come up with is to use an [Arduino Leonardo][1] and stack 3 [Adafruit Music Maker Shield][2] on each other.

**Reasons why I think it might be technically feasible:**

  <s>1. Each shield can share communication over I2C</s>

 2. Looking at the [VS1053b Datasheet][3] (the IC used in the shield) the chip at max load consumes Maximum 60mA, and typically 37mA. Arduino can drive a max of 500mA so these three shields should consume a small portion of that.
The Arduino will also be powered via 12v power supply.

**Details i'm not so clear on:**

 1. How will I differentiate between each shield when sending instructions or do I need to even need consider this if I want them to function as one?

  [1]: https://store.arduino.cc/usa/arduino-leonardo-with-headers
  [2]: https://www.adafruit.com/product/1790
  [3]: https://cdn-shop.adafruit.com/datasheets/vs1053.pdf

body:
The shield actually uses SPI.

So you will need to trace the chip select and make sure that each shield uses a different arduino pin.


body:
The shields use SPI. There are more slave select pins on the shield for different devices of the shield. The first shield can use the default pins, but on next shields you must bend the default pins of the shield to side and connect them with a jumper cable to other set of pins of Arduino.

Then in sketch you need to define the select pins in constructor for each instance of the handling object Adafruit_VS1053.

    Adafruit_VS1053_FilePlayer musicPlayer =
      Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);
    Adafruit_VS1053_FilePlayer musicPlayer2 =
      Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS_2, SHIELD_DCS_2, DREQ_2, CARDCS);
    Adafruit_VS1053_FilePlayer musicPlayer3 =
      Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS_3, SHIELD_DCS_3, DREQ_3, CARDCS);

They will be not in microseconds sync since you must instruct them individually.

Use only one SD card because the SD library can't support more of them. Advantages of one SD card are only one cs pin and less active devices on SPI. There is no direct read by the player from SD card on the same shield.

Note: The SPI device is the SD card not the adapter. An empty adapter is nothing on bus so you can put the card for example into the shield on top and do not need bend the SD card cs pins on other shields.


message:
Interfacing with an SSI sensor?

I'm trying to interface with version RM08S of [this rotary encoder](https://www.rls.si/eng/rm08-super-small-non-contact-rotary-encoder) using an Arduino Mega. The sensor supports a "Synchro serial interface (SSI), single ended" interface. I'm unfamiliar with this protocol.

Despite the name, it doesn't appear to match the description of the formal [SSI or RS-422 specification](https://en.wikipedia.org/wiki/Synchronous_Serial_Interface), since that requires two wires for differential clock and data lines, whereas this sensor only has a single wire for each. This makes it sound more like IIC, but without the bus-like functionality.

Googling finds very few results on interfacing the Arduino to SSI devices, much less any standard libraries. [This forum thread](https://forum.arduino.cc/index.php?topic=232369.0) asks a similar question, but doesn't seem to resolve the issue.

Since there's just a clock and data line, would reading from this be as simple as toggling clock, and then reading the 10-bits of data from the data line, sequentially with each clock tick, accounting for whatever bits are used to pad the packet?

body:
It's just SPI.

    SPI.begin();
    SPI.setDataMode(SPI_MODE2);

    // ...

    uint8_t h = SPI.transfer(0x00);
    uint8_t l = SPI.transfer(0x00);
    delayMicroseconds(20); // Indicate EOT
    uint16_t v = (h << 8) | l;
    v >>= 4; // for 12 bit resolution, 5 for 11 bit, 6 for 10 bit etc.

For 8 bit resolution or less you only need one SPI.transfer, and subtract 8 from the right-shift amount.

Wiring is simple: clock to SCK (52 or ICSP 3) and data to MISO (50 or ICSP 1).

The timing diagrams in [the datasheet](https://www.rls.si/en/fileuploader/download/download/?d=0&file=custom/upload/RM08D01_11.pdf) (page 5) describe it all in detail.


message:
eclipse photon with cdt-arduino plugin can't upload sketches

i've recently decided to give eclipse-photon-cdt a shot. i use it with the built in arduino plugin, downloaded my feather m0 board config and tried to upload an empty sketch. failed, the console shows it tries to connect but fails. of course arudino ide 1.8.5 succeeds wonderfully.
point is if i copy paste the command line activating bossac i get the same result. i also know why. when using scripts i need to use a python scripts that uses serial signaling to reset the feather into bootloader mode. arduino ide does it on his own probably using java. eclipse doesn't do that which sounds like a huge bug to me.

am i missing something ? or did they actually assumed i'll press twice on the reset button on the board each and every time i want to upload a sketch ?

body:
It sounds to me like Eclipse doesn't know how to reboot the board into the bootloader.

Traditional Arduinos automatically boot into the bootloader when the board is reset, and the board resets every time you open the serial port thanks to the USB chip having DTR connected (through a capacitor) to the reset pin of the man MCU.

Chips with a direct USB connection can't do that (boards like the M0 Feather, the Leonardo, etc).  Instead they have to be rebooted by opening the serial port at 1200 baud and then closing it again.

With the "traditional" boards the IDE neither knows, nor cares, about rebooting the board - it just happens. However with direct USB boards the IDE has to have specific code to perform the reboot at the right time. The Arduino IDE has that code. However I would guess that the Eclipse plugin either doesn't implement that, or doesn't have the ability to implement it.

So you will have to manually reset the board for programming.


message:
How to repeat the code

I want to make my biped robot keep walking, but it only move for twice, this biped robot project is important for my Capstone project. The code below is the code that I used

    #include <Servo.h>

    int HipR_Pin = 9;
    int HipL_Pin = 10;

    int KneeR_Pin = 5;
    int KneeL_Pin = 6;

    int AnkleR_Pin = 3;
    int AnkleL_Pin = 11;

    Servo HipR;
    Servo HipL;

    Servo KneeR;
    Servo KneeL;

    Servo AnkleR;
    Servo AnkleL;

    void setup() {
      HipR.attach(HipR_Pin);
      HipL.attach(HipL_Pin);
      KneeR.attach(KneeR_Pin);
      KneeL.attach(KneeL_Pin);
      AnkleR.attach(KneeR_Pin);
      AnkleL.attach(KneeL_Pin);
    }

    void loop() {

      for (int i=0; i < 7; i++)
      {
        RightStep1;
        LeftStep1;
        RightStep2;
        LeftStep2;
        RightStep3;
        LeftStep3;
        RightStep4;
        LeftStep4;
      }
      ;
    }

    void RightStep1()
    {
      HipR.write(80);
      HipL.write(80);
      KneeR.write(100);
      KneeL.write(100);
      AnkleR.write(20);
      AnkleL.write(20);

    }

    void LeftStep1()
    {
      HipR.write(90);
      HipL.write(90);
      KneeR.write(70);
      KneeL.write(70);
      AnkleR.write(20);
      AnkleL.write(20);

    }

    void RightStep2()
    {
      HipR.write(70);
      HipL.write(70);
      KneeR.write(80);
      KneeL.write(80);
      AnkleR.write(10);
      AnkleL.write(10);

    }

    void LeftStep2()
    {
      HipR.write(60);
      HipL.write(60);
      KneeR.write(90);
      KneeL.write(90);
      AnkleR.write(20);
      AnkleL.write(20);

    }
    void RightStep3()
    {
      HipR.write(40);
      HipL.write(40);
      KneeR.write(60);
      KneeL.write(60);
      AnkleR.write(10);
      AnkleL.write(10);

    }

    void LeftStep3()
    {
      HipR.write(50);
      HipL.write(50);
      KneeR.write(70);
      KneeL.write(70);
      AnkleR.write(20);
      AnkleL.write(20);

    }
    void RightStep4()
    {
      HipR.write(60);
      HipL.write(60);
      KneeR.write(60);
      KneeL.write(60);
      AnkleR.write(10);
      AnkleL.write(10);

    }

    void LeftStep4()
    {
      HipR.write(70);
      HipL.write(70);
      KneeR.write(50);
      KneeL.write(50);
      AnkleR.write(20);
      AnkleL.write(20);

    }

body:
To call a function you need to add parentheses after the function name.

    void loop() {

      for (int i=0; i < 7; i++)
      {
        RightStep1();
        LeftStep1();
        RightStep2();
        LeftStep2();
        RightStep3();
        LeftStep3();
        RightStep4();
        LeftStep4();
      }
      ;//<<--also remove this stray semi-colon
    }


body: In addition to @Gerben's answer, you aren't giving any time for your movements to complete.  `.write()` doesn't wait for the movement to complete - it just sets the target angle.  You should add enough `delay(...)` calls to wait for your movements to finish before you start a new one.


body:
Instead of all the different step functions you can better parameterize them for example

    void LeftStep4()
    {
      HipR.write(70);
      HipL.write(70);
      KneeR.write(50);
      KneeL.write(50);
      AnkleR.write(20);
      AnkleL.write(20);
    }

will be

    void LeftStep4()
    {
      Move(70, 70, 50, 50, 20, 20);
    }

and create a function

    void Move(int hipR, int hipL, int kneeR, int kneeL, int ankleR, int ankleL)
      HipR.write(hipR);
      HipL.write(hipL);
      KneeR.write(kneeR);
      KneeL.write(kneeL);
      AnkleR.write(ankleR);
      AnkleL.write(ankleL);
    }

The other functions will also be one liners like the first function LeftStep4.


body:
This may not be a direct answer to your question but... when I see so
much code repetition, I cannot help but suggest you try to avoid
repeating yourself. All your `Step()` functions do exactly the same
_actions_, only with different _data_. You can then factor the actions
into a single function, and provide it different data as parameters.
There are many ways to achieve this in C++. I am going to show four of
them, in order from the most basic to the most esoteric.

The simplest one is to use a plain function and give it the angles as
parameters. This is basically what Michel Keijzers’ answer suggests. My
take on it would be

    void Step(uint8_t hip, uint8_t knee, uint8_t ankle)
    {
        HipR.write(hip);
        HipL.write(hip);
        KneeR.write(knee);
        KneeL.write(knee);
        AnkleR.write(ankle);
        AnkleL.write(ankle);
    }

which you can then use in the main loop as

    Step( 80, 100,  20);  // right 1
    Step( 90,  70,  20);  // left 1
    ...

The next step in code modularity would be to group all the angles for a
single step into a compound data structure called a `struct`, then the
function to perform a step takes a single parameter which is this data
structure:

    struct Step {
        uint8_t hip;
        uint8_t knee;
        uint8_t ankle;
    };

    void doStep(Step s)
    {
        HipR.write(s.hip);
        HipL.write(s.hip);
        KneeR.write(s.knee);
        KneeL.write(s.knee);
        AnkleR.write(s.ankle);
        AnkleL.write(s.ankle);
    }

These structs would be defined as

    Step RightStep1 = { 80, 100,  20};
    Step LeftStep1  = { 90,  70,  20};
    ...

and used in `loop()` as

    doStep(RightStep1);
    doStep(LeftStep1);
    ...

One step further, you can embed the function within the data structure.
The embedded function then becomes a “method” of the data structure
which is now called an “object”:

    struct Step {
        uint8_t hip;
        uint8_t knee;
        uint8_t ankle;
        void perform() {
            HipR.write(hip);
            HipL.write(hip);
            KneeR.write(knee);
            KneeL.write(knee);
            AnkleR.write(ankle);
            AnkleL.write(ankle);
        }
    };

The structs can be defined just as before, and used as

    RightStep1.perform();
    LeftStep1.perform();
    ...

One last technique involves making the objects themselves behave as
functions that can be called. This kind of callable object is called a
“functor”, and is kind of syntactic sugar over a method call. We just
have to rename the relevant method as `operator()`:

    struct Step {
        uint8_t hip;
        uint8_t knee;
        uint8_t ankle;
        void operator()() {
            HipR.write(hip);
            HipL.write(hip);
            KneeR.write(knee);
            KneeL.write(knee);
            AnkleR.write(ankle);
            AnkleL.write(ankle);
        }
    };

The structs are still defined in the same way, but now they can be used
as if they were plain functions:

    RightStep1();
    LeftStep1();
    ...

I suggest you use whatever technique you feel the most comfortable with.
There is a logic progression though: the more you improve your C++
skills the more comfortable you will be with the latest ones.


message:
How do I connect my Luxorparts keypad to my Arduino?

I just bought a 12 digit keypad from Luxorparts and it doesn't come with any schematics showing how it's wired at all. How do I figure out how to connect it to my Arduino?

body:
There's a guide here that helped me out: [Keypad Tutorial][1], that will show you the means of figuring out how the keypad is wired. I followed it and figured out that for that specific keypad (the Luxorparts keypad) the setup is as follows:

(From left to right on the keypad pins and on the rows and columns)

Pin1: Not connected
Pin2: Connected to the 2:nd collumn
Pin3: Connected to the 1:st row
Pin4: Connected to the 1:st collumn
Pin5: Connected to the 4:th row
Pin6: Connected to the 3:rd column
Pin7: Connected to the 3:rd row
Pin8: Connected to the 2:nd row
Pin9: Not connected

I modified the example code from the link above to reflect this specific Keypad:

    #include <Keypad.h>

    const byte ROW0 = 3;
    const byte ROW1 = 8;
    const byte ROW2 = 7;
    const byte ROW3 = 5;

    const byte COL0 = 4;
    const byte COL1 = 2;
    const byte COL2 = 6;

    const byte ROWS = 4; // Four rows
    const byte COLS = 3; // Three columns
    // Define the Keymap
    char keys[ROWS][COLS] = {
      {'1','2','3'},
      {'4','5','6'},
      {'7','8','9'},
      {'#','0','*'}
    };
    // Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins.
    byte rowPins[ROWS] = { ROW0, ROW1, ROW2, ROW3 };
    // Connect keypad COL0, COL1 and COL2 to these Arduino pins.
    byte colPins[COLS] = { COL0, COL1, COL2 };

    // Create the Keypad
    Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

    #define ledpin 13

    void setup()
    {
      pinMode(ledpin,OUTPUT);
      digitalWrite(ledpin, HIGH);
      Serial.begin(9600);
    }

    void loop()
    {
      char key = kpd.getKey();
      if(key)  // Check for a valid key.
      {
        switch (key)
        {
          case '*':
            digitalWrite(ledpin, LOW);
            break;
          case '#':
            digitalWrite(ledpin, HIGH);
            break;
          default:
            Serial.println(key);
        }
      }
    }
To run that, simply connect each pin from the keypad, in order, to the arduino, so the second pin from the keypad goes to the second digital pin on the Arduino and so on.

I asked the question after I'd already figured out the answer in hopes of helping anyone else who bought that specific keypad.

  [1]: https://playground.arduino.cc/Main/KeypadTutorial


message:
How to pass 2 parameters with RCSwitch library?

I'm learning Arduino's world, but knowing very little about C and C++.

I'm trying to achieve a little RF transmitter which should send the temperature and  humidity from a DHT-11 sensor to a Raspberry Pi.

I'm using the `RCSwitch` library to [send information][1] with the Arduino, and the `433Utils` library to [receive it][2] on the RPI.

Using those 2 libraries demos, I was able to send an integer, holding temperature or humidity information (`mySwitch.send("00001010");`), and read it on the RPI.

**But how can I send both informations so that the RPI will know which one is the temperature and the humidity ?**

I know I could just send both and assume the lowest is the temperature, but this would be very messy and not very rewarding.

## EDIT : ##
Following Edgar's answer in https://arduino.stackexchange.com/a/52992/11604, I know write:

    void send_string(const char *str){
     int i = 0;
     for (char *p = str; *p; p++ ) {
      mySwitch.send((i<<8) + *p, 16);
      i++;
     }
    }

    void loop() {
     delay(1000);
     h=40.650;
     t=32.0078;
     hic=33.586;
     String x = "$H" + String(h) + "T" + String(t) + "HI" + String(hic);
     send_string(x.c_str());
    }

Works perfectly ! (see his complete answer for the RPI-side code)

  [1]: https://github.com/sui77/rc-switch/blob/master/examples/SendDemo/SendDemo.ino
  [2]: https://github.com/ninjablocks/433Utils/blob/master/RPi_utils/RFSniffer.cpp

body:
The library you have chosen is not designed for transmitting information between nodes. It is intended for sending simple ON/OFF commands to RF-connected switches.  Bending it to send data in the way you want would be difficult.  Not impossible, but difficult.

Instead you should be considering a more suitable system, such as the popular [RadioHead](http://www.airspayce.com/mikem/arduino/RadioHead/) library. It appears to have Raspberry Pi support out of the box:

> Raspberry Pi Uses BCM2835 library for GPIO http://www.airspayce.com/mikem/bcm2835/ Currently works only with RH_NRF24 driver or other drivers that do not require interrupt support. Contributed by Mike Poublon.

Alternatively a small Arduino as an interface between the RF module and the Pi may be another option.


message:
Passing out an argument

I can't figure out why ` test` is not passed properly to `test1`

    #include <Arduino.h>

    char *test1;
    char *status_reply(char *test) {
            int ans_rel = 1;
            int ans_led = 0;
            int ans_sw = 1;
            sprintf(test,"%d%d%d",ans_rel,ans_sw,ans_led);
            Serial.println(test);
    }

    void setup() {
            Serial.begin(9600);
            status_reply(test1);
            Serial.println(test1);
    }

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

body:
This is not about Arduino. It is C. You have only a pointer to char now. You must allocate memory for the c-string.

`char test1[128];`

If you pass pointer to sprintf, the function will write to memory where the pointer points. Something somewhere in memory will be overwritten and the following print will print the string, but later the memory will be used for something else and your c-string disappear.


message:
Can client IP address be obtained from Arduino Ethernet2 library for W5500 during client.connected() call?

I've found posts explaining how to get client IP by modifying the W5100 Ethernet library and the Adafruit CC3000 library but not the Ethernet2 lib for W5500 chip, which is different enough that the W5100 mod won't work. I suspect the TCP Socket struct will contain it, but haven't been able to find its declaration anywhere to confirm this so I can modify the library to make it accessible.

body:
Use the new update of the 'old' Ethernet library. It is version 2.00 and you can install or update it in the Library Manager in IDE. Note, **it is not Ethernet2 library**. The new Ethernet library supports W5500 and has `client.remoteIP()`.

[example][1]

      if (client.connect(server, 80)) {
        Serial.print("connected to ");
        Serial.println(client.remoteIP());

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

> New features in version 2.0.0
Auto-detection of W5100, W5200, and W5500 Ethernet hardware.

  [1]: https://github.com/arduino-libraries/Ethernet/blob/master/examples/WebClient/WebClient.ino
  [2]: https://i.stack.imgur.com/ss9JV.png


body: This solution works: http://forum.arduino.cc/index.php/topic,82416.0.html if "W5100.readSnDIPR(_sock, remoteIP);" is replaced with "w5500.readSnDIPR(_sock, remoteIP);" [note the lower case 'w']. I didn't think it would because I can't find readSnDIPR() in the Ethernet2 library source, but after reviewing the Wiznet 5500 data sheet (https://www.mouser.com/pdfdocs/w5500_ds_v100e.PDF) I realized it was probably a read of the "Socket n Destination IP Address" register and decided to try it and see if it linked. It did, and successfully returns the remote IP after connecting.


message:
When using an Arduino as an ISP, is the capacitor required or not?

Looking at [Arduino as ISP and Arduino Bootloaders][1], it is stated

> The 10 µF electrolytic capacitor connected to RESET and
> GND of the programming board is needed only for the boards that have
> an interface between the microcontroller and the computer's USB, like
> Mega, Uno, Mini, Nano. Boards like Leonardo, Esplora and Micro, with
> the USB directly managed by the microcontroller, don't need the
> capacitor.
>

Some of the Fritzing diagrams show the electrolytic capacitor connected between the `RESET` and `GND` pins:

[![Mega as ISP to Uno][2]][2]

But it is not shown in *all* of the images on that page.

Nor it is shown in this image from Nick Gammon's [Atmega bootloader programmer][3] (see [original image][4]):

[![Uno programming a Mega][5]][5]

So, is the capacitor *really* needed, when using a Mega or Uno as an ISP, and if so, why exactly?

----

I was wondering after having written [this answer][6] to the question [How to install new ATMEGA firmware via the ISP pins?][7] for a 3D Printer control board.

  [1]: https://www.arduino.cc/en/Tutorial/ArduinoISP
  [2]: https://i.stack.imgur.com/vHoWv.jpg "Uno to Mega programming"
  [3]: https://www.gammon.com.au/bootloader
  [4]: https://www.gammon.com.au/images/Arduino/Atmega_Chip_Detector9.jpg
  [5]: https://i.stack.imgur.com/PscDO.jpg "Uno programming a Mega"
  [6]: https://3dprinting.stackexchange.com/questions/6685/how-to-install-new-atmega-firmware-via-the-isp-pins/6686#6686
  [7]: https://3dprinting.stackexchange.com/questions/6685/how-to-install-new-atmega-firmware-via-the-isp-pins

body:
The purpose of the capacitor is to prevent the "master" Arduino (the Mega in the first image above) from resetting when the serial port is opened.  If that board resets, then programming fails.

There are many ways of preventing that reset - some more permanent than others - but the capacitor trick is one of the simplest.

So yes, you do need the capacitor unless you have made other modifications to prevent the reset.

I think the purpose of the second image is more to illustrate how to use the ICSP headers and where to connect the target's reset pin on the master. It is to be seen as complementary to the first image.

----

Edit:

It seems what you are using is *not* Arduino As ISP, but instead something written by Nick Gammon that acts as a standalone programmer.  The rules for Arduino As ISP do not apply in this case. Since you are not programming via the master Arduino (as you would with Arduino As ISP) there is no need to prevent the master from resetting.

----

Here's a little history about the auto-reset system:

Originally, when the Arduino used the FT232, the DRT signal would reliably reset it automatically. The operating system (all operating systems) would automatically assert DTR when the port was opened, and all was well.

Then, out of the blue, and without telling anyone, Future Tech removed that auto-DTR asserting from the FT232 driver for Windows. Since Windows doesn't control DTR for you, but leaves it up to the driver or the software (and all other operating systems automatically control DTR for you - Windows *has* to do the opposite of everyone else - it's in their remit...!) all of a sudden the boards stopped resetting properly for programming.

So Arduino added specific reset code into the IDE to get around the problem (interestingly enough: if you watch the DTR pin on Linux you see it being asserted multiple times when programming - both the OS and the IDE are toggling it).

But then Arduino moved to the ATmega8U2 (and later the ATmega16U2) chip which uses the standard CDC/ACM instead of the custom FT232 driver. Now the auto DTR assertion was working again, but they kept the manual assertion in the IDE to cope with older boards in Windows.

I guess they didn't put the DTR assertion workaround in the bootloader programming code since you don't really want DTR asserted at that point anyway.

So if you have an FT232-based Arduino and are running Windows I guess there is no need for the capacitor, since DTR won't be asserted by the OS.

However in Linux and OS X, regardless of the USB chip, you will need the capacitor, since it will *always* assert DTR.

But then along came China and threw the CH340G into the works.  Now we have a third option, with dodgy drivers from who knows where. And who has the slightest clue what they do? Do they assert DTR for you? Your guess is as good as mine.  If it doesn't, then you won't need the capacitor. If it does, then you will.

It's all such a mess now thanks to too many options and combinations.  It's simpler just to have the capacitor regardless, since it won't stop it working if it's not actually needed in your specific configuration.


body:
If you're using Nick Gammon's programmer, the RESET signal to the target board comes from the Arduino programmer - from Pin 10. Read his instructions:
https://www.gammon.com.au/bootloader

You modify the 6 pin cable as shown on his website.[![Cut wire 5 and attach to Pin 10 of the programmer board][1]][1]

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


message:
Running code through functions

I am making a led cube where sequential lighting is used. So basically i need to repeat my commands for a given time. After much reasearch nothing turned up so decided to ask here.

----------
Here is the code i need to reproduce in a working format

    void loop(){
      runfor(500){
        DigitalWrite(5,HIGH);   //this is the command to be executed in other
                                //function
      }
    }
    void runfor(uint32_t duration){
      int timer = millis();
      while((millis()-timer)<=duration){
      //DigitalWrite(5,HIGH); will execute here
      }
    }

So basically DigitalWrite(or any other code if used) will be repeatedly executed for 500 milliseconds

body:
**EDIT** due to misunderstanding the question.

If you want to be able to pass instructions into a function, you will have to have a function for each set of instructions (that is, you cannot pass arbitrary statements as a function parameter), and then you adjust your `runfor()` function to accept a pointer-to-a-function parameter.

    typedef void (*callback_function)(void);  // defining the type here makes the code easier to read when used in other places.

    void runfor(uint32_t duration, callback_function patternCode){
      uint32_t timer = millis();
      while ((millis()-timer)<=duration) {
        //get these commands from caller function
        patternCode();
      }
    }

    void pattern1() {
      // Light pattern #1
    }

    void pattern2() {
      // Light pattern #2
    }

    void setup() {
      // Setup code
    }

    void loop() {
      runfor(1000, pattern1);
      runfor(2000, pattern2);
    }

----------
**ORIGINAL ANSWER**

Your starting pseudo-code is nearly there.

    void runfor(uint32_t duration){
      uint32_t timer = millis();
      while ((millis()-timer)<=duration) {
        //get these commands from caller function
      }
    }

Changes I made:

1. change `int` to `uint32_t` to accommodate all possible values of `millis()`.

2. change `for` keyword to `while`, which is the correct keyword for the loop type you want.

3. added semicolon after your `timer` assignment, per C syntax.


message:
Arduino: command not found

After installing the Arduino IDE on MacOS (1.8.5), I am trying to run some commands in the terminal to flash the firmware on an Uno R3.

I have successfully connected and uploaded through the GUI, but would like to use the command line for the `johnny-five` API (https://github.com/rwaldron/johnny-five/wiki/Getting-Started).

However, when running

    arduino --install-library "Firmata,Servo"

I get the following error:

> -bash: command not found

How do I install the command line interface?

body:
Instructions to installing and binding the Arduino CLI can be found at

https://github.com/arduino/arduino-cli#getting-started

Once you install the binary, copy the executable into a directory which is in your PATH environment variable (such as `/usr/local/bin/`).

Note: You may have to rename the binary to `arduino-cli`.


message:
Why is there no embedded c code in arduino libraries?

When I took a look at how the arduino libraries were coded I expected to see register names like I/O registers(PINx,DDRx,PORTx) and other such registers with values assigned to them but instead I saw normal C code with functions and a class.

Why isn't there any embedded C in the structure of the library? Am I misunderstanding something very basic? Please help me understand.

body:
Because the Arduino API abstracts those things.

If you put that kind of low-level code into a library the library becomes non-portable.  By sticking to the Arduino API (digitalWrite, pinMode, etc) the library can be used on all boards.


body:
If you take a look at the Arduino core library (e.g., the AVR version of
[wiring.c][]), you will see lots of low-level register access. That's
why the core code is specific to a processor architecture.

Other libraries are built on top of the core API in order to be
portable.

[wiring.c]: https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/wiring.c


message:
setting output analog/digital pin to ground

So I need to automaically eject a CD from a Blu-Ray drive, I have a wire welded on the drive's card that if manually connected for a split second (pulse) to the ground of that same card on the drive, will eject the CD. Now in order to do that automatically I'm using an Arduino Nano and I connected that wire to an analog pin "d1" set its mode to Output and connected the grounds of both Arduino and drive together. Here's my code [1]

[1]: https://pastebin.com/HXR2ef1x

    int ds1 = A2; //pin that indicates the existence of the CD inside the drive if HIGH and its inexistance otherwise
    int d1 = A3;  //pin connected to the wire that if connected to ground ejects the CD

    void setup() {
      Serial.begin(9600);
      pinMode(ds1, INPUT);
      pinMode(d1, OUTPUT);
      while((!analogRead(ds1))) //if the CD isn't inside the drive wait
      {}
    }

    void loop() {
      analogWrite(d1,0); //eject CD
      delay(500);
      while(!analogRead(ds1)) //if the CD isn't inside the drive wait
      {}
      delay(1000);
    }

I'm thinking that maybe setting the pin to 0 doesn't necessarily mean I connected it to the gnd, it's just a possibility if you see anything wrong with the code or have any suggestion please help me

body:
Yes, setting a pin to OUTPUT and setting it LOW effectively connects the pin to ground (via a few ohms of resistance).

There's a couple of things wrong with your code, though, which you should address:

* Use digitalWrite() not analogWrite().

analogWrite(pin, 0) is effectively the same as digitalWrite(pin, 0), but it's ambiguous to someone reading your code.

* You never "release" the pin, so once it goes LOW it stays LOW.  You should emulate *open drain* by setting it to INPUT when not using it.

* You should get into the habit of putting repeated code into functions to make it more understandable what's going on.

For example:

    void setup() {
      Serial.begin(9600);
      pinMode(ds1, INPUT);
      pinMode(d1, INPUT);
      waitForCD();
    }

    void loop() {
      triggerEject();
      waitForCD();
      delay(1000);
    }

    void triggerEject() {
      pinMode(d1, OUTPUT);
      digitalWrite(d1, LOW); // Press the button
      delay(100); // This is how long the button is pressed for
      pinMode(d1, INPUT); // Release the button
    }

    void waitForCD() {
      while(!analogRead(ds1)) //if the CD isn't inside the drive wait
      {}
    }

* `!analogRead(ds1)` will only ever be true if the voltage at pin A2 is exactly zero volts. If you really want to read an analog voltage here you should find a threshold value that the value is compared to:

    while (analogRead(ds1) < 100)) {}

Or it may be that you actually want to use `digitalRead()`...


message:
Atmel studio 7 vs Arduino IDE for register level coding?

Which one is better to get started with register level embedded c coding?
Also which one is used professionally?

body: Atmel Studio for professional. Arduino is for fun and is normally the first step into embedded c programming using the atmega328 (Arduino)


body:
I actually wouldn’t recommend either for professionally developing for Atmel chips. Although Atmel Studio is a nice enough IDE (the simulator is amazing!), it does make it *very* difficult to unit test your code or to set up a build server. I would personally recommend you set up a Make (or possibly CMake) based setup directly on top of the `avr-gcc` tool chain and then simply use the text editor of your choice.

As for learning about programming against raw registers, I have to recommend Atmel Studio and one of their XPlained evaluation boards. Atmel Studio includes a simulator that actually shows you, bit by bit, the current state of the registers.


message:
ssPin, resetPin, updatePin, ps0, ps1, osk - was not declared in this scope

The code below produces the  error:

> ssPin was not declared in this scope

This error is repeated for all elements of DDS, i.e. `ssPin`, `resetPin`, `updatePin`, `ps0`, `ps1` and `osk`

Can anyone spot the problem?

    #include <SPI.h>
    #include <AD9954.h>
    AD9954 DDS(ssPin, resetPin, updatePin, ps0, ps1, osk);

    void setup() {
    SPI.begin();
    SPI.setClockDivider(4);
    SPI.setDataMode(SPI_MODE0);
    delay(500); // let things get set up...

    DDS.initialize(400000000); // initialize DDS with 400 MHz clock

    }

    void loop() {

     DDS.setFreq(25000000); // set DDS to 25 MHz
      delay(2000);

    }

body:
The line:

    AD9954 DDS(ssPin, resetPin, updatePin, ps0, ps1, osk);

does not have any content above it which declares that those variables exist. You can declare them like

    const uint8_t ssPin, resetPin, updatePin, ps0, ps1, osk;

You'll likely also want to assign values to them, corresponding to the pins being used:

    const uint8_t ssPin=4, resetPin=5, updatePin=6, ps0=7, ps1=8, osk=9;

(the actual values should be the pin numbers being used in your particular case.)

The file `AD9954.h` declares these variable names as private inside the class. They aren't available for use outside the class. The call to `DDS(...)` is the constructor, where you pass in pin definitions, and the values get assigned to those variables inside the class. But you can pass in literals or other variables in the constructor. You could even declare the same variable names in your main source file, but you can't ever directly access private variables from outside the class.


message:
How come my switch is triggering with out pushing the button?

New here, sorry If my formatting is bad.

    int button = 2;
    int relay = 3;
    int speaker = 4;

    void setup()
    {

      pinMode(button, INPUT_PULLUP);
      pinMode(relay, OUTPUT);
      pinMode(speaker, OUTPUT);

    }

    void loop()
    {
      if(digitalRead(button) == 0)
      {
        digitalWrite(relay, HIGH);
        tone (speaker, 100, 300);
        delay (3000);
      }
      else
      {
        digitalWrite(relay, LOW);
      }
    }

I want the relay to trigger and stay open only while the button is pressed.   However for some reason touching pin 2 triggers the relay and sound, even if I'm not connecting it to the ground.

If i remove the `tone (speaker, 100, 300);` it only triggers when the button connecting pin 2 to ground is pressed, but obviously doesn't play the tone.

body:
> I want the relay to trigger and stay open only while the button is
> pressed. However for some reason touching pin 2 triggers the relay and
> sound, even if I'm not connecting it to the ground.

Touching a pin is like connecting it to ground with a resistor (human body is conductive). It may or may not be stronger then the pull-up resistor.
> If i remove the tone (speaker, 100, 300); it only triggers when the
> button connecting pin 2 to ground is pressed, but obviously doesn't
> play the tone.

Activation of the neighbor pin influences the pull-up on pin 2. Try external pull-up on pin 2.


message:
Push button control of multiple relays

I'm new to arduinos and have not been able to find/create a working bit of code for my project. I'd like to control several different relays (standard 5v optical relays) with push buttons. I want one pushbutton1 to turn on/off relay1, pushbutton2 to turn on/off relay 2, etc.

I ran into troubles using delay statements as debouncers because I guess it locked out the remainder of the code while it ran? I then tried to use a flagging approach covered here:

https://github.com/VRomanov89/EEEnthusiast/blob/master/03. Arduino Tutorials/01. Advanced Button Control/ButtonSketch/ButtonSketch.ino

    const int numOfInputs = 2;
    const int inputPins[numOfInputs] = {2,3};
    const int outputPin = 10;

    int LEDState = 0;
    int inputState[numOfInputs];
    int lastInputState[numOfInputs] = {LOW,LOW};
    bool inputFlags[numOfInputs] = {LOW,LOW};
    int inputCounters[numOfInputs];

    long lastDebounceTime[numOfInputs] = {0,0};
    long debounceDelay = 50;

    void setup() {
      for(int i = 0; i < numOfInputs; i++) {
        pinMode(inputPins[i], INPUT);
        digitalWrite(inputPins[i], HIGH); // pull-up 20k
      }
      Serial.begin(9600);
      pinMode(outputPin, OUTPUT);
    }

    void loop() {
      setInputFlags();
      resolveInputFlags();
      resolveOutputs();
    }

    void setInputFlags() {
      for(int i = 0; i < numOfInputs; i++) {
        int reading = digitalRead(inputPins[i]);
        if (reading != lastInputState[i]) {
          lastDebounceTime[i] = millis();
        }
        if ((millis() - lastDebounceTime[i]) > debounceDelay) {
          if (reading != inputState[i]) {
            inputState[i] = reading;
            if (inputState[i] == HIGH) {
              inputFlags[i] = HIGH;
            }
          }
        }
        lastInputState[i] = reading;
      }
    }

    void resolveInputFlags() {
      for(int i = 0; i < numOfInputs; i++) {
        if(inputFlags[i] == HIGH) {
          // Input Toggle Logic
          inputCounters[i]++;
          updateLEDState(i);
          printString(i);
          inputFlags[i] = LOW;
        }
      }
    }

    void printString(int output) {
          Serial.print("Input ");
          Serial.print(output);
          Serial.print(" was pressed ");
          Serial.print(inputCounters[output]);
          Serial.println(" times.");
    }

    void updateLEDState(int input) {
      // input 0 = State 0 and 1
      if(input == 0) {
        if(LEDState == 0) {
          LEDState = 1;
        }else{
          LEDState = 0;
        }
      // input 1 = State 2 to 6
      }else if(input == 1) { // 2,3,4,5,6,2,3,4,5,6,2,
        if(LEDState == 0 || LEDState == 1 || LEDState > 5) {
          LEDState = 2;
        }else{
          LEDState++;
        }
      }
    }

    void resolveOutputs() {
      switch (LEDState) {
        case 0:
          digitalWrite(outputPin, LOW);
          break;
        case 1:
          digitalWrite(outputPin, HIGH);
          break;
        case 2:
          analogWrite(outputPin, 30);
          break;
        case 3:
          analogWrite(outputPin, 70);
          break;
        case 4:
          analogWrite(outputPin, 100);
          break;
        case 5:
          analogWrite(outputPin, 155);
          break;
        case 6:
          analogWrite(outputPin, 255);
          break;
        default:
        break;
      }
    }

But was unable to alter the code to get it to work... could someone help me write a bit of code which will allow me to do what I want it to do? I'd rather not buy a matrix-style shield to accomplish this, but I will if I have to.

What I want to do:

 - Turn on relay1 by pressing momentary pushbutton1
 - Turn off relay1 by pressing momentary pushbutton1
 - Turn on relay2 by pressing momentary pushbutton2
 - Turn off relay2 by pressing momentary pushbutton2
 - etc.
 - etc.

Thank you in advance!

body:
To use this sketch, you will need the [Bounce2][1] Library, and two N.O. switches connected between GND and the Arduino Digital Pins specified. I'm not sure if there is a limit to the number of Bounce2 objects you can create. Have a look at the Bounce2.h and Bounce2.cpp files.

[1]: https://github.com/thomasfredericks/Bounce2

    #include <Bounce2.h>
    byte buttonOneState = 0;
    byte buttonTwoState = 0;
    const byte buttonPin1 = 4;
    const byte buttonPin2 = 5;
    const byte debouncerInterval = 50;

    // Instantiate ONE OR MORE Bounce2 object(s).
    Bounce debouncer = Bounce();
    Bounce debouncer2 = Bounce();

    void setup(){
      Serial.begin(9600);
      pinMode(buttonPin1, INPUT_PULLUP);
      pinMode(buttonPin2, INPUT_PULLUP);
      debouncer.attach(buttonPin1);
      debouncer.interval(debouncerInterval);
      debouncer2.attach(buttonPin2);
      debouncer2.interval(debouncerInterval);
    }

    void loop(){

      // Button 1
      if(debouncer.update()){
        if(debouncer.read() == 0){
          if(buttonOneState == 0){
            Serial.println("Turn Relay 1 ON");
            buttonOneState = 1;
          }
          else{
            Serial.println("Turn Relay 1 OFF");
            buttonOneState = 0;
          }
        }
      }

      // Button 2
      if(debouncer2.update()){
        if(debouncer2.read() == 0){
          if(buttonTwoState == 0){
            Serial.println("Turn Relay 2 ON");
            buttonTwoState = 1;
          }
          else{
            Serial.println("Turn Relay 2 OFF");
            buttonTwoState = 0;
          }
        }
      }

    }


body:
You can use [this Button library from JChristensen][1] (in GitHub)

You only need to read the brieve (altough usefull) documentation and you can control, no only the state of many buttons, you also can read the time that the buttons are pressed.

Hope you can solve your little problem :D

TIP: Try with 50ms of delay when you instantiate the *button object*

  [1]: https://github.com/JChristensen/JC_Button


body:
Here is the final solution I've implemented:

    /*  Thanks to VE7JRO for giving me this solution to my problem.
     *  Thread found at https://arduino.stackexchange.com/questions/55540/push- button-control-of-multiple-relays
     */

    #include <Bounce2.h>
    byte buttonOneState = 0;
    byte buttonTwoState = 0;
    byte buttonThreeState = 0;
    byte buttonFourState = 0;
    const byte buttonPin1 = 2;
    const byte buttonPin2 = 3;
    const byte buttonPin3 = 4;
    const byte buttonPin4 = 5;
    const byte relayPin1 = 9; //Relay pin 1
    const byte relayPin2 = 10; //Relay pin 2
    const byte relayPin3 = 11; //Relay pin 3
    const byte relayPin4 = 12; //Relay pin 4
    const byte debouncerInterval = 50;

    // Instantiate ONE OR MORE Bounce2 object(s).
    Bounce debouncer = Bounce();
    Bounce debouncer2 = Bounce();
    Bounce debouncer3 = Bounce();
    Bounce debouncer4 = Bounce();

    void setup(){
      Serial.begin(9600);
      pinMode(buttonPin1, INPUT_PULLUP);
      pinMode(buttonPin2, INPUT_PULLUP);
      pinMode(buttonPin3, INPUT_PULLUP);
      pinMode(buttonPin4, INPUT_PULLUP);
      debouncer.attach(buttonPin1);
      debouncer.interval(debouncerInterval);
      debouncer2.attach(buttonPin2);
      debouncer2.interval(debouncerInterval);
      debouncer3.attach(buttonPin3);
      debouncer3.interval(debouncerInterval);
      debouncer4.attach(buttonPin4);
      debouncer4.interval(debouncerInterval);
      pinMode(relayPin1, OUTPUT); //Define pin as output
      pinMode(relayPin2, OUTPUT); //Define pin as output
      pinMode(relayPin3, OUTPUT); //Define pin as output
      pinMode(relayPin4, OUTPUT); //Define pin as output
    }

    void loop(){

      // Button 1
      if(debouncer.update()){
        if(debouncer.read() == 0){
          if(buttonOneState == 0){
            Serial.println("Turn Relay 1 ON");
            digitalWrite(relayPin1, HIGH);
            buttonOneState = 1;
          }
          else{
            Serial.println("Turn Relay 1 OFF");
            digitalWrite(relayPin1, LOW);
            buttonOneState = 0;
          }
        }
      }

      // Button 2
      if(debouncer2.update()){
        if(debouncer2.read() == 0){
          if(buttonTwoState == 0){
            Serial.println("Turn Relay 2 ON");
            digitalWrite(relayPin2, HIGH);
            buttonTwoState = 1;
          }
          else{
            Serial.println("Turn Relay 2 OFF");
            digitalWrite(relayPin2, LOW);
            buttonTwoState = 0;
          }
        }
      }

      // Button 3
      if(debouncer3.update()){
        if(debouncer3.read() == 0){
          if(buttonThreeState == 0){
            Serial.println("Turn Relay 3 ON");
            digitalWrite(relayPin3, HIGH);
            buttonThreeState = 1;
          }
          else{
            Serial.println("Turn Relay 3 OFF");
            digitalWrite(relayPin3, LOW);
            buttonThreeState = 0;
          }
        }
      }
      // Button 4
      if(debouncer4.update()){
        if(debouncer4.read() == 0){
          if(buttonFourState == 0){
            Serial.println("Turn Relay 4 ON");
            digitalWrite(relayPin4, HIGH);
            buttonFourState = 1;
          }
          else{
            Serial.println("Turn Relay 4 OFF");
            digitalWrite(relayPin4, LOW);
            buttonFourState = 0;
          }
        }
      }

    }


message:
Passing a reference as a variable

I have a function for manually jogging a stepper motor using the AccelStepper library. At the beginning of the function I would like the motor in question to be selected until told to stop.

Here is what I imagine it would look like:

    AccelStepper X_Axis(AccelStepper::DRIVER, 3, 2);
    AccelStepper Y_Axis(AccelStepper::DRIVER, 5, 4);
    AccelStepper Z_Axis(AccelStepper::DRIVER, 7, 6);

    void ManualJog(int Dir, int Spd, int axis)
    {
      int i;
      if (Dir == 0){i = 1;}else{i =- 1;}
      setSpeed(i * Spd);
      switch(axis)
        {
          case 1:
          axis = X_Axis;
          break;

          case 2:
          axis = Y_Axis;

          case 3:
          axis = Z_Axis
        }
      while (!Serial.available()){

          axis.runSpeed();
        }
      }

The axis variable should map to whichever axis is called and so control the desired stepper.

How can I achieve this?

Note: I submitted this to StackOverflow with no response. Any help would be appreciated

body:
To do it in the form you have, you would want to use a *pointer*.

    void ManualJog(int Dir, int Spd, int axis)
    {
      int i;
      AccellStepper *thisAxis = NULL;

      if (Dir == 0) {
        i = 1;
      } else {
        i =- 1;
      }
      setSpeed(i * Spd);
      switch(axis)
      {
        case 1:
          thisAxis = &X_Axis;
          break;

        case 2:
          thisAxis = &Y_Axis;
          break;

        case 3:
          thisAxis = &Z_Axis
          break
      }

      if (thisAxis != NULL) {
        while (!Serial.available()) {
          thisAxis->runSpeed();
        }
      }
    }

Briefly: the `&` before the name of a variable in assignment means "Give me the address of this variable".  A `*` before a variable when declaring that variable means "Make this variable hold the address of another variable of this type".  You then have the address variable hold the address of your chosen axel, and then "dereference" that with the "poiner dereference operator" `->` (instead of using `.`).

A check is added to see if `thisAxis` has actually been assigned anything or not, although you could use the `default:` case in your switch to abort on an invalid axis number instead.

Depending on how the rest of your program works, though, it may be possible to not use the "axis" integer at all, but pass a reference to the correct stepper to the function:

    void ManualJog(int Dir, int Spd, AccelStepper &axis) {
      int i;
      if (Dir == 0) {
        i = 1;
      } else {
        i =- 1;
      }
      setSpeed(i * Spd);
      while (!Serial.available()) {
        axis.runSpeed();
      }
    }

In this example the `&` before the `axis` variable in the function prototype means "Pass me the address of the variable", and a new variable is created located in the same memory space. This is the *pass by reference* operator in C++.


body:
How about using an array?

    const int x = 0;
    const int y = 1;
    const int z = 2;

    AccelStepper axis[] = { {AccelStepper::DRIVER, 3, 2}, ... };

    void ManualJog(int Dir, int Spd, int axisIdx)
    {
       axis[axisIdx].runSpeed();
    }


message:
Memory leakage caused by String Concatenation

In [this link][1], section "Memory, memory, memory" it's been told that doing many String concatenations in sequence, e.g.: using operator+() multiple times, will cause memory fragmentation, which may lead to the fact that total heap not being totally used.

An alternative I'm suggesting is using strcat() with char buffers and not using Strings at all, and then convert from resultant char buffer to String if a String is needed at the end?
Would that be an escape from fragmentation of the heap?

Clarification: I will specify the upper bound of the char buffer beforehand, as if I know the maximum needed/to-be-used size.

  [1]: https://arduino-esp8266.readthedocs.io/en/latest/faq/a02-my-esp-crashes.html#other-causes-for-crashes

body:
If you size the buffer to be able to hold your final string, then yes, that method will avoid the fragmentation caused by the `String` concatenation function.

Note that `String` holds the string as a C-style char array internally; it is the concatenation procedure which dynamically allocates and deallocates memory, causing the fragmentation.


body:
Your method would *reduce* the fragmentation. But will your application need do this once? A few times? Must it run forever? If your application uses malloc()/free() or new/delete pairs often, it will fragment the heap, causing it to grow, and eventually cause a stack collision. This is not so much about the Arduino being a resource-limited device; it will eventually happen in any continuously running device with a fixed amount of memory.

If you can set an upper bound to the buffer requirements, then pre-allocating a buffer-pool globally, locally as a file-level- or local-static, or on the heap (using malloc() [1]) - an array of "big-enough" buffers and enough of them for your application. Then always allocate/de-allocate one of these and you will avoid fragmentation. Your application (or buffer-handler library) will have to keep track of which buffers are free and which are in use, just as the system allocators do. But in exchange for writing this way, you get to allocate and deallocate memory, forever, fragmentation-free. Every request, and every return is the same size, so any free piece can fill a request with no need to grow the pool.

My personal preference is a static allocation (file-level or globally visible) because 1) it comes from lower memory which has the same effect as allocating it on the heap, and 2) it is declared as an array of arrays so array-indexing syntax works without manually having to write around it as you might if you malloc()ed on big chunk.

Note[1]: Though I have cautioned against using malloc() and free() calls, here and elsewhere on the site, the cause of fragmentation is repeated allocation and de-allocation from/to the heap. In this case, though, I'm suggesting using malloc() to allocate memory which will be kept for the rest of the program run.


message:
Shutdown the LED of my GY-85 sensor

I would like to shutdown the LED of my GY-85 (gyroscope) component. Is it possible?

body:
According to [this schematic][1], no. The LED is connected directly to power.

You will need to physically remove the LED to turn it off.

  [1]: http://www.haoyuelectronics.com/Attachment/GY-85/GY-85-SCH.jpg


message:
"not declared in this scope" error message

Error message `'dir1PinL' was not declared in this scope.` keeps coming up. Any ideas?

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

    #include "Arduino.h"

    /*motor control*/
    void go_Advance(void)  //Forward
    {
      digitalWrite(dir1PinL, HIGH);
      digitalWrite(dir2PinL, LOW);
      digitalWrite(dir1PinR, HIGH);
      digitalWrite(dir2PinR, LOW);
    }

    void go_Left(void)  //Turn left
    {
      digitalWrite(dir1PinL, HIGH);
      digitalWrite(dir2PinL, LOW);
      digitalWrite(dir1PinR, LOW);
      digitalWrite(dir2PinR, HIGH);
    }

    void go_Right(void)  //Turn right
    {
      digitalWrite(dir1PinL, LOW);
      digitalWrite(dir2PinL, HIGH);
      digitalWrite(dir1PinR, HIGH);
      digitalWrite(dir2PinR, LOW);
    }

    void go_Back(void)  //Reverse
    {
      digitalWrite(dir1PinL, LOW);
      digitalWrite(dir2PinL, HIGH);
      digitalWrite(dir1PinR, LOW);
      digitalWrite(dir2PinR, HIGH);
    }

    void stop_Stop()    //Stop
    {
      digitalWrite(dir1PinL, LOW);
      digitalWrite(dir2PinL, LOW);
      digitalWrite(dir1PinR, LOW);
      digitalWrite(dir2PinR, LOW);
    }

    /*set motor speed */
    void set_Motorspeed(int speed_L, int speed_R)
    {
      analogWrite(speedPinL, speed_L);
      analogWrite(speedPinR, speed_R);
    }

    //Pins initialize
    void init_GPIO()
    {
      pinMode(dir1PinL, OUTPUT);
      pinMode(dir2PinL, OUTPUT);
      pinMode(speedPinL, OUTPUT);

      pinMode(dir1PinR, OUTPUT);
      pinMode(dir2PinR, OUTPUT);
      pinMode(speedPinR, OUTPUT);
      stop_Stop();
    }

    void setup()
    {
      init_GPIO();
      go_Advance();//Forward
      set_Motorspeed(255, 255);
      delay(5000);

      go_Back();//Reverse
      set_Motorspeed(255, 255);
      delay(5000);

      go_Left();//Turn left
      set_Motorspeed(255, 255);
      delay(5000);

      go_Right();//Turn right
      set_Motorspeed(255, 255);
      delay(5000);

      stop_Stop();//Stop
    }

    void loop()
    {
    }

This is the entire error message:

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

    Arduino: 1.8.6 (Windows 10), Board: "Arduino/Genuino Uno"

    C:\Users\William\Documents\smartcar-lesson1\smartcar-lesson1.ino: In function 'void go_Advance()':

    smartcar-lesson1:20:16: error: 'dir1PinL' was not declared in this scope

       digitalWrite(dir1PinL, HIGH);

                    ^

    smartcar-lesson1:21:16: error: 'dir2PinL' was not declared in this scope

       digitalWrite(dir2PinL,LOW);

                    ^

    smartcar-lesson1:22:16: error: 'dir1PinR' was not declared in this scope

       digitalWrite(dir1PinR,HIGH);

                    ^

    smartcar-lesson1:23:16: error: 'dir2PinR' was not declared in this scope

       digitalWrite(dir2PinR,LOW);

                    ^

    C:\Users\William\Documents\smartcar-lesson1\smartcar-lesson1.ino: In function 'void go_Left()':

    smartcar-lesson1:27:16: error: 'dir1PinL' was not declared in this scope

       digitalWrite(dir1PinL, HIGH);

                    ^

    smartcar-lesson1:28:16: error: 'dir2PinL' was not declared in this scope

       digitalWrite(dir2PinL,LOW);

                    ^

    smartcar-lesson1:29:16: error: 'dir1PinR' was not declared in this scope

       digitalWrite(dir1PinR,LOW);

                    ^

    smartcar-lesson1:30:16: error: 'dir2PinR' was not declared in this scope

       digitalWrite(dir2PinR,HIGH);

                    ^

    C:\Users\William\Documents\smartcar-lesson1\smartcar-lesson1.ino: In function 'void go_Right()':

    smartcar-lesson1:34:16: error: 'dir1PinL' was not declared in this scope

       digitalWrite(dir1PinL, LOW);

                    ^

    smartcar-lesson1:35:16: error: 'dir2PinL' was not declared in this scope

       digitalWrite(dir2PinL,HIGH);

                    ^

    smartcar-lesson1:36:16: error: 'dir1PinR' was not declared in this scope

       digitalWrite(dir1PinR,HIGH);

                    ^

    smartcar-lesson1:37:16: error: 'dir2PinR' was not declared in this scope

       digitalWrite(dir2PinR,LOW);

                    ^

    C:\Users\William\Documents\smartcar-lesson1\smartcar-lesson1.ino: In function 'void go_Back()':

    smartcar-lesson1:41:16: error: 'dir1PinL' was not declared in this scope

       digitalWrite(dir1PinL, LOW);

                    ^

    smartcar-lesson1:42:16: error: 'dir2PinL' was not declared in this scope

       digitalWrite(dir2PinL,HIGH);

                    ^

    smartcar-lesson1:43:16: error: 'dir1PinR' was not declared in this scope

       digitalWrite(dir1PinR,LOW);

                    ^

    smartcar-lesson1:44:16: error: 'dir2PinR' was not declared in this scope

       digitalWrite(dir2PinR,HIGH);

                    ^

    C:\Users\William\Documents\smartcar-lesson1\smartcar-lesson1.ino: In function 'void stop_Stop()':

    smartcar-lesson1:48:16: error: 'dir1PinL' was not declared in this scope

       digitalWrite(dir1PinL, LOW);

                    ^

    smartcar-lesson1:49:16: error: 'dir2PinL' was not declared in this scope

       digitalWrite(dir2PinL,LOW);

                    ^

    smartcar-lesson1:50:16: error: 'dir1PinR' was not declared in this scope

       digitalWrite(dir1PinR,LOW);

                    ^

    smartcar-lesson1:51:16: error: 'dir2PinR' was not declared in this scope

       digitalWrite(dir2PinR,LOW);

                    ^

    C:\Users\William\Documents\smartcar-lesson1\smartcar-lesson1.ino: In function 'void set_Motorspeed(int, int)':

    smartcar-lesson1:57:15: error: 'speedPinL' was not declared in this scope

       analogWrite(speedPinL,speed_L);

                   ^

    smartcar-lesson1:58:15: error: 'speedPinR' was not declared in this scope

       analogWrite(speedPinR,speed_R);

                   ^

    C:\Users\William\Documents\smartcar-lesson1\smartcar-lesson1.ino: In function 'void init_GPIO()':

    smartcar-lesson1:64:10: error: 'dir1PinL' was not declared in this scope

      pinMode(dir1PinL, OUTPUT);

              ^

    smartcar-lesson1:65:10: error: 'dir2PinL' was not declared in this scope

      pinMode(dir2PinL, OUTPUT);

              ^

    smartcar-lesson1:66:10: error: 'speedPinL' was not declared in this scope

      pinMode(speedPinL, OUTPUT);

              ^

    smartcar-lesson1:68:10: error: 'dir1PinR' was not declared in this scope

      pinMode(dir1PinR, OUTPUT);

              ^

    smartcar-lesson1:69:11: error: 'dir2PinR' was not declared in this scope

       pinMode(dir2PinR, OUTPUT);

               ^

    smartcar-lesson1:70:11: error: 'speedPinR' was not declared in this scope

       pinMode(speedPinR, OUTPUT);

               ^

    exit status 1
    'dir1PinL' was not declared in this scope

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

body:
It doesn't look like you've created any variable with that name in your code.  That's what that error message usually means.  You must create a variable and give it a value before you can use it elsewhere.  Go find any good C++ tutorial and go through the first bit of it and you will learn these sorts of basics pretty quick.

Your code would need a line at the top that looks something like:

    int dir1PinL = 2

or whatever number value you want that variable to have depending on what pin you're actually talking about there.  Similar for the other variables you are trying to use.


message:
ESP8266 12-E can't connect to any Access Point with converted variables from strings to char arrays

**I'm using an esp8266 12-E nodemcu**
I wrote a code that scans the available WiFi networks, print them through serial communication,ask the user which network he wants to connect to and then the password for that network. The problem is that the nodemcu won't connect to that network. I think that the problem is when I convert the strings **buffer_pw** and **buffer_ssid** to the char arrays **password** and **ssid**. Why does it give problems to connect?

    #include <ESP8266WiFi.h>

    int num_ap; //number of access points
    String buffer_ssid = "empty"; //temporary stores the ssid in here because then it has to be converted in a char array
    String buffer_pw = "empty"; //temporary stores password and same thing as^^
    bool askPW = false; //"Did I already ask the password?"
    bool connesso = false; //"Did I already connect?"

    void setup()
    {
      Serial.begin(9600);
      WiFi.mode(WIFI_STA); //put the nodemcu in sta mode so that it can connect to access points
      WiFi.disconnect();   //it disconnects from any access point it was connected to
      Serial.println("Setup completo");
      num_ap = WiFi.scanNetworks(); //scans for access points
      if (num_ap == 0)   //if there aren't any access points available
      {
        Serial.println("Nessun Access Point rilevato");
      }
      else //if there are some access points available
      {
        Serial.println("Access Point rilevati:");
        delay(200);
        for (int i = 0; i < num_ap; i++)
        {
          Serial.println(" ");
          Serial.print(i + 1);
          Serial.print(") ");
          Serial.print(WiFi.SSID(i)); //print access point's ssid
          Serial.print(" ");
          Serial.print("(Potenza segnale: ");
          Serial.print(WiFi.RSSI(i)); //prints access point's rssi(strength of signal)
          Serial.print(")");
          delay(50);
        }
        delay(500);
        Serial.println(" ");
        Serial.println(" ");
        Serial.println("A quale Access Point ti vuoi connettere?");

      }
    }

    void loop()
    {
      if (buffer_ssid == "empty") //if the variable has the standard value "empty" so if the user has already given an ssid. I need this to execute  this piece of code once
       {
        if (Serial.available() > 0)
         {
          buffer_ssid = Serial.readString();  //stores user input(the ssid) in buffer_ssid
          if (buffer_ssid != "empty") //if the variable isn't empty(if the code has successfully saved the ssid) prints the ssid
           {
            Serial.println(buffer_ssid);
           }
         }
       }

      if(buffer_ssid != "empty") //if the user has given an ssid
      {
       if(askPW == false) //if the code has asked the password(I need this in order to execute this piece of code once)
        {
         Serial.println("Inserire la password per connettersi all'Access Point, se non serve premere spazio e invio"); //"insert the password"
         askPW = true;
        }
        if (Serial.available() > 0)
        {
          buffer_pw = Serial.readString(); //saves user input(the password) in the variable buffer_pw
          if(buffer_pw != "empty") //if the code has successfully saved the password so it hasn't the standard value "empty"
          {
            Serial.println(buffer_pw);
          }
        }
      }

      if (buffer_pw != "empty" && buffer_ssid != "empty") //if buffer_ssid and buffer_pw aren't "empty", so if the user inserted them
      {
        if(connesso == false) //in order to execute this piece of code once
        {
         //converts the strings buffer_ssid and buffer_pw in char arrays(I have to do this because WiFi.begin() doesn't accept strings)
         char ssid[buffer_ssid.length()];
         buffer_ssid.toCharArray(ssid,buffer_ssid.length());
         char password[buffer_pw.length()];
         buffer_pw.toCharArray(password,buffer_pw.length());
         //start connecting
         Serial.println("Connessione in corso");
         Serial.println(ssid); //prints ssid
         Serial.println(password);//prints password so I know that they were converted succesffully
         WiFi.begin(ssid,password);//start connecting
         while(WiFi.status() != WL_CONNECTED) //while it's not connected
         {
          Serial.print(".");
          delay(500);
         }
          Serial.println("Connesso!"); //"Connected!"
          Serial.println("Il mio ip locale: ");
          Serial.print(WiFi.localIP()); //nodemcu's local IP

        }
        connesso = true;  //set connesso to true so that this piece of code doesn't loop
      }
    }

body:
Problem is that you set to `toCharArray` the length of the String. But the second parameter is the maximum allowed length of the output and there is then no space for the terminating zero and string is cut at last character.

The function toCharArray knows the size of the String. The second parameter should be the size of the char array `buffer_ssid.toCharArray(ssid, sizeof(ssid));`

And next problem could be that you copy the CR/LF characters from input into ssid and password. You can see it in debug printouts.


message:
Arduino Uno won't upload code and overheats

We are using an Arduino Uno R3 connected via USB to a computer. The main problem is that we can't upload any code to the board. We get this error in the Arduino IDE console:

> avrdude: ser_open(): can't open device "\.\COM1": The system cannot find the file specified
Problem uploading to board. Visit http://www.arduino.cc/en/Guide/Troubleshooting#upload

My computer may not recognize the board, the IDE won't find any port (COM) and on the board I got the three LEDs turned on, they don't even blink, they stay turned on as long as I have connected the Arduino to the computer. Apart from that, the Arduino heats too much and too fast. I don't have anything connected to it yet. I've tried resetting the board with its built-in button, I've also tried changing the USB cable, even the computer, different system architecture and OS. I don't to want to mess up the board even more, so I don't know what to do. Could you point out what's the problem with my board?

If you need more information, I will try to post as much as you need to help me out.

body:
The fact that it doesn't blink the LED when plugged in or reset indicates that the bootloader of the main microcontroller no longer works.
The fact that the computer no longer recognizes the board as a serial port means that the USB-to-Serial interface doesn't work.
The fact that it heats up tells you that at least one of the chips on the board is dead.

I'm afraid that you'll have to get yourself a new Arduino.


body:
First of all (with unplugged Uno) visually (and maybe with help of some magnifying glass) check, that really there is nothing stuck there, what should not be (tin ball, pice or wire or such) and that all copper lines on PCB are OK (and not shorted or broken). Also check all chips, resistors etc. are visually clean, good soldered and undamaged. If something looks damaged or burned, the it is probably damaged and should be replaced anyway.

If you connect it (I suggest USB charger, to be sure to not damage computer) and the main chip (MCU) is hot, I think, that it is dead.

If some other chip is hot and MCU not so much, then maybe the MCU is not dead, but something else is broken. (probably the hot part, but maybe also some resistor/capacitor shortcuted)

The way it is now makes it is dead for you anyway, so there is not much to came worse.

I would try to connect it only to USB charger (to not damage expensive computer by bad luck) and measure voltage on various points of the board (from ground). There should be 5V straight at 5V pin, also on the same 5V on ISP head, one pin of USB connector and on all power pins on MCU and the other chip between it and USB (new R3 have some atmega there too).

Take schema for that and try to measure on the right places. Be carefull to not shortcut anything with your voltmeter rod (it is easy to connect two legs with it and it may damage something not damaged yet). You can try to check voltage anywhere safely, on some places there should be 0V, on some 5V, but in default setup (no program working yet) the i/o pins are INPUT on boot, so just High resisteance and no strong voltage on them (you should get probably weak 0V until there is some interference).

If you identify (or thing so) wrong part, you can try to replace it with new one - good training even if you botch it and you risc youst price of the new part. Even the MCU can be changed with good soldering pen and some effort. The schema is simple, but the legs are tiny and many of them.

As it is effectively dead for you now, the worse what can happen is, that you burn the new part too and throw it all away (as you would anyway). The best what can happen is that you repair it and it will work flawlessly.

I build some "arduinos" from the SMD chip and other parts on home made PCBs - all worked well. So If you want some entertainment and practise, it is not bad think to try.

If you do not want risc the price of new MCU, but want the practise, yout take away and thyen resolder the (already broken) MCU - it would not repair it, but you can see for yourself, if you think you are able do similar experiments and if you enjoy it.

---

I found, that some chineese cheap clones have voltage stabilisers, that can break on shortcut and then do anything (usually the output is then shortcuted to input, so the power goes full where only stabilised 5V should be, but also can shortcut to ground, burn to total resistance, or something random between)

It is usually not good idea have arduino connected to two powersources (like external power source for servos AND USB for programming it) at the same time, as there may be different voltage on both and big currents between in some cases. If you need more power for servos (or something) and USB for serial/programming, then better there should be no direct connection between the external source power and Arduino +5V/+3.3V or any pin - just common ground, everything other separated by at least transistor (base on pin, collector on external source) or so.


message:
How to connect Mg995 and arduino nano since nano can only output 40mA at max?

<h>Datasheet for Mg995 shows:</h1>

    Current draw at idle 10MA
    No load operating current draw 170MA
    Stall current draw 1200MA

Maximum current that an arduino nano can output is 40mA.
So, what intermediary component should I use to make the connection between the two work?

body:
The servo has 3 Pins to connect: Vcc, GND and PWM. The power, which actually drives the servo is drawn through the power lines Vcc and GND. The PWM pin, which is connected to an Arduino output pin, does not draw mich current. It is only for the PWM (-like pulsed) signal, which tells the servos driver, which angle is requested. But you should not power the servo through the Arduino. You have to connect it directly to a power supply with the correct voltage, because some parts of the Arduino can get fried, when drawing too much current through it.

So all in all: Connect the PWM pin directly to an Arduino output pin and supply the power from the source directly to the servo, not going through the Arduino.