text:
What does Arduino do in 15ms?
I was wondering why there is a 15 ms delay between each iteration of a the main loop.
Code:
The following code shows the execution time expressed in microsec between each loop
void setup()
{
  Serial.begin(9600);
}

void loop()
{
  Serial.println();
  Serial.print("Start: ");
  Serial.print(micros());
  Serial.print("/////////////////////");
  Serial.print("End:");
  Serial.print(micros());
}

Output:
Start: 789452/////////////////////End:821692
Start: 837292/////////////////////End:869532
Start: 885132/////////////////////End:917372
Start: 932972/////////////////////End:965212

Arduino needs 32,240 msec to print the messages to serial and to call the micros() function twice. And this it's fine. Now, considering the difference between the values of the End and the following Start, one question arises:
What does Arduino do between each loop?

Your serial connection is set to 9600 baud, which is 9600 actual data bits per second. The communication consists (*) of 8 bit characters and every bit is useful data (no parity), so you would be able to achieve at most 9600 / 8 = 1200 characters per second.
You have a message of 46 characters including the line break, which brings you to 1200 / 46 = 26 iterations per second.
1000 milliseconds / 26 iterations = about 39 milliseconds per iterations.
This is the theoretic maximum you would get if you would send the data over serial without any other overhead. Pretty close to the 32 + 15 = 47 milliseconds you measured.
Since you print a part of the message (Enter + 'Start:') between the end of the previous iteration and the start of the next (if you take the call to micros() as the start and end), it makes sense that a part of the time is in between there as well.
So the actual overhead you are looking at is about 8ms per iteration. This delay is spread out over the loop and the call overhead of the various functions you use. After all, when you call Serial.print, a lot of work needs to be done before the data can actually be sent to the serial port. You would probably gain more speed/less overhead if you would construct one big string, and send it with a single print command.
Arduino itself is slow, but still much faster than this. It should be able to do a big(ger) number of iterations per second, but you basically limited it by initialising the serial connection to such a slow speed. You can partially eliminate this by picking a higher number. I think both your Arduino and any modern serial port should be able to handle 115200 baud. Nevertheless, you will always have a relatively big overhead when you are sending data over serial. Use your bandwidth wisely, and reduce the number of calls to Serial.print as much as you reasonably can.
*
) 8 bit, no parity is the de facto default. See Serial.begin() for more information about initializing the serial connection.

Note that the 9600 figure is "bits per second", not "baud". You are right that "baud" means "actual data bits" (as opposed to overhead bits, such as start, parity and stop bits), but that distinction is often lost - and in this case incorrect. Each character is 10 bits - 1 start, 8 data, and 1 stop - so the correct number is 960 characters per scond.

@JohnBurger Thanks for that addition. The default setting is indeed 8 data bits and 1 stop bit, no parity, so with a start bit that would be 10 bits per character indeed. You can by the way configure this in the optional second parameter of Serial.begin(). Anyway, the documentation says 'bits per second (baud)', so if you are right, then the docs are wrong (or I misunderstood something).

Like I said: your definition of the original term "baud" is factually correct - but that usage has been confused with "bits per second" for so long now that the distinction is lost to the general public. They'll say "9,600 baud" when they mean "9,600 bps", so documentation follows this (incorrect) convention - although you'll note they used parentheses! In fact, if you were to say to someone "Set your baud rate to 7,680", you'd be correct but unsatisfied, as you won't be able to establish communicatons...

@JohnBurger, The distinction between "baud rate" and "bit rate" is not about which bits are data, and which bits are framing.  The "baud rate" on a wire tells how many times per second the line state changes.  When there are only two line states (usually called "0" and "1", or "mark" and "space"), then the baud rate equals the bit rate.  But when you're using modems for long-distance comms, there can be four or eight line states, and the baud rate then is 1/2 or 1/3 of the effective bit rate.  All most of us ever care about is effective bit rate.  Baud rate is for modem designers.

@jameslarge Huh. I was taught what I explained above nearly 30 years ago. I can find other articles on the web with the same misunderstanding (or indeed the opposite w.r.t. bps vs baud!) - but all the scholarly articles agree with your description. Apologies @GolezTrol!

Also note that "how many times per second the line state changes" isn't completely correct either: it should be "...the line state could change". A series of 0 or 1 bits (for NRZ encoding) would not involve line state changes, but the number of bits sent would still go up.

@JohnBurger, D'Oh!  Of course you are right.

Just check the sourcecode
for (;;) {
    loop();
    if (serialEventRun) serialEventRun();
}

So it does a check if serialEventRun is True, and then a jump back to the beginning of the for-loop. And then a call to loop.
Also note that Serial.print is blocking if the TX-buffer is full. So you might want to add a delay somewhere to ensure the buffer is never full.

Your code is slightly off if you want to accurately time this
Serial.print("End:");
Serial.print(micros());

Will get micros() before printing to serial, and then take the time to print it. You also print some text before taking the time at the top of the loop. Your 15 ms is the time to print these to serial between reading micros. For example, change the loop code to something like this:
uint32_t time, endTime;
...
void loop(){
    time = micros();

    Serial.print(endTime);
    Serial.print('\t');
    Serial.print(time);
    Serial.print('\n');

    endTime = micros();
}

and you should only see a small difference. It showed a 4 microsecond difference when I ran it. The only other thing that runs outside the loop is the serial event handlers, but if you don't use one it obviously doesn't take long.

TL;DR: The delays you measure (32.24 ms between Start and
End, and 15.6 ms between End and Start) are exactly what
is expected from the amount of data you send through the serial port.
Yes, exactly: there is zero overhead from the CPU doing other things.
Let me show how the expected timings can be computed. First, a note
about the exact baud rate. A rate of 9600 bps implies that each bit
takes about 104.17 µs to send. However, the Arduino being clocked
at 16 MHz, it cannot achieve this exact baud rate. Instead, when
you request 9600 bps, you get the closest value it can achieve,
which is about 9615 bps. Then, each bit takes exactly
104 µs. Or at least “exactly” as per the Arduino clock: it really
takes 1664 CPU cycles.
Then, as already noted in previous answers, one character is worth
10 raw bits. It thus needs 1040 µs to be transmitted.
Now, let's look at your code. It should be noted that
Serial.print(micros());

is compiled into something equivalent to
unsigned long timestamp = micros();
Serial.print(timestamp);

i.e. the timestamp is taken and then it is transmitted. Your loop()
is then equivalent to:
void loop()
{
    Serial.println();                       //  2 chars: CR and LF
    Serial.print("Start: ");                //  7 chars
    unsigned long time_start = micros();
    Serial.print(time_start);               //  6 chars
    Serial.print("/////////////////////");  // 21 chars
    Serial.print("End:");                   //  4 chars
    unsigned long time_end = micros();
    Serial.print(time_end);                 //  6 chars
}

By folding the last Serial.print() of one iteration into the beginning
of the next one, one gets the pseudo-code:
forever {
    print 15 chars;  // 15*1040 = 15600 µs
    read time_start;
    print 31 chars;  // 31*1040 = 32240 µs
    read time_end;
}

The computed durations match exactly your printout. This shows that,
once the Serial output buffer is full, the timing of your code
execution is completely governed by how fast the UART sends the bits out
the line. The time taken by the Arduino to do actual CPU work (calling
micros(), formatting numbers...) is irrelevant because the CPU works
in parallel with the UART and, being faster, it ends up waiting for
the UART anyway.

Re "zero overhead from the CPU": Because there is hardware transmit buffer (even if it is only one slot)?

@PeterMortensen: Indeed. The one-byte hardware buffer and the larger software buffer, combined, ensure that the UART is never stalled, waiting for the CPU to provide data to send. Without the hardware buffer, the latency of the “USART data register empty” interrupt would show up in the transmission.

At 9600now each data byte needs 10 bits to be transmit. Or 1ms per byte.
20 bytes will take 20me to transmit.
However, the existence of a buffer and the way the transmission is carried out can greatly impact the duration of execution of your code - actual time for transmission is invariant however.
If your transmission is done via the interrupt, the execution can be almost instantaneous.

“the existence of a buffer and the way the transmission is carried out can greatly impact the duration of execution of your code”. In the OP's example, this is true only at the very beginning. Once the output buffer is full, the timing of the code execution is entirely dictated by the UART.

("me" → "ms")


text:
Assembling a float from an array of bytes
I would like to convert an array of bytes, received from serial, to a float.
Let's consider this exemple. I'm sending 0.12 byte-wise from an Android application. The conversion from float to array of bytes in the Android side is handled by this function
public static byte [] float2Bytes(float value)
    {
        return ByteBuffer.allocate(4)./*order(ByteOrder.LITTLE_ENDIAN).*/putFloat(value).array();
    }

When bytes arrive, they are stored in an array and the assembled.
hiBytew1 = bufferBytes[9];
//Serial.println(hiBytew1);
loBytew1 = bufferBytes[10];
//Serial.println(loBytew1);
hiBytew2 = bufferBytes[11];
//Serial.println(hiBytew2);
loBytew2 = bufferBytes[12];
//Serial.println(loBytew2);
float conAck = assemble(hiBytew1, loBytew1, hiBytew2,loBytew2);

How can I achieve this kind of conversion assuming that bytes are received in the correct order?

Just cast the pointer.
float conAck = *((float*)(bufferBytes + 9));

This needs parentheses around “bufferBytes + 9”.

Right, otherwise it will advance sizeof(float) * 9 bytes instead.

Grazie Ignacio, so it will automatically assemble the sequence in a float variable? Nice

@UserK: It will tell the compiler that the bytes it will be looking at are a float.

@userk there is no assembly. Floats are already stored as bytes in memory. You are asking android to put the 4 most meaningful bytes in the buffer. Then you are trekking arduino to consider the bytes together as a float. If you are to store the same number in memory it week have the same representation. In a nutshell, this is an O(1) operation.

Ok grazie prakharsingh95

source: Stack Exchange

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

sort: votes


text:
How to set address for using more than MPU9250
I am trying to build a project that contains more than one MPU 9250, until now I'm still confused to MPU9250. If I were going to that, does anybody here know how to set addresses to each of the MPU's I am going to use? Thank you for spending time reading my question. I hope someone will help me get through this.

It is possible to have up to two MPU 9250 devices on an I2C bus without any extra logic. Pin 9 (AD0/SD0) defines the lowest bit in the I2C address of the device. Please see Chap 7.2 I2C Interface
If you need to connect more than two devices this can be done by connecting the AD0/SD0 pin of each device to a chip select pin on the arduino. This pin is asserted when addressing the device (This solution was provided by @Gerben, see comments below).
An example with three MPU 9250: Arduino D4-D6 are used as chip select pins. MPU1 AD0/SD0 pin connected to D4, MPU2 pin to D5, and MPU3 to D6. D4..D6 are initiate to HIGH. When addressing a MPU the chip select pin is set to LOW and the lower I2C address is used for access. The other MPUs will be listening for the higher I2C address.
Cheers!

