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

Which "Arduino" are you using? For example, is it an Uno, with a separate USB-Serial interface between the USB port and the serial interface on the MCU, or is it something like a Leonardo, with on-board USB support on the microcontroller? The "unplug it and plug it back in" behaviour is rather different between the two.

It is an UNO, and the garbage values are the exact number of characters that I send it, e.g. if I send "Hello", I'll get "?????" where the '?' character is the same I described above. Like a black box with a '?' inside.

If it's the exact same number of characters, that leads me to guess that the bps rate is properly matched and you have some problem with corruption of the data. I suspect that the '?' in a black box is not actually a particular value but an "I don't want to interpret this" value. Anyway, can you update the question to have a copy of your "echo" program code, mention the host PC platform (Win, Linux, etc.) you're using, and what program (that's not the monitor) you're using to view the serial port traffic?

What bugs me is that the Arduino Serial Monitor does something which "fixes" the serial port. As if it aligned some values or something. My custom program will work fine after using the Monitor at least once if the Arduino gets reset. It works fine with the weighing machines, which are in a textile factory, so I guess the code is OK. Those machines are connected through an old fashioned serial port connector though.

Could it be related to handshake protocol? I don't know much about it.

Tweak the question to make it quite clear that the first code sample is running on a PC under Windows 10. (This took me surprisingly long to figure out!)

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".


text:
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) 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.

you might be able to detect floating analog inputs, but it's better to glance at the board.

It is quite easy actually:
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.

Great, thats what I was looking for! But why on Uno this code returns "20 digital pins" if I see 14 (0-13)?

@madneon, My guess is that these macros are counting the 6 PWM pins as 6 additional pins.

@madneon: because the analog inputs A0 through A6 are also the digital pins 14 through 19.

This is very neat. Didn't know that. But does it really show all connected pins of the chip or does it just tell about how many theoretical i/o's are present on the atmega?

@ansi_lumen: it's the number of available pins on the board, not on the chip.

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, 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 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.

I added more details in last section of question.

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.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
How can I connect a Fona to an Adafruit feather?
I have this adafruit-feather-huzzah-esp8266:
https://learn.adafruit.com/adafruit-feather-huzzah-esp8266/pinouts
and I want to connect a Fona board. But I am not certain which pins have the aforementioned software serial pins
necessary to make the required connections.
https://www.arduino.cc/en/Reference/SoftwareSerial
from the Fona tutorial:
https://learn.adafruit.com/adafruit-fona-3g-cellular-gps-breakout/arduino-wiring
which pins on the adafruit-feather-huzzah-esp8266 should I use for pin:
"TX connects to digital 3 (9 on Leo/Micro, 10 on Mega) "
where the feather doesn't have this a pin3.
similarly, which pins correspond to RST and RX?

you want RX-TX, TX to RX, reset to whatever you have free.

I'll try it, although in the tutorials it is not configured that way

if you need softwareserial, as opposed to hw, on the ESP pins 4+5 are going to be your best bet. if you don't need SPI, 13+15 will work as well.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
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. 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 :)

i've built a ton of "things", but i've never used a shield; don't be limited by less than your imagination. the next-simplest is to look for "modules" aka "bricks". there are plenty of Hall-effect based current sensors on ebay, and voltage just needs a few resistors to measure.

Where did you get that the linked shield only measures Arduino's energy consumption? It is clearly stated that it connects up to three AC current sensors.

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 )

P=VI for DC, or for AC with a purely resistive load. For AC with other kinds of loads you should include the power factor.

Yes, that's perfectly true. I just assumed, it'll be DC.


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

Please edit your question to include part # and/or datasheet link for the device.  Presumably it uses some communications protocol which you have left us to guess at.

Connect the data wire to RX, and connect RX to TX through a a 10K resistor?

Maybe it only communicates one way?

A bus called OneWire exists and may be what you are looking for. Just guessing. And you need to connect the ground of the devices too. So you will end up with two wires.

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.


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

