body:
It is very unclear what you are trying to achieve here. You are clocking
the ADC at its maximum frequency, which has it take one reading every
13 µs, and yet you are delaying for 10 ms after sending one
reading through the serial port. So basically your Matlab program is
getting one reading out of every 769 you take.

If you want fast data acquisition with a consistent sampling frequency,
you basically have two options:

* clock the ADC as fast as you dare, buffer the data in RAM and, when
  the buffer is full, send it to the host computer
* set a high baud rate and take the data as fast as the UART can send
  it.

The first option allows for faster sampling rates, but only as short
bursts, as limited by the available RAM. Given what you have already
written I assume you want continuous acquisition, and thus the second
option. I also assume you are using an Arduino Uno or similar.

At 115.2 kb/s (actually 117.647 kb/s given the rounding), every bit sent
takes 136 CPU cycles, or 8.5 µs. One byte takes 10 bits
(start bit + 8 data bits + stop bit), i.e. 85 µs.
This means there is no point in clocking your ADC that fast: you can set
the prescaler to 64 and each reading will take 52 µs.

What I would do here is configure the ADC to be triggered by
Timer 1, and have that timer deliver the trigger signal every
1360 CPU cycles _exactly_. Then,

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

    ISR(ADC_vect)
    {
        Serial.write(ADCH);
    }

assuming of course you have set the left-adjust mode (`ADLAR` bit in
`ADMUX`).

With the ADC and the UART working at the very same frequency, you keep
the UART busy without ever filling the output buffer. If your ADC runs
faster than the UART, the buffer will fill out and your timings will get
nasty. On the other hand, if you are really confident in your timings,
you could skip the `Serial` managing of that buffer and just do
`UDR0 = ADCH` in the ADC ISR.


sender: user

message:
Problem with Micro SD card breakout

I was connecting my arduino uno to a adafruif micro SD card breakout and everything worked just fine, i could read the sd, write to it and see all the info about it. To do it i just followed the tutorial in [here](https://learn.adafruit.com/adafruit-micro-sd-breakout-board-card-tutorial/library?view=all).

My problem is that when I arrived home the exact some thing wouldn't work and I couldn't read the SD card anymore.

 I was thinking it could be a bad contact problem since sometimes i get:

    Initializing SD card...initialization failed. Things to check:
    * is a card inserted?
    * is your wiring correct?
    * did you change the chipSelect pin to match your shield or module?

And other times (almost never), i would just get:

    Initializing SD card...Wiring is correct and a card is present.
    Card type: SD2
    Could not find FAT16/FAT32 partition.
    Make sure you've formatted the card

I would like to know if I can assume it is the breakout board failling and I would buy a new one, or if it can be any other thing.

Thank you in advance!

sender: assistant

body:
Did you try:

 1. Reading the SD card in your computer ... if  you can read (or write) files, that means the SD card is intact
 2. Use a SD card that worked before or similar. Some bigger SD cards (like SDHC, SDXC have less good compatibility). Preferably use a 2 GB or smaller card (unless you have used bigger cards successfully and of the same or smaller type, e.g. SD, SDHC, SDXC).
 3. Try different formattings, like FAT, FAT16, FAT32. I think FAT is the mostly recognized formatting.
 4. Check connections/wires to/from SD breakout, maybe during your leave accidentally you (or someone else) or due to pressure/tension, a contact/wire got loose.
 5. Check another SD card in the SD breakout where the SD card you know is good. If this also does not work, it must be the breakout (or Arduino).
 6. Replace every piece of hardware (including wires) one by one and recheck if it works (after you are sure the SD card itself is ok).


message:
Communication between Genuino Zero and Arduino Uno using UART

I want to make my Arduino Uno and Genuino Zero communicate using UART. My Genuino Zero is the transmitter and the receiver is the Arduino Uno.

For the Arduino Uno, I am using the SoftSerial library. I have uploaded the transmitter and receiver codes.

My connection is as below:

>Genuino Zero (RX) pin 0 ---------------- Arduino Uno pin 11
>
>Genuino Zero (TX) pin1  ---------------- Arduino Uno pin 10
>
>Ground ----------------------------------   Ground

The Arduino Uno's pin 10 is Rx and pin 11 is Tx, using SoftSerial.

The transmitter transmits 'a'. The receiver receives 'a' and turns a LED on. My problem is that on the receiver, I am not getting anything.

My code is here:

https://www.dropbox.com/s/4w8o2h2k4zs0it5/transmitter.txt?dl=0
https://www.dropbox.com/s/d50uizoz3iove9w/receiver.txt?dl=0

-------------------receiver---------------------

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(10, 11); // RX, TX

    /* Simple Serial ECHO script : Written by ScottC 03/07/2012 */

    /* Use a variable called byteRead to temporarily store
       the data coming from the computer */
    byte byteRead;

    void setup() {
    // Turn the Serial Protocol ON
      Serial.begin(9600);
       mySerial.begin(9600);
      pinMode(LED_BUILTIN, OUTPUT);
    }

    void loop() {
      char a[8];
      /*  check if data has been sent from the computer: */
      if (Serial.available()) {
        /* read the most recent byte */
        byteRead = Serial.read();
        Serial.print("rushin\r\n");
        /*ECHO the value that was read, back to the serial port. */
        if(byteRead == 0x61) {
          digitalWrite(LED_BUILTIN, HIGH);
          Serial.write(byteRead);
        }
      }
      if (mySerial.available()) {
        /* read the most recent byte */
        byteRead = mySerial.read();
        mySerial.print("rushin\r\n");
        /*ECHO the value that was read, back to the serial port. */
        if(byteRead == 0x61) {
          digitalWrite(LED_BUILTIN, HIGH);
          mySerial.write(byteRead);
         }
      }
    }

    -------------------transmitter----------------------------------

    /*
      DigitalReadSerial
     Reads a digital input on pin 2, prints the result to the serial monitor
     This example code is in the public domain.
     */

    // digital pin 2 has a pushbutton attached to it. Give it a name:
    int pushButton = 7;
    // the setup routine runs once when you press reset:
    void setup() {
      // initialize serial communication at 9600 bits per second:
      Serial.begin(9600);
      // make the pushbutton's pin an input:
      pinMode(pushButton, INPUT);
    }

    // the loop routine runs over and over again forever:
    void loop() {
      // read the input pin:
      int buttonState = digitalRead(pushButton);
      // print out the state of the button:
      Serial.println("a");
      delay(1000);
      // delay in between reads for stability
    }

body:
Your Arduino Zero transmitter code transmits to the USB Serial ('Serial') only. If you want it to transmit to the serial comm on pin 0 and pin 1, you must have it write to Serial1. (Check variants.cpp file ) you will see that Serial1 is uses SERCOM0 which is on pin 0 and 1.

So, Your code should look like this (noitce "Serial" is replaced with "Serial1"):

    void setup() {
      // initialize serial communication at 9600 bits per second:
      Serial1.begin(9600);
      // make the pushbutton's pin an input:
      pinMode(pushButton, INPUT);
    }

    // the loop routine runs over and over again forever:
    void loop() {
      // read the input pin:
      int buttonState = digitalRead(pushButton);
      // print out the state of the button:
      Serial1.println("a");
      delay(1000);
      // delay in between reads for stability
    }


message:
Arduino UNO USART problems

I need to send 6 bytes value from Arduino UNO to the [actuator][1] using serial port in order to make it extends. I have added a button to send the data. For example, 0 20 1 1 0 0. The communication settings are 9600 baud rate, 8 data bits, no parity and 1 stop bit. I have used MAX 232 to build a TTL to RS232 circuit. The actuator does not move. Are there any problems on my program? I am new to create USART code. I think I have some problems on transmit function. I am using the build in USART with c code. Here is my code:

 #define BAUD_PRESCALER 0x67
 int buttonPin1 = 4;
 int buttonState1 = 0;

 void setup() {
  // put your setup code here, to run once:
  pinMode(buttonPin1, INPUT_PULLUP);
 }

 unsigned char data1 = 0x00; // 0
 unsigned char data2 = 0x14; // 20
 unsigned char data3 = 0x01; // 1
 unsigned char data4 = 0x01; // 1
 unsigned char data5 = 0x00; // 0
 unsigned char data6 = 0x00; // 0

 void USART_Init(void) {
  /*Set baud rate */
  UBRR0 = BAUD_PRESCALER;
  UCSR0A = 0x00;
  /*Enable receiver and transmitter */
  UCSR0B = 0x08;
  /* Set frame format: 8data, 1stop bit */
  UCSR0C = 0x06;
 }

 void USART_Transmit( unsigned char data ) {
  /* Wait for empty transmit buffer */
  while ( !( UCSR0A & (1<<UDRE0)) )
  {
   ;
  }
  /* Put data into buffer, sends the data */
  UDR0 = data;
 }

 void loop() {
  // put your main code here, to run repeatedly:
  buttonState1 = digitalRead(buttonPin1);
  if (buttonState1 == LOW)
  {
   USART_Init();
   USART_Transmit(data1);
   USART_Transmit(data2);
   USART_Transmit(data3);
   USART_Transmit(data4);
   USART_Transmit(data5);
   USART_Transmit(data6);
  }
 }

  [1]: http://www.zaber.com/wiki/Manuals/T-LA#Initial_Setup_and_Testing

body:
I would recommend you to use the arduino's built in UART library. Try this code:

    int buttonPin1 = 4;
    int buttonState1 = 0;

    unsigned char data1 = 0;
    unsigned char data2 = 20;
    unsigned char data3 = 1;
    unsigned char data4 = 1;
    unsigned char data5 = 0;
    unsigned char data6 = 0;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);           // set up Serial library at 9600 bps
      while (!Serial);              // wait till UART initialized, for arduino UNO

      pinMode(buttonPin1, INPUT_PULLUP);
    }

    void loop() {
        // put your main code here, to run repeatedly:
        buttonState1 = digitalRead(buttonPin1);
        if (buttonState1 == LOW)
        {
            Serial.write(data1);
            Serial.write(data2);
            Serial.write(data3);
            Serial.write(data4);
            Serial.write(data5);
            Serial.write(data6);
        }
    }

You should know that as long as the button is pressed data is being sent to the actuator. With that being said, with one button press you may have the commands sent 10 times. Thus, you have to deal with that in your code.


body:
The first thing I do when I have a transceiver that doesn't work is a loopback test. This rules out a lot of potential issues like the wrong pin being used or MAX 232 not being connected correctly.

Receiving your transmission on a PC using USB to RS232 adapter (if you have one) would also be a helpful test.


body:
I think that your BAUD rate setting is wrong. The `UBRR0` register is a 16 bit wide one thus should be accessed in two 8 bit part, via `UBRR0H` and `UBRR0L`. You can check it in the [datasheet][1].

If you further check the datasheet there is an example code in addition to the USART description which shows a correct way of initialization.