You could connect the AD0/SD0 pin to an arduino pin (source). That way you can set the unit you want to communicate with to one address, and all the other units to the second address.

@Gerben Please explain how this would work. Sounds like you are talking about chip select for SPI. For I2C, one of the MPU 9250 should have the AD0/SD0 pin tied to GND and the other to VCC (preferable with resistor).

By connecting the AD0/SD0 address pin to the arduino, you can change the address "on the fly". So you set the pin to HIGH on every module except one, and then use address 1101000 to connect to the one module with AD0/SD0 set low. This however assumes that the module allows changing the address on the fly, and doesn't e.g. only read the AD0 pin on powerup. See also; http://hackaday.com/2015/03/27/using-i2c-addresses-as-chip-selects/

@Gerben Thanks that explains the idea. It is actually a bit like SPI chip select addressing but with the I2C address match instead. Thanks for sharing that!

This is the type of information which a Data Sheet is intended to communicate.  In I2C mode the AD0 pin selects between two possible addresses,
1101000 for AD0=0 and
1101001 for AD0=1.
In SPI mode you can presumably have as many as you like by giving each its own chip select.
That said, using multiple sensors may not be very useful unless your apparatus is flexible - only the 3 accelerometer axis would be expect to yield different values based on position relative to the center of rotations.

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


text:
Arduino C, Led > binary alternative all lights
I'm trying to alternatively have a random int generate a binary number with 4 lights.
This is my current code, However, it seems that all the lights(leds) go on, I don't think the minus option works. As in, it won't take a value from the currently randomized digit. (randombinary = randombinary - x)
I also tried just "randombinary - x"

const int button = 2;
const int redone = 13;
const int redtwo = 8;
const int greenone = 12;
const int greentwo = 7;
int randomnumber = 0;
int randombinary = 0;

void setup() {

  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(2, INPUT);

}
  void loop() {

delay(1000);

  int randomnumber = (1, 15);
  randombinary = randomnumber;

  if (randombinary >=8){
    digitalWrite(redone, HIGH);
   randombinary = randombinary - 8;
  }
 else {
   digitalWrite(redone, LOW);
 }

  if (randombinary >=4){
    digitalWrite(greenone, HIGH);
   randombinary = randombinary - 4;
  }
  else {
    digitalWrite(greenone, LOW);
  }

  if (randombinary >=2){
    digitalWrite(redtwo, HIGH);
  randombinary =  randombinary - 2;
  }
  else  {
    digitalWrite(greentwo, LOW);
  }

  if (randombinary >=1){
    digitalWrite(greentwo, HIGH);
  randombinary =  randombinary - 1;
  }
  else  {
    digitalWrite(greentwo, LOW);
  }

  }

Would appreciate any help!

Please edit your question and state what you want to happen.  Eg, "Generate a random number.  Turn on light x if ..., turn off light x if ..., turn on light y if ..., turn off light y if ..." and so forth.

Code review (one possible solution can be found below)

Absolute numbers in the code, like 15 as the limit for the random numbers are generally considered harmful. It would be better to give all absolute numbers a constantsname and use these throughout. The OP code did not use the constants for the pins, for instance.
Writing similar pieces of code in a row makes maintenance hard. Therefore, group similar items in any kind of list, like an array, and iterate over them.
Functions should have expressive names clearly stating what is going on inside.
Functions should be short and concise, ideally having only a few lines.

Try something along these lines:
// setting the number of bits to analyze, corresponding pins and corresponding powers of two.
// the latter is here for instructional purposes although it is redundant.
const int numberOfBits = 4;
const int randLimit = 15;   // 2^(1+numberOfBits)-1 actually;
int ledPins[numberOfBits] = {13, 8, 12, 7};
int bitValue[numberOfBits] = {8, 4, 2, 1}; // the powers of two

void turnOffAllLeds ()
{
  Serial.println ("turning all off");
  for (int i = 0; i < numberOfBits; i++)
  {
    digitalWrite (ledPins[i], LOW);
  }
}

void selectivelyTurnOnLeds(int value)
{
  turnOffAllLeds ();

  // now for each bit, check if it is set in the value, if yes: turn on corresponding led
  for (int i = 0; i < numberOfBits; i++)
  {
    if ((value & bitValue[i]) > 0)
    {
      digitalWrite (ledPins[i], HIGH);
    }
  }
}

void setup()
{
  for (int i = 0; i < numberOfBits; i++)
  {
    pinMode (ledPins[i], OUTPUT);
  }
}

void loop()
{
  selectivelyTurnOnLeds (random (randLimit));
  delay (1000);
}

P.S. When posting a question, please also post what your code is supposed to do. If it were not for a lazy prechristmas workday, I would not have taken the time to reverse engineer your code.

Thank you !! My apologies for the late reply, I'm working on it now, Yours is very tough, I cannot seem to get it working, yet I myself am not sure how exactly you've done it, this is a bit over my level. I for example, don't know how where the "i" is linked to, nor do I know why you put (int value) after the selectivelyturn... void. I thank you kindly, and I'm sorry for not being clear in my question, it was the first time I've entered a forum for help.. It's always giving the value of 15, but the leds change nevertheless

int randomnumber = (1, 15);

Guess you have missed to call random. That statement actually always returns 15. C is a strange language.
int randomnumber = random(1, 15);

Cheers!

Thanks a bunch! You're a savior, Now only I have to make it so that I have the button input match the random binary which results into a victory LED if it's completed. :S It's going to be tough

I actually just moved it into a new void, as due to the loop, it kept recreating a new binary. Now it only shows the value of 8, each time.. do you happen to know what could possibly be wrong? Nothing in the code changed

Something must have changed if you moved it into a new void! Post the new code under the old to keep the history of the question.

Thank you for your time, I've replied to this inquiry myself with the new code and issue.

So here's the new version, very strange, when I set the number on random, it doesn't work. However, if I enter a number myself, it does.
const int button = 2;
const int redone = 13;
const int redtwo = 8;
const int greenone = 12;
const int greentwo = 7;
int randomnumber = 0;
int randombinary = 0;

void setup() {

  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(2, INPUT);

      maarten();

    }
      void loop() {

      }

      void maarten(){

      int randomnumber = random(1, 15);
      randombinary = randomnumber;

    if (randombinary >=8){

      digitalWrite(redone, HIGH);
      randombinary = randombinary - 8;
    }
    else {
      digitalWrite(redone, LOW);
 }

    if (randombinary >=4){

      digitalWrite(greenone, HIGH);
      randombinary = randombinary - 4;
    }
    else {
      digitalWrite(greenone, LOW);
    }

    if (randombinary >=2){

      digitalWrite(redtwo, HIGH);
      randombinary =  randombinary - 2;
    }
    else  {
      digitalWrite(greentwo, LOW);
    }

   if (randombinary >=1){

     digitalWrite(greentwo, HIGH);
     randombinary =  randombinary - 1;
   }
   else  {
     digitalWrite(greentwo, LOW);
  }

  }

But now the setting (maarten) is only done once?

Please do the edits in the main question so folks know which code to work with.  I'd replace the conditional subtraction math with bitwise operations on an unsigned value  "unsigned int randombinary; ... digitalWrite(redone,randombinary && 0b1000 ); ..."


text:
Detecting grass, pavement, gravel
I think about building my own robotic mower, therefore I would like to detect if the surface the mower in moving on is grass, pavement, gravel ... etc.
Which sensors would be the best choice in order to achieve this?
The benefits:

no parimeter wire to bury
possible lawn edge detection (here most mowers fail to do a good job)

I have found this DIY mower page (where they apparently already implemented a grass sensor). Grass sensor. Other useful info can also be found (mixed in english and german).
They are measuring the capacity of the underground in about 2cm (1inch) height.
On gravel or other hard material this is near 0 (as the sensor is in the air). On grass the value is higher.
Haven't though of this solution, should be the way to go.

You could try to use a force sensitive sensor to detect when grass blades touch it.

I like this "bumper" idea, as it can serve two purposes. Tiny force means grass (good). Big force means object (bad). No force (no grass).

Yes and no ... you are mowing the grass and changing the surface the mower is detecting. But it might be a good indication for the mower to know if he already mowed this region ... as a complementary sensor not a bad idea at all.

A combination of colour sensors as the predominant one and proximity sensors as the secondary one should work fine. Around $10 so definitely worth trying out. Also, the code should be relatively easy.
Here are links as samples. I hope this helps :)
$6 colorvsensor
$4 Proximity  sensor

You may need to use a combination of sensors. I can't think of any single sensor that can reliably detect the different surfaces.
An IR sensor could detect the difference between grass (cooler) and pavement/gravel (warmer).
An ultrasonic ranging sensor could detect the difference in heights between the grass and pavement/gravel.
A photoelectric sensor could detect the difference in reflectivity between the grass and gravel/pavement.
A visual camera could be used with image processing to detect color differences, although this may be too processing intensive for an Arduino.
A final possibility would be measuring the resistance to movement of the wheels. The robot will travel easier over the hard surface of pavement/gravel.
I would think that a combination of the above sensors would provide the most reliability and accuracy. However, it will still likely be limited to one location without recalibration. The weather will even cause a change in some of the sensors (photoelectric for example on a sunny vs. cloudy day).

Definitely a sensor combination is the solution ... a camera detecting the greenish colour plus IR ... pattern detection is out of scope.


text:
SparkFun ESP8266 find out when on battery power and when charging
For one of my projects I use the SparkFun ESP8266 board with an additional LiPo battery in cases power supply goes down.
Now I would like to communicate the power loss - or the fact that the board is running on battery power via WiFi.
Is there a way to find out (in code) when the board switches from mains power to battery and back?

Can I connect ADC pin to ground in order to make this method work? Otherwise what is the easiest way to disconnect ADC pin on esp8266 thing dev board ?

You can implement this software if the voltage is different in both cases.
The voltage from the power supply should be higher than the voltage of the battery, but do not exceed the permissible values.
Then you can use ESP.getVcc() :

ESP.getVcc() may be used to measure supply voltage. ESP needs to
  reconfigure the ADC at startup in order for this feature to be
  available. Add the following line to the top of your sketch to use
  getVcc:
ADC_MODE(ADC_VCC);
TOUT pin has to be disconnected in this mode.
Note that by default ADC is configured to read from TOUT pin using
  analogRead(A0), and ESP.getVCC() is not available.

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