This is a pure programming question: the answers would be no different if you were running the same code on a PC instead of an Arduino. You need to ask this on stackoverflow.com. (Well, actually you need to search there for the no doubt many existing questions asking things similar to this. :-))

Oh, so things purely related to Arduino should be posted here, while anything related to coding itself should be done in stackoverflow. Alright, i guess I finally know how this works, time to re-post this in the right place. :)

you can't shift array to left but you can move your pointer to right it will work similarly. for eg. your array array=[1,2,3,4,5,\0], you can denote any array element by array[i] and you can increment value of i by i++.

Actually, coding related specifically to the Arduino (e.g., "I have a problem when using this Arduino library") should be posted here. But what you've described is a generic programming problem. A good rule of thumb is to think, "would this application work just as well on a PC as on an Arduino, and the code I'm asking about be unchanged or almost unchanged?"

Hmm, I guess it then belongs in here? I mean, when it comes to other programming languages like Java, I would have no problem creating an ArrayList instead to do the job. I was actually unsure as to how to do this in arduino, hence why I thought about adding this here instead. I wasn't really used to a different language and the low amount of available memory. xD

Maybe this will be useful for you
http://playground.arduino.cc/Code/QueueArray

Template Queue class from Cosa; https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/Queue.hh used in the Event class https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/Event.hh

Alternatively a double linked cyclic list (queue) with fast insert and remove at any position; https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/Linkage.hh used in Job/Scheduler queues; https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/Job.hh

You wrote: “the problem with array I believe is that it doesn't allow me to shift the data to the left”. No, that's not the problem: you can shift the data if you wish with memmove(). The problem is that doing so is inefficient, as you would be copying all the data each time you shift out one element. That's why the answers you got suggest implementing the queues as circular buffers.

@Tsubakura: The reason it still belongs in SO rather than here is because what you're asking is a pretty generic question about doing something in C. It's useful to say, when posting problems like this, "I know how to do this in Java" and perhaps even provide a small fragment of Java code so we can see how you're thinking and explain just the stuff you don't understand, rather than the stuff you do.

I wrote a simple queue library some weeks ago, you can find it in the arduino library manager, or here:
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
Hope this can help!

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 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 is easy to implement. Usually Fibonacci heaps and binomial heaps 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 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 at arduino.cc.  This library apparently uses dynamic allocation.  It provides methods push(), pop(), peek() et al.  Also see QueueArray Library For Arduino 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 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 may also be of interest.
As noted in Mikael Patel's comments above, Cosa platform software includes a Queue class, which is a “Template class for ring-buffer for queueing data elements”, with usage of the class illustrated in an Event class, which in turn is used in a Job class.

I had an arduino project that I needed to build a queue for.
You can download the source code 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);
}


text:
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." );
}

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

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).


text:
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++;
      }
    }
  }
}

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

You do not need to recopy the entire file, it is possible to simply read/modify/write the specific blocks containing the data to be changed.

@ChrisStratton True, but looking at the code from the OP, it also processes the entire file. But as you mention, it is not mandatory to read it completely or even sequentially.

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!

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.

It's not clear that this answers the question asked, in large part because the question is unanswerably unclear, and needs to be closed.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


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

You need to convert the ASCII characters to a number.

how?? can i use atoi ??

how about strtol? is allows a base.

i use it this way. but i am getting compiler error.....

ret = strtol(byteRead, &ptr, 10);

i tried atoi(byteRead). but it is also giving me compiler error

No no no. Read the whole string into a buffer (a[8]), null terminate and pass to the functions. You cannot use byteRead that is a single byte!

i tried that way too. but its not giving me any value

void loop()
{
if (Serial.available())
{
char* readString;
for(int i=0; i<4; i++)
{
readString[i]=Serial.read();
}
int a = atoi(readString);
Serial.println(a);
}
}

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!

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

Comments are not for extended discussion; this conversation has been moved to chat.


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

Have you tried calculating the cyclometric complexity of this code?  It looks horrible.  I think it is a memory issue, probably a segmentation violation.  The order or you loops looks quite strange, the inner and then the outer.  Have you tried running this on a desktop (Linux or Windows) to get some debug data.