>     #define FOSC 1843200 // Clock Speed
>     #define BAUD 9600
>     #define MYUBRR FOSC/16/BAUD-1
>     void main( void )
>     {
>         ...
>
>         USART_Init(MYUBRR)
>         ...
>     }
>
>     void USART_Init( unsigned int ubrr)
>     {
>         /*Set baud rate */
>         UBRR0H = (unsigned char)(ubrr>>8);
>         UBRR0L = (unsigned char)ubrr;
>         /* Enable receiver and transmitter */
>         UCSR0B = (1<<RXEN0)|(1<<TXEN0);
>         ...
>     }

As you can see the UBRR's value is calculated using the system clock speed `FOSC`, with `MYUBRR` macro which is an equation from the datasheet. Later this value is being set in two part upper 8 bit:

    UBRR0H = (unsigned char)(ubrr>>8);

lower 8 bit:

    UBRR0L = (unsigned char)ubrr;

(Your transmit function seems to be correct. And as I commented it is enough to call the USART init once in the `setup()`.)

  [1]: http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf


message:
What is the phase of tone?

Is it garanteed (with some precision) that the phase of a PWM-signal generated by `tone` is the same on each pin? Can it be altered (by internal means of Arduino) so that it's different on different pins?

I'm looking for a way to adjust phases of signals from several pueso-buzzers by either adjusting distances (least preferrable) or programmaticaly (most preferrable) or by external components (if they're not very complicated).