text:
Timer (or other) interrupt happens while servicing an interrupt - how to accurately handle the second one?
This seems like a simple question but I'm not finding an answer so far: at a high level, say I have a timer interrupt and some input interrupt. The input arrives, the ISR is entered, interrupts are (automatically by default?) disabled, I service the input (quickly!), but while that's going on a timer used for some other purpose fires. I don't want to miss that timer but because interrupts are disabled my input processing won't get interrupted for it.
I exit the input ISR and interrupts are (automatically?) re-enabled. Assuming the timer is uncomplicated (it wouldn't overflow twice during my input ISR) how do I accurately handle the fact that it overflowed during my input ISR and I "missed" it?
Would this differ if instead of the timer I simply had a second input2 that similarly might fire during my input1 processing (but would present a useful input long enough to process after input1, presuming I knew it triggered)?
I'm not looking to nest interrupts here, just to understand what happens when an interrupt happens during another ISR which has temporarily disabled them - do they pend and fire after the blocking ISR returns, or are they just lost?

Q1:

... exit the input ISR and interrupts are (automatically?) re-enabled

Yes, the RETI (return from interrupt) instruction enables interrupts.  See third paragraph of section 7.7 in Atmel's document #8271 (a 650-page spec sheet for the Atmega 48, 88, 168, 328 series), which says:

When an interrupt occurs, the Global Interrupt Enable I-bit is cleared and all interrupts are disabled. The user software can write logic one to the I-bit to enable nested interrupts. All enabled interrupts can then interrupt the current interrupt routine. The I-bit is automatically set when a Return from Interrupt instruction – RETI – is executed.

Q2:

Assuming the timer is uncomplicated (it wouldn't overflow twice during my input ISR) how do I accurately handle the fact that it overflowed during my input ISR and I "missed" it?

If the timer is running a clock, set the timer control bits to automatically reload the count register upon each overflow (or underflow).  That will leave a full count period for processing each timer interrupt.
That is, you can pre-load a next-timer-count (I think it can be different from the current count if necessary), so the timer can start its next interval automatically.  If the timer is used for some purpose more complicated than that, you may need a nested interrupt.
Q3:

Would this differ if instead of the timer I simply had a second input2 that similarly might fire during my input1 processing (but would present a useful input long enough to process after input1, presuming I knew it triggered)?

If indeed input2 sticks around long enough to process after input1 processing is done, no problem.  Its interrupt will occur after the first interrupted code sequence executes one more instruction after the RETI occurs.  (See paragraph 6 of section 7.7 in doc8271.)
If input2 is brief, several different things can happen.   (a) If it is shorter than a clock cycle, in general it won't trigger an interrupt.  (b) If it is a level-interrupt-triggering event on INT0 or INT1 that ends while another interrupt is being processed, it won't trigger an interrupt.  (See discussion on page 72, section 13.2.3, of doc8271 of INTF0 and INTF1 being clear for level interrupts.) (c) If it is an interrupt-flag-setting event that sets a flag and ends while another interrupt is being processed, it will trigger an interrupt after the global interrupt flag is set, unless current processing clears its flag.
I think the above accurately states what happens on Atmega devices, but I suggest you also see doc8271 – and run tests – to see for yourself.  Here is part of what paragraphs 4 and 5 of section 7.7 in doc8271 say regarding (b) and (c):

There are basically two types of interrupts. The first type is triggered by an event that sets the Interrupt Flag.  ... Interrupt Flags can also be cleared by
  writing a logic one to the flag bit position(s) to be cleared. If an interrupt condition occurs while the
  corresponding interrupt enable bit is cleared, the Interrupt Flag will be set and remembered until the interrupt is enabled, or the flag is cleared by software. Similarly, if one or more interrupt conditions occur while the Global Interrupt Enable bit is cleared, the corresponding Interrupt Flag(s) will be set and remembered until the Global Interrupt Enable bit is set, and will then be executed by order of priority.
The second type of interrupts will trigger as long as the interrupt condition is present. These interrupts do not necessarily have Interrupt Flags. If the interrupt condition disappears before the interrupt is enabled, the
  interrupt will not be triggered.

So, based on some slow timer I need to do some background task, but one in a while I'll get an input during which the timer interrupt would've fired, but because I was processing that input (though quickly) I missed the timer's interrupt. Will the timer overflow interrupt stay flagged so that I can process it after I return from my ISR? (Similarly once triggered will the interrupt for input2 be ready for processing after input1 is done, even if data is a bit stale?)
I (think) I see the point about reloading the timer, but that seems like it'd skew timings unnecessarily.

Actually, that might fall under the "input flag setting event" thing above.


text:
Controlling EL wire or panels with arduino
I understand that el wire and paper needs a special power source known as an inverter to light it up.
If I wanted to control it from an arduino, what point would I connect the arduino to the light or inverter?

upstream slow blinking
The simplest approach:
Use a relay to turn the lights on and off. Control that relay with an Arduino.
("How to turn a relay on and off with an Arduino?" is a separate question).
Cut either one of the wires feeding power into the EL inverter ("upstream of the inverter"),
and connect the 2 cut ends of the (formerly) one wire to the contacts of the relay.
power source ---- (relay contacts) ---- EL inverter ---- (EL wire)
           +--------------------------------+    +---------+

downstream slow blinking
Alternative approach:
Use at least 2 pieces of EL wire.
Wire one always-on;
use a relay to connect or disconnect the other wire ("downstream of the inverter"). (The relay and controlled wire can be either directly connected to the inverter, or end-to-end connected to the always-on wire -- it doesn't matter for this application).
                                   always on
power source ---- EL inverter ---- (EL wire) ---- (relay contacts) ---- (EL wire)
           +----------+    +---------+   +-------------------------------+

Control that relay to control the EL wire with an Arduino, same as before.
dimming and PWM
Many low-cost relays are rated for only about 10,000 operations, so if you use them to blink for a long or short part of each second, they're only guaranteed to last for about 3 hours.
If you want to blink faster than that (and most people dim EL lights by blinking them much faster than that), you'll have to use something other than a relay.
Also, most people seem to want to do the switching "downstream" of the inverter, so they can "share" a single EL inverter and use it to power lots of independently controlled pieces of EL wire.
Perhaps the simplest approach is to use an off-the-shelf zero-crossing solid-state relay (SSR).
("How to wire a SSR to an Arduino?" is a separate question).
power source ---- EL inverter
          +-----------+   | |
                          +----- EL wire (always on)
                          | +-----+
                          | |
                          +----(SSR)-- EL wire
                          | +-----------+
                          | |
                          +----(SSR)-- EL wire
                          | +-----------+
                          | |
                          +----(SSR)-- EL wire
                          | +-----------+
                          | |
                          +----(SSR)-- EL wire
                          | +-----------+
                          | |
                          ... etc.

Because most SSRs are overkill for this application -- most of them have heatsinks bonded to high-power triacs designed to handle far more current than we need to light up a EL wire --
some people save a few dollars by assembling their own SSRs out of zero-crossing optocouplers, triacs, etc.
(A lower-cost, low-power triac is more than adequate for controlling EL wire, even without a heatsink).
The SparkFun EL Escudo Dos Arduino shield for controlling electroluminescent wire(c)(d);
Diana's SparkFun EL Sequencer(e)(f)(g);
the seeedstudio EL Shield(h)(i)(j)(k);
Tully Gehan's Cool Neon Arduino Shield(m)
etc.
uses such zero-crossing optocouplers, triacs, etc.
(requires a separate EL inverter).
According to some people on the Arduino forums talking about EL wire(n)(p),
some people save a few pennies by using normal optocouplers rather than zero-crossing optocouplers. Non-zero-crossing optocouplers seem to work fine for short pieces of EL wire but seems to destroy the triacs (failing "always on") with a few dozen feet of EL wire.
Some people save a few more pennies by skipping the optocoupler,
wiring the Arduino directly to the control gate of the triac, and the VCC pin of the Arduino directly to the MT1 pin of the triac.
(q) (r) (s) (t)
If there were some way to only turn the triac on near the zero-crossing, this could work great; but without zero-crossing control, this has the same problems as the above normal non-zero-crossing optocouplers.
always-on
The "extra" always-on bit of EL wire is because some people say
"never run the inverter without at least 1 foot of EL attached"(a) because running some EL inverters with no load "can damage the inverter"(b).

For a simpler option, there are Arduino shields for controlling El Wire.  Sparkfun makes a couple and they have some sample code and projects.
https://www.sparkfun.com/products/10878

You could connect the Arduino to the light using a relay or any electronic switches (transistors and etc) that can take around 10 to 15mA per meter (so its distance dependent). You could use this link https://learn.adafruit.com/el-wire/soldering-to-el-wire to find out where to solder the switch connections to

EL wire runs on high voyage AC power. So you can't just use transistor. A relay or triac should be used.

Well, there are transistors that can withstand high voltages but I do agree a relay or triac would be more appropriate. Just listing out the options.

So the arduino would control the relay that is between the inverter/power source and the light either allowing current to flow or resisting it?

Yes. EL wire > Relay > Source

Yup, but note that you wont be able to use PWM according to Adafruit due to the characteristic of the EL wire

If I'm using the 5v from the arduino and this inverter (http://elwirecraft.co.uk/el-products/portable-inverters/mini-portable-1xaaa-battery-inverterdriver-for-1m-el-wire-or-50sq-cm-el-tape/) what kind of relay should I buy?

I'm not sure how much is the voltage output of the inverter in the link but the Adafruit one has an output of 100VAC so you might need a relay that can handle a voltage of 100VAC or more (contact voltage). In addition to that, the relay would also need to support a coil voltage of 5v. Coil resistance then depends on the model of Arduino you are using. For example, you'll need a coil resistance that will give 40mA or below for Arduino UNO or you could control a transistor to switch the relay as suggested by this link http://forum.arduino.cc/index.php/topic,17227.0.html


text:
Sketch stops printing after writing a few times
I am trying to build a random horoscope printer. I have a series of strings in an array which I am storing in program memory. I then pick a random number and print that index concatenated with a title. But it often (but not always) only runs 4 or 5 times.
#include <avr/pgmspace.h>

const char string_0[] PROGMEM = "You have a great need for other people to like and admire you. ";
const char string_1[] PROGMEM = "You have a tendency to be critical of yourself. ";
const char string_2[] PROGMEM = "You have a great deal of unused capacity which you have not turned to your advantage. ";
const char string_3[] PROGMEM = "While you have some personality weaknesses, you are generally able to compensate for them. ";
const char string_4[] PROGMEM = "Your sexual adjustment has presented problems for you. ";
const char string_5[] PROGMEM = "Disciplined and self-controlled outside, you tend to be worrisome and insecure inside. ";
const char string_6[] PROGMEM = "At times you have serious doubts as to whether you have made the right decision or done the right thing. ";
const char string_7[] PROGMEM = "You prefer a certain amount of change and variety and become dissatisfied when hemmed in by restrictions and limitations. ";
const char string_8[] PROGMEM =  "You pride yourself as an independent thinker and do not accept others' statements without satisfactory proof. ";
const char string_9[] PROGMEM = "You have found it unwise to be too frank in revealing yourself to others. ";
const char string_10[] PROGMEM = "At times you are extroverted, affable, sociable, while at other times you are introverted, wary, reserved. ";
const char string_11[] PROGMEM = "Some of your aspirations tend to be pretty unrealistic. ";
const char string_12[] PROGMEM = "Security is one of your major goals in life. ";

const char* const string_table[] PROGMEM = {string_0, string_1, string_2, string_3, string_4, string_5, string_6, string_7, string_8, string_9, string_10, string_11, string_12};

void setup() {
  Serial.begin(9600);
  randomSeed(analogRead(2));
}

void loop() {
    Serial.println("WE GOING TO LOOP NOW");
    char buffer[50];
    int rand = random(0,12);
    Serial.println(rand);
    strcpy_P(buffer, (char*)pgm_read_word(&(string_table[rand]))); // Necessary casts and dereferencing, just copy.
    char text[15] = "Your horoscope";
    String output;
    output = strcat(text, buffer);
    Serial.println(output);
    delay(1000);
}

I also sometimes don't seem to get very clean results, but I'm not sure why. I.e. printing WWWW... and missing the first part of the string in the serial monitor.
WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWE GWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWE GOING TO LOOP NOW
1
Your horoscopeYou have a tendency to be critical of yourself.
WE GOING TO LOOP NOW
3
or them. While you have some personality weaknesses, you are generally able to compensate for them.
WE GOING TO LOOP NOW
4
Your horoscopeYour sexual adjustment has presented problems for you.
WE GOING TO LOOP NOW
2
ge. You have a great deal of unused capacity which you have not turned to your advantage.

What you see is undefined behavior. You define your buffer to have a length of 50 bytes:

char buffer[50];

This is too short for most of the strings you want copy into it and you will thus overwrite other variables.
The simplest solution is to increase the buffer size so that the longest string fits (e.g. 150). You will see that it then works as you expect. Take a look at http://linux.dd.com.au/wiki/Arduino_Static_Strings for hints how to avoid wasting RAM for the buffer.


text:
Unusual LCD behaviour
Can someone please tell me what's going on with my LCD screen and how I can fix this issues below?
I have the following:

Arduino Uno R3 w/ ATMEGA 328P-PU
16x2 LCD
TowerPro MicroServo SG90
DPDT Slide Switch w/ 120 ohm resistor

Objective:
Read the sensor value (If switch is on or off), and move a servo accordingly while displaying switch state on LCD.
Issue:
LCD display seems to receive random data during program run (see image). All starts up well, and as soon as a few seconds have lapsed in the void loop(), the screen becomes garbled. Also, the switch value (while debugging) gets a zero reading while HIGH, acting accordingly as if the switch was off. The servo motor runs as it should, but gets random pulses every now and again where it starts to buzz, but doesn't turn.
Images:
Three images below.

Schematic:

Coding:
#include <LiquidCrystal.h>
#include <Servo.h>

const int sensorPin = A0;    // select the input pin for the potentiometer
int ledPin = 13;      // select the pin for the LED
int sensorValue = 0;  // variable to store the value coming from the sensor
int oldPos = 0;
int pos = 0;
int oldStat = 0;

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
Servo servo;

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcd.setCursor (0, 0);
  lcd.print("Starting up FSS!");
  delay(700);
  lcd.clear();
  lcd.print("Init SERVO...");
  delay(500);
  servo.attach(9);
  lcd.clear();
  lcd.print("SERVO Success!");
  delay(400);
  lcd.clear();
  lcd.print("Testing SERVO...");
  servo.write(0);
  delay(200);
  servo.write(90);
  delay(200);
  servo.write(45);
  delay(300);
  lcd.clear();
  lcd.print("SERVO Running!");
  lcd.clear();
  lcd.print("Select AUX Source");
  pinMode(ledPin, OUTPUT);
}

void loop() {
  lcd.clear();
  lcd.setCursor (0, 0);
  lcd.print("Select AUX Src");
  lcd.setCursor(0, 1);

  sensorValue = analogRead(sensorPin);
  Serial.print("Sensor: ");
  Serial.println(sensorValue);

  if(sensorValue == 0){
    //if(sensorValue = oldStat){
      oldStat = sensorValue;
      digitalWrite(ledPin, LOW);
      lcd.print("Switch is OFF");
      pos = 45;

      Serial.println("Switch is OFF");
    //}
  } else{
    digitalWrite(ledPin, HIGH);
    lcd.print("Switch is ON");
    pos = 120;
    Serial.println("Switch is ON");
  }

  if (pos != oldPos){
    servo.write(pos);
  }

  oldPos = pos;

  delay (700);
}

Insufficient decoupling. Put a 100nF cap on the supply lines at the LCD and a 100uF cap on the supply lines at the servo.

I'll need to get the 100nF and then I'll install that. I'm also going to build a voltage supply apart from the base. If the decoupling works, I'll mark as answer. Thanks!

Get a dozen or so. They're one of the most common to use.

Electronics is not my strong suit (obviously) so what's happening here? The arduino is behaving correctly (and probably reading the value correct) but it just can't display it because of noise from the servo affecting the transmission to the LCD? So a Serial.println would print the correct value or not?

@Madivad: The servo has caused the power to the panel to go pear-shaped, so you can't even know if the electronics in it are in any shape to be sent any commands or data.


text:
Separate Timer Instance
I'm trying my best attempt here after failing in Googling the answer, but here goes:
I'm trying to get a separate instance to start running in the background when a pin goes HIGH. How should I attempt this? PLEASE explain your answer, so that I can learn as well. I'm using an Arduino Uno R3 with a Commercial Ir RX-Tx.
Basically:
Sensor -> Low -> Loop
Sensor -> High -> Start Other Event for 5 min -> Loop while Counting down to reset state.
My thoughts here are:
Do this via 555-timer OR get some functional coding (anyone maybe want to share here what solutions they have found?)
Thanks.

The answer can be summed up into one three word phrase: "Finite State Machine". A technique you should learn and learn well. Google it and marvel at the results now you know what to search for,

A separate instance of what?

Arduino Uno has two interrupt pins: 2 and 3, and by hooking up the output of your IR, which goes from LOW to HIGH, it will trigger the function that you defined in the code.
For example this is a piece of code that runs when the pin 2 RISING:
void setup() {
    attachInterrupt(0, doSomething, RISING);
}

void loop() {
}

void doSomething() {
    //Do your stuff
}

Look here for further information link


text:
How to drive a 4bit GLCD?
i've got a huge (about 6 x 23 cm) graphics LCD. I used my multimeter and the datasheet the LCD driver chips (6 x KS0104 and 2 x KS0103) to get the pinout. It has the following pins: GND, M, FCS (not 100% shure), CL1, CL2, D0-3, VDD and a ground for the metal part.
My problem is that i dont know how i can drive a 4bit GLCD with an Arduino because i didnt found a library which can do this (e.g. OpenGLCD supports only the KS0104 which is an 8 bit controller)

What type of Arduino? A driver for that will require a lot of memory.

I already got an UNO but if it is necessary i could buy a MEGA (if it works).

How large is the LCD? Number of pixels. According to the product description (KS0104) it is 4-bit per pixel (16 levels gray-scale). Is that correct?

i counted about 17 pixels on 1 cm so this should be something like 391x138

That gives a total of 54K pixels. And with 4-bit per pixel, two pixels in a byte, 27K byte to store a packed off-screen bitmap. Even an Arduino Mega would have too little memory for that. This might explain why there are no supporting library for that device.

You might be right but i think i could also buy a DUE or ZERO (if necessary) and the main problem is not the amount of pixels, it is the 4bit connection (which is not supported by any GLCD library).


text:
Is the analogread function averaging the samples taken by the ADC?
In many development boards the analog voltage data which is sampled by the ADC can be sent to the serial port. But the data speed I see on the serial port by HyperTerminal or Serial monitor is much slower than the sampling rate.
Lets take Arduino as an example. As far as I understand the analogread() function samples an analog input at 10kHz rate. It means 10000 samples taken per second.
But when I use the Serial Monitor it seems the data speed which we see as upcoming/flowing line by line per second on Serial Monitor is much slower.
Is that because the analogread() is averaging the samples before the data is sent to the serial port?

analogRead() doesn't send the samples anywhere. I think you need to look at some example code and then revisit your question.

ok i edited to: "Is that because the analogread() is averaging the samples before the data is sent to the serial port?"

That function only reads the ADC value, it doesn't do anything else. The 10KHz you mention is related to how often you can call that function, it has nothing to do with what the rest of the code is doing with that data.

"In many development boards the analog voltage data which is sampled by the ADC can be sent to the serial port" I've yet to see one that does this unless you write a program to do so. "Lets take Arduino as an example" So are you talking generally or just Arduino? Since this is a software question the answer will depend on the exact software used.

It can sample at 10kHz, doesnt mean it does. When you analogRead and serialPrint, it does it once and prints once. If you want some sort of running average you have to implement it, there's nothing obscure running in the background.

@WesleyLee No indeed I dont want averaging. But when I see the readings in Serial Monitor it is much much slower rate. Let me put it this way. If I use a watch and start and stop sampling for 1 second I must have at least 10000 sampled data by the ADC. But the serial monitor shows muc much less lines than that. Why is that happening?

So what do I see at the Serial Monitor then? It is not all the samples, it is not the average. It is what then? :(

We can't tell what you are seeing on the Serial Monitor because that varies from firmware to firmware. I'll repeat myself: if you use analogRead then Serial.print in a loop, you are seeing all the samples.

@WesleyLee thanks for the last clarification. that was what i was asking about.

If you have a loop that calls analogRead() to take a reading, and then serialPrint() to send the reading, each pass through the loop will take at least the sum of the time for those two functions calls together.
When you first call serialPrint(), it returns in uS, as it doesn't actually send data, but puts it into the 64 deep transmit buffer, to be sent in the background. If the transmit buffer is emptying slower than you are filling it (at 9600 baud, it's sending roughly one character per mS, so you can send at most 100 off 10 character messages per second) then eventually when called, it will find not enough space in the transmit buffer for the whole message, and will Block, that is not return, until there is enough space. Each call to serialPrint() will now take 10mS (assuming 10 characters at 9600 baud). That's what slows your loop down.
To send faster, choose a higher baud rate, and reduce the number of characters in the message.

void loop()
{
val = analogRead(analogPin);    // read the input pin
Serial.println(val);             // debug value
}

it is sad that using analogread as above code in a loop we will never know the exact sampling rate right?

The sampling period is the time it takes for a loop to complete. So the rate would be 1/looptime.

@WesleyLee last question. can we trust each loop time will ve equal? thanks

I'm not sure since I don't know how Arduino deals with jamming stuff on its serial buffer.

I've told you, it has a 64 long buffer, it returns fast when there's buffer available, it blocks when there isn't. I had my 'scope on a debug pin last week timing a serialPrint(), so I know which orifice I'm talking out of!

@user16307: “Can we trust each loop time will be equal?” No, you can't. Sending “1000” takes longer than sending “999”: one more byte to send. And then there is the timer 0 interrupting your code roughly every millisecond: each time it's interrupted, the loop takes ≈ 6.25 µs longer to complete (assuming an AVR-based Arduino). If you want constant sampling rate, forget analogRead() and read the datasheet: the ADC can be auto-triggered by a timer, or even by itself (free running mode).

As far as I understand the analogread() function samples an analog input at 10kHz rate.

No, it samples an analog input at once per invocation. This means that if it is run 10000 times within a second (assuming it can be run that many times within a second) then the code is sampling at 10kHz. But if it's run only twice per second then the code is sampling at 2Hz.

Let me ask the same question to you. When I see the readings in Serial Monitor it is much much slower rate. Let me put it this way. If I use a watch and start and stop sampling for 1 second I must have at least 10000 sampled data by the ADC. But the serial monitor shows much much less lines than that. Why is that happening?

Because your understanding of how analogRead() works is completely and irredeemably broken.

@user16307 -- "If I use a watch and start and stop sampling for 1 second I must have at least 10000 sampled data by the ADC" That assumption is wrong to begin with, any reasoning based on that will be wrong.

If during that second you call analogRead once, you will have one sample.

Imagine analogread is in a loop and sampling 5kHz per second. Now we use a watch and start and stop sampling for 1 second. At the serial monitor you will see much much less lines of voltage readings. But actually the samples are 5000

You get one sample per call. Ever. Always.


text:
Need help modelling and coding a feedback scenario

Above illustration is the basic setup for the question. The scenario will be the following:

A potentiometer(providing 0 to 5V) is an analog input to A0. This
  potentiometer voltage is converted to PWM(pin9) which controls a fan M1. Which
  means the human controls directly the M1 fan speed.
This directly speed-controlled M1 fan creates air pressure on a sensor
  Sen1.
On the other hand I want M2 fan to reach to a speed(via pin10 PWM) such that Sen2
  should output the same voltage as Sen1. Which means eventually voltage
  at A1 analog input should be equal to A2. So one can achieve same air pressures at Sen1 and Sen2.

I'm not experienced in PID or other type of controls. I would be glad if someone can help me to relate parameters and code this scenario.

You may find Robotics Stackexchange useful for questions like this.

If you want, I can move this to the Robotics Stack Exchange. Just say if you do.

Well, (very) simply you could slowly increase/decrease the PWM value driving M2 until the voltage at A1 equals that of A2. If you make the time between adjustments long enough you should not get any (significant) oscillations.
However, more likely you want to get to the correct M2 PWM value quickly and for that you need a Proportional, integral, Differential (PID) control algorithm. Explaining this in detail is outside the scope of a S.E. answer, but in summary:
You have a value that signifies the current state of the system - which will be the A2 reading.
You also have a value that states where you want to get to - which will be the A1 reading.
You also have a control value - which will be the PWM value of M2
The Proportial part looks at how far away the A2 reading is from the A1 reading.
The  Integral part looks at how quickly we (the A2 reading) are moving towards (or away from) the desired value (the A1 reading). The Differential part looks at how long we have been away from the desired value.
Each of these (PID) parts (with tuning values that you set) contributes towards determining a new value for PWM at M2 and this iterates around with new values getting the current state closer and closer to the desired value.
There are lots of Arduino PID examples around. I'd suggest you read up on the algorithm itself and have a look at the Arduino.cc samples here.

PID loops are a good way to go for something like this, but, you don't need to implement all three parts.  I have done industrial control using just the P and I.  Start by implementing just the proportional part.
For this, you calculate the error between the input signal (Va0) and the feedback signal (Va1). This is just a subtraction Err = Va0 - Va1.
You now multiply the Err by a constant and add that to Va0 to adjust the PWM.
A bit like this pseudo code:
  k = 0.5;
  Err = Va0 - Va1;
  pwm = Va0 + (Err * k);

Then set the pwm to the new calculated value.
This gives a correction proportional to the error.
Experiment with k.  Start at 1. See how it goes.
Depending on the sensors you may have to apply some gain and/or offset to the Va1 reading in order to make it so that when the motor is at the correct speed, the calculated Va1 reading reads the same as the Va0 input.  For example, say the output range of the sensor is 0V to 2.5V, you will need to multiply by 2 before calculating the Err.
The P part of PID can give acceptable results.  The next stage would be to implement an I part. Do the P and see whether the I is needed.

I want M2 fan to reach to a speed(via pin10 PWM) such that Sen2 should output the same voltage as Sen1.

simple:
  adc_sens1 = readadc(SENS1_PIN); //read adc on sense 1 pin
  adc_sens2 = readadc(SENS2_PIN); //read adc on sense 2 pin
  if (adc_sens2>adc_sens1 + SENS_DELTA) pwm_set(M2_PIN, --dc_ms); //if sens2 value too high, slow down m2's duty cycle -> positive correlatin assumed
  if (adc_sens2<adc_sens1 - SENS_DELTA) pwm_set(M2_PIN, ++dc_ms); //otherwise, increment duty cycle

No error check, no boundary check, ..... but the basic idea is the same.

authors: Вадим Дашкевич


text:
A confusion with setting timers
I was reading a tutorial on timers. My aim is to generate 16MHz pulse output from the pin 8.
Here is the code I modified from the tutorial (I use Arduino's ATmega328P):
#include <avr/io.h>
#include <stdint.h>

int main (void)
{
    DDRB |= (1 << 0); // Set LED as output
    TCCR1B &= ~(1 << CS11); // Set up timer
    TCCR1B &= ~(1 << CS12); // Set up timer
    TCCR1B |= (1 << CS10); // Set up timer

    for (;;)
    {
        // Check timer value in if statement
        if (TCNT1 >= 0)
        {
            PORTB ^= (1 << 0); // Toggle the LED
            TCNT1 = 0; // Reset timer value
        }
    }
}

I use the following formula:

Target Timer Count = (1 / Target Frequency) / (1 / Timer Clock
  Frequency) - 1

So Target Timer Count = 0 in my case.
But I get 615kHz on scope.
My timer setting should output 16MHz since I use no prescaler:

What am I doing wrong?

You can have the timer toggle the led, instead of doing it yourself (by using the COM1A1/COM1B1 bits in the TCCR1A register. To set the maximum value of the timer from 65535, set the timer to CTC mode, and set OCR1A to 1 (or maybe 0). If you want to do software PWM, just use while(true){PORTB ^= (1 << 0);}.

If you want to output a signal at the same speed as the system clock, I would not recommend using a timer.  You can output the system clock to Port B Pin 0 by programming the CKOUT fuse on the 328P.
The reason I suggest not using a timer to output a signal at the same frequency of the system clock is that the compare of TCNT1 you have as well as the toggle of the output will take clock cycles so the output will never quite be the clock speed.
If you use a timer for outputting a signal, I suggest using CTC mode of Timer 1 using the output compare to set the top.  You can then either poll the appropriate Output Compare Match flag or handle the related interrupt.

I agree with this. This is the only way that the Atmega328P running at 16 MHz can output a 16 MHz signal. Using timers the maximum you can get is 8 MHz. If you want to see code that does 8 MHz using timers see Example of generating 8 MHz signal


text:
At what frequency/rate does the digitalRead function read an input?
Consider the following code:
void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
  }
  else {
    // turn LED off:
    digitalWrite(ledPin, LOW);
  }
}

The line buttonState = digitalRead(buttonPin); checks the input voltage.
But how is that checked internally?
I mean at what rate the input is checked?

The check is performed in one single cycle, but the whole routine takes WAY longer. It's not clear what you are asking. For info: http://jeelabs.org/2010/01/06/pin-io-performance/ Summary: "digitalRead() takes 3712 ns, direct port read takes 151 ns, a ratio of 25:1

So it is roughly 0.3MHz right? That could be the answer to my question?

As I said it's not clear what you ask: your input is checked once every loop, meaning that you need the time for one digitalRead, one IF, one digitalWrite, one JUMP to the beginning othe next loop. DigitalRead COULD work at 0.3 MHz if you call it continuously, but you are doing more stuff.

Add a delay at the end of the loop and measure micros() once at the beginning of the loop, once at the end before the delay, and send via Serial.println(microsAfter-microsBefore).

I did some benchmarking on the cost of Arduino - in that case for digital write. I can easily do so for digital read as well. When I get time, I will provide more definitive answers. It is sufficient to say now that the cost in performance is quite substantial in avrs and considerably less on stm32.

When I get time, I will provide more definitive answers.

I did follow through with this, and the result is here, towards the end of the page: https://dannyelectronics.wordpress.com/2016/05/01/the-price-of-avr-arduino/
the short answer is: digitalRead() takes 4.9us to execute on a 16MIPS Arduino Uno, or 79 ticks (=instructions).
the fastest you can read digitalRead() is then 200KHz (= 1/4.9us).
Hope it helps.

It read a port just like it reads memory (to which it's mapped.) So speed is how fast an instruction can read memory.  EEPROM is a different animal.
Might get it a little faster by replacing
buttonState = digitalRead(buttonPin);
    with
buttonState = PORTB & _BV(buttonPin);
Assuming it's PORTB that you are using. This will alleviate at least one function call, I would think, and will generate a single instruction to read the port into the variable. It may require an instruction to load the variable address, but that's up to the compiler.  The replacement may be more trouble porting to other micros.  Normally you don't see a variable as a parameter although legal, usually a constant in a #define.
_BV(INPUT_PIN_X) is a macro (BV is for 'bit value') that expands to
(1 << INPUT_PIN_X)
dannyf times seem quick to me, but it sounds like he's done the testing. Is he taking into account the complete function call as part of the time?  I run at 1Mhz normally, so it's more difficult to relate.
Take Majenko advice and start reading the generated assembler :)
Best of luck.

For pins above 7, won't, for example _BV(13) give you masks like B1000000000000 and not work sensibly with PORTA or PORTB? Wouldn't buttonState = *portInputRegister(digitalPinToPort(buttonPin)) & digitalPinToBitMask(buttonPin); be more robust?

Ack -- digitalRead(buttonPin) gives a 1 or 0, while PORTB & _BV(buttonPin) could give you 0,1,2,4,8,16,32,64,128 depending on the state of the pin and which pin on the port you are looking at.

That depends on the frequency your Arduino runs at.
It's basically once per iteration of the loop, and that depends on everything that is happening in the loop.
You can examine the assembly language output of the compiler (disassemble the .elf file using avr-objdump -h -S <elf file>) and count the number of clock cycles per iteration (the datasheet has the number of clock cycles per instruction). However that is tedious.
If you want to read the input at a specific frequency then you should do it using a timer interrupt.

Can you give a rough number for a short code like in my example?

No, I can't. Not just like that. You could toggle an IO pin each iteration of your loop and read the frequency using an oscilloscope, then double it. That is how fast the loop is running at that moment in time.

It is based on the frequency of the arduino and the 'amount' of operations in loop() and serial_event() methods, is it not? More operations in the loop,  lower the read frequency.


text:
Unable to obtain pulse train at 32Hz with 20us pulse width with Uno
I tried to obtain 32Hz pulse train(between 30Hz and 35Hz is also fine) with around 20us pulse width with Arduino Uno but couldn't succeed. The problem is:
If I do the following:
void setup() {

    TCCR1B = TCCR1B & B11111000 | B00000101;

    pinMode(pwmPin9, OUTPUT); // sets the pin as output

}

void loop() {

analogWrite(pwmPin9, 1)

}

I can set the freq. roughly at 30Hz but analogWrite(pwmPin9, 1) will give minimum 100us cannot go down to 20us.
digitalWrite method with delay on the other hand doesn't work to obtain frequencies below about 60Hz.
How can I obtain a pulse train output with between 30Hz to 35Hz and with around 20us pulse width?

Instead of digitalWrite() write the values directly to the PORT register. This takes a lot less time than the big digitalWrite() function. Also you can do this with a timer compare interrupt, so that you will be able to get exactly the frequency you want.

could you write an answer an an example?

For this kind of problems, the first thing to do is convert the two
relevant times (the signal period and the duration of the HIGH state)
into a number of CPU cycles. With a 16 MHz clock that gives:

HIGH time: 20 µs =    320 CPU cycles
period: 31.25 ms = 500000 cycles (±7%)

Then divide those numbers by the available prescaler values, to get the
corresponding number of prescaled clock cycles:
prescaler       1      8    64     256      ...
HIGH time     320     40     5       1.25   ...
period     500000  62500  7812.5  1953.125  ...

Ideally, you want a prescaler that gives you integer numbers, in order
to avoid rounding errors. And since you are using a 16-bit timer, you
want these numbers to be no larger than 216. Or twice that if
you use a phase-correct PWM mode, but I prefer to avoid that
complication if possible.
From the table above, it appears that a prescaler of 8 is ideal. 64
would be practically as good, with a frequency error of only
64 ppm, which is less than the frequency tolerance of the ceramic
resonator clocking your Uno.
Then you use either OCR1A or OCR1B to set the high time, depending
on whether you are outputting to pin OC1A (digital 9) or OC1B (digital
10). An you use either OCR1A or ICR1 to set the period. Since you
are outputting on pin 9, the OCR1A register will be used to set the
high time, thus you have to use ICR1 to set the period. Then you
search the table of modes in the datasheet and find the one relevant to
this mode of operation is mode 14: fast PWM with the TOP value
defined by ICR1. This gives the following configuration:
void configure_timer_1()
{
    DDRB  |= _BV(PB1);    // set pin 9 = PB1 = OC1A as output
    TCCR1A = 0;           // reset timer
    TCCR1B = 0;           // ditto
    OCR1A  = 40 - 1;      // HIGH for 40 * 8 CPU cycles
    ICR1   = 62500 - 1;   // period = 62500 * 8 CPU cycles
    TCCR1A = _BV(COM1A1)  // non inverting PWM on pin OC1A
           | _BV(WGM11);  // mode 14: fast PWM, TOP = ICR1
    TCCR1B = _BV(WGM12)   // ditto
           | _BV(WGM13)   // ditto
           | _BV(CS11);   // clock at F_CPU/8
}

Note that OCR1A and OCR1B have to be set to desired number of cycles
minus one.

analogWrite is 8-bit.
The reciprocal of 30Hz (the time per full period) is 0.0313.
0.0313 divided by 256 (28) is 0.000122, or 122uS.
At 8 bits that's the smallest time that the 30Hz waveform can be cut up into.
To get smaller slices you need a higher resolution PWM signal. This question and answer shows how it can be done, but it's limited to which pins can be used, since you need the PWM channels attached to the 16-bit timer.

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


text:
Data acquisition/logging question
I want to use an Arduino Uno for a data-acquisition purpose.
Normally adhoc data acquisition boards can record each sample at a desired sampling rate. So that I can plot all the samples recorded. I want to do the same sort if thing with Arduino.
I want to record 30 minutes of analog voltage input at 4kHz sampling rate and record all the samples taken to a PC.
And at the end I want to be able to plot the data with all samples not the averages ect.
Is there an easy workaround for this?

Depending on your data format that could be up to 28MB of data. No way an Arduino alone can deal with that without somewhere to off-load the storage to, such as maybe an SD card (that is if the Arduino can store data on SD that fast). 4kHz is a reasonable sampling speed for the Arduino, though you can't really use analogRead() for that. Instead you want to investigate free-running and/or timer based sampling.

Here is a program I wrote that follows an approach somewhat similar to
Michael Stachowsky's answer:

The ADC is configured with the prescaler set to 128 (just like the
Arduino core does), which gives a 104 µs conversion time,
significantly shorter than the 250 µs sampling period you want.
The first conversion takes longer, and it is discarded.
It is also configured an auto-trigger mode, and the timer 1 overflow
flag is selected as its trigger source.
The timer 1 is configured to loop every 500 × 8 = 4000 CPU cycles
(clocked at F_CPU / 8, with TOP = 499), which
provides the required 250 µs sampling period. It is set in a PWM
mode even though the PWM outputs are not used, simply because in this
mode the overflow flag is set every time the timer loops.
An interrupt is triggered every time an ADC conversion is complete.
The interrupt service routine clears the timer overflow flag (this is
required because the ADC is triggered by the rising edges of this
flag), saves the result in a global variable and sets a global flag.
The main loop waits for that flag and sends the data through the
serial port, in binary, LSB first:

the sample number modulo 64 (6 bits)
the sample value (10 bits).

The serial port runs at 115.2 kb/s, it can then transmit the two bytes
of data in about 174 µs, which is less than the sampling period.
The sample numbers, and a 16-byte preamble can be used as a sanity
check by the receiving end.

#include <avr/interrupt.h>

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

    // Transmit preamble.
    for (int i = 0; i < 16; i++)
        Serial.write(0xff);

    // Start the ADC.
    ADMUX  = _BV(REFS0)   // reference = Vcc
           | 0;           // input = ADC0
    ADCSRA = _BV(ADEN)    // enable the ADC
           | _BV(ADSC)    // start first conversion
           | _BV(ADPS0)   // prescaler = 128,
           | _BV(ADPS1)   // ditto
           | _BV(ADPS2);  // ditto

    // Wait for the first conversion to complete.
    loop_until_bit_is_set(ADCSRA, ADIF);

    // Wait for the preamble to be fully transmitted.
    Serial.flush();

    // Stop timer 1.
    TCCR1A = 0;
    TCCR1B = 0;

    // Configure the ADC in auto-trigger mode.
    ADCSRA |= _BV(ADATE)   // enable auto-trigger
            | _BV(ADIF)    // clear interrupt flag
            | _BV(ADIE);   // enable interrupt
    ADCSRB  = _BV(ADTS1)   // trigger source = timer 1 overflow
            | _BV(ADTS2);  // ditto

    // Configure Timer 1.
    ICR1   = 500 - 1;     // period = 500 * 8 CPU cycles
    TCCR1A = _BV(WGM11);  // mode 14: fast PWM,
    TCCR1B = _BV(WGM12)   // ... TOP = ICR1,
           | _BV(WGM13)   // ... overflow flag set on TOP
           | _BV(CS11);   // clock at F_CPU / 8
}

volatile uint16_t reading = 0xffff;
volatile bool reading_available;

ISR(ADC_vect)
{
    TIFR1 |= _BV(TOV1);    // clear timer overflow flag
    uint16_t x = reading;  // work on a copy of the reading
    x &= ~0x03ff;          // remove previous ADC value
    x |= ADC;              // add current ADC value
    x += 0x0400;           // increment sample number
    reading = x;
    reading_available = true;
}

void loop()
{
    // Wait for a reading to be available.
    while (!reading_available) ;

    // Grab a copy.
    uint16_t x = reading;
    reading_available = false;

    // Transmit, LSB first.
    Serial.write(x >> 0);  // low byte
    Serial.write(x >> 8);  // high byte
}

How you deal with the data on the receiving end (save to file, skip
preamble, check sample number consistency, extract sample values, plot
them...) is up to you. You can use whatever language and tools you want.
It is not an Arduino-related question.
Addendum: More about the binary format used.
There is a preamble consisting of 16 0xff bytes. This can be useful
because it is not uncommon to get in one file a mix of data from two
different runs of the program. The buffering of the serial port on the
PC can lead to this happening. If you do not want that preamble, remove
the two lines right after the “Transmit preamble.” comment.
Then there is a continuous stream of 16-bit unsigned integers
(uint16_t), transmitted LSB first (i.e. little endian). The byte order
can be changed by swapping the two Serial.write() by the end of the
program.
Each of these integers contains an ADC reading in the lower 10 bits and
a sample number in the upper 6 bits. The sample number can be extracted
by right-shifting (x >> 10 in C) and could be used as a sanity check
(the number should increment by 1, modulo 64, from one sample to the
next). The ADC reading can be extracted by masking out the sample number
(x & 0x03ff).
If you do not want the sample numbers, you can simplify the ISR to:
ISR(ADC_vect)
{
    TIFR1 |= _BV(TOV1);    // clear timer overflow flag
    reading = ADC;         // read the ADC result
    reading_available = true;
}

and remove the (now useless) initialization of the reading variable.

Thanks I uploaded the code. In Arduino IDE's serial monitor I'm see weird characters not ones and zeros or numbers. How can I convert the upcoming data to numbers? And which analog input is this code sampling?

@user16307: It's sampling analog input 0. You can sample another input by replacing the 0 in the line | 0;  // input = ADC0. You see weird characters because it's binary data, not text. If you want text, you will have to convert it. How you do the conversion is up to you, and it's not an Arduino question.

Thanks a lot. But I would be glad at least of you tell me which binary format is this code sending data? If I save the data and when I convert the binary to text I need to know the format saved. Is it uint16? Im not so familiar with. MATLAB has functions to read such binary. I mean is this data uint16 little endian?

@user16307: Yes, it's uint16 little endian. I amended the answer to make the format more explicit, and to provide instructions on how you can change it.

Im still trying to extract the time and voltage readings from your code. Is 8 bit part is time in seconds and the other 8 bit part is voltage reading? Why dont you use Serial.print instead of Serial.write?

@user16307: No, it's 6 bits: sample number and 10 bits: voltage reading. Serial.print() would format the result in ASCII, which would be easier to deal with on the receiving end, but it takes more bytes to send. At 4 K samples/second, there is no time to send ASCII-formatted readings through Serial. Binary is your only option.

Amazing explanation. Thanks. So what I need to do is to divide the 16 bit to two parts 6 bit and 10 bit in C# part. I still couldn't manage it. Maybe I should only use the voltage readings. In that case I will update the ISR(ADC_vect) as you mentioned in addendum. In that case the line Serial.write(x >> 0);  // low byte will send the voltage readings right?

I think I was wrong.   Both Serial.write(x >> 0);  // low byte
Serial.write(x >> 8);  // high byte should be used to transmit 10 bit data. Now I only receive voltage data by setting ISR(ADC_vect) to ur suggestion. I use Realterm terminal program and get values of tens of thousands as voltage readings as uint16. Shouldnt the uint16(eventhough it can up to around 65000) format output max 255 since max ADC is 10 bit? Did you try this code before? Please test your code with Realterm if u have time. I dont understand why Im having that big numbers.

oh sorry my mistake again the baud rates were not matching before. now it works 5V corresponds 1024. is that ICR1   = 500 - 1;  line setting sampling  rate? is it possible to sample 1Hz modifying this code? thanks anyway..

@user16307: In order to get a 1 Hz sampling, you have to set the prescaler to 256 (replace CS11 by CS12 in the code), and set ICR1 = 62500 - 1.

This question is actually two or three different questions.
To the first: is it possible to record 30 minutes of data with an arduino uno at 4KHz: no.  Assuming even that you are only taking 1 byte of data at a time, the uno only has 2K of RAM, so you'd be out of RAM in under a second.
To the second: can you instead send this data to a PC at the desired rate: possibly, depending on how much data you are taking.  If it's just a single analog channel, then you can most likely do it.  Anything more and I doubt it.  The problem is that you'll simulutaneously have to read the analog at the correct time AND send the data to the PC, presumably over the serial.  As long as you use Serial.write, NOT Serial.print, then your UART should be more than fast enough at high baud rates to handle a single channel with minimal overhead.  However, that would mean that you have to reconstruct the data on the PC, but that's the third question, to which I shall turn shortly.
If you need absolute real-time operation, then you need to use timer interrupts, which are not native to the Arduino libraries, if I recall correctly.  However, a quick google for "Arduino timer interrupt" leads me here: http://playground.arduino.cc/Code/Timer1, which is where you should start.
In terms of plotting the data: that's not an Arduino problem, that's a problem for whatever you choose to use to collect and analyze your data.  I suggest Excel, since it's relatively common, or Google Sheets, since it's free.  If you have access to Matlab, though, that's a much more powerful program.  Either way, that is off topic for this forum.

Rather than a timer interrupt, I would use a timer to trigger the ADC, and the ADC interrupt to read the data. This will provide a more steady acquisition rate than triggering the ADC from a timer ISR.


text:
Reading a tachogenerator
I'm trying to read a tachogenerator from a washing machine. It outputs an alternating current, with multiple periods per revolution. The voltage for my test case (constant rpm) reads 5.5V. I attached the tachogenerator to Digital 2 and GND and ran this sketch, just to see if a change is detected:
int ledPin = 13;
volatile int state = LOW;

void setup() {
  pinMode(ledPin, OUTPUT);
  attachInterrupt(0, blink, RISING);
}

void loop() {
  digitalWrite(ledPin, state);
  delay(500);
}

void blink() {
  if (state == LOW) state != state;
}

Unfortunately, the LED does not light when I start the motor. When I measure the voltage while it is connected to the Arduino, it shows only about 0.7V, which would explain why the LED is not reacting. But why is this?

There's an obvious code problem in your blink() function:
state != state;

The above statement will never modify your state variable. The != operator in C/C++ does not perform an assignment (unlike operators such as += and -=). It's a comparison operator which just tests for inequality. You presumably meant to do this:
state = !state;

That may not fix your problem entirely though. You might find that the interrupt doesn't get reliably triggered anyway because it's not designed to handle AC. I'd recommend using an external comparator circuit to generate a clean digital signal, such as a Schmitt trigger.


text:
Are INTx pins the only ones eligible for Software Serial?
As opposed to PCINT (Atmel's Pin Change INTerrupt, INTx is arduino-compatible interupt)  In other words, does Software Serial use atmel's pin change or arduino falling interrupt?

SoftwareSerial uses PCINT.  AltSoftSerial uses INT0 or INT1, which has FALLING, RISING, CHANGE or LOW LEVEL options.  See Section 12.2, p. 71 of the Atmel ATmega328 spec, for example.


text:
Can the IDE handle a 32khz main clock?
I read somewhere that having the main clock be 32768Hz messes not only with micros() and millis(), but with some other stuff too. Is this true? Will I have to forgo the Arduino IDE to program for an avr running at 32768Hz?

Do you still need to know if filter capacitors are required? https://electronics.stackexchange.com/questions/416523/32khz-crystal-for-avr-caps-needed

@VE7JRO No. And are you able to answer this question?

Sorry, I don't have a definitive answer for you. There is a debate about it here: https://forum.arduino.cc/index.php?topic=75397.0

Please tell us why you want a main clock of 32.768kHz. Have you heard of the XY-problem http://xyproblem.info/ Most microcontrollers and processors that are used in arduino boards are capable to use a crystal of 32.768kHz but the arduino code is not for such a low clock.

Yes, things will break. The main culpret is this:
#define clockCyclesPerMicrosecond() ( F_CPU / 1000000L )

With any value below 1000000 the result of that calculation will be 0.
That means code like micros() will break, since it uses:
return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());

64/0 is ... um ... yes... And whatever that ends up being is then multiplying the tick count. So ... the result of micros() is ... um ... yes...
In fact, when trying to compile anything you get (certainly on UECIDE):
• Error at line 103 in file wiring.c:
    ‣ division by zero [-Werror=div-by-zero]

Since that's erroring when compiling code there's not a lot you can do about it.
However, one idea does spring to mind - one that is a little "crazy" I guess.

Set your boards.txt entry to 3276800Hz

The calculations will all then be valid - however, they will all be out by a factor of 100.
With the board actually running at 32768, and the API thinking it runs at 3276800, all you need to do is use values 100x less than you would normally in your calculations.
For instance, to delay 1 second you'd use delay(10); instead of delay(1000);.  Or you'd multiply the return value of millis() by 100 to get the real number of milliseconds.
Baud rates will have to be 100x faster - so use Serial.begin(960000); instead of Serial.begin(9600);.
Of course, the clockCyclesPerMicrosecond() is not geared towards working with values like 3276800, and F_CPU/1000000L will result in 3 not 3.2768 as you'd like, so timing calculations will be a little bit off. You may need to tweak things like baud rates accordingly to compensate.


text:
Yun as bluetooth master
How does one make an outgoing bluetooth connection?  I have already installed packages for bluetooth, and have run hcitool scan to find the BT address. And I'm using a USB BT dongle.
Output of lsusb
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 002: ID 058f:6254 Alcor Micro Corp. USB Hub
Bus 001 Device 003: ID 0a12:0001 Cambridge Silicon Radio, Ltd Bluetooth Dongle (HCI mode)
Bus 001 Device 004: ID 058f:6366 Alcor Micro Corp. Multi Flash Reader

Outgoing connection to what?

what connects matters?

Yes, it matters. You use different commands to configure different kinds of connections.  Bluetooth is a vast topic, so you have to be specific or we'll be here for the next month.

I'm trying to stream audio from an sd card to a headset

@Majenko Is generic pairing instructions possible?

No, as I said you use different commands for different devices.  I don't have BT on my Yún at the moment to play, but this may help you: http://unix.stackexchange.com/questions/96693/connect-to-a-bluetooth-device-via-terminal

@Majenko No Bluez-tools for yun... :(

There's "bluez-utils" - have you looked at that?  Different package systems name things differently.

Also, in my experience, getting bluetooth audio to work on Linux has meant integration with Pulse Audio, which I doubt you'll have on the Yùn.


text:
ATTINYx5 usi for uart?
Can the ATTINYx5 use its universal serial interface for a better UART than the Sofware Serial library alone? If so, is there a library or tutorial for this?

An answer got deleted. Spooky. (it was about the hardware Serial lib)

Here is a receive only USI UART for the ATtinyX5 and ATtinyX4.

AVR307 describes implementation of a half duplex UART implementation using the USI. Note that full duplex is not possible due to the synchronous design of the USI.

That implementation uses ISR(TIMER0_OVF) to clock bits in and out. This is not needed on the ATtinyX5, since you will clock the USI from TIM0_COMPA and set timer0 to CTC mode instead of periodically reloading the seed.


text:
List of Arduino board preprocessor #defines
When one selects a board within Arduino IDE, a preprocessor definition is added to one of the behind-the-scenes files.
After a lot of hunting and some good fortune I found that the format of this definition is:
#define ARDUINO_<PROCESSOR-DESCRIPTOR>_<BOARDNAME>

Some are easy to guess (ARDUINO_AVR_UNO, for example), but others are less so. The Pro Micro has '16' or '8' appended to the definition depending on the speed. I do not know if the definition is different for 5V or 3.3V. I haven't managed to guess the definition for the Mega2560, but it isn't anything obvious.
Question 1: Is there a list in existence of the possible definitions?
Question 2: Is there any distinction, as far as compilation and preprocessor involvement is concerned, between BoardX-5V and BoardX-3.3V, and how is this distinction defined?

What do you need it for? It would probably be more useful to differentiate between processors (e.g. ATMega328), instead of boards.

I have a multi-node project that uses an Uno, a Leonardo and a  of Pro Minis. The code is nearly identical for the three versions but to ease debugging I want to be able to upload (or at least compile from) the same code for everything.

Switch on File>Preferences>Compile Verbose. Then build/verify and inspect the output. You will see the -D defines that are passed to the compiler. This makes it easy to determine the difference between your boards.

Grep did not work for me as shown. Found the path by looking at the verbose compiler output. I discovered the SparkFun boards.txt file on my computer was located here:
C:\Users\Jim\AppData\Local\Arduino15\staging\packages\sparkfunboards.1.1.10.tar\avr-1.1.10\boards.txt

The list of board symbols can be generated by this shell command:
$ grep board= boards.txt | cut -f2 -d= | sort -u
AVR_ADK
AVR_BT
AVR_DUEMILANOVE
AVR_ESPLORA
AVR_ETHERNET
AVR_FIO
AVR_GEMMA
AVR_LEONARDO
AVR_LILYPAD
AVR_LILYPAD_USB
AVR_MEGA
AVR_MEGA2560
AVR_MICRO
AVR_MINI
AVR_NANO
AVR_NG
AVR_PRO
AVR_ROBOT_CONTROL
AVR_ROBOT_MOTOR
AVR_UNO
AVR_YUN

The boards are defined by the "build.board" property in the boards.txt file.
mini.build.board=AVR_MINI

This property is used by the build recipe together with ARDUINO_-prefix.
-DARDUINO_{build.board}

Cheers!

+1, thank you for that list. It's a shame it doesn't spit out the dual-speed versions to remove any doubt, but this answers the question more than well enough.

The board property is the same for both versions of pro-mini while not for mega. Maybe boards.txt should be updated with distinctive names for the pro-mini variants, e.g. AVR_MINI_16MHZ, AVR_MINI_8MHZ.

For those looking - I was trying to find the define for a NodeMCU ESP8266 - so based on the info in this answer, it is ARDUINO_ESP8266_NODEMCU
Thanks !

Mikael has the right answer, but there are multiple boards.txt files depending on the installed boards with board manager,
modifying the command to:
grep board= `find . -name boards.txt` | cut -f2 -d= | sort -u

and running it from your base Arduino directory collects the whole set.

Adding detail to Bill's answer adding to Mikael's: The packages you download through the Board Manager reside in (as of 1.8.9 and many revs prior):

linux: /home/(your login)/.arduino15 You can also run Bill's one line script in your Arduino installation folder, to get the 'builtin' boards.

The first blank is the platform. This is "AVR" for AVRs, "SAM" for SAM-based Arduinos, etc. This is derived from the platform directory containing the core.
The second blank is the board. This comes from the entry in boards.txt in the core itself, and is the identifier before the first period.
There is no difference between compilation processes with regards to voltages; any speed difference is given in F_CPU and the board itself should not be checked for this.
So there is no definitive list, since the list is of arbitrary size due to its source.

This is true only when boards.txt doesn't define a build.board value and one is automatically generated by the Arduino IDE.

If you're looking for ESP32 boards this can be achieved using a similar technique to mentioned in other answers but the location of the boards.txt files is different (although using the find, or mdfind on MacOS, command to locate works on unix based systems as mentioned in @bill's answer) - the base directory will be the same but a different sub directory: Arduino15/packages/esp32
If you want a list of only the unique defines then you can use this command:
awk '/board=/ {split($0, a,"=");print a[2]}' `find ~ -path '*/esp32/*' -name boards.txt` | sort | uniq

Or on a Mac it is faster to use mdfind:
awk '/board=/ {split($0, a,"=");print a[2]}' `mdfind -name boards.txt -onlyin ~/Library/Arduino15/packages/esp32` | sort | uniq

The names of the boards can be useful so you list these with this alternate command:
grep 'board=' `find ~ -path '*/esp32/*' -name boards.txt`

Or on Mac:
grep 'board=' `mdfind -name boards.txt -onlyin ~/Library/Arduino15/packages/esp32`

bill's answer includes the esp32 boards if they are installed

That is true but for people are only interested in ESP32 boards they can use my approach - as I've added an esp32 specific path filter. Also folks searching for ESP32 board defines wouldn't have found this answer till now.


text:
How to shake hands (Atheros-ATmega comms)
How does one assert, from the Linux user land (root-er land?) on the Atheros AR9331, the 32u4's arduino-pin 7 for communication handshake?


text:
Yum as eth->wlan adaptor
Is there a way to make a yun an Ethernet-wifi bridge? Applications include giving wifi to raspberry pi and other Ethernet only devices and vice versa.

You know you can get a real high-performance Wifi access point for much cheaper...

@MattiVirkkunen Already got one of those...in the other room. And no, I can't move it or the wired only device.

I'm sure any shop will be happy to sell you another one. Or three! Probably should've said "Wifi client" since some devices only support AP mode. And for an RPi, just get a USB Wifi adapter...

@MattiVirkkunen I don't have a lot of money. Besides, i have a spare yun (haven't found something to do with it yet besides hosting a kittens game server)