I think this is a pure coding error, so you might get better feed back on Stackoverflow.

@Matt Okay - thanks. Sorry for asking this, but when you ask if I have tried running this on a desktop, what do you mean by that? Do you just want my to move my code to a desktop computer and upload it from there?

Please calculate the amount of memory you are allocating on the heap. My guess is that you have allocated more than the 8K byte available. Trim your data structures. Even the mega is a MCU. Program accordingly, i.e. with limited resources in mind.

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.

I couldn't do all the work for you :)

You might want to look at the line b_score.push_back(std::vector<std::vector<float>>(999)); I suspect that is where the problem is (and the two similar lines above)

Yes, that did turn out to be the issue. Thank you very much


text:
Wemos D1 & Relay shield
For one of my hobby projects I would like to use:

Wemos D1 mini pro (schematic)
Wemos D1 Relay Shield (schematic)

to control the 24V (19W) mist maker.
My current wiring is this:

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.

Please let me know if any additional information is needed.

I am not sure, if a question about grounding should have been migrated here. D1 mini is not an Arduino and there aren't even any references to Arduino core firmware being used.

@gre_gor I understand what you mean but a Wemos D1 Is programmed through the Arduino IDE by default (that's what you mean by the core firmware?) So this is the right place for this board.  However I think this is really an electronics question, but ...

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.

I agree.  EMI noise from ultrasonic ~1A current may or may not affect other high Z inputs, which may benefit from twisted pair wires or shielded pair for power and decoupling LC filter near load.

I tested this wiring out and it seems that there are no issues with EMI noise. So all good. Thanks for answering this.


text:
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).

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.

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.

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.

Okay thanks, do you know if there any alternatives to arduino that would support heavier calculations then? Something like a pc-level motherboard but similar to arduino (so that you can easily combine different electronics, parts etc)

Within Arduino there is the Due which is like an arm processor and has more processor power but not close to a 3.4 intel either ... you could either go into the direction of raspberry pi, or maybe you should rethink your project. Like asking the question why you need a 3.4 GHz intel, why not do the calculations on a 'normal'  computer?

I am going to write a program that recognizes objects in a video in real time (probably at around 15 fps). Since it would be in real time the response should be as fast as possible, that is why id like to skip the streaming of data part. The goal is to make a robot that is independant of other devices so i cant have an usb connection either.

hmm actually, raspberry pi 3 has 1.2ghz that would probably suffice to be honest.

For video the Arduino will be too slow anyway. You need a lot of bandwidth for processing video. Probably the raspberry pi 3 is the way to go ... you could do the video processing on that, and leave the motor controls probably to the Arduino (if you need it when you have the raspberry).

Though the Raspberry Pi models are pretty anemic compared to regular PCs, they also do have a surprisingly decent GPU on them that may come in useful in applications such as image processing. And of course they have all the nice IO pins etc. like the Arduino. If you need PC-level power, you probably want to build your robot around a laptop.


text:
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
Kindly help me out since it has been days since I have stuck up in this issue.
Thank you!

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

What was it? I hate not knowing and someone else may stumble on this thread and it saves them asking.


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

Try "static int a = 0;"

It has to do with int a;. There's no "starting point" of what a is.

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.)


text:
How to recreate this basic ALPS switch board in Arduino?
I want to recreate this existing ALPS switch board (the board on the left) in Arduino, so I can control the switches (and 3 memory + 1 menu buttons) from my laptop. The ALPS switch board connects to a controller board (PSM) with relays, microprocessor, and DC motors connected to it.

The idea is to use Arduino to completely replace the ALPS switch board, while still preserving the controller board connection and current wiring and connector (16 pins + 2 empty pins).
Is there a way I can just connect the 16-pin connector directly to header pins on a certain Arduino variant? And program the individual pins, to replicate the manual switch input + 4 buttons?