body:
The [arduino.cc description of `tone()`](https://www.arduino.cc/en/reference/tone) says “Only one tone can be generated at a time”, so presumably you are using some other software to generate tones on multiple pins.  For example, [Brett Hagman's `play()` code](https://code.google.com/archive/p/rogue-code/wikis/ToneLibraryDocumentation.wiki), which Arduino `tone()` is derived from, uses multiple timers, one per tone.

When using `play()`, you probably can adjust phase by calling  [`delayMicroseconds()`](https://www.arduino.cc/en/Reference/DelayMicroseconds) between the two  `play()` calls that start up the tone generation; for example:

    play(11, 440);
    delayMicroseconds(235); // Move 2nd tone 8 cm closer
    play(9, 440);

Note, because `tone()` and `play()` use one timer per output (for example, timer 2 for first tone, timer 1 for next tone, timer 0 for third tone) there usually will be some timer prescale mismatches between 8-bit and 16-bit timers, which may result in slightly different frequencies, leading to some constant phase shift rate if you use that method.

With the speed of sound about 340.29 m/s in air at standard pressure, the wavelength of say 440 Hz would be under a meter, so I presume you would move speakers just a few tens of cm for phasing; hence a few hundred to a few thousand microseconds of phase offset.  If you want good programmatic control, and also want to have quite a few speakers, external hardware in the form of a delay line or a bucket brigade chip is an obvious approach.

You could simulate a program-controlled delay line fairly easily using a handful of 74HC595 SIPO shift registers, as follows:  Connect the DS of the first '595 to your `tone()` output pin.  Connect the Q7S output of each '595 except the last to the DS of the following '595.

Now use another timer to repeatedly clock your tone data into the shift register chain.  That is, connect all STCP and SHCP inputs in parallel to a timer output pin.  (Eg, OC1A, OC1B, OC2A, or OC2B, which might be pins like 9–12 on an Uno or Nano).  Run that timer at 10 to 100 KHz, ie, at some rate *f* that gives you the resolution and range of phase changing that you need.

Calling the shift register outputs o₀, o₁, o₂..., we have oⱼ delayed by (j-i)/*f* seconds relative to oᵢ.  That is, successive SR outputs represent different taps for different delays.


body:
The main principle behind working with buzzers, in its simplest form, comes down to something along the lines of

    digitalWrite(buzzerPin,HIGH);
    delay(half_tone_frequency);
    digitalWrite(buzzerPin,LOW);
    delay(half_tone_frequency)

that, when repeated is enough to generate some tone on a single buzzer. However - to get desired tones (frequencies) right, you have to be mindful of the exact time that passes between each part of the code (the pin needs to oscillate in some frequency to produce a tone of that frequency)

So technically, its possible to create different sounds on different buzzers connected on different(!) pins at the same time, if you know exactly how much time each pin spends HIGH and LOW. This is naturally simpler when they do not need to be active concurrently.


body:
If you want fine control over the phases, I assume you may also care
about having low phase noise. In this case your best bet is to avoid
toggling the pins in software and go for a hardware signal generation.

With an Arduino Uno or similar board, this can probably achieved by
programming a timer. I would try the following:

Configure Timer 1 in waveform generation mode 12, i.e. CTC
mode with TOP = ICR1. Set the compare output mode of both channels
to toggle on compare match. Set ICR1 so that the timer has _half_ the
period of the signal you want. Now you can independently adjust the
phases of both outputs by writing to `OCR1A` and `OCR1B`.

Note that those registers are not double buffered in this mode, so you
have to be careful about when you write them.

The Arduino core library has no support for such timer configuration:
you will have to learn how to program it yourself. If you are not
familiar with the subject matter, I recommend you start by reading
[Nick Gammon's tutorial on timers](https://www.gammon.com.au/timers).


message:
Serial Port configuration with asio C++ library

I've made a small interface using the asio C++ library to open serial ports and do I/O from/to them.
It works with my Arduino Uno and other hardware as well (industrial weighing machines), but I only specify the port and baud rate.

The following code is run in the client application, which runs both on my Windows 10 Student Edition x86_64 machine, and on old 32 bit  Win XP machines that communicate with the weighing machines:

    /*this is inside a constructor*/
    /*iosvc gets passed by reference, port_ is a member variable of type asio::serial_port,
     npuerto is the name of the port (e.g. "COM3") */

    port_(iosvc_, npuerto),

    /*...*/

    port_.set_option(asio::serial_port_base::baud_rate(baudios));

 The Arduino is programmed to do a serial echo of whatever is sent to it, for testing purposes. This is the echo code:

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

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

It works fine with my Arduino until I unplug it and plug it back in. After replugging it all the values returned are garbage, specifically some sort of '?' character inside a black box, don't know the bit value though, but it's constant. The problem gets fixed when I open an arduino IDE Serial Port monitor.
If I close it, and once again use my own software to open up the serial port, all the values are fine.

From this I concluded that the Arduino IDE Serial Port monitor is doing something when it opens up the port that I'm not doing.

Any clues? Flow control? Handshake?
Thanks

body:
Can you include all the other calls you make related to setting up the serial port along with `asio::serial_port_base::baud_rate(baudios)`? Ideally, split that out into a separate function (that takes parameters such as baud rate) that you know is the only thing doing this setup.

As I mentioned in the comment, getting back the right number of chararacters but incorrect characters looks as if the baud rate is correct but something else is wrong. The first thing that comes to mind is the bits/parity/stop bits settings. Typically you want to be using 8 bits, no parity, often referred to as "8N1".


message:
How to get number of available pins in code?

Different boards have different number of pins.

Is there a way to know this number in code (at least digital and analog pins), or do I have to determine board type (like in [this thread][1]) and know the number of pins by myself?

----------

*Reasoning for this is that I'm creating prototype using Uno and using 2-3 analog pins for temperature readings, but I want to be able to use the same code for different board in the future with eg. 8 analog pins, so I don't have to remember to change pin numbers in code and maybe solder it convenient way etc. Also being able to use for eg. "last available analog pin" for certain job could help keep code/schematics nice and clean.*

  [1]: https://arduino.stackexchange.com/questions/21137/arduino-how-to-get-the-board-type-in-code

body:
In the ultimate case, a "board" is not something you can determine programmatically in software; it's not possible in general to tell if, e.g., a particular pin on the microcontroller is connected to a corresponding head pin on the board.

That said, as [Edgar Bonet point out](https://arduino.stackexchange.com/a/36683/31794), the Arduino board definitions used in the IDE will generally do what you want. Just keep in mind, these are just someone saying "the board should be like this"; a cheap clone board, for example, might be different without a new and proper board definition.

With running code on the microcontroller itself, examining what it can see of the board, you can usually tell which microcontroller you're using. But that just tells you about the chip and its pins, and not about where leads from those pins might go. It sounds to me as if you're asking to find a way to see if your particular microcontroller (e.g., an ATmega328P) is on, say, an [Arduino Uno](https://www.arduino.cc/en/Main/ArduinoBoardUno) or some other board where certain MCU pins may or may not be hooked up to board pins. The MCU can't tell whether any of its particular pins are connected to headers on the board. As a more specific example, someone could build a board with an MCU with 100 digital IO pins available, yet if only ten of these are brought out to pins on the board, the others are not easily usable.
uino.cc/en/Main/ArduinoBoardUno) or [Arduino Nano]

For your application, you're thinking in a good direction when considering how to make things easier for others using your code. However, I'd suggest that in the long run it's better just to have clear definitions in an obvious place in your sketch (at the top of the file in a single-file sketch, perhaps in a `config.ino` in a multi-file sketch, or passed in to an initialization function for a library) that says explicitly what pins are used and is easy to change for others. Having the default pins used by the sketch move around if I load the sketch on a different board strikes me as rather confusing.

Keep in mind your audience: the people who are going to be using this on a board different from yours are Arduino hobbyists, and so they're already (or will soon become :-P) familiar with the idea of pins, pin definitions in code, and pin conflicts.


body:
It is quite easy actually:

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

    Serial.print("number of digital pins: ");
    Serial.println(NUM_DIGITAL_PINS);
    Serial.print("number of analog inputs: ");
    Serial.println(NUM_ANALOG_INPUTS);

Note that these are compile-time constants defined as macros in a file
named `pins_arduino.h`. There is one such file for every board supported
by the Arduino environment. Just to take Curt J. Sampson's example, if
someone “made a board with an MCU with 100 digital IO pins available,
yet if only ten of these are brought out to pins on the board”, then the
macros would tell you you have 10 digital pins. Assuming of course that
you installed the proper support package for that particular board.


body:
You can identify the host processor at run time - each one has its own signature - but not necessarily the board it's running on (consider an Uno and a breadboard-uino for example). So you'd have to make each kind of board you use distinguishable in some way, such as jumpering 3 pins each high or low to make a 3-bit binary code representing one of 8 board types. The next solution is to define that code or some other identifier at compile time with a #define statement, and use the identifier in one or more #ifdef statements to compile board-specific pin definitions.

If you plan on using standard boards the IDE knows about, the IDE pre-defines some useful symbols for you. Here's the compile command the IDE used for an empty sketch for an UNO (I've reformatted it for readability):

    "/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-g++"
    -c
    -g
    -Os
    -Wall
    -Wextra
    -std=gnu++11
    -fpermissive
    -fno-exceptions
    -ffunction-sections
    -fdata-sections
    -fno-threadsafe-statics
    -MMD
    -flto
    -mmcu=atmega328p
    -DF_CPU=16000000L
    -DARDUINO=10612
    -DARDUINO_AVR_UNO
    -DARDUINO_ARCH_AVR

The last four lines make the equivalent of #defines for the clock-frequency, the IDE version number, the Arduino-board, and the overall MCU architecture, respectively.

So in your code, a block like:

    #ifdef ARDUINO_AVR_UNO
       // pin definitions for Uno here
    #endif

will only be compiled if you selected "Arduino/Genuino Uno" as your board type in the IDE. There are similar symbols for other board types. So for a Nano, `ARDUINO_AVR_NANO` would be defined instead.


message:
Trying to make a wattmeter

I've been trying to make a wattmeter using arduino but cannot find the shield I need to buy to put onto my arduino to make it. There are no such parts in the Arduino Store and online the best I could find is [this][1]. This measures the arduino's energy consumption, however, not other things. I am really new at this and thoroughly lost. I would be really glad if someone could help me with this problem :)

  [1]: http://www.robotshop.com/en/energy-monitor-shield-arduino.html?gclid=CJD6jtrgiNMCFQmqaQody_0CPQ

body:
You will need an Ampere meter and a Voltmeter. Watts is `Volt` * `Ampere`.

There are logic level compatible units out there for ampere meters ranging from a few mA to at least dozens of Amperes.

Also for voltmeters there are several logic level compatible units available, to plug in your project.

The rest is math. (Watts = A * V )


message:
Single-channel serial communication

I'm trying to communicate with a device which only uses a single wire at 9600 Baud. How can I use my Arduino UNOs RX/TX-Pins to recieve and transmit on that one wire?

body:
Bidirectional Asynchronous Serial schemes are not uncommon.  The famous ones, like RS485, utilize special line drivers and differential signalling, but for short distances you can accomplish something similar using the ability of most MCU's, including the Arduino's ATmega, to tristate the serial transmit pin.

Essentially, you would wire the shared line to both the receive and transmit pins, and when it is not the Arduino's "turn" to transmit, you would configure the Transmit pin as an *input* rather than as an output.

It's then up to a software protocol to make each node transmit at only the appropriate time.  Often a bus master can transmit essentially at whim, and subservient device(s) are only allowed to transmit in reply to specific queries from the master.  Of course the master should not transmit when it has just request a reply.

Also note that you cannot change the pin over to input mode when the last character is *loaded* into the UART, rather it has to stay in output mode until the last sent character has been clocked out onto the wire.

While putting a resistor between the transmit pin and the shared line could provide some theorectical safety against bus contention introduced by software errors, in practice the hardware will typically survive such conflicts during development, and having too large a resistor there may cause problems with signal quality.  If you are going to use a resistor, it should be sized for source termination of the line impedance, *not* for electrical protection.  You may also want a weaker pulling resistor to give the bus a known state when no one is driving it.  If this state matches the last driven one, the resistor won't have to overcome capacitance to "drive" the line, but rather merely "hold" it in the last driven position.

If you are using a device like the Uno which has only one hardware serial interface, you will have to decide if you are going to use the hardware interface at the cost of breaking the ability to use that to debug or upload sketches, or if you are going to use a software UART ("Software Serial" or its variants) on arbitrary digital pins.  If you do the later, it would be entirely possible to rework a library to receive and transmit on the *same* pin, rather than requiring two distinct ones.


message:
Creating a queue in Arduino?

Does anyone know if there is a way to create a queue of some sort for arduino?

My project consists of simulating multiple traffic lights with crossing pedestrians on an Arduino breadboard. Since I need to assume the situation where on all sides are cars waiting + pedestrians having pressed the button, I needed to figure out a way to store these inputs into an array of some sort.

However, the problem with array I believe is that it doesn't allow me to shift the data to the left, so that the next one will be selected in the queue. Deleting the data inside an array would only merely make it null, which doesn't work.

Greatly appreciated if someone can help me by pointing to the right direction.

body:
Regarding how to “create a queue of some sort for Arduino”, about the first thing to settle is how many items may need to be queued.  On a typical personal computer with gigabytes of RAM, queue size often is not much of an issue ... one just allocates a few more megabytes whenever necessary.  On an typical Arduino, however, with a few kilobytes or few tens of kilobytes of RAM, use of dynamic (heap) allocation is risky unless you carefully analyze possible execution paths.

If you are ok with a fixed queue size, the next issue is what kind of queue, eg FIFO, LIFO, priority, etc.  The question's concern about a “shift the data to the left, so that the next one will be selected in the queue” issue suggests a FIFO (first in first out) queue is desired.  For this, a [circular buffer or circular queue](https://en.wikipedia.org/wiki/Circular_buffer) is a relatively-low-overhead method often used.  Using terms from the wikipedia article, Start and End pointers are maintained, marking next-data-out and last-data-in positions.  Via modular arithmetic or `if` tests, each of these pointers wraps to array front whenever it goes past the array end.   The queue is empty if `Start == End` (modulo N, if queue size is N) and full if `Start == End+1`.

If an interrupt-driven process can modify pointers asynchronously to the main thread of execution, then synchronization methods need to be used to ensure atomic updates of pointers.  (This is true for all kinds of queues, not just circular ones.)

If instead of a FIFO queue you need a priority queue, a [binary heap](https://en.wikipedia.org/wiki/Binary_heap) is easy to implement. Usually [Fibonacci heaps](https://en.wikipedia.org/wiki/Fibonacci_heap) and [binomial heaps](https://en.wikipedia.org/wiki/Binomial_heap) are not worth the extra trouble of implementing, except when you need efficient heap merging or secondary operations like decreasing keys of elements.  The [Summary of running times](https://en.wikipedia.org/wiki/Binomial_heap#Summary_of_running_times) section of wikipedia's binomial heap article shows the complexity of different operations across different heap structures.  Note that with Arduino RAM being so limited, a complexity difference like Θ(log n) vs Θ(1) is negligible; simplicity of code, leading to a compact implementation, is more important.

Note, also see [*QueueList Library For Arduino*](http://playground.arduino.cc/Code/QueueList) at arduino.cc.  This library apparently uses dynamic allocation.  It provides methods `push(), pop(), peek()` et al.  Also see [*QueueArray Library For Arduino*](http://playground.arduino.cc/Code/QueueArray) at arduino.cc, which provides the same methods as *QueueList*, plus `enqueue` and `dequeue()` as synonyms for `push()` and `pop()`.  Where *QueueList* uses lists to build its data structures, *QueueArray* uses arrays.

[*OsWrap* at arduino.cc](http://playground.arduino.cc/Code/OsWrap) is a heavy package (eg 15KB flash, 1.5KB RAM) that supports various message and priority queue structures.

Depending on your rationale for using a queue, [*Task Scheduler Library*](http://playground.arduino.cc/Code/TaskScheduler) may also be of interest.

As noted in Mikael Patel's comments above, [Cosa](https://github.com/mikaelpatel/Cosa) platform software includes a [Queue](https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/Queue.hh) class, which is a “Template class for ring-buffer for queueing data elements”, with usage of the class illustrated in an [Event](https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/Event.hh) class, which in turn is used in a [Job](https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/Job.hh) class.


body:
I wrote a simple queue library some weeks ago, you can find it in the arduino library manager, or here:
[Queue](https://github.com/SMFSW/Queue)

I think you need FIFO implementation, but LIFO is also implemented in the lib & possibility to overwrite previous records when full.
It can handle any structure or data type (as long as it's size is fixed for memory allocation), defining a number of records in the queue, then you're good to go.

2 methods are implemented to interact with the queue, push() & pull().
I'll probably add a peek() later on if needed.

I also noticed this other FIFO only queue lib in the library manager when I commited mine: [MD_CirQueue](https://github.com/MajicDesigns/MD_CirQueue)

Hope this can help!


body:
I had an arduino project that I needed to build a queue for.

You can [download the source code][1] and copy into a file called `Queue.h` next to your arduino `project.ino` file.

Here is a simple interactive example (with the Serial monitor) to see how its used, make sure you set the `baud rate` to 115200 and `No new line`.

    #include "Queue.h":

    Queue<char> queue(10);

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

    void loop() {
      while(Serial.available()) {
        queue.push(Serial.read());
      }

      Serial.print(millis() / 1000);
      Serial.print(": ");
      int count = queue.count();
      if (count > 0) {
        Serial.print("Found ");
        Serial.print(count);
        Serial.print(" items.. '");
        Serial.print(queue.pop());
        Serial.print("' is the oldest. Next is.. '");
        Serial.print(queue.peek());
        Serial.println("'.");
      } else {
        Serial.println("Nothing to process...");
      }
      delay(2000);
    }

  [1]: https://github.com/sdesalas/Arduino-Queue.h/blob/master/Queue.h


message:
I2C broadcast and reply on Arduino M0+

I am trying to set up several ATSAM-based AVR chips in a master/slave broadcasting arrangement. I want the master to be able to send a broadcast message to I2C address 0, and then for slaves to respond with different information. I have seen other implementations where this has been successful since I2C devices will typically self-arbitrate and if they are configured to back-off when arbitration is lost, the master can repeat its request and iterate over all addresses on the bus.

The challenge is that while I have Wire.beginTransmission(0) working to reach my slaves from the master, I cannot get Wire.requestFrom(0,6) to work. The slave acts as though no message had arrived in the reply case. This is in the reduced case of one master and one slave.

In the example below, changing RequestFrom to the slave address will work.

I am aware that on the SAMD architecture, ArduinoCore does not configure the SERCOM for I2C broadcasts so I made a one-line modification as follows to enable it:

    sercom->I2CS.ADDR.reg = SERCOM_I2CS_ADDR_ADDR( ucAddress & 0x7Ful ) | // 0x7F, select only 7 bits
                          SERCOM_I2CS_ADDR_ADDRMASK( 0x00ul ) |
                          SERCOM_I2CS_ADDR_GENCEN // added by JAG

My master code:

    #include <Wire.h>

    void setup() {

      Serial.begin(9600);
      Serial.println("Sketch start" );

      Wire.begin(); // join i2c bus (address optional for master)
    }

    byte x = 0;

    void loop() {

      Serial.print("-- Top of loop:" );
      Serial.println( millis() );

      Wire.beginTransmission(0); // transmit to device #8
      Wire.write("x is ");        // sends five bytes
      Wire.write(x);              // sends one byte
      Wire.endTransmission(true);    // stop transmitting

      // delay( 500 );

      uint8_t recvSize = Wire.requestFrom(0, 6);    // request 6 bytes from slave device #8

      Serial.print( "Got bytes: " );
      Serial.print( recvSize );
      Serial.print( "---> ");

      while (Wire.available()) { // slave may send less than requested
        char c = Wire.read(); // receive a byte as character
        Serial.print( "[") ;
        Serial.print(c);         // print the character
        Serial.print( "]" );
      }
      Serial.println();

      x++;
      delay(500);
    }

 My slave code:

    #include <Wire.h>

    void setup() {
      Wire.begin(9);                // join i2c bus with address #8
      Wire.onReceive(receiveEvent); // register event
      Wire.onRequest(requestEvent); // register event
      Serial.begin(9600);           // start serial for output
      Serial.println( "Starting up" );
    }

    void loop() {
      delay(500);
        Serial.print( "In top of loop (slave): " );
        Serial.println(millis() );
    }

    // function that executes whenever data is received from master
    // this function is registered as an event, see setup()
    void receiveEvent(int howMany) {
      while (1 < Wire.available()) { // loop through all but the last
        char c = Wire.read(); // receive byte as a character
        SerialUSB.print(c);         // print the character
      }
      int x = Wire.read();    // receive byte as an integer
      SerialUSB.println(x);         // print the integer
    }

    // function that executes whenever data is requested by master
    // this function is registered as an event, see setup()
    void requestEvent() {
      Wire.write("hello"); // respond with message of 6 bytes
      // as expected by master
      Serial.println( "<<<< Writing a response." );
    }

body:
If you broadcast data using Wire.send(data), the slaves would receive this in there onReceive handler but as far as I can remember, the I2C slave will not respond on a Wire.requestFrom(...) broadcast from the master.

Imagine x slaves responding all at the same time to the request...


body:
The I2C protocol supports bus arbitration only for masters sending (if more than one master in the bus starts sending at the same time). So, if any slave device would really respond to the General call address 0 with data, the data would geht corrupted if another slave would send data too. With this background it is reasonable, why an I2C slave device wouldn't respond to a request at the General call address.

If you have too many chips in the bus or don't want to address Thema directly due to another reason, you can send a trigger message to the General call address and let the other chips send their data as masters. Keep in mind, that in this case all involved chips must implement correct bus arbitration (and I'm not sure if the Wire library supports this).


message:
Arduino : How to write a variable value into a text file and modify it in the SD card?

I want to write a variable value into a text file in the SD card and modify it while reading if needed.
I found a text reading code which reads a desired line in the text file.(not tested)

   //reading code

    #include <SD.h>

    int stepToLoad = 1;
    int endOfLineNumber = 0;
    int stepCount = 0;
    int stringIndex = 0;
    File configFile;
    char inputString [1280];
    char inputChar;

    void setup() {
      stepToLoad = 13;
      if (!SD.begin(36)) {
        return;
      }

      if (SD.exists("config.txt")) {
        configFile = SD.open("config.txt");
        getStepCount();
        getStepData();
        configFile.close();
      }
    }

    void loop() {

    }

    void getStepData() {

      if (configFile) {
        while (configFile.available()) {
          inputChar = configFile.read(); // Gets one byte from serial buffer
          if (inputChar != '^') { // define breaking char here

            inputString[stringIndex] = inputChar; // Store it
            stringIndex++; // Increment where to write next

          } else {
            endOfLineNumber++;
            stringIndex++;
            if (endOfLineNumber == stepToLoad) { //this is the correct line to load

              break; //break out of the "while" loop
            } else { //not the correct line to load, reset and continue

              stringIndex = 0;
            }
          }

        }

      }
    }

    void getStepCount() {
      if (configFile) {
        while (configFile.available()) {
          inputChar = configFile.read(); // Gets one byte from serial buffer
          if (inputChar == '^') { // define breaking char here
            stepCount++;
          }
        }
      }
    }

body:
As far as I know it is not possible to read a file and meanwhile change a value.

What normally is done is:

- Read the file
- Store it in memory
- Change the value in memory
- Write the file

However, since the SRAM memory is very limited, the following approach is better:

- For every buffer (512 bytes):
  - Read 512 bytes buffer
  - Change values in the buffer if needed
  - Write 512 bytes to another file
  - Until the end of the file to read is reached
- Remove the original file
- Change the name of the new file to the old file


body:
> How to write a variable value into a text file and modify it in the SD card?

This software design issue depends much on the chosen representation on file. In principle, there are two design dimensions. The first is textual or binary representation. The second is fixed or variable size records.

With textual representation (e.g. Serial.print) values are converted to text and stored on the file. The size of the record (e.g. line) depends on the number of characters needed for the value. New-line is often used as the record delimiter. To locate a specific record the file has to be scanned. There is no way to calculate the position of a record. When reading back the value the textual representation must be parsed and the internal representation in memory restored.

With binary representation (e.g. Serial.write) values are written directly from memory to the file. The size of the record is fixed as the size of a struct. Locating a specific record is easy; record index time record size. The SD library file.seek(position) is perfect to index the record. When reading the value back to memory there is no need for conversion as in textual representation.

It should be added that fixed size textual representation is also possible, e.g. make each line the same length by using a padding character (space, etc).

A text file with variable values is the more difficult as it is both textual representation and variable record. It is also the most inefficient as it requires compute power for the value representation conversions. The major advantage is that the text file can be generated with a ordinary text editor. No special tool or program is needed.

Binary file format with fixed records will require initialization.

Cheers!


body:
It was super complicated for me at first but I understand it now. I'll upload just the DS3231 Code with the SD card functionality

    #include <Wire.h>
    #include <DS3231.h>
    #include <SPI.h>
    #include <SD.h>

    DS3231 clock;
    RTCDateTime dt;
    File myFile;
    String fileName = "000000.txt";

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

      // Initialize DS3231
      Serial.println("Initialize DS3231");;
      clock.begin();

      // Set sketch compiling time
      clock.setDateTime(__DATE__, __TIME__);

      // Set from UNIX timestamp
      // clock.setDateTime(1397408400);

      // Manual (YYYY, MM, DD, HH, II, SS
      // clock.setDateTime(2016, 12, 9, 11, 46, 00);
    }

    void getName(){
      String date = clock.dateFormat("mdy", dt);
      fileName[0] = date[0];
      fileName[1] = date[1];
      fileName[2] = date[2];
      fileName[3] = date[3];
      fileName[4] = date[4];
      fileName[5] = date[5];
    }

    void sdCard() {
      if (!SD.begin(4)) {
        Serial.println("initialization failed!");
        while (1);
      }

      Serial.println("initialization done.");

      getName();

      myFile = SD.open(fileName, FILE_WRITE);

      if (myFile) {
        Serial.print("Writing to file...");
        myFile.println("testing 1, 2, 3.");
        Serial.println("done.");
      }
      else {
        Serial.println("error opening file");
      }
    }

    void loop()
    {
      dt = clock.getDateTime();

      Serial.print("Long number format:          ");
      Serial.println(clock.dateFormat("H:i:s", dt));

      sdCard();
      getName();

      myFile = SD.open(fileName, FILE_WRITE);
      myFile.println("Testing 1...2...3...")

    }

So what I did here was initialize the variable for the text name with placeholders and I used the date in a 6 digit format. Both variables being a string, I can set the first position of the text name to be the first position of the date. So all values are replaced. Should be the same thing for an 8 digit text name, but after that there is a limit, not including the file extension.


message:
Convert serial value into hex using in Genuino zero

hello there my code is here.

    /* Simple Serial ECHO script : Written by ScottC 03/07/2012 */

    /* Use a variable called byteRead to temporarily store
       the data coming from the computer */
    byte byteRead;

    void setup() {
    // Turn the Serial Protocol ON
      Serial.begin(9600);
    }

    void loop() {
       char a[8];
        int b;
       /*  check if data has been sent from the computer: */
      if (Serial.available())
      {
        /* read the most recent byte */
        byteRead = Serial.read();
        Serial.print(byteRead,HEX);
      }

  now when i send '12' from terminal, it prints 3132. means it is ASCII value. but i want to print 12. can you help me?? how to do it??

body:
To convert Decimal or Integer value to Hexadecimal you can go this way..

    byteRead = Serial.read();  //Read your value
    myValue =  String(byteRead, HEX); //Convert it into Hexadecimal
    Serial.println(myValue); //Print in serial Monitor
    myValue1 = String(byteRead,DEC); //Convert it ino Decimal
    Serial.println(myValue1); //Print in serial Monitor


body:
There are several issues with your sketch. The most important is the lack of understanding for the difference between internal and external representation.

The sketch reads a single character from Serial and prints the value as a hexadecimal number. The character is ASCII; a number that represents symbols in our alphabet.

Your goal is to read characters into a string and then convert the string to a number assuming that the string represents a hexadecimal number ('0'..'9' and 'a'..'f' or 'A'..'F').

The sketch should be 1) scan string, 2) parse and convert string to number, 3) print the number.

Scanning the string requires skipping whitespace and then collecting characters until a whitespace.

The sketch could look something like this:

    void setup() {
      Serial.begin(57600);
      while (!Serial);
      Serial.println(F("Serial started..."));
    }

    void loop() {
      const size_t BUF_MAX = 16;
      char buf[BUF_MAX];
      char* bp = buf;
      char c;

      // Skip whitespace
      do {
        while (!Serial.available());
        c = Serial.read();
      } while (c <= ' ');

      // Scan token until whitespace
      *bp = c;
      do {
        while (!Serial.available());
        c = Serial.read();
        *++bp = c;
      } while (c > ' ');
      *bp = 0;

      // Print scanned token
      Serial.println(buf);

      // Convert to number and print
      const int BASE = 16;
      long val = strtol(buf, &bp, BASE);
      if (*bp == 0)
        Serial.println(val);
      else
        Serial.println(F("not a number"));
    }

This allows scan of hexadecimal numbers with possible sign (as defined by `strtol`). By changing the BASE to zero `strtol` will use the notations for base definitions (prefix '0' for octal, '0x' for hexadecimal). Last, please observe the parse error handling provided by `strtol`(*bp != 0).

Cheers!


message:
Arduino restarts when a function is called

When I call a function, get_split(), the Arduino restarts. I have tried to find what is causing this, but I have had no luck. Here is my code:

    std::vector<std::vector<std::vector<std::vector<float>>>> get_split(std::vector< std::vector< float > >& dataset) {
      std::vector<int> class_values; // declares vector 'class_values'
      for (int i = 0; i < dataset.size(); i++) { // loops through each value in dataset (the dataset contains vectors)  and appends the last value in each vector to class_values
        class_values.push_back(dataset[i][dataset.size()]);
      }
      std::vector<std::vector<std::vector<float>>> b_index;
      b_index.push_back(std::vector<std::vector<float>>(999));
      std::vector<std::vector<std::vector<float>>> b_value;
      b_value.push_back(std::vector<std::vector<float>>(999));
      std::vector<std::vector<std::vector<float>>> b_score;
      b_score.push_back(std::vector<std::vector<float>>(999));
      std::vector<std::vector<std::vector<float>>> b_groups;
      for (int i = 0; i < dataset[0].size(); i++) {
        for (int j = 0; j < dataset.size(); j++) {
          std::vector<std::vector<std::vector<float>>> groups = test_split(i,  dataset[j][i], dataset); // gets the split of the dataset (assigns each vector in the dataset to either 'left' or 'right')
          float gini = gini_index(class_values, groups); // calculates the gini
          if (gini < b_score[0][0][0]) {
            b_index[0][0][0] = i;
            b_value[0][0][0] = dataset[j][i];
            b_score[0][0][0] = gini;
            b_groups = groups;
          }
        }
      }
      std::vector<std::vector<std::vector<std::vector<float>>>> vals;
      vals.push_back(b_index);
      vals.push_back(b_value);
      vals.push_back(b_groups);
      return vals; // returns the values.
    }

This code is meant to check the gini of splitting a certain function (the gini_index() function works fine). Then it calls test_split which assigns the vector values into two sub-vectors in the vector groups, left and right. Then I just choose the split with the lowest gini.

When I delete everything in the function it doesn't restart, but I have deleted the first for loop, and also the part where it returns a vector, but still no luck. Also when deleting the for loop underneath the declaration of b_groups, it still doesn't work. I don't think it is a memory/storage issue because the Arduino IDE says that I'm only using 3% of that.

PS: I have used the library StandardCplusplus library to include vectors.

body:
Your code is very complex and running it in an environment where you have limited debug facilities is making life worse for yourself.

When an Arduino reboots it is usually because it has thrown a memory error.  This happens when you try and access memory that is no longer your program's to access (or never was yours).  In this case I originally suspected, based on the complexity of your code, that you were accessing a vector element that you could no longer access.

To prove this I 'ran it on a desktop', in my case a Windows 7 box with Visual Studio 2015 (but you could have used Linux, GCC and GDB).  This meant I wrote a little wrapper program and stubbed the functions you called.  This resulted in the error message shown below.

This is my 'desktop' code:

    #include <vector>

    std::vector<std::vector<std::vector<float>>> test_split(const int& i, const float& f, std::vector< std::vector< float > >& dataset)
    {
     std::vector<std::vector<std::vector<float>>> vals;
     return vals;
    }

    float gini_index(const std::vector<int>& class_values, const std::vector<std::vector<std::vector<float>>>& group)
    {
     return 1.0f;
    }

    std::vector<std::vector<std::vector<std::vector<float>>>> get_split(std::vector< std::vector< float > >& dataset) {
     std::vector<int> class_values; // declares vector 'class_values'
     for (int i = 0; i < dataset.size(); i++) { // loops through each value in dataset (the dataset contains vectors)  and appends the last value in each vector to class_values
      class_values.push_back(dataset[i][dataset.size()]);
     }
     std::vector<std::vector<std::vector<float>>> b_index;
     b_index.push_back(std::vector<std::vector<float>>(999));
     std::vector<std::vector<std::vector<float>>> b_value;
     b_value.push_back(std::vector<std::vector<float>>(999));
     std::vector<std::vector<std::vector<float>>> b_score;
     b_score.push_back(std::vector<std::vector<float>>(999));
     std::vector<std::vector<std::vector<float>>> b_groups;
     for (int i = 0; i < dataset[0].size(); i++) {
      for (int j = 0; j < dataset.size(); j++) {
       std::vector<std::vector<std::vector<float>>> groups = test_split(i, dataset[j][i], dataset); // gets the split of the dataset (assigns each vector in the dataset to either 'left' or 'right')
       float gini = gini_index(class_values, groups); // calculates the gini
       if (gini < b_score[0][0][0]) {
        b_index[0][0][0] = i;
        b_value[0][0][0] = dataset[j][i];
        b_score[0][0][0] = gini;
        b_groups = groups;
       }
      }
     }
     std::vector<std::vector<std::vector<std::vector<float>>>> vals;
     vals.push_back(b_index);
     vals.push_back(b_value);
     vals.push_back(b_groups);
     return vals; // returns the values.
    }

    int main(void)
    {
     std::vector<std::vector<float>> dataset;

     std::vector<std::vector<std::vector<std::vector<float>>>> result = get_split(dataset);

     return fgetc(stdin);
    }

Now you need to workout where it is crashing, easy in Visual Studio but very difficult on an Arduino.  However I would look at simplifying the code too.

[![Your bug][1]][1]

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


message:
Wemos D1 & Relay shield

For one of my hobby projects I would like to use:

 - [Wemos D1 mini pro][1] ([schematic][2])
 - [Wemos D1 Relay Shield][3] ([schematic][4])

to control the `24V` (`19W`) mist maker.

My current wiring is this:
[![enter image description here][5]][5]

As you can see the both grounds (12V and 5V) are attached to the `com` connector of the power supply.

I wonder whether grounds should be decoupled (for whatever reason) - i.e. to use separate power supplies? If the above wiring is OK I would really like to know in which circumstances (if any) a separate power supplies would be needed.

Thanks for all your answers in advance.

  [1]: https://www.wemos.cc/product/d1-mini-pro.html
  [2]: https://www.wemos.cc/sites/default/files/2016-09/mini_pro.pdf
  [3]: https://www.wemos.cc/product/relay-shield.html
  [4]: https://www.wemos.cc/sites/default/files/2016-09/relay_new.pdf
  [5]: https://i.stack.imgur.com/ottsS.png

body:
That grounding scheme looks right since the Load ground is coupled back to the supply separately from the logic ground.

The only reason you would separate supplies would be to isolate them for safety or other reasons. For example, if the load side was a large or ac voltage.

Isolation requirements vary with application so it is hard to be more specific than that here.


message:
How to combine 3.4ghz intel processor with arduino board

Im totally new to arduino but have some programming experience. I have an idea that i would like to realize but it requires way better hardware than what a standard arduino board offers. I would like to use my 3.4 ghz intel processor for example...

The question might seem very stupid to most people here but i actually did not find the answer anywhere (here, google, arduino website), but is it possible to combine the simplicity of arduino and the power of pc-level hardware without using a server? (The calculations should be made locally on the arduino).

body:
Of course you can combine it, but it depends what you need. If you say you need to do the calculations on the Arduino, and assuming the electronics will also be driven from the Arduino, I wonder what you want your 3.4 intel processor to do.

If you want to let the Arduino use the intel directly, that will be impossible or at least impractical. The number of pins used by the intel will be very high and the Arduino runs on 16 MHz so never can provide the intel with enough data to keep it busy.


body:
It depends what you want to do.

An Arduino gives you are simple low cost board for interfacing to peripherals.  If you are interfacing to kit then you probably want to stick with a microprocessor because of its real time behaviour, its low cost and its simplicity.

If you then want to crunch numbers send the data back to a beast of a processor and crunch numbers, where you have features like floating point and clever stuff.

The two processors you talk about are both good at what they are aimed at, but not much use at the other.,

Looking at it another way, you are a farmer and have a tractor for ploughing the fields, a quad bike for chasing sheep, and a Porsche for nipping down the shops.  You could go shopping in the tractor same as you could try to plough the field with the Porsche, but you look a bit of a [fool].

You could look at Netduinos, ESP8226, ESP32, Pi's or PICs.

You can get a PC card that talks to an I2C bus and could control the microprocessors using that.


body:
How real time do you need things to be?

Arduino gives you very good control of timings because there is no operating system getting in the way switching between tasks in the background.

If you need hard real time then you need to work bare metal, mbed gives you a more processing power while still maintaining the ease of use and reliable tight timing. That will get you up to around 150 MHz with an FPU but still a long way from PC capabilities.

You can run bare metal code on any CPU but doing so without an easy to use set of libraries can have a very steep learning curve, I don't know of any faster systems that allow you to do this in an accessible way.

If you can live with a few ms of delay in the system then you can run something with an OS which opens up a lot more possibilities. The Pi is at the low end of the range in both price and performance. The odroid or beagleboard boards give you more power for more money but are still fairly good in terms of price. I'm not sure what exactly you want to do but four 2 GHz CPUs is enough to do quite a lot of number crunching if you can multi-thread the task.


message:
Analog reading via bluetooth

I am making a project in which I am trying to communicate the LDR values collected by one arduino(slave) to another arduino(master) via bluetooth. The readings of the LDR is displayed on the serial monitor.
The slave part of the arduino code :

     #include <SoftwareSerial.h>
      SoftwareSerial BTSerial(10, 11); // RX | TX
      #define ldrPin A0
      int ldrValue = 0;
      void setup() {
         pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
         digitalWrite(9, HIGH);
         pinMode(ldrPin, INPUT);
         BTSerial.begin(9600);
         Serial.begin(9600);

       }
       void loop()
        {
         ldrValue = analogRead(ldrPin);
         BTSerial.println(ldrValue);
         Serial.println(ldrValue);
         delay(10);
        }
I tried getting the readings of LDR in serial monitor to check whether the readings are correct. The readings shown in Serial monitor were correct.

The code of master part of the project which receives the readings from slave :

    #include <SoftwareSerial.h>
    SoftwareSerial BTSerial(10, 11); // RX | TX
    const byte numChars = 1024;
    char receivedChars[numChars];   // an array to store the received data

    boolean newData = false;

    void setup() {
    pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH  to switch module to AT mode
    digitalWrite(9, HIGH);
    BTSerial.begin(9600);
    Serial.begin(9600);
    Serial.println("<Arduino is ready>");
    }

    void loop() {
       recvWithEndMarker();
       showNewData();
     }

    void recvWithEndMarker() {
       static byte ndx = 0;
       char endMarker = '\n';
       char rc;

       while (BTSerial.available() > 0 && newData == false) {
         rc = BTSerial.read();

         if (rc != endMarker) {
            receivedChars[ndx] = rc;
            ndx++;
            if (ndx >= numChars) {
                ndx = numChars - 1;
            }
        }
        else {
            receivedChars[ndx] = '\0'; // terminate the string
            ndx = 0;
            newData = true;
          }
        }
      }

       void showNewData() {
          if (newData == true) {
           Serial.print("This just in ... ");
           Serial.println(receivedChars);
           delay(1000);
           newData = false;
        }
       }
But The serial monitor did not show the correct readings of LDR . Instead it showed something like this

    <Arduino is ready>
     This just in ... 8
     This just in ... 3
     This just in ... 4
     This just in ... 3
     This just in ... 3
     This just in ... 3
     This just in ... 3
     This just in ... 4
     This just in ... 3
     This just in ... 4
     This just in ... 3
     This just in ... 3
I have referred this link for the Arduino serial communication:
[Serial Input][1]

  [1]: http://forum.arduino.cc/index.php?topic=396450.0

 Kindly help me out since it has been days since I have stuck up in this issue.

Thank you!

body:
1. A byte is 8 bits, it can hold a maximum value of 255.  You can not store the number 1024 in a byte.  You might want to rethink the type on `ndx`.

2. If `(ndx >= numChars)` then why not set newData to true and print it out.  Something has gone wrong if it gets this far and you want to recover if you can.

Apart from those minor issues your code should work as you expect it to.  Do you have a printout of what the slave's serial output was?  (What you were expecting).  Could it be something to do with the differences between SoftwareSerial and Serial?

**Edit:**

I have just run a stubbed version of you code on a PC and it ran fine, so I'm going to point my finger at the SoftwareSerial link.  It could well be a misinterpretation of the interface it provides.


message:
Button that increments a counter

#include <Adafruit_RGBLCDShield.h>
    #include <utility/Adafruit_MCP23017.h>
    Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

    void setup() {
      lcd.begin(16, 2);
      lcd.setCursor(0,0);

    }

    void loop() {
      uint8_t buttons = lcd.readButtons();
      int a;
      if (buttons) {

        lcd.clear();
        lcd.setCursor(0,0);

        if (buttons & BUTTON_UP) {
          a+= 1;
          lcd.setCursor(0,0);
          lcd.print(a);
        }
      }

I am trying to make a counter that increments everytime the button UP is pressed. Currently, all it is doing is printing 1 everytime the button is pressed. Any help would be nice! Thanks!

body:
Your code, simplified, is:

    void loop()
        int a;
        a += 1;
    }

The problem here is that, by putting the declaration of your counter variable within the `loop()` function, you've made it local to that function. Every time `loop()` is called, a new variable `a` is created, initialized to zero, and then incremented.

You want to move the declaration outside of `loop()`, creating a global variable that will remain in existence and maintain its value after `loop()` exits, so that the value is still there when `loop()` is called again:

    int a = 0;
    void loop() {
        a += 1;
    }

(This could also be done with a static variable, but that's probably beyond the scope of this question.)


message:
Connect Multiple L293D Motor Controllers to Arduino

I would like to connect 3 L293D Motor controllers to an Arduino Uno with the hopes of powering 6 different dc motors. I was just wondering how to wire this being that one motor controller (which allows for 2 dc motors to be controlled) already takes up most of the pins on the Arduino, thanks.

Below is the wiring diagram for how I am hooking up 1 L293D motor controllers to the Arduino.

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

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

body:
The suggestion of using an [Adafruit Motor Shield V2 for Arduino](https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/overview) seems fairly good, although that particular shield controls only four DC motors at once.  That shield has a dedicated PWM driver chip on it, which removes the overhead of motor and speed control from the MCU.  That might allow you to drive four motors via the shield, and two via wires from the Arduino; or, stack two motor shields on the Uno.

If you definitely want to drive six motors from the Arduino, you may need to add a couple of control chips.  You could add a 74HCT04 hex inverter and a 74LS595, to create inverted drive signals and enable signals.  For example, the first PWM drive would go to L293 pin 1A and to '04 pin 1A; the first '04 output, 1Y, would drive L293 pin 2A.  One of the '595 outputs would go to L293 pin 1,2EN.

Alternately, you could use two '595s, with outputs to control L293 pins 2A; 4A; 1,2EN; and 3,4EN on each of three L293's.  The six PWM outputs from the Uno would go to 1A and 3A on the several L293's.  Using motor shields probably is a better idea, however.


body:
If you want to make your own circuit.. then you need two IC 74HCT595(8-bit serial-in, serial or parallel-out shift register). You have to wiring with your arduino and L293D you can go this way..
[![Wiring schematic with Arduino][1]][1] . This Circuit diagram is an Idea, don't think its actual circuit you have to modify this schematic accroding to your application.

Data Sheet link [74HCT595 DATASHEET][2]

  [1]: https://i.stack.imgur.com/XlSf8.png
  [2]: https://www.arduino.cc/en/uploads/Tutorial/595datasheet.pdf


message:
Logging small capacitance

I'm measuring capacitance of a system using a multimeter, and found that the value is very small (fluctuate from 50pF to 100 pF). The system is dynamic so the capacitance changes over time.

Now I need to log this value to some text file (csv for example). How could I do this with Arduino? If it's resistance, I could have built a simple voltage divider and sense the voltage using ADC. Also C is very small, I haven't been able to construct some measuring circuit for C.

body:
Each Arduino capacitance meter relies on a property of resistor capacitor (RC) circuits- the time constant. The time constant of an RC circuit is defined as the time it takes for the voltage across the capacitor to reach 63.2% of its voltage when fully charged. Larger capacitors take longer to charge, and therefore will create larger time constants. The capacitance in an RC circuit is related to the time constant by the equation:

*TC = R x C*

where
*TC = time constant in seconds
 R = resistance in ohms
 C = capacitance in farads*

Rearranging the equation to solve for capacitance gives:

*C = TC/R*

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/FNf5I.png)

<!-- End schematic -->

Example: 1 megohm * 1 microfarad = 1 second
[![enter image description here][1]][1]

Each capacitance meter has an RC circuit with known resistor values and an unknown capacitor value. The Arduino will measure the voltage at the capacitor and record the time it takes to reach 63.2% of it’s voltage when fully charged (the time constant). Since the resistance value is already known, we can use the formula above in a program that will calculate the unknown capacitance.

As your Capacitance is too Small in Pico Farad Range so you can directly measure Capacitance through your analog pin like this way...
[![Schematic][2]][2] You said that your capacitor in dynamic in nature so you have to take atleast 10 values and average it to get accurate value.

  [1]: https://i.stack.imgur.com/g3Wv9.jpg
  [2]: https://i.stack.imgur.com/hsTpS.png

Code for measure Low capacitance in pF range

    const int OUT_PIN = A5;
    const int IN_PIN = A0;
    const float IN_STRAY_CAP_TO_GND = 24.48;
    const float IN_CAP_TO_GND  = IN_STRAY_CAP_TO_GND;
    const float R_PULLUP = 34.8;
    const int MAX_ADC_VALUE = 1023;

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

    void loop()
    {
        pinMode(IN_PIN, INPUT);
        digitalWrite(OUT_PIN, HIGH);
        int val = analogRead(IN_PIN);
        digitalWrite(OUT_PIN, LOW);

        if (val < 1000)
        {
          pinMode(IN_PIN, OUTPUT);

          float capacitance = (float)val * IN_CAP_TO_GND / (float)(MAX_ADC_VALUE - val);

          Serial.print(F("Capacitance Value = "));
          Serial.print(capacitance, 3);
          Serial.print(F(" pF ("));
          Serial.print(val);
          Serial.println(F(") "));
        }
        else
        {
          pinMode(IN_PIN, OUTPUT);
          delay(1);
          pinMode(OUT_PIN, INPUT_PULLUP);
          unsigned long u1 = micros();
          unsigned long t;
          int digVal;

          do
          {
            digVal = digitalRead(OUT_PIN);
            unsigned long u2 = micros();
            t = u2 > u1 ? u2 - u1 : u1 - u2;
          } while ((digVal < 1) && (t < 400000L));

          pinMode(OUT_PIN, INPUT);
          val = analogRead(OUT_PIN);
          digitalWrite(IN_PIN, HIGH);
          int dischargeTime = (int)(t / 1000L) * 5;
          delay(dischargeTime);
          pinMode(OUT_PIN, OUTPUT);
          digitalWrite(OUT_PIN, LOW);
          digitalWrite(IN_PIN, LOW);

          float capacitance = -(float)t / R_PULLUP
                                  / log(1.0 - (float)val / (float)MAX_ADC_VALUE);

          Serial.print(F("Capacitance Value = "));
          if (capacitance > 1000.0)
          {
            Serial.print(capacitance / 1000.0, 2);
            Serial.print(F(" uF"));
          }
          else
          {
            Serial.print(capacitance, 2);
            Serial.print(F(" nF"));
          }

          Serial.print(F(" ("));
          Serial.print(digVal == 1 ? F("Normal") : F("HighVal"));
          Serial.print(F(", t= "));
          Serial.print(t);
          Serial.print(F(" us, ADC= "));
          Serial.print(val);
          Serial.println(F(")"));
        }
        while (millis() % 1000 != 0)
          ;
    }


body:
Measuring small capacitance value via RC constant estimation essentially requires precise time measurement. ATmega chips have [`TCNT1`](https://stackoverflow.com/questions/29593616/using-atmega-tcnt1) timer which can be programmed to increment each clock cycle, and can be stopped by a comparator using bit `ACIC` in `ACSR` register. Running a counter at 16 MHz will give you a resolution of 62,5 ns which is enough for capacity measurements in picofarad range. [Here](https://github.com/svn2github/transistortester/blob/master/Software/trunk/ReadCapacity.c)'s an example of code which uses this measurement technique.

`AnalogRead` is about 1000 times slower, so you'll be limited to nF range if you use it.

Note that you should calibrate your system when measuring such a small capacitance. This is done by running a measurement **with your probes connected** but without the target system. You will then subtract this capacitance value (typically 20-50 pF, depending on the probes you use) from your raw measurements to obtain the capacitance of your system alone.


body:
For capacitance as small as pF, The RC time constant method yields dirty results on an Arduino board.

You can use the Arduino pins built in small capacitance (which is in Pf itself) to create a "capacitance divider" circuit and calculate much like you would resistance from a voltage divider circuit.

See this excellent post by Nethercott for reference
[Arduino capacitance meter][1]

  [1]: http://wordpress.codewrite.co.uk/pic/2014/01/21/cap-meter-with-arduino-uno/


body:
> (fluctuate from 50pF to 100 pF).

a few ways for such small values -> assuming you can really read it like a capacitor.

1) form a lc tank and measure its frequency -> most effective in measuring small value capacitance. but needs precision inductor / calibration, and is subject to parasitics.

2) charge / discharge it via a CCS: and measure the time. simplest as a ccs can be formed via a large resistor. not effective with really small capacitance;

3) charge transfer: using the capacitance of the adc. very effective against small capacitance: < 10x of adc capacitance. needs calibration.

each has its own problems.


body:
The standard way to measure a resistance with an Arduino is to build a
voltage divider by putting it in series with a known resistance. I have
tried the same approach for measuring capacitances, and it turns out it
works well in the 100 pF range! The circuit is like this:

      ┌───────────── Arduino digital output
      │
    ──┴── known
    ──┬── cap
      │
      ├───────────── Arduino analog input
      │
    ──┴── unknown
    ──┬── cap
      │
     GND

The only catch is that you have to do the measurement relatively fast,
otherwise you would be measuring the ratio of the leakage resistances.
Here is the measurement protocol:

1. Set both pins to `OUPUT` `LOW` in order to discharge both capacitors.
2. Delay for one or two CPU cycles to make sure they are fully
   discharged.
3. Set the analog input pin to `INPUT` mode: this will make it high
   impedance and isolate the node connected to it.
4. Set the digital output to `HIGH`: this will charge the two capacitors
   in series to 5 V.
5. Delay for one or two CPU cycles for the voltage to stabilize.
6. Take an analog reading.

Now you can derive the capacitance from the reading using the same
formula you would use with resistors, only with impedances (or, simply
1/C) instead of resistances:

    C_unknown = C_ref × (1024 − reading) ÷ reading;

The same formula can be derived by considering that the node connected
to the analog input, which includes one plate of each capacitor, has
zero net charge.

A few things worth noting:

* You will get the best resolution by choosing the reference capacitance
  close to the one you want to measure.
* The delays are not actually needed: as the capacitors charge and
  discharge very fast, a single CPU cycle is about 24 time constants.
* If you were to measure large capacitances (several nanofarads) with
  this setup, you would want protective resistors in series with the
  Arduino pins, but _then_ the delays become mandatory. In the
  100 pF range I would not worry about the in-rush currents.
* If the delay in step 5 is too long, your measurement will be affected
  by the leakage of the caps and the analog input pin.
* You need not worry about the 14 pF cap on the sample and hold
  circuit: it will slightly affect the _very first_ measurement but,
  once that cap is charged, subsequent measurement will not be affected
  as long as the unknown cap does not change to much between consecutive
  measurements. You _do_ need to calibrate out the stray capacitance of
  the pin and probes.


body:
Because the capacitance to be measured is well below 1 nF (50-100 pF), you'll encounter serious problems trying to measure it with the ADC of the Arduino due to its input capacitance (14 pF according to datasheet). Add the stray capacitances of wires, headers and the Arduino board itself and you'll easily end up with 25 pF input capacitance, which is in the same order of magnitude of what you're trying to measure (= A VERY BAD THING).

What to do, then? Well, the main options are these...

Use an external measurement circuit
-----------------------------------

This would mean including active devices (op amps, comparator, timers...) and precision passive components. A true HW-based solution.

The accuracy of the measurement in this case would be entirely up to the design (circuit topology and component selection) of the external circuit. The circuit would provide either an analog voltage or a signal whose frequency could be measured by the Arduino without introducing any additional significant errors.

An example using a 555 timer (an additional 4 pF compensation capacitor is needed between OUT and TH for improved accuracy):

[![555 timer capacitance meter][1]][1]

[![Frequency vs capacitance][2]][2]

**Source:** [Use Analog Techniques To Measure Capacitance In Capacitive Sensors][3], an article by Martin Tomasz published in Electronic Design.

Think of the external circuit as a "sensor" or as a signal conditioning circuit for a "sensor" (the capacitance to be measured). In fact, the dynamic capacitance you're trying to measure probably comes from a sensor (moisture, humidity?), isn't it?

Connect the capacitor directly to analog pins of Uno and calibrate the readings
---------------------------------------------------------------

It may sound amazing, but something as simple as this works (at the expense of accuracy, of course):

[![Uno as capacitance meter][4]][4]

How's that? Because the input capacitance problem that we detected at the beginning is big enough to seriously impair accuracy, but doesn't make the measurement completely unfeasible. Thus, we can calibrate that effect out and still have a valid (although with reduced accuracy) measument in the target range (50-100 pF).

The calibration is done through some hardcoded default values in the following Arduino sketch (source [here][5] from braulio777). For better accuracy you should calibrate the values of `IN_STRAY_CAP_TO_GND` and `R_PULLUP` in the sketch by comparing measurements of some capacitors with their already known capacitance values (provided you can do this).

    //Digital Capacitance Meter
    //Measuring from 0.000pF to 1000uF

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(11, 9, 5, 4, 3, 2);
    const int OUT_PIN = A4;
    const int IN_PIN = A0;
    const float IN_STRAY_CAP_TO_GND = 24.48;
    const float IN_CAP_TO_GND  = IN_STRAY_CAP_TO_GND;
    const float R_PULLUP = 34.8;
    const int MAX_ADC_VALUE = 1023;

    void setup()
    {
      pinMode(OUT_PIN, OUTPUT);
      pinMode(IN_PIN, OUTPUT);
      lcd.begin(16, 2);
      }

    void loop()
    {
        pinMode(IN_PIN, INPUT);
        digitalWrite(OUT_PIN, HIGH);
        int val = analogRead(IN_PIN);
        digitalWrite(OUT_PIN, LOW);

        if (val < 1000)
        {
          pinMode(IN_PIN, OUTPUT);

          float capacitance = (float)val * IN_CAP_TO_GND / (float)(MAX_ADC_VALUE - val);

          lcd.setCursor(0,0);
          lcd.print("Capacitance = ");
          lcd.setCursor(0,1);
          lcd.print("                ");
          lcd.setCursor(0,1);
          lcd.print(capacitance, 3);// for the best precision
          lcd.print("pF ");

        }

        else
        {
          pinMode(IN_PIN, OUTPUT);
          delay(1);
          pinMode(OUT_PIN, INPUT_PULLUP);
          unsigned long u1 = micros();
          unsigned long t;
          int digVal;

          do
          {
            digVal = digitalRead(OUT_PIN);
            unsigned long u2 = micros();
            t = u2 > u1 ? u2 - u1 : u1 - u2;
          }

          while ((digVal < 1) && (t < 400000L));

          pinMode(OUT_PIN, INPUT);
          val = analogRead(OUT_PIN);
          digitalWrite(IN_PIN, HIGH);
          int dischargeTime = (int)(t / 1000L) * 5;
          delay(dischargeTime);
          pinMode(OUT_PIN, OUTPUT);
          digitalWrite(OUT_PIN, LOW);
          digitalWrite(IN_PIN, LOW);

          float capacitance = -(float)t / R_PULLUP
                                  / log(1.0 - (float)val / (float)MAX_ADC_VALUE);

          lcd.setCursor(0,0);
          lcd.print("Capacitance = ");
          if (capacitance > 1000.0)
          {
            lcd.setCursor(0,1);
            lcd.print("                ");
            lcd.setCursor(0,1);
            lcd.print(capacitance / 1000.0, 2);
            lcd.print("uF ");

          }

          else
          {
            lcd.setCursor(0,1);
            lcd.print("                ");
            lcd.setCursor(0,1);
            lcd.print(capacitance, 2);
            lcd.print("nF ");

          }

        while (millis() % 1000 != 0);
    }
        }

The example code above outputs measured values to an LCD display. For your intended application, the best option probably is to write data to an external SD card.

**Disclosure:** I have not tested the code above myself.

  [1]: https://i.stack.imgur.com/rPguC.gif
  [2]: https://i.stack.imgur.com/aSec7.gif
  [3]: http://electronicdesign.com/analog/use-analog-techniques-measure-capacitance-capacitive-sensors
  [4]: https://i.stack.imgur.com/a4Btil.png
  [5]: https://pastebin.com/njjKZrfv


message:
What happens if you write >10000 times to the flash memory of an ATmega?

I realized that I'm uploading code every 5 minutes and doing relatively intensive trial-and-error development, and that this habit could cause problems down the road, especially if I'm working on a custom board (non-Arduino) where the chip isn't readily replaceable.

What will happen?

I noticed that *avrdude* verifies the written flash. So will it simply start noticing errors and possibly be unable to write without failing?

Or will it work sometimes, sometimes not?

**Example of heavy use:** A custom PCB where easy replacement of the MCU is not possible. 10,000 writes would equal 100 days, each 8 hours of development, with flash write every 5 minutes.

I have several habits that drive frequent flash writing: I inject benchmarks into my code, test speed improvements of small optimizations, program size optimizations, and so on.

I now try to restrain myself from flashing too frequently and doing more code revisions before testing, rather than testing immediately.

**In conclusion:** Yes, it's unlikely, and arguably, if you're working full-time on a board, less intensively, for, say, a year, you can probably afford to buy another board when the first one starts failing the flash-verification.

body:
Although it's not a direct answer to your question, it might be an answer for your problem (the need to do intensive trial-and-error.

Probably you are testing mostly your program (changes), and not your hardware (changes). Since I don't assume you change your hardware (breadboard) every 5 minutes.

In case the program is quite complicated, probably it will be best to write a specific off-line test program, and run it on a computer instead of an Arduino. You probably have to stub some classes/libraries you use, but it might save you a lot of time. Also you have the benefit of a better IDE and many more debug possibilities. After the tests on the offline test program pass, you try it on the Arduino.

This way you probably need to upload the program just a few times per day on the Arduino.


body:
AFAIK the manufacturer say, that the number of write cycles is guaranteed. Usually the chip is able to endure little more (for manufacturer to be safe to keep the guarantee), individual chips may, on random, endure much, much more.

Also the failure can result in two kinds of problems - first one is better in a way - the write just fail, following read returns "something" (usually part of written value, but some bits always set to the same 0/1). The second one is, that the wearing makes the write unreliable - you write it, you read it it is ok, but after some time (like days/months) the content is changed and if you read it again, you will get "something" as in previous case.

It would be better to make sure you are able to exchange the chip, before going to "normal use" and put there fresh one - use a socket/create new board/unsolder old chip and solder new one. Use the weared chip for more testing/developement, but for production use a fresh one with only few cycles of reflashing. Also software emulators could speed up your developement a lot and decrease the need to/number of reflashing the chip on the board.


body:
This [Wikipedia article][1] about Flash memory discusses failure mechanisms including references to relevant papers. One point that surprised me was "Read Disturbance" of adjacent cells after a large number (>100,000) of reads from one cell since last erase, causing the adjacent cell(s) to read back erroneously. There's probably more there and in the referenced articles than you ever wanted to know about Flash failure mechanisms.

However...

At 5min per test, 10000 tests will take you 35 days working around the clock or 100+ days @8hrs/day, maintaining that rate of testing. My point being that you're not likely to reach 10K cycles. But if you are concerned about putting a heavily used chip in the field (and I might be, too, in some cases), socketing board #1 would be worth your while.

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


body: Assuming that you don't have to fine tune each board individually, just don't send the board that you do your testing/adjusting to the 'field'.....keep it in-house, and only use new boards for field use.


body:
> What will happen?

it may not pass parity check. so uploading code wouldn't be possible.

with that said, I have never had one flash-based mcu failure due to endurance. that's countless mcus since as far as I can remember.

to give you some sense of design headroom, I wrote-to and then read-back from eeprom on a pic over several hours @ 10ms per read/write, without a failure. that eeprom is rated 1M in endurance.

so unless you get some weird parts or you write to it repeatedly over a long period of time, flash failure is unlikely a practical issue.


message:
Formula for decision making when in contact with an obstacle using Arduino

I am currently working on an obstacle avoidance robot project and I have seen numerous algorithms for obstacle avoidance a very good example is this [Obstacle avoidance algorithm][1] [Editor's note: by user3880651],
but unfortunately non of those algorithm works with Arduino so upon my research I found this [blog][2]

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

and in there the author talks about an effective way to avoid obstacles and even has a formula he uses for avoiding obstacles at different positions e.g (Front and sides) but doesn't really explain how he got the formula so I was wondering if anyone as an effective formula or algorithm for obstacle avoidance that works with Arduino thanks for your help in advance

  [1]: https://arduino.stackexchange.com/questions/36307/obstacle-avoidance-algorithm
  [2]: http://www.rmcybernetics.com/projects/DIY_Devices/diy-robot-arduino.htm
  [3]: https://i.stack.imgur.com/ePQxK.png

body:
The algorithm mentioned in the blog uses a Fuzzy Logic Controller to perform obstacle avoidance. You can read up more on fuzzy logic here: https://www.calvin.edu/~pribeiro/othrlnks/Fuzzy/home.htm

> newMotorSPD_L = basicVelocity + urgMotor_L + (urgTurn_R/4) - (urgTurn_L/2) + 60;
newMotorSPD_R = basicVelocity + urgMotor_R + (urgTurn_L/4) - (urgTurn_R/2) + 60;

Based on the code, the formula is basically made up of variables with different weight/ratio.

**basicVelocity** is the default moving velocity of the robot when there is no obstacle or wall detected.

**urgMotor_L/urgMotor_R** is the ouput of the controller for frontal object detection/avoidance by getting the difference between the left and right ultrasonic sensor.

**(urgTurn_R/4) - (urgTurn_L/2)** is probably the left/right bias?

**+60** at the end is probably to offset the error of the motor. (Assuming all other variable are 0, the robot should be still at 60 for their case?)

To simplify what the formula does, it can be shown using this graph:
[![enter image description here][1]][1]

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


body:
Obstacle avoidance doesn't really have any practical use unless it works alongside a goal finding algorithm.

Take a look [here][1] for a simple introduction (and a few modifications) to [this excellent paper][2] on goal finding with obstacle avoidance.

You can also experiment with the python code (add obstacles, change positions of goal and start points, and step through the decision process). Keep in mind that in this code, ***sensor inputs are also simulated*** and so the code is much more complex than that would actually need to be deployed on a robot with real world sensors.

  [1]: https://bayesianadventures.wordpress.com/2015/08/31/obstacle-avoidance-for-clever-robots/
  [2]: http://www.wseas.us/e-library/conferences/2009/tenerife/CIMMACS/CIMMACS-03.pdf


message:
Nano + ESP8266 control pins with REST API

I connected and flashed successfully an ESP8266 module to a Nano. Now I want to control pins values with a REST API, but all the libraries I found are for using standalone ESP8266 modules (without Arduino) or for Arduino with some other modules like CC3000 etc. Can anybody recommend a library please?

body:
You can use Firmata to control the Arduino pins, just having the ESP8266 publish a web page exposing the Firmata operations you desire to expose and sending the user actions to the Arduino via serial using the Firmata protocol.

To make your life easier you can consider your ESP8266 an equivalent of your serial console: everything you write _from_ the ESP82667 becomes input data on the console for your Arduino and the other way around.

In Firmata, each command can be read from a generic _Stream_, with `Serial` being the default implementation.


message:
Using EEPROM to write a counter value

I have made a program that increments a counter everytime the up button is pressed. I am trying to write this value to EEPROM, so that when I turn my board off and on again, the value before power off is shown on screen.

I wrote this code but the value doesn't seem to be written to EEPROM. The counter incrementation works fine.

    #include <EEPROM.h>
    #include <Adafruit_RGBLCDShield.h>
    #include <utility/Adafruit_MCP23017.h>
    Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

    int addr = 0;
    byte value;

    void setup() {
      lcd.begin(16, 2);
      lcd.setCursor(0,0);
    }

    int a;
    void loop() {
      uint8_t buttons = lcd.readButtons();
      if (buttons) {

        lcd.clear();
        lcd.setCursor(0,0);

        if (buttons & BUTTON_UP) {
          a+= 1;
          EEPROM.write(addr, a);
          value = EEPROM.read(addr);
          lcd.print(value);
          delay(100);
        }
      }
    }

Thanks for the help!

body:
just add `a = EEPROM.read(addr);` in your setup
also, you can remove `byte value` and use `a` you wrote to memory in the previous line


message:
Adding slave device to Arduino Uno-SPI | Configuring pins

I recently started an oled project. I use a small "128X64 OLED LCD LED Display Module" and I control it using SPI protocol(with my Arduino).

It is the only device connected to the microcontroller. But I have some questions regarding the pins. I found [this][1] tutorial and it uses pins 9 as DATA(known as MOSI) and 10 as CLK( or SCK). But the [datasheet][2] for my microcontroller(328) shows that pin 11 is MOSI and 13 is CLK.

Obviously..it works. So I think the program provided by the adafruit(that I used-Adafruit_SSD1306) took care of MOSI and generated the clock impulses on pin 10.etc. . But then what are those pins on the board and why are called like that? I mean it seems to me that everyone can just use other pins for MOSI/CLK(at least).What is their purpose?

Question #2: What does DC (or D/C) means?

    #define OLED_MOSI   9
    #define OLED_CLK   10
    #define OLED_DC    11
    #define OLED_CS    12
    #define OLED_RESET 13
**VS**
[![enter image description here][3]][3]
(328<=>128)

  [1]: https://learn.adafruit.com/monochrome-oled-breakouts/wiring-1-dot-3-128x64
  [2]: https://www.arduino.cc/en/Hacking/PinMapping168
  [3]: https://i.stack.imgur.com/75nMY.png

body:
You can answer these questions by opening the library and looking "under the hood". This is the most beautiful advantage of open source projects.

Here are the links to the relevant files in the library, so I can comment on them.

 - [INO example file](https://github.com/adafruit/Adafruit_SSD1306/blob/master/examples/ssd1306_128x32_spi/ssd1306_128x32_spi.ino)
 - [Library header file](https://github.com/adafruit/Adafruit_SSD1306/blob/master/Adafruit_SSD1306.h)
 - [Library source file](https://github.com/adafruit/Adafruit_SSD1306/blob/master/Adafruit_SSD1306.cpp)

Ok, first of all let's have a look at the example. you can see that the constructor is called as

    Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

When looking at the lines 144 and following of the source file, you can see

    hwSPI = false;

Wait, this means that it is not using the hardware SPI? Sure! In the following overload, then, you can see that if you call the constructor as `Adafruit_SSD1306(int8_t DC, int8_t RST, int8_t CS)`, you will use the hwSPI.

Now, I'm not sure whether you know the difference between HW and SW implementations, so here they are. The HW implementation is a peripheral which can run "on its own" and provide the microcontroller the results (automatically send and/or receive the bytes). The SW one, on the other hand, is an emulation done by the microcontroller.

You can also see it in the example:

    // If using software SPI (the default case):
    #define OLED_MOSI   9
    #define OLED_CLK   10
    #define OLED_DC    11
    #define OLED_CS    12
    #define OLED_RESET 13
    Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

    /* Uncomment this block to use hardware SPI
    #define OLED_DC     6
    #define OLED_CS     7
    #define OLED_RESET  8
    Adafruit_SSD1306 display(OLED_DC, OLED_RESET, OLED_CS);
    */

So you can use the second part to initialize a display which will use the hardware SPI (so MISO = 12, MOSI = 11, SCK = 13). If you want to free the microcontroller in order to be able to do other tasks, use the HW peripheral.

As fot the DC pin, it is labeled "DataCommand". I think it is a pin to tell the controller whether the data shared through the SPI port is a command or it is data


message:
Student Code: map function not functioning

We made this code in class:

     int red = 6;
      int green = 7;
      int blue = 8;
      int pot = A0;
      int potVal = 0;
      int chosenColor = 0;

    void setup() {
      // put your setup code here, to run once:
      pinMode(red, OUTPUT);
      pinMode(green, OUTPUT);
      pinMode(blue, OUTPUT);
      pinMode(pot, INPUT);
      Serial.begin (9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      potVal = analogRead(pot);
      chosenColor = map(potVal, 0, 1023, 1, 3);
      if(chosenColor = 1) {
        redCycle();
      }

      else {
        analogWrite(red,255);
      }

      if(chosenColor = 2) {
        greenCycle();
      }

      else {
        analogWrite(green,255);
      }

      if(chosenColor = 3) {
        blueCycle();
      }

      else {
        analogWrite(blue,255);
      }
      Serial.println(chosenColor);
      Serial.println(potVal);
      delay(500);
    }

    void redCycle() {
        analogWrite(red,0);
      for(int i=0; i < 256; i+=5) {
        analogWrite(red, i);
      }
    }

    void greenCycle() {
      analogWrite(green,0);
      for(int i=0; i < 256; i+=5) {
        analogWrite(green, i);
      }
    }

    void blueCycle() {
      analogWrite(blue,0);
      for(int i=0; i < 256; i+=5) {
        analogWrite(blue, i);
      }
    }

When we open the serial monitor we find that chosenColor is always 3 regardless of what the potVal is reading. I am sure is something simple but we can't find where is the error. Please help.

body:
As Edgar Bonet pointed out,  “`chosenColor = 3` means 'let chosenColor take the value 3'”.  That is, your  `potVal = analogRead(pot);  chosenColor = map(potVal, 0, 1023, 1, 3);` sequence may very well be working, but by the time you get to `Serial.println(chosenColor);` you have changed `chosenColor` to 3.

First, the statement `if(chosenColor = 1) {...}` changes `chosenColor` to 1. Then the statement `if(chosenColor = 2) {...}` changes `chosenColor` to 2.  Finally, `if(chosenColor = 3) {...}` changes `chosenColor` to 3, just before you print out the current value of `chosenColor`.

When you wish to compare two numeric values for equality, use `==` instead of `=`.


body:
You are confusing `=` (assign) with `==` (compare).

eg.

### Wrong! ...

    if (chosenColor = 3)  // this assigns 3 to chosenColor

### Correct:

    if (chosenColor == 3)   // compare

---

> Still not sure why the map function is not working.

You just *assumed* it is not working. Before making assumptions like this do a Serial print to show what the return value of the map function is. (Directly after calling `map` - not later on in the code).


body:
Although not related to your main problem, I would like to point out
that there _is_ an issue with your use of the `map()` function. Or maybe
I should say, with the `map()` function itself. Since it works with
integer arithmetic, and integer division by default rounds towards zero,
you get a mapping that may be quite different from what you expect.

In the table below, I am showing the result of
`map(potVal, 0, 1023, 1, 3)`. The column labeled “not rounded” is what
you would get if the mapping was done in floating point. The last column
is the rounded value you actually get out of `map()`:

    potVal  not rounded  rounded
    ----------------------------
        0     1.00000       1
                ...
      511     1.99902       1
      512     2.00098       2
                ...
     1022     2.99804       2
     1023     3.00000       3

As you see, you have 512 possible values of `potVal` mapped
to 1, 511 values mapped to 2 and one single value mapped
to 3.

I assume you would rather have one third of the range mapped to each
value. This can be achieved by writing `map(potVal, 0, 1024, 1, 4)`:

    potVal  not rounded  rounded
    ----------------------------
        0     1.00000       1
                ...
      341     1.99902       1
      342     2.00195       2
                ...
      682     2.99805       2
      683     3.00098       3
                ...
     1023     3.99707       3

This gives 342 values mapped to 1, 341 values mapped
to 2 and 341 values mapped to 3. Now, the problem is that
this way of using `map()` is confusing. You may prefer to write
something more explicit instead, like:

    if (potval < 1023/3) chosenColor = 1;
    else if (potval < 1023*2/3) chosenColor = 2;
    else chosenColor = 3;


body:
Not sure if this helps but I wanted a slider with a range of 0 to 200 to give 3 values; 0 for the first third of movement, 1 for the second third and 2 for the last third

I used map(slider value, 0, 134, 0, 2)