Yes, you can.  I use one to connect my Sky box (Ethernet only) to my WiFi network,
It's not an easy task though and you have to have a good understanding of networking and routing.
Basically you have to set the Yun up as a router to route packets between the Ethernet and the WiFi interfaces.  You set the Ethernet interface up on a separate subnet to your existing WiFi network, and set a static route on your main router to send traffic destined to your new Ethernet subnet to the Yun's WiFi IP address.
Your Ethernet devices can then be allocated an IP address on the Ethernet subnet (turn on DCHP for that interface on the Yun) and will use the Yun as the default gateway.
There are probably ways you can enable bridging on the Yun to tie the Ethernet and WiFi interfaces together so it becomes transparent but I haven't investigated that yet.


text:
USART, SPI or Bit-Bang for the continuous transfer of bytes without inserted extra bits
I have heard that

The SPI hardware introduces a 9th, HIGH bit between bytes
USART still uses start and stop bits when in synchronous mode

Are both these statements true? Can I modify the built-in SPI library to avoid #1? Or will I have to bit-bang the protocol needed?

Page 217&220 of Atmel-42735B-ATmega328/P_Datasheet_Complete-11/2016 do not mention an 9th bit and to me it seems highly unlikely. Have you actually tried if it works for you?

@Paul I've tried it, but it didn't work, but it could be a problem with the actual program. Sucks that no datasheet exists for my use case