See pin diagram attached (seen from the other end of the wiring, on the controller board side), where I get a little bit confused about terminal #C4 - #C7.
If easily possible, I want to use the controller board power, not the Arduino power.
I’m also not sure about what the 2000 Ohm resistor on the left side does exactly.
Edit 1:
Hopefully the new picture above clears things up a bit. The switch board connects to a PSM (Power Seat Module), which controls the DC motors of an early 2000s car power seat (don't think the OEM matters here). I want to control the PSM with my Arduino (so I don't have to use the ALPS board anymore). In other words, I have to replicate all the functionality from the ALPS board with my Arduino.
Edit 2: A picture of underside of Alps board:

Edit 3:
The P/N for the switch board is: ALPS ANJ971038D RH DR. And for the PSM (which includes the relays): ALPS ANV971018A. There is no public documentation that I found for any of the 2 boards. The pinout diagram above is from the dealership, but I'm not allowed to post further details about it.
Here are the results of what I measured myself using my multimeter. When the switch board is powered from the PSM I measured 4,5V on the + and - of the 4 memory buttons in neutral position. By pressing a memory butting the voltage drops to 0V. The + and - on the white switches measured 11,90V in neutral position. According to the pinout diagram the voltage is supposed to drop to 0V, but this didn't happen when I moved the switch while measuring. I also measured a resistance of 1490 Ohm between pin 2 and 5 of a white switch (so the neutral position), while the switch board was being powered! No resistance when the board is disconnected from the PSM.
I also measured pin #C4 and #C6/7 right from the connector, and I got 0,99V. #C5 and #C6-7 gave me 2,95V. Pin #C4 and #C5 are connected to the resistor (R1).
The switches are all momentary switches.
2 pictures of sketches/measurement results:

I think there's not enough information given for anyone to say (unless they happen to have that same board, and can read your mind to discover what you want to do).   Please edit your question to include the part number and model number the board is out of.    Please edit your question to indicate which switch connects to which pin, which switches are momentary or latching, and draw a picture of before and after  – ie, where the switch board is now, with what it connects to, and where you want it after whatever the conversion is.

Yes you could do that, if you could find the matching half of the connector.  You then run the leads off to your Arduino and write a program to do what you want.  How you do it is anyone's guess, but you could do it.

Before we can answer this question we will need a little more information from you. I can see that this board is for an electronic seat adjustment system. Do you want to replace the board in the picture with an Arduino or do you want to keep it and have the board control an Arduino? Also, what car is this board from?

@Matt I just edited. Is it more clear for you now?

@jwpat7 I just added more details. I think the pin diagram is clear enough on what pin connects to what switch, right? Which switch is doing what is printed on the switch board. All of the switches are in neutral mode as you can see on the picture. If you manually move the switch left or right or up or down, a signal will be send to the PSM and the motors to change the seat position. Let me know if you need further clarification.

That's much better. You probably wont find an off the shelf Arduino variant which would directly accept the plug but you can use an Arduino Uno with the Proto shield and wire up your own headers.  Please could you upload a picture of the underside of the ALPS switchboard and I'll try and figure out what that resistor is for.

@Matt Okay sounds good! Someone also told me I should use 8 relays (8 actions in total with the manual switches). I don't know why he said that or why I need it, if I can just directly program the pins from Arduino? (Still leaves open the question about the meaning of #C4 - #C7) Underside pic: https://imgur.com/a/CKSDZ

I was assuming you'd make some sort of graphical user interface on the software side which will replace the switches which will program the pins, so i'm not sure why they said that. That picture looks good, I'll get right on figuring out what the resistor does. Would it be possible for you to trace the wires to figure out which pins are connected on both ends? I'm not 100% sure but i think the #C4 and #C5 pins are used for diagnostics (The ECU uses them to check whether the board is connected and will bring up a fault code if not). I have a few people i can ask

Please could you get a picture of the board with the switches (Switches up pointing up like this picture at the top of this page) as top down as possible, i'm having a hard time seeing all the traces as some of them are hidden by the switches

CocoaNut, since the cable wiring at the Alps board end has a different pinout than the relay board end, you still should say which switch connects to which pin, and which switches are momentary or latching.  Also include all the documentation links and part numbers you have available, such as for the Alps board, the relay board, the PSM.  This will save time for people who are trying to help, by allowing them to find stuff on the web.   For example, there apparently is some document that you got the relay board pinout diagram from; what's the doc's name, and where is it found?

@Matt Yes, I indeed want to make a GUI! But after talking to an Arduino webshop guy, he also recommended me to use relays, based on the fact the switches are supplied with Ubat. So I measured 11,90V on 4 of the 6 switch pins when in neutral position. According to the pin diagram the voltage is supposed to drop to 0V as long as the switch is operated. When I operated the switch the voltage didn't change at all though on my multimeter.
I'll update my question later to reflect this information.

@Matt When I have my multimeter set to 2000 Ohm, it’ll either give me 1979 Ohm or 001 between C4/C5 and the resistor! So looks like you’re right :-)!
I also measured 0,99V and 2,95V on the C4-C7 circuits. Here’s a picture from a better angle: https://imgur.com/a/8bpZo (my Stack reputation doesn’t allow me to add it to the question).

Relays are good but as they are a mechanical device they have a higher rate of failure than a solid state device. I have personally used these MOSFETS in many projects and would highly recommend them http://www.ebay.co.uk/itm/10PCS-IRLB3034-IRLB3034PBF-HEXFET-Power-MOSFET-TO-220-NEW-/191736129878?hash=item2ca45d2956:g:n7cAAOSwI-BWQvbo     Here's the data sheet  http://www.infineon.com/dgdl/irlb3034pbf.pdf?fileId=5546d462533600a40153566027b22585

Have you been able to trace the wires between the plugs, as soon as you send me that information i will be able to start designing you a control board. Also, which Arduino would you like to use? I'd recommend an Arduino nano as they can be very easily integrated in to a custom circuit board.

@Matt Interesting, didn't know that! Thanks! I've been busy collecting answers, I hope to be able to update my post soon. I ordered some Arduino gear yesterday already. I have an Arduino Uno R3, Relay Shield v3.0 (4 relays, couldn't find one (in stock) with 8 relays), RedBear BLE Shield and an ARDX starter kit, so I have some extra components, wiring, breadboard, etc. The Arduino Nano looks good for a later stage in the project I think! (Same for MOSFETS, as it looks like it needs to be custom made, not an off the shelf shield)

http://i.imgur.com/GNR6K13.jpg   This is a picture of my most recent project's control board with the nano in the middle. Hopefully we'll be able to make something like this for your use-case or even get a custom PCB made but they can be expensive. If you don't mind me asking, what is your background? Have you got much electronics or programming experience?

@Matt Super cool! Looks exciting! Sorry it took me so long, but  I just added the extra information! (Still figuring out how to answer the "momentary or latching" question from yesterday.) Is this good enough for you? I have done some iOS projects and UI/UX design projects. So not a lot of electronics or Arduino programming experience. Do you have a website or a way to chat outside of this comments section ;)? I'm seeing a warning now to "avoid extended discussions in comments" ;-)

@jwpat7 Just added the details. Thanks for pushing ;-)!

CocoaNut, great, +1.  Note, the pinout voltages in diagram might be what you should see with cables attached both ends and under power, vs only one end hooked up. @Matt, you can flag the moderator to move the discussion to Arduino.stackexchange chat, if you want, which will key the discussion to the question.  Or just click on StackExchange, at top left corner of this page, then click 'chat' in the CURRENT COMMUNITY section, and open a chat.


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

Hey you can use Adfruit Motor Shield v2 [https://www.adafruit.com/products/1438] it allows 2 connections for 5V 'hobby' servos, Up to 4 bi-directional DC,Up to 2 stepper motors.

The suggestion of using an Adafruit Motor Shield V2 for Arduino 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.

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

if I were to wire exactly this diagram, however, would it still work for controlling 6 dc motors?


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

How much precision is required? Do you need to have a precise measure of the capacitance, or detecting a trip condition would be good enough? What is your application?

It's a capacitive sensing application.

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

Source: Use Analog Techniques To Measure Capacitance In Capacitive Sensors, 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):

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

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