#2 is false. It's basically USART in SPI mode.  #1 Without using clock signal, it's possible there is some pause as you can't write data in advance.

BTW: what is the use case? Why do you even need this bitstream?

@KIIV your question is most relevant here, because the question does not make sense. It is a typical http://xyproblem.info/ When it is for the maximum number of bytes per second, then extra bits or bytes can not be the issue. When it is for a communication protocol then there is manchester code. When a byte needs to be transferred without delay, then 8-bit parallel between two arduino boards is possible plus extra interrupt. There are many ways and many solutions if we would know the problem.

Are both these statements true?

Neither of those statements are true.
SPI never inserts extra bits. That would break everything if it did. What you are probably seeing (or think you are seeing) is a delay between bytes being sent. That delay is irrelevant, since the data is only ever sampled on an edge of the clock signal (which edge depends on the mode of the SPI communication) and with no clock edge in that delay period there is no data.
USART in synchronous mode is SPI. There are no start or stop bits in synchronous mode, since the clock is used to synchronise the communication rather than needing start or stop bits.

The SPI peripheral on the ATMega328 cannot continuously send data without a brief pause after every byte, as it does not sample the input buffer immediately after clocking the last bit, no matter what settings are used. At best, you can clock out bytes at the speed you expect +2 clocks when using assembler. The UART does allow continuous streaming of data, and should be used for maximum speed if you do not also need the clock signal. I have tested this with cycle-counted code, setting the SPI peripheral to 8Mhz (its maximum speed with a 16Mhz crystal, as the Arduino UNO uses). With the UART, using a 16 cycle loop in ASM, it's possible to load it with data continuously (I have used this to generate composite video). With the SPI peripheral, you need to add 2 clocks after the peripheral finishes, before it can load the next byte. So at 8Mhz, you can load data into it every 18 clock cycles. This is why it may appear to be clocking out 9 bits instead of 8, if you don't take account of the clock signal.