Nice find,+1! I'm surprised how precise this method seems to be, considering it's based on the parasitic pin properties. Though I suppose this only works well with good EMI shielding or in EMI-free conditions.

Thank you :-)
I imagine you are right, though i never had the chance to stretch this method to its limits. From my experience with it, i was able to produce satisfactory results using an Arduino Uno board & 15cm long regular jumper wires in a day-to-day environment.

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

simulate this circuit – Schematic created using CircuitLab
Example: 1 megohm * 1 microfarad = 1 second

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...
 You said that your capacitor in dynamic in nature so you have to take atleast 10 values and average it to get accurate value.
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)
      ;
}

And what about the load capacitances of the arduino pins?

According to the ATmega328 datasheet it's around 14 pF. Too close to the measuring range for comfort. Plus any stray capacitance due to wires and to the Uno board and headers.

−1: This method is not really suitable for such small capacitances: you would need an insanely large resistance value, otherwise the time constant would be too short for making a good measurement. If you want to do an RC time constant measurement, you should instead use the method described in Dmitry Grigoryev's answer.

Yeah you are right. But I have tasted it and giving me good result not so precise and accurate but satisfactory. Cool down dude I have given him a generalized Idea not the solutions for his problem.

You gave “an idea”, and then a piece of code that does something very different from that idea. If you authored that code, why don't you explain what it actually does? If not, why don't you give credit to the original author?

Measuring small capacitance value via RC constant estimation essentially requires precise time measurement. ATmega chips have 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'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.

(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.

What is CCS??

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:

Set both pins to OUPUT LOW in order to discharge both capacitors.
Delay for one or two CPU cycles to make sure they are fully
discharged.
Set the analog input pin to INPUT mode: this will make it high
impedance and isolate the node connected to it.
Set the digital output to HIGH: this will charge the two capacitors
in series to 5 V.
Delay for one or two CPU cycles for the voltage to stabilize.
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.


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

As far as I know, avrdude checks every written byte. You will know when it failed. Some have done tests with the EEPROM, but I don't know a test with Flash. The old ATmega8 has the same numbers for flash (10k) and EEPROM (100k), but the newer chips are better. I suppose it starts failing after many 10k of writing.

@Jot, I'm still not sure if the consequence will be corrupted flash, if avrdude will gradually fail more frequently and have to retry, or if the flash will simply be incapable of being written to correctly, e.g. always yield an incorrect reading.

The datasheets tend to be conservative, and the numbers they give are usually valid for a wide temperature range. In room temperature conditions, chances are you can go far beyond the 10K cycles limit. You just cannot be 100% certain, as Atmel does not make any promise beyond 10K.

What I'm trying to ascertain, is how it will fail.

Actually, it will be undefined behaviour. Basically anything could happen and it should be avoided to do so.

@Paul, So in extreme cases, it would be relevant to separately keep track of flash write count? Since failure mode wouldn't behave predictably? E.g. a repeated failure on flash write

Soms programmer-boards or IDE's actually do this indeed. But often, you don't reprogram the micro more than 10.000 times.

This Wikipedia article 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.

Indeed. My concern is mainly in regards to actively developing on a custom PCB, with an ATmega2560 which wouldn't be too much fun to replace manually, although doable (100 pins + risk of hard-to-see short circuit of the pins). Or alternatively, buying several boards.

The reason for the high number of writes is that I'm fine-tuning various functions for automation, sensing etc. -- perhaps some of that could be alleviated by writing to the EEPROM via serial etc. etc. but that's a lot more complicated than just rebuilding/reflashing ;)

My first thought is whether any of those functions could be tuned out-of-system? And if not, what is the cost of a failure in the field vs. the steps necessary to prevent one? Will failure cost some downtime? A global service call? A customer relationship? Killing a patient? Some scenarios just simply justify even a huge upfront investment to avoid them. Ouch - talk about the rock vs. the hard place...

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.

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.

10k write cycles is a lot though.

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.

In my experience, this would be better suited as a comment than an answer.

I think it depends on what is more important: the answer of the question itself or the solution of his problem.

It is a good answer, because 10k trials is too much and it is better to fix the underlying problem. Perhaps delays are used which needs to be tuned (instead of using millis). Perhaps more than one Arduino board can be used, or Arduino Due with multiple tasks. I think that only a random generator to create working code would require so many trials.

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.


text:
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 [Editor's note: by user3880651],
but unfortunately non of those algorithm works with Arduino so upon my research I found this blog

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

I'm not voting to close this because it is Arduino based, but I think you might get a better (but more generic) response on the robotics forum, but don't mention 'Arduino' otherwise it will get bounced back to here :)
Good luck

As there's the code given in the blog, you may try reverse engineer it to understand the principles?

Both links posted are 100% about Arduinos. You asked for an algorithm, an several were given. An algorithm is not code; it's a method. Is your duty to implement that method in C, Java, Perl, Assembler or whatever is your language of choice.

Possible duplicate of Obstacle avoidance algorithm

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:

Obstacle avoidance doesn't really have any practical use unless it works alongside a goal finding algorithm.
Take a look here for a simple introduction (and a few modifications) to this excellent paper 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.


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

break the problem into parts: 1. get the api to talk to the nano. 2. get the nano to control the pins. #1 is harder

i can communicate with nano and send AT commands thorough it so all i need is a library

we're getting to the key part: you can send commands to it. Thinking about it, you might not be able to accept http connections to it, as a server. That makes sense, because it would be hard to code the back and forth with the server over serial. TBH, using the ESP as a module is weak sauce; the ESP is far faster, has way more RAM and flash. it's usually easier to push data from your 5v sensors on a nano into the ESP and then talk to the world with the ESP. I don't know why everyone does it backwards at first...

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.


text:
Attiny13 analogread() not working on all pins
I am new here and perhaps you could help me. I am trying to program Attiny13 with the following short sketch which uses ADC (analogread()) function, that is supposed to work like this:

reads voltage from voltage divider using photoresistor - analogread() from A1 (ADC1)
turns LED on/off whenever there is low light (covering photoresistor) - digitalwrite() LED at 3 (PB3)

however it does not work on each of the ADCs:
- works when I use A3 (ADC3) as analogread
- does not work when I use A1 (ADC1) or A2 (ADC2) as analogread
Do you know what might be the reason? Same code, but works on 1 of the ADCs only.
I program uC with USBASP programmer, but I don't think this matters since with 1 of the ADCs all works fine. Also it works on Arduino Mega 2560 and uC Atmega88, so something wrong with Attiny13.
Sketch that does not work:

int state = 0;

void setup()
{
pinMode(3, OUTPUT);
}

void loop()
{
    int reading = analogRead(A1);

    if (reading < 100) // ONCE I COVER PHOTORES. IT GOES INTO THIS LOOP AND TURNS ON/OFF THE LED
    {
        state = !state;
        digitalWrite(3, state);
        delay(200);
    }

    delay(100);
}

Please add links to attiny core and version info. for all components and tools.

Agreed. The fault will be in the definitions for the "board" or the core - whatever that may be for your setup.


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

The only time you read the EEPROM is right after writing it, which is pointless. You need to EEPROM.read() in setup() if you want the value restored at boot time.

That did the trick. Appreciate it man!

Also you only want one value to store the counter in, not two. Either a or value - take your pick.

The EEPROM.read and EEPROM.write read and write only a single byte. You can use EEPROM.put and EEPROM.get to read and write an (unsigned) int or a (unsigned) long.

I see you always use address 0, since EEPROM has a limited write life (like 10K or so), maybe it's best to use difference addresses. 10K presses is a lot, but not unrealistic over a long time probably.

@MichelKeijzers: The EEPROM is rated for 100K write cycles.

My normal EEPROM method is to set a variable to the desired value, along with a timestamp variable. Reset the timestamp variable every time the button is pressed. Then when a certain time has elapsed since the last press write the value to EEPROM. That way if you press the button 50 times in quick succession you only get one write to EEPROM. A couple of seconds delay on the write works well.

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

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/