text:
Input clock limit
If you use an external oscillator, and divide-by-8 internally, can you apply up to 160MHz on PB6? For example, can I use my 50MHz oscillator to clock my 328p @ 6250KHz? Note: when I say oscillator I don't mean resonator or crystal

No! 20 MHz max (Please see 8.8 External Clock, pp. 34). The 50MHz clock could be divided by 8 with a counter or the 150MHz clock by 16 with a faster counter.
Cheers!

So divide-by-8 doesn't apply to external oscillators?

Exactly. The external clock is max 20 MHz and then it may be divided internally.


text:
Analog INPUT_PULLUP for resistive sensors?
Can you use the internal pull-up on an ADC pin? Is it correct usage? Example of hardware usage would be a cadmium photocell between Ax and GND. Software is the same, except declaring Ax as INPUT_PULLUP instead of INPUT.

Can you use the internal pull-up on an ADC pin?

Yes.

Is it correct usage?

No. The exact pullup resistance varies from pin to pin and chip to chip, so depending on it for the high side is problematic at best.
Ideally you should be disabling the digital circuitry on an analog input entirely by writing to the DIDR0 and DIDR1 registers appropriately.

There is the convenience factor, though


text:
[Arduino UNO]Receive Serial Data from multiple sources
I have the following system:

As a master, I have an Arduino UNO Chip, more specifically an Atmel MEGA328P. The important thing is that this microcontroller has only one hardware Serial port, and that port is used to communicate with a WiFi adapter.
The problem I'm facing with is that I want to receive data from a Compass and a GPS modules. Booth send data via Serial protocol. The 328p Chip have only one serial which is busy!
I can't use SoftwareSerial as I don't want any delay on master board!
I can't also use Arduino Mega2560 which have 3 Serial ports as its sizes are too big.
So there are are my approaches:

Using MCP4725 I2C DAC for Compass, but what we do with GPS?
Using and intermediate Arduino UNO Chip?
On that chip I could use Software serial but how to transfer data to MASTER using only digital and analogic pins? Maybe using 10 pins to implement a parallel transfer?
Perhaps there is possible to convert Compass and GPS data to analogic then transfer to MASTER?

Anyway, what possibilities would I have to play around?

That was a lot of design restrictions. You might want to look at an I2C/SPI to UART bridge; http://www.nxp.com/products/interface-and-connectivity/interface-and-system-management/bridges/i2c-spi-slave-to-uart-irda-gpio-bridges:MC_51852

Maybe you should consider stepping away from Arduino boards and exploring the plethora of more capable boards that are out there - most of which can be programmed with the Arduino IDE using the Arduino API.

You chose the wrong part.  Lots of ARM Cortex parts have 3 UARTs, some of them have Arduino ports.

@ChrisStratton Only 3? I'm used to working with chips that have 6 UARTs... ;)

@Majenko : Can you guys provide some links please? It would be very usefully :)

This answer summarizes the possibilities:
1) HardwareSerial is always best.  You are using that for WiFi.
2) AltSoftSerial is the best software serial library, but it requires pins 8 & 9.  Very efficient and non-blocking!  Strongly recommended for the GPS connection.
3) NeoSWSerial is next best, but it supports only 9600, 19200 and 38400.  It is non-blocking on receive, so it could be used for the GPS connection.
4) SoftwareSerial is the worst.  :P  Not suitable for the GPS connection, as you have discovered.
I'll also mention my GPS library, NeoGPS.  It is smaller and faster than other libraries, and there are examples that show how to make it run during the RX character interrupt, saving even more time.  It can also be configured for just the messages and fields that you actually use, saving RAM, program space and execution time.

I think softserials are working based pinchange interrupt. This wont make you any significant delay i hop.Or you should go gps or wifi modules with SPI or IIC interface.

SoftwareSerial uses PCINT to start reception. During reception it blocks all other operations. That causes significant delays, especially at lower baud rates.