text:
Undervoltage from solar panels
So i'be been toying with the idea in my head of creating a solar powered weather station with an arduino, two 6V 2W solar panels in parallel, two 5V USB battery packs, and an adafruit module which converts voltages from 3-12V to 5V (to charge my batteries). I'm also working on using some small relays or MOSFETs for the arduino switch between batteries.
The problem: If my solar panel voltage drops below 3V, the adafruit board will supply the batteries with a n unstable voltage below 4.8V. I need some sort of circuit or sensor that is capable of detecting when the voltage  from the solar panels drops below 3.3V and which will open the circuit to protect the batteries from unstable voltages.

You have selected a number of things that don't go well together. It is possible to use relays or mosfets to switch between batteries, and the Arduino could be used to measure a voltage. Or you can make a circuit with a few electronic components (e.g. a comparator). However, no one does it like that. It would be unreliable.
Every solar power charging module can handle darkness as well. Some modules will also create 5V.
This Adafruit module has no 5V output, it only contains the charging part: Adafruit:USB / DC / Solar Lithium Ion/Polymer charger - v2
It is out of stock at the moment, and you need solar cells, battery, a cable, and a DC-DC converter to make 5V.
When it is dark and the battery is empty, I assume the output drops and the Arduino stops working. Adafruit made a tutorial for it that shows the DC-DC converter and also Collin shows a DC-DC converter: Youtube, Collin's Lab: Solar
There are other modules like that. For example the Sparkfun Sunny Buddy.
Take care that the batteries don't get too hot.
It is possible to run some Arduino boards directly from a battery (3.1 to 4.2V). Then you would not need the DC-DC converter.
Buy solar cells that are the best in low light conditions. With enough sunlight, the power is no problem. It is the dark winter days that could be a problem.

So I've looked at many solar panel charge controllers and modules, and I found that pretty much all of them are just variable input D.C.-DC Step down converters, taking inputs from 6V or above. That would mean that the batteries would only charge in direct sunlight. However with the adafruit module I found, the input voltage can be anywhere from 3-12V.                                                              It sounds like I will try a comparator, which I have never used.

The other problem (which is very likely to occur) is that even with 2 solar panels in parallel at 3V there isn't enough current to charge the batteries properly. So i'll just set the comparator to a higher voltage.

In my opinion, you are still going in the wrong direction. If the voltage of a solar cell is low, then there is probably not enough current either. If you want even the smallest energy from the solar panel, try a energy harvester module. The solar charging modules have a chip specifically for that, it is not just a DC-DC converter. Don't connect solar panels parallel, set them in series.

I see what you're saying with the voltage dropping. However, why wouldn't I put them In parallel? It draws less current from each of them and still keeps them above 6V each in good sunlight right?

Maybe you can if they always have the same amount of light, but it doesn't make sense and it has no advantages. In series it is possible to add a bypass diode to each panel. In series the MPPT can be used to the maximum. The solar charging modules use a switching regulator, that means with more voltage and less current as input, they can create a lower voltage with more current.

ok I'll do series panel with some sort of charge controller, thanks!


text:
Debouncing, or problem with my code?
I'm using a simple microswitch on pin 2, to activate an external interrupt.
void pause()
{
  Serial.print("\n\nPause\n\n");
  delay(1000);
}

void setup()
{
  pinMode(2, INPUT_PULLUP);
  attachInterrupt(0, pause, RISING);
  Serial.begin(9600);
  delay(1000);
}

void loop()
{
  Serial.print("\nGoing");
  delay(100);
}

When I tap the micro switch, some reason, my serial monitor output looks like this:

Just to clarify, there is no delay between any of
Is this just some serious debouncing, causing my Arduino to find lots of rising instances? or is there some kind of problem in my code?

Just to clarify, there is no delay between any of - any of what?

Be careful using delay functions in an ISR!!! Read the italics: https://www.arduino.cc/en/Reference/AttachInterrupt

I have a page about using switches but since I don't want to give a link-only answer I'll summarize here.

Detect switch changes
What is needed is to detect a transition. That is, either:

It was closed and is now open.

Or:

It was open and is now closed.

To do that you need to "remember" the previous state of the switch and detect a change, like this:
const byte switchPin = 8;
byte oldSwitchState = HIGH;  // assume switch open because of pull-up resistor

void setup ()
  {
  Serial.begin (115200);
  pinMode (switchPin, INPUT_PULLUP);
  }  // end of setup

void loop ()
  {
  // see if switch is open or closed
  byte switchState = digitalRead (switchPin);

  // has it changed since last time?
  if (switchState != oldSwitchState)
    {
    oldSwitchState =  switchState;  // remember for next time
    if (switchState == LOW)
       {
       Serial.println ("Switch closed.");
       }  // end if switchState is LOW
    else
       {
       Serial.println ("Switch opened.");
       }  // end if switchState is HIGH
    }  // end of state change

  // other code here ...

  }  // end of loop

This code looks for changes, and only displays something when the switch changes.

By the way, you should be doing neither delay nor Serial.print inside an interrupt, as both of the rely upon interrupts being active, and interrupts are not active inside an ISR.

Debouncing
A simple technique is just to build in a short delay, for example 10 milliseconds (ms). For example:
const byte switchPin = 8;
byte oldSwitchState = HIGH;  // assume switch open because of pull-up resistor
const unsigned long debounceTime = 10;  // milliseconds

void setup ()
  {
  Serial.begin (115200);
  pinMode (switchPin, INPUT_PULLUP);
  }  // end of setup

void loop ()
  {
  // see if switch is open or closed
  byte switchState = digitalRead (switchPin);

  // has it changed since last time?
  if (switchState != oldSwitchState)
    {
    oldSwitchState =  switchState;  // remember for next time
    delay (debounceTime);   // debounce
    if (switchState == LOW)
       {
       Serial.println ("Switch closed.");
       }  // end if switchState is LOW
    else
       {
       Serial.println ("Switch opened.");
       }  // end if switchState is HIGH
    }  // end of state change

  // other code here ...

  }  // end of loop

In the above code the delay is inside loop (where it is OK to use it) and causes a short pause to allow the switch to stop bouncing.

Debouncing without delay
The above code is fine in simple applications, and if you test it, you should find that the message "Switch closed." and "Switch opened." should only occur once per switch press. But, there's a problem. If you hang around the Arduino forums for a little while you will probably see people telling you "don't use delay". There are various reasons for this, not the least is which that using delay stops your code from doing anything else useful (like testing sensors, controlling motors, flashing LEDs, etc.).
The code below does not use delay, but rather checks for the time that has elapsed after you hit the switch, and sees if the "debounceTime" (in this case 10 ms) has elapsed. If not, it ignores the transition.
const byte switchPin = 8;
byte oldSwitchState = HIGH;  // assume switch open because of pull-up resistor
const unsigned long debounceTime = 10;  // milliseconds
unsigned long switchPressTime;  // when the switch last changed state

void setup ()
  {
  Serial.begin (115200);
  pinMode (switchPin, INPUT_PULLUP);
  }  // end of setup

void loop ()
  {
  // see if switch is open or closed
  byte switchState = digitalRead (switchPin);

  // has it changed since last time?
  if (switchState != oldSwitchState)
    {
    // debounce
    if (millis () - switchPressTime >= debounceTime)
       {
       switchPressTime = millis ();  // when we closed the switch
       oldSwitchState =  switchState;  // remember for next time
       if (switchState == LOW)
          {
          Serial.println ("Switch closed.");
          }  // end if switchState is LOW
       else
          {
          Serial.println ("Switch opened.");
          }  // end if switchState is HIGH

       }  // end if debounce time up

    }  // end of state change

  // other code here ...

  }  // end of loop

More information on the Arduino site: http://arduino.cc/en/Tutorial/Debounce

It is essential for me to use an interrupt, because I need to be able to pause my entire program, at the push of a button, then resume it when the button is pushed again. I heard from other people that I cannot use any type of delay in the interrupt, is this true?

You don't really pause a program with delay, it is now just doing something else (waiting for a timer to reach a certain time). Timers depend on interrupts to update counters as the hardware timer will overflow (roll over) very rapidly.
I suggest a redesign. In your main loop, for example, you could detect the switch press, and then not do anything until it is pressed again. For example, where I had "other code here" in my example:
static bool switchWasPressed;

if (switchWasPressed)
  {
  // do nothing
  }
else
  {
  // do what you want to do continuously
  }

Now, in the code which detects switch presses you toggle switchWasPressed. So instead of:
Serial.println ("Switch closed.");

You put:
switchWasPressed = !switchWasPressed;  // toggle switch press state

It is essential for me to use an interrupt, because I need to be able to pause my entire program, at the push of a button, then resume it when the button is pushed again. I heard from other people that I cannot use any type of delay in the interrupt, is this true?

No, it isn't essential to use an interrupt. Interrupts are not for lengthy pauses. See my extended answer above.

Do you really need to use an interrupt to debounce a switch? If not, this library may work for you: https://playground.arduino.cc/uploads/Code/Debounce.zip. It is easy to use and assumes you are using a normally open switch with one connection to ground and the other connected to pin 4 on the Arduino.
    #include <Debounce.h>
    const byte SWITCH = 4;

    Debounce debouncer = Debounce(50, SWITCH);

    void setup(){
      Serial.begin(9600);
      pinMode(SWITCH, INPUT_PULLUP);
    }

    void loop(){
      if(debouncer.update()){
        if(debouncer.read() == 0){
          Serial.println("Button Pressed");
        }
        else if(debouncer.read() == 1){
          Serial.println("Button Released");
        }
      }
    }

your code works as coded - whether it works as expected is unknown.
basically the isr is triggered on the first edge, and the execution loops around in the isr, and the execution returns one second later.
As a result,  your code missed most of the "bouncing", actually it missed all bounces other than the very first one.
not an effective debouncing strategy.
yes, delays or while loops can be used in an isr, so long as you know what you are doing.

Please take the time to use proper English on this site. Proper English includes starting sentences with capital letters. As a reasonably high-rep user, who posts a lot of useful answers, you are setting standards for others to follow. Please take the time to capitalize your sentences correctly. Thanks!

Yes, it is bouncing of your button.
You are seeing it because delay() does not work, and cannot be used, in an interrupt.
Also delaying in an interrupt is completely opposite to the whole ethos of interrupt programming.

Thanks, but is there a way for me to put a delay in the interrupt, so the second I press the button it just pauses before any debouncing can occur?

No, but you can record the time the interrupt occurred (hint hint)

source: Stack Exchange

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

sort: votes


text:
RH_RF24_MAX_MESSAGE_LEN in RH_RF24.h
I use  RH_RF24.h to control Si4463, and realize some simple communication between two Si4463 . But I don't know the mean of RH_RF24_MAX_MESSAGE_LEN in this example.
RH_RF24_MAX_MESSAGE_LEN is a constant ? If so , what decides it ? And if I need to sent and receive  a long  char string , how to do it ?

RH_RF24_MAX_MESSAGE_LEN is probably defined in the header file RH_RF24.h.
It doesn't matter what size it is, you should always use RH_RF24_MAX_MESSAGE_LEN rather than the number because the value might change in the library and this will break your code if you have used the number.
If you want to send a message that is larger than RH_RF24_MAX_MESSAGE_LEN then you will need to 'fragment' the message (unless the library supports that).
I would use the first byte of the message as the type of message and define one of those types as a multi part string.  Then send a number of these message and reassemble the data on the receiver. When the receiver sees a message that contains a character with the ASCII value 0 then that is the end of the string.

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


text:
Can I run a loop in setup()
Are loops not allowed in setup()? The following doesn't print anything inside the for loop to the serial terminal
Code:
void setup() {
  Serial.begin(9600);
  Serial.println("Ping");
  for (int i = 0; i >= 10; i++) {
    Serial.println(i);
    Serial.println("Pong");
  }
}

void loop() {

}

Output:
Ping

In principle yes, you can use a loop in setup() however this specific code
for (int i = 0; i >= 10; i++) {
  Serial.println(i);
  Serial.println("Pong");
}

will result in the body of the loop never executing, as the loop test i >= 10 is initially false.
You probably meant i <= 10
Generally speaking, it would be poor program structure to use a loop in setup() in place of one in loop(), however if you need a loop to apply similar operations to a range of things, or to briefly busy wait on a condition as part of setting up operation, that kind of thing could be appropriate.

You could (and I occasionally do) write your entire program in the setup() function. Setup() and loop() are constructs provided for your convenience, but they aren't necessary. In C/C++ compiled programs, it conventional for the C run-time code to call main(), and for main() to be written by the programmer.
It is conventional within the Arduino IDE world to bury the complicated stuff to let new user get productive quickly with a gentle learning curve.
That includes a pre-written main() that provides the calls to setup() and loop() for you.
The following main() function is typical of a number of pre-written Arduino main() functions, but you don't have to use the pre-written one; you can supply your own. It will need to call init(), and Arduino library function that prepares the hardware and software environment into a known state; after that you're good to go.
/*
 * main.cpp
 *
 *  Created on: Dec 13, 2011
 *      Author: jrobert
 */

#include "WProgram.h"

int main(void){
    init();
    setup();
    for(;;)
        loop();
}

extern "C" void __cxa_pure_virtual() {
    while (1)
        ;

}

While that was true years ago, this is not sound advice today (2015).  The current main() includes (if (serialEventRun) serialEventRun();)  after loop().  The user's loop() is expected to return; in order to yield time back for other services to run.

Correct, modern versions do include such a call. But that is exactly the point: The C main() function is where the run-time setup hands over control to the user; what the user writes from there down is up to him/her. Every program doesn't need every facility, and it is assumed that you know what you are doing when you circumvent the provided ones. Do also note, that unlike setup() and loop(), which you must provide (or the linker will fail), 'if (serialEventRun)` specifically honors the lack of such a requirement by testing for the existence of serialEventRun() before trying to call it.

... An equally reasonable addition to main() would be calls to similarly optional functions for timer events, Ethernet or WiFi events, and even some less critical interrupts. These support facilities aren't at all necessary; in fact I can't remember when I've seen an Arduino program that actually used serialEventRun() instead of managing serial on its own.


text:
Why is setup() executed twice at runtime?
Code:
void setup() {
  Serial.begin(9600);
  Serial.println("hello");
}

void loop() {
}

Output:
hello
hello

Why does hello print twice?

Just tried it on my Arduino Uno - only executes once for me. Could it be a residual value in your Serial Monitor

I considered that so I created a new file, restarted the device and Sketch. Still there...

Your Arduino must be resetting as it starts
1 how are you turning it on ?
2 how are you connecting the serial monitor ?
3 what else is connected ?

I think it depends on how quickly you start the serial monitor after downloading a program or resetting the Arduino and on operating system buffering.  Ie, your OS (which is what?) buffers a "hello", then you start the serial monitor, which resets the Arduino and produces the second  "hello"

@jwpat7 That seems the most plausible as sometimes connected lights blink on boot when they are no suppose to.

jwpat7's suggestion sounds the most plausible. Try opening the IDE's built-in serial monitor before you upload your program. The later IDE's will disconnect their own monitor for the duration of the upload and reconnect it again when the upload is done. That way there will be only one reset and you should see the program output only once.

If I open my serial monitor, my arduino sometimes resets twice. I wouldn't worry about this.

Add a 'Serial.println("world"); while(1){};' to your loop, and see if you get just one cycle of loop() per setup().

@DaveX, I get Hello world Hello world, so it looks like the device is resetting every time, like @Gerben's.

Please edit the question to indicate what type of Arduino you are running this on.  They are not all the same with respect to serial port.

Since you get hello world twice, it is also entering into the endless loop twice.  Folks are right in that you are seeing two boot-up cycles -- it isn't that the setup is running twice in one poweron/reset cycle.

It isn't, it's displaying the previous message from when you didn't have the Serial Monitor open yet, plus the new message caused by the Arduino resetting from the Serial Monitor being opened.
If you put a longer message in there you'll probably see the first line get cut off and then the full line.


text:
Use Arduino to transmit signal to a vibrating pager
I am an engineer at a machine shop. When a machine stops running, I want to be notified via a vibrating pager (like at restaurants). My plan is to attach the arduino board in the machine and when the machine stops (quits vibrating) I want it to trigger the vibrating pager that I have in my pocket. By what means can the arduino communicate with the vibrating pager to cause it to go off? SMS? Wifi? Bluetooth would likely be out of range. Other options?

I'd go with an internet solution (wifi), and use an online service to send a pager message. That way, in the future you could change/add other types of notification, like: SMS, e-mail, push-notification, webpage (with e.g. history information)

If the machines are CNC, add a program step at the end of the G-code to turn on a digital output to the Arduino, rather than trying to detect  “when the machine quits vibrating”

I don't write the g-code, so I'm not sure how that would work. But that sounds like a good idea. I will talk to them about that.
Let's say the digital output is turned on..then how would I make the Arduino begin communication with the receiver? Is it just a matter of coding something along the lines of "if there is digital input, do this ..."?

To do SMS through a GSM shield like https://www.arduino.cc/en/Main/ArduinoGSMShield with a dataplan, and the device should be accessible anywhere you can get reception.  With a wifi shield like https://www.arduino.cc/en/Main/ArduinoWiFiShield101 you could make it work within your wifi network.
Sparkfun's sales guide at https://www.sparkfun.com/pages/wireless_guide indicates there are a few bluetooth modules that reach 100m, so if your range is less than 100m, bluetooth is a possibility.


text:
5v input on ATmega328p running on 3.3v
The ATmega328p can run on 5v but will it cause problems if it runs on 3.3 v and one input signal is 5v?

Logic levels can be different across differently made integrated circuits and processors.  You should not directly connect differently powered devices together.  Logic level differences (as described here) should be dealt with using logic level converting devices such as this one.

The voltage at any input must be less than VCC+0.3V unless it is restricted to only a few milliamperes (so it doesn't burn out the clamping diode). Use a proper voltage translator if it is available, otherwise use a 1kohm or greater resistor (at the cost of life expectancy for the MCU).


text:
What's the difference between setting a variable outside a function and setting a variable inside a function?
I'm programming C++ for arduino and today I have seen an example like this
void loop() {
    byte variable = 0; // << This variable is the question.
    //more stuff here
}

Is the same as this?:
byte variable = 0;

void loop() {
    //stuff here
}

If the answer is "no", my question is "why?".
Thanks for your time!

To make them act the same while restricting scope of variable to loop(), use eg void loop() {     static byte variable = 0; ...}

The difference is not only about where you set the variable, but about where you defined it as well.
Defined outside the function, it will have global scope and lifetime, meaning it is visible everywhere and it exists for the entire duration of the program.  If you then place an initializer inside the function, whatever value it had just before function-entry will be replaced by the initializer value.
If you define it inside the function (and without a "static" specifier) it only exists while that function is executing, and is only visible to code inside the function. Because it only comes into existence when the function is entered, you must initialize it within the function, somehow.
If you define it inside the function, but with a static specifier,
static byte variable = 0;

then it will exist for the entire execution of the program but will only be visible to code within the function. In addition, an initializer on its definition (as opposed to other assignments to the variable) will only be executed once, just before the program begins executing, and will not be executed within function.
Using local and static (as opposed to global) variables is considered good program-variable hygiene because it hides those variables (to a greater or lesser degree) from code that needn't and shouldn't be able see or alter them.

No, it's not the same. Instructions within the loop() repeat every time the program gets to the end. If you set your variable at the start of the loop, it will automatically get reset to the default when you might not want it to be reset. The author of the example wants to reset to default every time the loop completes.


text:
Using two digits to display a number using TM1637 and a 4-digit display
I decided to build a digital clock using a 4-Digit Display (TM1637) from Grove.
For that, I have been using the DigitalTube library by Grove for the TM1637 controller.
My idea is to use the two first digits of the display (left to right) to display the hour and the two last digits to display the minutes. However, managing displays is difficult and all the libraries I have found for the previously mentioned controlled can only display one number per digit.
Here you have an example:
Using tm1637.display(1,2);, lets you display a "2" in the second digit (L to R), using tm1637.display(0,3); lets you display a 3 on the firt digit and etc.
As I said, I want to display the hour on the first two digits and the minutes in the two last digits.
I've have readed all the examples coming with the DigitalTube library but nothing was useful.
Note: I'm using the DS3231 for managing the time with a RTC.
I don't know if you undestand my question. If not, let me know please.
Arduino UNO R3.

Using tm1637.display(digit#, value); calls, you can display a two-digit number using division to isolate the tens digit and mod to isolate the units digit.  For example, if hour and mins have hour and minute values, respectively, consider code like:
tm1637.display(0, hour/10);
tm1637.display(1, hour%10);
tm1637.display(2, mins/10);
tm1637.display(3, mins%10);

Code like the above is suitable in cases where values don't exceed 99, and where displaying a leading zero is ok.
If you don't want to display the leading zero when hour is less than 10, add an if test and blank the first digit in that case.


text:
Simple example multiplexer usage
I'm new at multiplexing with arduino (I use arduino from some years), and -as title says- I'd like to learn. I'm trying to build an expandible system with 3 sensors, and I'd like to use a 74hc595b1 to link them, leaving some pins free. My first question is: is It possible? And second, can you kindly link me a simple -but very simple- example about multiplexers in arduino? Thankyou!

What kind of sensors? Also, the 74hc595b1 is a shift register, not a multiplexer.

I have a hc-sr04 sensor and a temperature sensor (I think a P-MOS)

Neither of those are suitable for using with a shift register

So, how can I do with more sensors?

Get a board with more pins, or use two boards and make them communicate with each other.

And so -and sorry for the many questions- i can use a multiplexer just for output? i.e. a 7segments display?

You can use a shift register for that, yes. A multiplexer is a very different thing and is not what you have there.

i just bought an 8-IO adding PCF8574T for less than $1.50USD, look into it. If you want good analog IO, a 16-bit ADS1115 adds 4 hi-res input for about $2.50....

There's a detailed explanation of multiplexer use in this answer.

For connecting 8 analog devices to an Arduino, using only 3 Arduino pins, look at say a 4051 multiplexer IC: 4051 example

authors: Дмитрий Цветков


text:
How to connect an industrial sensor to Arduino Uno?
I want to use a sensor to read pressure in rooms. But sensor like MPX series isn't capable to read air pressure change under 100 Pa. So I want to use industrial sensor like Dwyer 607 Series, and dont have a clue how to connect it to arduino. Anyone can help?
Thanks :)
Fyi, this is the manual instruction for the sensor http://www.dwyer-inst.com/PDF_files/E_76_low.pdf

here is a tutorial which explains how you can connect 4-20mA industrial sensors with Arduino.
How to interface 4-20mA with arduino

That uses the industry standard 4-20mA current loop system. For that you really need a special chip to interface it.
You can buy shields that interface to 4-20mA current loops.


text:
How many and fast interrupt pin can handle in Uno?
So I am using Arduino UNO to do phase cutting and read Fan RPM.
For phase cutting, every half frequency it will triggers interrupts and then arduino will triggers TRIAC. Half frequency(50Hz) is 20ms. And for reading rpm, my fan running at 950rpm or 15.83rps, or doing a revolution for 63ms.
I think both of that works is doing a fast work, and I am afraid if I do it simultaneously the arduino will get an error(like a skip on one half wave, or a skip on reading one revolution), or will it not? Thanks.

You are talking about tens of milliseconds, ages at the scale of the MCU. Unless you do silly things in the ISR, your Arduino should have no problem keeping with that pace.

If you are having problems (which is unlikely), you could use the RPM output as a clock input for timer1. That way the hardware wil count the revolutions for you. You can than add an interrupt for when the counter get to a certain value, and do some calculations based on that. That way you'd have a lot fewer interrupts.

Let's do some math here.
UNO works at a 16 MHz clock rate. That's a clock cycle every 62.5 nanoseconds, or 16.000 cycles every millisecond. That means plenty of processing power within 20 millisecond, if used wisely (i.e., avoiding processing-intensive functions).
Conclusion: you shouldn't find any major problem if you do a good work with your code. Just keep things simple and don't go through the roof with what you intend to do each 20 ms.

You can find the number of external interrupt and pcint pins from the data sheet.
If you use interrupts, the overhead is about 20 or so ticks, or just over 1us. That gives you the minimum.
If polling, and you are lucky, 1 tick is all it takes. 1 /16th of a us.

If two interrupts happen at the same time they will both execute in the numerical order of their INT number (INT 0 will trigger before INT 1). But they will both execute - just one will be a little delayed.
If one interrupt occurs whilst the other is executing the second interrupt will trigger once the first has finished.
As long as both your interrupt routines combined take less than the time than the time between triggerings of the most rapid interrupt you won't get any issues.


text:
How might the SD library be reading phantom files?
I have the Sparkfun CAN Bus shield with integrated SD card writer attached to an Arduino Mega 2560. I can delete a logged file from the SD card using Windows, log more data using the SD library, then look at the logged data in, say, Excel. The new log file will include the logged data from the old, deleted file.
The card is formatted in Windows in FAT32 and the logged file has the same name as the original. It seems like the SD card reader/SD library is able to 'recover' the deleted file by name, open it for writing having read its uncorrupted contents, and continue logging to it, despite it having been 'deleted' in Windows. I know a deleted file doesn't get rid of the data unless it is overwritten, but there seems to be some bug/oversight in how the SD library in card reader or how it interrogates the SD card or FAT32 volume for the existence of the file.
Has anyone come across this before? Is it a bug or am I doing something wrong?

Do you remove and reinsert the card from/into the arduino with the power still on?

I have implemented a switch to initialise writing (file.open();) and stop writing (file.flush(); file.close();). This was done with the intent of ensuring the system need not be powered off to remove the card. You make an interesting point if the library maintains some kind of awareness of past files.

It could be caching at the block level, not just the file level. Not sure if there is a way to flush that cache...

The SdVolume class seems to have a cacheClear() function which flushes the block-level cache and invalidates all the cache entries. You don't normally have access to the volume entry of the SDClass, so you would have to break it down into card/volume/root in your sketch instead so you can access all the individual parts (or modify the SDClass to allow access).

Personally though I never use SD.h because it's horrendously slow and badly written. I use (various implementations of) FatFS.

How do you connect sdCard on CAN-BUS shield with Arduino Mega2560? Can I see the code and interface?
Thankyou

How large is the file when it is deleted in Windows? I can imagine what you describe happening if there's a bug in the Arduino File System (see below) - but that requires relatively small files (less than 4K or so).
I assume that the SD card has zero or more "static" files, that don't change; and then the log file, that grows. That is, when the log file is deleted, the newly-freed blocks get re-used again for the new log file?
I also assume that you're using Windows' "Safe Removal" mechanism - giving it a chance to tidy up the SD Card before you yank it out.

To delete a file in FAT, the file system needs to do two steps:

Unlink the used blocks from the File Allocation Table (the eponymous F.A.T.).
These should be set back to zero - making it hard to accidentally re-use them again unless they're the same blocks again (which, for SD Cards, is unlikely due to wear levelling!)
Mark the directory entry as available again.
This is done by merely overwriting the first character of the directory entry with 0xE5. When FAT needs a new directory entry, it will use entries with either 0x00 or 0xE5. If the deleted file is being "resurrected", then a bug could be that it re-uses the directory entry but doesn't zero the existing contents, allowing the existing block number and length to be appended to.

Rather than deleting the file in Windows, try renaming it to something else entirely. That way the Arduino will create a new file, and you shouldn't have the problem. If you still do (worse: if the renamed file gets corrupted) then it's a caching problem. If you don't, then it's a bug in the file system.

The files have been of varying sizes from 1 to 100 kB. At present this is the only file on the card, though hopefully that won't be a limitation going forward. Yep, using 'Safe Removal' in Windows, there seem to be plenty enough corruption issues with SD cards to make that procedure mandatory. Have to admit, I don't know how file allocation tables work, especially on SD cards. When you say unlinking the blocks, is a link to a set of blocks literally just the start and end block? What does the directory entry look like and are you referring to the character array of its name to overwrite?

Without going into the whole FAT mechanism: 1) In the FAT a file is defined as a series of blocks that are indexed as a "chain" of clusters: the directory entry defines the first cluster, and each entry in the F.A. Table defines the next cluster in the chain - with -1 to end it. 2) The directory entry contains six entries: the name; the attributes (read only, directory, etc); the create and modified times; the start cluster; and the size of the file. And yes, when deleting the file the first character of the name array is modified.


text:
Can I prevent the Stepper library from holding the motor?
I'm using the Stepper library to control a single stepper motor. When the Arduino is not running the motor it is holding the motor shaft in place. For my application, this is very wasteful and puts unnecessary strain on the motor.
Is the Stepper library supposed to do this or is something else up with my circuit? Can this behavior be overridden?

use disable output class in  accelstepper library.
http://www.airspayce.com/mikem/arduino/AccelStepper/

The ability to release all the stepping motor coils depend on the hardware and software used. For example, the Adafruit.com hardware and software has this function to release all the stepping motor coils.  Investigate their approach and determine if you can contribute to the library you are using by porting this feature.  Also investigate if this feature is not (serendipitously) already part of the library you are using.  For instance, it is not unreasonable to expect the library you are using to return Atmel pins to a passive input state (which, depending on the hardware, may release the stepper) when you destroy the instance of the stepper library class.

//for all pins used for controlling stepper motor assign all of them LOW

#include<Stepper.h>
const int stepsPerRevolution = 200;
Stepper myStepper(stepsPerRevolution, 10, 11,12,13);

void setup() {
  myStepper.setSpeed(30);

Serial.begin(9600);
}

void loop(){

 Serial.println("clockwise");
  myStepper.step(stepsPerRevolution*5);
  delay(300);
digitalWrite(10,LOW);
  digitalWrite(11,LOW);
digitalWrite(12,LOW);
digitalWrite(13,LOW);

}

Stepper library has nothing to do with this. What holds your motor are those GNDs or 0 Volts applied to control pins of your Stepper motor.
What you are looking for is UL2003A. The way ULN2003A works is solution to your problem.
Assuming your stepper is unipolar, Here is a complete tutorial on how to use Stepper motor with UNL2003A.

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


text:
Watchdog don't work with Atmega328PB
I have a code that is working fine using WatchDog timer to auto reset in case something goes wrong, but now i got a arduino with ATMega328PB, and the old code just don't active the watchdog.
#include <avr/wdt.h>

wdt_enable(WDTO_8S);
for(int i = 0; i < 10; i++)
{
    delay(1000);
}

This is the code to test, but the reset that should happen just doesn't happen.
In the datasheet say that the watchdog still there to use, but i have no idea how to active it now.

have a look at some of the tutorials that are available on the web

I didn't find no tutorials for the 328PB model

section 15.8 of https://ww1.microchip.com/downloads/en/DeviceDoc/ATmega328PB-Automotive-Data-Sheet-40001980B.pdf

I already saw the example in the datasheet, but I couldn't compile it, is there any other option?

couldn't compile it ... what does that mean? ... what error did you get?

For example __watchdog_reset(); there are 3 functions that I don't know how to replace or implement to keep the code functional, and there is also how to set the watchdog time

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


text:
Where could I find the "Serial.find()" source code?
As written in the title, could you tell me where to find the source code of the function "Serial.find()"?
I haven' t installed the Arduino IDE, so I'm glad if you could me link a web resource, or if you directly copy the source code here .
Thanks for your time.

It is part of the Stream class which the Serial class inherits from.

https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/Stream.cpp#L93

It just calls findUntil() which is a little further down in the same file:

https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/Stream.cpp#L114

That itself calls findMulti() which is where all the magic happens:

https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/Stream.cpp#L256

int Stream::findMulti( struct Stream::MultiTarget *targets, int tCount) {
  // any zero length target string automatically matches and would make
  // a mess of the rest of the algorithm.
  for (struct MultiTarget *t = targets; t < targets+tCount; ++t) {
    if (t->len <= 0)
      return t - targets;
  }

  while (1) {
    int c = timedRead();
    if (c < 0)
      return -1;

    for (struct MultiTarget *t = targets; t < targets+tCount; ++t) {
      // the simple case is if we match, deal with that first.
      if (c == t->str[t->index]) {
        if (++t->index == t->len)
          return t - targets;
        else
          continue;
      }

      // if not we need to walk back and see if we could have matched further
      // down the stream (ie '1112' doesn't match the first position in '11112'
      // but it will match the second position so we can't just reset the current
      // index to 0 when we find a mismatch.
      if (t->index == 0)
        continue;

      int origIndex = t->index;
      do {
        --t->index;
        // first check if current char works against the new current index
        if (c != t->str[t->index])
          continue;

        // if it's the only char then we're good, nothing more to check
        if (t->index == 0) {
          t->index++;
          break;
        }

        // otherwise we need to check the rest of the found string
        int diff = origIndex - t->index;
        size_t i;
        for (i = 0; i < t->index; ++i) {
          if (t->str[i] != t->str[i + diff])
            break;
        }

        // if we successfully got through the previous loop then our current
        // index is good.
        if (i == t->index) {
          t->index++;
          break;
        }

        // otherwise we just try the next index
      } while (t->index);
    }
  }
  // unreachable
  return -1;
}


text:
How do I connect components to the Arduino with a motorshield?
How would I connect components to the Arduino with this motor shield?

Thanks :)

What components? I don't understand your question.

@NickGammon for example if i wanted to hook up a rc reciever? or just something to the arduino e.g. i want to use the pins of the arduino? thanks

If you are up for a little soldering, look into stackable Arduino headers. (Feel free to shop around for those, adafruit was just the first result.) You could then use male jumpers and a breadboard to connect anything that fits in a breadboard.
Just be careful to avoid pins that the shield is already using.

How would I attach them to the shield?

First, desolder the old headers on the shield, then follow the Make It section of this tutorial to attach the new headers.


text:
Displaying binary to LEDs
I've written a program for Arduino UNO and 3 LED lights. The program is supposed to turn an inputted number into binary and then display it on the LEDs, on being 1 and off being 0 I have looked it over quite a few times and don't understand why it is not working as it should. I'm a beginner at working with Arduino so I probably just need a more experienced eye to show me where I have messed up. I have a link to a picture of the Arduino setup below. Thanks!
https://drive.google.com/file/d/0B8k_WNZ3eFOkZHkwNUllTEp4WGM/view?usp=sharing
//setting up lights
const int lightOne = 13;
const int lightTwo = 12;
const int lightThree = 11;

//array of the lights for when printing the binary
int lights[] = {lightOne, lightTwo, lightThree};

void setup() {
  //setting pin modes and starting up the serial monitor
  pinMode(lightOne, OUTPUT);
  pinMode(lightTwo, OUTPUT);
  pinMode(lightThree, OUTPUT);
  Serial.begin(9600);
}

//converts a given number into binary
String binary(int number) {
  String r;
  while(number!=0) {
    r = (number % 2 == 0 ? "0" : "1")+r;
    number /= 2;
  }
  return r;
}

//outputs the binary string to the lights (not expecting numbers larger than     9)
void printBinary(String binaryNumber) {
  for (int i = 0; i < sizeof(binaryNumber); i++) {
    digitalWrite(lights[i+11], (binaryNumber[i] == '0' ? LOW : HIGH));
    delay(2000);
  }
}

void loop() {
  int input = Serial.read();                //get the number
  String binaryNumber = binary(input);      //convert number to binary
  Serial.println(binaryNumber);             //print binary to serial monitor
  printBinary(binaryNumber);                //display number in binary on     LEDs

}

Welcome to SE Arduino!
Long Version
You have a couple of things to look at:

Don't use String class it has too much overhead for Arduino.
Your conversion function is not really necessary because you can convert it on your Serial.println() by specifying binary as output. eg: Serial.println(number, BIN);
The Serial.read returns an integer, but that int only contains a byte (unsigned) value anyway (unless there's nothing to be read, in which case it returns -1). Because you're taking a number (not really relevant) and you want it to be a number on the return, just use int or byte (unsigned: 0 <-> 255) or char (signed: -127 <-> +128).
You could/should/doesn't matter if you use Serial.available() or not, it is a matter for yourself, I usually do, but it's non blocking anyway and if there's nothing there to be read, it'll just continue on anyway. Although if you're not going to use it, you should test for that -1 as what you're doing at the moment is taking that and converting it to binary (which is 0xFF which is everything on). This is one of your major problems in the code (the other is in the Short Version section.
You're using "0" and "1" which are ASCII values, and you haven't indicated how you're getting the number. So it may be ASCII (byte) or actually a byte value. ie, "0" is 48 (dec) or 30 (hex). Whereas a 0 is just zero. Funnily enough, because you're using modulo (%) it doesn't really matter because you're only interested in the lowest nibble, which for the sake of your code, doesn't matter what's encoded at the higher end. ie: 1 (0b00000001) is the same as "1" = 49 (dec) = 0x31 = 0b00110001 when used with %2.
Ditch your delay(2000). Delays are evil* :) You could write the values to the pins all day, you're not going to cause any problems, if you want to output less to your serial port (which you should do), you could do timed outputs back to Serial. ie, do your Serial.println() once a second, or record the values into backup/old variables and compare them, and only print the output if the value changes
The big one is in the next section

Short Version
This is your main problem, on this line:
digitalWrite(lights[i+11], (binaryNumber[i] == '0' ? LOW : HIGH));

I think you need:
digitalWrite(lights[i], (binaryNumber[i] == '0' ? LOW : HIGH));

You already have the pin value encoded in the array, you don't want to add 11 to the index, that's going to throw you above your three light values :)
* Delays are evil: It's a matter of opinion, and that's just how I feel, I actually googled it and this is just a random response. But it contains the crux of what I'd say anyway: http://www.makeuseof.com/tag/arduino-delay-function-shouldnt-use/

I was going to rewrite your code, but you've given it a pretty good stab anyway, so take my info above on board and give it another shot. If you have any problems post your new code in an update to the question and we can help you work on it further. If you're under the pump and just want an answer, let us know and I or someone else can give you how we'd do it, but there's nothing better to learning than doing it yourself. It will stick in your head a lot better after giving it another go yourself. You won't make mistakes like that index again (or not in that way, anyway)

Thanks! I actually originally didn't have the index mistake, but when I was looking back over it last night my tired mind though I had made a mistake where there wasn't one and changed it.

It is amazing what the tired mind does sometimes. I find I am often trying to finish "one thing" before calling it a night, and it can have me stumped for hours! At some point, I give up and call it quits. The next morning, refreshed, you take one look at it and see something that you simply can't believe you missed the night before, and in 30 seconds you've fixed the previous 4+ hours of angst. You think to yourself, the next time this happens, I'll just go to bed. But the next time it happens, you spend another night on one problem, that takes another 30 secs to fix the next day, again! lol

I'll definitely do that next time and save myself the trouble lol

You need to check that there are characters available before reading. Please see documentation of Serial.read() (and Serial.available()).
Cheers!


text:
How to learn electronics/programming with Arduino?
I want to learn core and mechanics of microcontrollers with Arduino, and I don't really know where to find good source of knowledge.
Every Arduino related tutorial is about very basic stuff like connecting the LCD display without explaining what every pin does. When it comes to programming tutorials only explain what functions are needed and do not explain what happens inside the hardware.
For example i know what delay() function does, and I know that I can find definition in the source files:
void delay(unsigned long ms)
{
    uint16_t start = (uint16_t)micros();

    while (ms > 0) {
        yield();
        if (((uint16_t)micros() - start) >= 1000) {
            ms--;
            start += 1000;
        }
    }
}

But what I really want to know what that code does, and how to write own functions. I would appreciate if you could provide me with any starting point. Should I just follow the source files until I get it or is there any better reference?
I have Arduino Leonardo, and experience in programming in C/C++.

For information about the “core and mechanics of microcontrollers with Arduino”, there are numerous articles with lots of details on the arduino.cc forum.  However, most of the code posted there sucks, as does most of the code posted here on Arduino Stackexchange.  That's a natural consequence of people posting code that doesn't work and they wonder why.
For a reasonably organized and accurate body of information about Arduino hardware and software, see Nick Gammon's Arduino pages.  Also see arduino.land pages.  For better understanding of Arduino software internals, see garretlab's “Internal Structure of Arduino Software” pages, which are well organized and quite informative about the subjects they cover.
Regarding the specific delay() code shown in the question, first consider this slightly simpler version, from Arduino 1.6.3:
void delay(unsigned long ms) {
    uint16_t start = (uint16_t)micros();
    while (ms > 0) {
        if (((uint16_t)micros() - start) >= 1000) {
            ms--;
            start += 1000;
        }
    }
}

Ignoring data type constraints, it's evident that the while loop counts down ms from its original value to zero.  The burden of the if executes about once per millisecond, because start advances 1000 microseconds each time within the if.
The casts of micros() – ie, where uint16_t appears in parentheses before micros() – tell the compiler to throw away the upper two bytes of micros() [which is actually an unsigned long, or uint32_t] and treat it as an unsigned 16-bit integer.  The low two bytes of micros() overflow every 65536 microseconds, on which occasions within a millisecond it will come to pass that although (uint16_t)micros() is less than start, due to use of unsigned arithmetic ((uint16_t)micros() - start) >= 1000.
The code you included has one more statement in the while loop:
    yield();

For most models of Arduino, yield() is an empty function, a do-nothing if compiled at all.  On the Due, with Scheduler.h in use to support cooperative (non-preemptive) multitasking using multiple stacks, yield() gives the scheduler an opportunity to schedule another task, if one is ready to run.  Note that if a  “cooperative” but malignant task always takes just under 65536 microseconds to do its work, it can happen that delay() as shown never returns.

There are two main topics there: Digital Electronics, and C++ programming, and the Arduino happens to bridge the gap between the two.
That's why it's hard to find tutorials in the style you want.  So instead of looking for Arduino tutorials that do what you want you need to split the topics apart and deal with them separately.
Search for C++ programming tutorials. That should help you understand the structure and syntax of a program better. Search for digital electronics tutorials. Good keywords are things like logic gates, combinational logic or digital interfacing and just digital electronics. That should help you understand things like logic levels, logical functions, inputs and outputs, and such like.
Once you have basic understanding in both fields you can begin to see how the two relate together. One of the most important skills any engineer has is understanding and interpreting datasheets. From datasheets you can find how the hardware operates and what you would need your program to do to make the hardware do what you want.


text:
Playing music with an Arduino
Good evening!
I am quite new with Arduino but not in programming. Still, I have already done some programs with few leds.
I was just wandering how to create a circuit and a program that would play the "happy birthday" song with the following materials:

I have a breadbord and some wires.
Else, do you have some links where I could start learning how to play music with it?

You are in luck: http://forum.arduino.cc/index.php?topic=178460.0

God! I'm trying it right away and send feedbacks soon!

Thanks to Mikael Patel for suggesting that link (your Google-Fu must be strong!).
I am pasting the code below so that this answer survives any possible future deletion of the read-only part of the Arduino Forum.
//ONG LIT YIT 2013-07-20
//This following code plays happy birthday melody on Arduino
//Put Piezo Buzzer on GDN and 9 (Positive and negative are reversible)
//this project requires a Piezo Buzzer and

// an Arduino board and
//jumper wires to connect Buzzer's (+) to ~9 and (-) to GND (any GND)

const int speakerPin = 9;
const int LENGTH = 28; // the number of notes
const char notes[LENGTH + 1] = "GGAGcB GGAGdc GGxecBA yyecdc";
const int beats[LENGTH] = { 2, 2, 8, 8, 8, 16, 1, 2, 2, 8, 8, 8, 16, 1, 2, 2, 8, 8, 8, 8, 16, 1, 2, 2, 8, 8, 8, 16 };
const int tempo = 150;

void playTone(int tone, int duration)
  {
  for (long i = 0; i < duration * 1000L; i += tone * 2)
    {
    digitalWrite(speakerPin, HIGH);
    delayMicroseconds(tone);
    digitalWrite(speakerPin, LOW);
    delayMicroseconds(tone);
    }
  } // end of playTone

void playNote(const char note, const int duration)
  {
  char names[] = {'C', 'D', 'E', 'F', 'G', 'A', 'B',
                  'c', 'd', 'e', 'f', 'g', 'a', 'b',
                  'x', 'y'
                 };
  const int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014,
                  956,  834,  765,  593,  468,  346,  224,
                  655 , 715
                };
  const int SPEE = 5;

  // play the tone corresponding to the note name
  for (int i = 0; i < 17; i++)
    {
    if (names[i] == note) {
      int newduration = duration / SPEE;
      playTone(tones[i], newduration);
    }
  }
} // end of playNote

void setup()
  {
  pinMode(speakerPin, OUTPUT);
  } // end of setup

void loop()
  {
  for (int i = 0; i < LENGTH; i++)
    {
    if (notes[i] == ' ')
      {
      delay(beats[i] * tempo); // rest
      }
    else
    {
      playNote(notes[i], beats[i] * tempo);
    }

    // pause between notes
    delay(tempo);
  }
} // end of loop

I also cleaned up the code a bit.


text:
How to use stm32duino control 5110?
I want to use stm32duino to control 5110, I use the library http://www.rinkydinkelectronics.com/download.php?f=LCD5110_Basic.zip
Before, I use arduino pro mini to control 5110 by this library, it works well. But when I use stm32, it fails. Whether this library is not suitable for stm32duino ? If so, which library is suitable for me ?

The library you linked to does not indicate it works for STM32 architecture. The display uses SPI, and each architecture has it's own way of implementing such peripherals.
There is this library: https://github.com/KenjutsuGH/Adafruit-PCD8544-Nokia-5110-LCD-library which is a port of the Adafruit 5110 driver to STMduino.

Thanks, do you know any library of stmduino for Si4463 (RH_Rf24) and Sx1278 ?

Search in stm32duino forum http://www.stm32duino.com/


text:
How to send sensor data from Arduino through NRF24L01 to Raspberry Pi

I am able to send text from the Arduino wirelessly to RPi.  I am now trying to send the sensor data I'm measuring to the Pi.  This is what I have below:

int moisture = A0;
int temp = 3;

//Skipping the setup and reading of the values

radio.write(&moisture);
radio.write(&temp);

//the above couple lines is where I start having trouble.  The RPi will spit output a seemingly random selection of numbers

As you haven't said or shown which NRF24L01 library you are using, one can't say for sure what the problem is, but in some NRF24 implementations, the write() method accepts (or requires) a second parameter, len, giving the number of bytes to be sent.  If the library you're using doesn't require that parameter, it could be defaulting it to some value, or could be treating the buffer as a string, to be terminated with a null byte.
Either of those cases could produce erratic results.
Instead of leaving off the second parameter, specify it.  For example:
radio.write(&moisture, 2);
radio.write(&temp, 2);

I recommend you to choose a platform for communication. You don't need to deal with the low level communication.
I suggest you to try https://www.mysensors.org/ It helps to wire your sensors, gives you example codes for the chosen sensors for data transfer in the direction to your Pi. There is a well documented API you can build your application on.
On the Pi you can use a serial gateway or/and a controller installed. These controllers are written to communicate with your sensors and other nodes. They give graphical web interface to visualize your data and their history. For a controller I recommend to start with https://www.domoticz.com/ or Openhab I think Domoticz is the better choice to start with on Pi.

most likely is that your nrf24l01 library only allow text or string communcaiton, not nuermical data.  when you send your measured data, nrf24l01 treats it as text.  so what you read is text (text's unicode numbers).  I encountered the same problem.

I will suggest you to provide valid size of data with write function for eg radio.write(&moisture,sizeof(moisture)). hope this will work for further explanation of this method www.robofever.in


text:
Problem sending array data from matlab to arduino
I've two LEDs connected to the arduino uno's pin 12 and 13. I want to control the LEDs independently from the MATLAB serial command.
Here is my MATLAB serial command from where I'm sending char array
s = serial('COM4','BaudRate',9600);
fopen(s);
output = [2,1];
data = char(output);
fprintf(s,'%d',data);
fprintf(s);

And this is my Arduino code to receive char array
char d[4];
void setup()
{
   Serial.begin(9600);
   pinMode(12,OUTPUT);
   pinMode(13,OUTPUT);
}

void loop()
{
    if(Serial.available()>0)
  {
    for(int i=0;i<3;i++)
    {
      d[i] = Serial.read();
    }
    d1 = d[0]-'0';
    if (d1 == 1)
   {
    digitalWrite(12, HIGH);
    delay(1000);
     digitalWrite(12, LOW);
    delay(1000);
    }
  else if (d1 == 2)
    {
    digitalWrite(12, HIGH);
    delay(2000);
    digitalWrite(12, LOW);
    delay(1000);
    }
    d2 = d[1]-'0';
    if (d2 == 1)
   {
    digitalWrite(13, HIGH);
    delay(1000);
     digitalWrite(13, LOW);
    delay(1000);
    }
  else if (d2 == 2)
    {
    digitalWrite(13, HIGH);
    delay(2000);
    digitalWrite(13, LOW);
    delay(1000);
    }
  }
}

The MATLAB command is intended to keep the LED on for the given seconds. When I tried this code for one LED(sending only single char) it worked fine. But when I tried it for two LEDs it turns on only LED connected to pin 12 twice.
Eg:
MATLAB command output = [2,1], turns on LED(pin 12) for 2 sec and then for 1 sec but I want it should be to turn on LED(pin 12) for 2 sec and LED (pin 13) for 1 sec.

And the question is?

If you look at the serial data sent in a terminal what is it? If the serial data is "2,1" then you want d2 = d[2]-'0'; not d2 = d[1]-'0'; Also instead of a load of if statements wouldn't be easier to get the time by multiplying the value by 1000? digitalWrite(12, HIGH);delay(d1*1000);

authors: Сергей Михновец


text:
Why does my ESP8266 making an HTTP request to an MDNS responder keep getting redirected to my ISP's search engine?
I have two ESP8266's trying to talk to each other, a 'host' and a 'client', if you will. I have the ESP8266mDNS.h responder running on the host at esp8266wifi.local. On sending an http GET request to  http://esp8266wifi.local/, I have the webserver send a simple "Success" message.
When I use my computer to access the host in a web browser, it responds just fine, "Success". But when I use the client ESP8266 to send the GET request, it appears to be redirected to my ISP's search engine. The raw html reads:
<meta http-equiv="refresh" content="0;url=http://search.frontier.com/search/?q=http://esp8266wifi.local/&t=0"/>

It appears to respond correctly when I connect to the IP address, http://192.168.0.10/ using ESP8266WebServer.h but when I use the mDNS request I get redirected. Is there any way to work around this?
EDIT:
I tested on my phone's internet browser and my Wii U console and I also get the same redirect to my ISP's search engine.

Those devices probably don't support mDNS, so they do a regular DNS lookup to the ISP's DNS servers. Because that domain name doesn't exist outside of your network, ISP points it to their search engine.


text:
How to initialize and run PCA9685?
I'm trying to write a simple code for initializing and running the PCA9685. I tested the board with Adafruit library and it's working.
But I just want to develop a simple code to include it in my various modules library for future projects.
I wrote a code, but I think I'm not understanding the work of the internal registers.
But according to the datasheet I configured only the auto increment and left the rest to default settings. Then I headed up to the last registers which are the all_led_on and all_led_offas wanting to run the outputs on/off to blink the LEDs. But I think these two registers are for enabling/disabling the pins. Is that right?
This is my code:
void pca9685_init(void){
    uint8_t i,val[]={0x20,0x04};
    i2c_start(PCA9685_BASE_WR);
    i2c_tx(PCA9685_MODE1);
    for(i=0;i<2;i++)i2c_tx(val[i]);
    i2c_stop();
}

void pca9685_all_on(void){
    uint8_t i,val[]={0x00,0x10};
    i2c_start(PCA9685_BASE_WR);
    i2c_tx(PCA9685_ALL_LED_ON_L);
    for(i=0;i<2;i++)i2c_tx(val[i]);
    i2c_stop();
}

void pca9685_all_off(void){
    uint8_t i,val[]={0x00,0x10};
    i2c_start(PCA9685_BASE_WR);
    i2c_tx(PCA9685_ALL_LED_OFF_L);
    for(i=0;i<2;i++)i2c_tx(val[i]);
    i2c_stop();
}

If you want it simple, then use the arduino Wire library and stop fooling around with i2c code that does not work. It took many years to remove bugs from the arduino wire library. The i2c bus is not that simple, so you might never get the quality level of the arduino wire library. What you do is making it overcomplicated and wasting your time. Sorry for my harsh words, I want to make very clear that you should not continue this way. Well, that is at least my opinion, trying to help you.

Absolutely I understand you and respect your goal that you don't want me to waste time with the actual communication library. But my i2c library worked for all my i2c modules and revised different i2c libraries to get it not perfect, but at least to run the basic functions of sending and receiving. Writing my own code helped me a lot in learning how to write code, it's difficult to me to go into projects without learning the internals. But I agree an internal library like Wire should be a very good choice.

@PerchEagle You shouldn't be afraid of the space bar. I know it's big and imposing, but don't be scared of pressing it once in a while ;)

I got you, the code looks so compact lol.

I thought about the space aspect just a moment, but I have a question: what are the appropriate locations to put space into? My most important location is when I use arithmetic, logical or rational operators. But I don't put them to the braces, or after the functions' names. It feel it well fit, but maybe you're right, it maybe more compact than what I feel.

@Jot Just to update what you told me about how the fails could be from my I2C library. You're right! My I2C library is missing something which is doing faulty behavior in the program!

The registers aren't for just turning the LEDs on or off.  They are for setting the ON and OFF times of the PWM. Bit 12 of each combined value is used as a "full" setting, so:
To set the LEDs on to full brightness you need to set:

PCA9685_ALL_LED_OFF_L to 0x00
PCA9685_ALL_LED_OFF_H to 0x00
PCA9685_ALL_LED_ON_L to 0x00
PCA9685_ALL_LED_ON_H to 0x10

This sets the off time to 0 counts and the on to be "full on".
It doesn't really matter what value you set the OFF to as long as you set ON to "full on" and off isn't set to "full off".
For off you should set the ON to 0 and the OFF to "full off" (reverse the above settings).
Section 7.3.3 of the datasheet says:

The turn-on time of each LED driver output and the duty cycle of PWM can be controlled independently using the LEDn_ON and LEDn_OFF registers.
There will be two 12-bit registers per LED output. These registers will be programmed by the user. Both registers will hold a value from 0 to 4095. One 12-bit register will hold a
  value for the ON time and the other 12-bit register will hold the value for the OFF time. The ON and OFF times are compared with the value of a 12-bit counter that will be running
  continuously from 0000h to 0FFFh (0 to 4095 decimal).
Update on ACK requires all 4 PWM channel registers to be loaded before outputs will change on the last ACK.
The ON time, which is programmable, will be the time the LED output will be asserted and the OFF time, which is also programmable, will be the time when the LED output will be
  negated. In this way, the phase shift becomes completely programmable. The resolution for the phase shift is 1⁄
  4096 of the target frequency.

So you have to set all 4 registers together for anything to happen.
There are also some examples shown in the datasheet as well which explain it better.
In simple terms:

There is a free-running counter that counts from 0 to 4095
When the ON time matches the counter the LED turns on.
When the OFF time matches the counter the LED turns off.
If a channel is "FULL OFF" it will be off regardless.
If a channel is "FULL ON" and not "FULL OFF" it will be on regardless.
"FULL OFF" always takes priority over everything else - even "FULL ON".

Some simple examples:

All off: ON=0x0000 OFF=0x1000
All on full: ON=0x1000 OFF=0x0000
50% duty: ON=0x0000 OFF=0x0800
25% duty: ON=0x0000 OFF=0x0400
25% duty with phase shift: ON=0x0100 OFF=0x0500

Yep, you're right. I did it, I have to update the 4 registers for all_on state, and again all 4 registers for all_off state.

@PerchEagle The datasheet isn't that obvious. As you can see by the edit history of my answer it took me a while to understand it fully.

Thanks dude again for the help I really appreciate it, it's not the first time you help me, now I learned that, I can proceed to go to the pwm operations and develop the library.

I have a quick question, why there's 12-bit for on and 12-bit for off. I wrote different values for only on time and got certain results and different results for off time, and also got different results. So what's the deal exactly with this chip? Is the full range of this device is 4096 ON + 4096 OFF = 8192.

No. There is a single 12 bit counter. It turns on or off when the counter matches the on or off value. That way you can control the phase as well as the duty cycle.

Anyway I haven't mastered this module, I need a lot more practice or just to know what does on/off time means? are they the same? Should I use one and that's enough or using both have more functionality? These are the questions I have for this module.


text:
How do you use SPI on an Arduino?
With reference to the Arduino Uno, Mega2560, Leonardo and similar boards:

How does SPI work?
How fast is SPI?
How do I connect between a master and a slave?
How do I make an SPI slave?

Please note: This is intended as a reference question.

Can you answer this related question https://arduino.stackexchange.com/questions/60703/can-serial-be-safely-used-in-an-spi-interrupt-routine

Introduction to SPI
The Serial Peripheral Interface Bus (SPI) interface is used for communication between multiple devices over short distances, and at high speed.
Typically there is a single "master" device, which initiates communications and supplies the clock which controls the data transfer rate. There can be one or more slaves. For more than one slave, each one has its own "slave select" signal, described later.

SPI signals
In a full-blown SPI system you will have four signal lines:

Master Out, Slave In (MOSI) - which is the data going from the master to the slave
Master In, Slave Out (MISO) - which is the data going from the slave to the master
Serial Clock (SCK) - when this toggles both the master and the slave sample the next bit
Slave Select (SS) - this tells a particular slave to go "active"

When multiple slaves are connected to the MISO signal they are expected to tri-state (keep at high impedance) that MISO line until they are selected by Slave Select being asserted. Normally Slave Select (SS) goes low to assert it. That is, it is active low. Once a particular slave is selected it should configure the MISO line as an output so it can send data to the master.
This image shows the way that data is exchanged as one byte is sent:

Note that three signals are outputs from the master (MOSI, SCK, SS) and one is an input (MISO).

Timing
The sequence of events is:

SS goes low to assert it and activate the slave
The SCK line toggles to indicate when the data lines should be sampled
The data is sampled by both master and slave on the leading edge of SCK (using the default clock phase)
Both master and slave prepare for the next bit on the trailing edge of SCK (using the default clock phase), by changing MISO / MOSI if necessary
Once the transmission is over (possibly after multiple bytes have been sent) then SS goes high to de-assert it

Note that:

The most significant bit is sent first (by default)
Data is sent and received at the same instant (full duplex)

Because data is sent and received on the same clock pulse it is not possible for the slave to respond to the master immediately. SPI protocols usually expect the master to request data on one transmission, and get a response on a subsequent one.
Using the SPI library on the Arduino, doing a single transfer looks like this in code:
 byte outgoing = 0xAB;
 byte incoming = SPI.transfer (outgoing);

Sample code
Example of sending only (ignoring any incoming data):
#include <SPI.h>

void setup (void)
  {
  digitalWrite(SS, HIGH);  // ensure SS stays high
  SPI.begin ();
  } // end of setup

void loop (void)
  {
  byte c;

  // enable Slave Select
  digitalWrite(SS, LOW);    // SS is pin 10

  // send test string
  for (const char * p = "Fab" ; c = *p; p++)
    SPI.transfer (c);

  // disable Slave Select
  digitalWrite(SS, HIGH);

  delay (100);
  } // end of loop

Wiring for output-only SPI
The above code (which sends only) might be used to drive an output serial shift register. These are output-only devices, so we don't need to worry about any incoming data. In their case the SS pin might be called the "store" or "latch" pin.

Examples of this are the 74HC595 serial shift register, and various LED strips, just to mention a couple. For example, this 64 pixel LED display driven by a MAX7219 chip:

In this case you can see that the board maker has used slightly different signal names:

DIN (Data In) is MOSI (Master Out, Slave In)
CS (Chip Select) is SS (Slave Select)
CLK (Clock) is SCK (Serial Clock)

Most boards will follow a similar pattern. Sometimes DIN is just DI (Data In).
Here is another example, this time a 7-segment LED display board (also based on the MAX7219 chip):

This uses exactly the same signal names as the other board. In both of these cases you can see that the board only needs 5 wires to it, the three for SPI, plus power and ground.

Clock phase and polarity
There are four way you can sample the SPI clock.
The SPI protocol allows for variations on the polarity of the clock pulses. CPOL is clock polarity, and CPHA is clock phase.

Mode 0 (the default) - clock is normally low (CPOL = 0), and the data is sampled on the transition from low to high (leading edge) (CPHA = 0)
Mode 1 - clock is normally low (CPOL = 0), and the data is sampled on the transition from high to low (trailing edge) (CPHA = 1)
Mode 2 - clock is normally high (CPOL = 1), and the data is sampled on the transition from high to low (leading edge) (CPHA = 0)
Mode 3 - clock is normally high (CPOL = 1), and the data is sampled on the transition from low to high (trailing edge) (CPHA = 1)

These are illustrated in this graphic:

You should refer to the datasheet for your device to get the phase and polarity correct. There will usually be a diagram which shows how to sample the clock. For example, from the datasheet for the 74HC595 chip:

As you can see the clock is normally low (CPOL = 0) and it is sampled on the leading edge (CPHA = 0) so this therefore is SPI mode 0.
You can change the clock polarity and phase in code like this (choose one only, of course):
SPI.setDataMode (SPI_MODE0);
SPI.setDataMode (SPI_MODE1);
SPI.setDataMode (SPI_MODE2);
SPI.setDataMode (SPI_MODE3);

This method is deprecated in versions 1.6.0 onwards of the Arduino IDE. For recent versions you change the clock mode in the SPI.beginTransaction call, like this:
SPI.beginTransaction (SPISettings (2000000, MSBFIRST, SPI_MODE0));  // 2 MHz clock, MSB first, mode 0

Data order
The default is most-significant bit first, however you can tell the hardware to process the least significant bit first like this:
SPI.setBitOrder (LSBFIRST);   // least significant bit first
SPI.setBitOrder (MSBFIRST);   // most significant bit first

Again, this is deprecated in versions 1.6.0 onwards of the Arduino IDE. For recent versions you change the bit order in the SPI.beginTransaction call, like this:
SPI.beginTransaction (SPISettings (1000000, LSBFIRST, SPI_MODE2));  // 1 MHz clock, LSB first, mode 2

Speed
The default setting for SPI is to use the system clock speed divided by four, that is, one SPI clock pulse every 250 ns, assuming a 16 MHz CPU clock. You can change the clock divider by using setClockDivider like this:
SPI.setClockDivider (divider);

Where "divider" is one of:

SPI_CLOCK_DIV2
SPI_CLOCK_DIV4
SPI_CLOCK_DIV8
SPI_CLOCK_DIV16
SPI_CLOCK_DIV32
SPI_CLOCK_DIV64
SPI_CLOCK_DIV128

The fastest rate is "divide by 2" or one SPI clock pulse every 125 ns, assuming a 16 MHz CPU clock. This would therefore take 8 * 125 ns or 1 µs to transmit one byte.
This method is deprecated in versions 1.6.0 onwards of the Arduino IDE. For recent versions you change the transfer speed in the SPI.beginTransaction call, like this:
SPI.beginTransaction (SPISettings (4000000, MSBFIRST, SPI_MODE0));  // 4 MHz clock, MSB first, mode 0

However empirical testing shows that it is necessary to have two clock pulses between bytes, so the maximum rate at which bytes can be clocked out is 1.125 µs each (with a clock divider of 2).
To summarize, each byte can be sent at a maximum rate of one per 1.125 µs (with a 16 MHz clock) giving a theoretical maximum transfer rate of 1/1.125 µs, or 888,888 bytes per second (excluding overhead like setting SS low and so on).

Connecting to Arduino
Arduino Uno
Connecting via digital pins 10 to 13:

Connecting via the ICSP header:

Arduino Atmega2560
Connecting via digital pins 50 to 52:

You can also use the ICSP header, similar to the Uno above.
Arduino Leonardo
The Leonardo and Micro do not expose the SPI pins on the digital pins, unlike the Uno and Mega. Your only option is to use the ICSP header pins, as illustrated above for the Uno. However the Leonardo and ProMicro don't expose the SS pin and thus cannot be used as an SPI slave.

Multiple slaves
A master can communicate with multiple slaves (however only one at a time). It does this by asserting SS for one slave and de-asserting it for all the others. The slave which has SS asserted (usually this means LOW) configures its MISO pin as an output so that slave, and that slave alone, can respond to the master. The other slaves ignore any incoming clock pulses if SS is not asserted. Thus you need one additional signal for each slave, like this:

In this graphic you can see that MISO, MOSI, SCK are shared between both slaves, however each slave has its own SS (slave select) signal.

Protocols
The SPI spec does not specify protocols as such, so it is up to individual master/slave pairings to agree on what the data means. Whilst you can send and receive bytes simultaneously, the received byte cannot be a direct response to the sent byte (as they are being assembled simultaneously).
So it would be more logical for one end to send a request (eg. 4 might mean "list the disk directory") and then do transfers (perhaps just sending zeros outwards) until it receives a complete response. The response might terminate with a newline, or 0x00 character.
Read the datasheet for your slave device to see what protocol sequences it expects.

How to make an SPI slave
The earlier example shows the Arduino as the master, sending data to a slave device. This example shows how the Arduino can be a slave.
Hardware setup
Connect two Arduino Unos together with the following pins connected to each other:

10 (SS)

11 (MOSI)

12 (MISO)

13 (SCK)

+5v (if required)

GND (for signal return)

On the Arduino Mega, the pins are 50 (MISO), 51 (MOSI), 52 (SCK), and 53 (SS).
In any case, MOSI at one end is connected to MOSI at the other, you don't swap them around (that is you do not have MOSI <-> MISO). The software configures one end of MOSI (master end) as an output, and the other end (slave end) as an input.
On some boards (like Leonardo, ProMicro — see above) the SS pin isn't exposed (rather it is connected to RX_LED). It is not possible to remap SS to another pin to be able to use those boards as an SPI slave as the AVR uses fixed SPI pins according to the datasheets (PB0-PB3 on 32U4).
Master example
#include <SPI.h>

void setup (void)
{

  digitalWrite(SS, HIGH);  // ensure SS stays high for now

  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();

  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);

}  // end of setup

void loop (void)
{

  char c;

  // enable Slave Select
  digitalWrite(SS, LOW);    // SS is pin 10

  // send test string
  for (const char * p = "Hello, world!\n" ; c = *p; p++)
    SPI.transfer (c);

  // disable Slave Select
  digitalWrite(SS, HIGH);

  delay (1000);  // 1 seconds delay
}  // end of loop

Slave example
#include <SPI.h>

char buf [100];
volatile byte pos;
volatile bool process_it;

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

  // turn on SPI in slave mode
  SPCR |= bit (SPE);

  // have to send on master in, *slave out*
  pinMode (MISO, OUTPUT);

  // get ready for an interrupt
  pos = 0;   // buffer empty
  process_it = false;

  // now turn on interrupts
  SPI.attachInterrupt();

}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
{
byte c = SPDR;  // grab byte from SPI Data Register

  // add to buffer if room
  if (pos < sizeof buf)
    {
    buf [pos++] = c;

    // example: newline means time to process buffer
    if (c == '\n')
      process_it = true;

    }  // end of room available
}  // end of interrupt routine SPI_STC_vect

// main loop - wait for flag set in interrupt routine
void loop (void)
{
  if (process_it)
    {
    buf [pos] = 0;
    Serial.println (buf);
    pos = 0;
    process_it = false;
    }  // end of flag set

}  // end of loop

The slave is entirely interrupt-driven, thus it can doing other stuff. The incoming SPI data is collected in a buffer, and a flag set when a "significant byte" (in this case a newline) arrives. This tells the slave to get on and start processing the data.
Example of connecting master to slave using SPI

How to get a response from a slave
Following on from the code above which sends data from an SPI master to a slave, the example below shows sending data to a slave, having it do something with it, and return a response.
The master is similar to the example above. However an important point is that we need to add a slight delay (something like 20 microseconds). Otherwise the slave doesn't have a chance to react to the incoming data and do something with it.
The example shows sending a "command". In this case "a" (add something) or "s" (subtract something). This is to show that the slave is actually doing something with the data.
After asserting slave-select (SS) to initiate the transaction, the master sends the command, followed by any number of bytes, and then raises SS to terminate the transaction.
A very important point is that the slave cannot respond to an incoming byte at the same moment. The response has to be in the next byte. This is because the bits which are being sent, and the bits which are being received, are being sent simultaneously. Thus to add something to four numbers we need five transfers, like this:
transferAndWait ('a');  // add command
transferAndWait (10);
a = transferAndWait (17);
b = transferAndWait (33);
c = transferAndWait (42);
d = transferAndWait (0);

First we request action on number 10. But we don't get a response until the next transfer (the one for 17). However "a" will be set to the reply to 10. Finally we end up sending a "dummy" number 0, to get the reply for 42.
Master (example)
  #include <SPI.h>

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

    digitalWrite(SS, HIGH);  // ensure SS stays high for now
    SPI.begin ();

    // Slow down the master a bit
    SPI.setClockDivider(SPI_CLOCK_DIV8);
    }  // end of setup

  byte transferAndWait (const byte what)
    {
    byte a = SPI.transfer (what);
    delayMicroseconds (20);
    return a;
    } // end of transferAndWait

  void loop (void)
    {

    byte a, b, c, d;

    // enable Slave Select
    digitalWrite(SS, LOW);

    transferAndWait ('a');  // add command
    transferAndWait (10);
    a = transferAndWait (17);
    b = transferAndWait (33);
    c = transferAndWait (42);
    d = transferAndWait (0);

    // disable Slave Select
    digitalWrite(SS, HIGH);

    Serial.println ("Adding results:");
    Serial.println (a, DEC);
    Serial.println (b, DEC);
    Serial.println (c, DEC);
    Serial.println (d, DEC);

    // enable Slave Select
    digitalWrite(SS, LOW);

    transferAndWait ('s');  // subtract command
    transferAndWait (10);
    a = transferAndWait (17);
    b = transferAndWait (33);
    c = transferAndWait (42);
    d = transferAndWait (0);

    // disable Slave Select
    digitalWrite(SS, HIGH);

    Serial.println ("Subtracting results:");
    Serial.println (a, DEC);
    Serial.println (b, DEC);
    Serial.println (c, DEC);
    Serial.println (d, DEC);

    delay (1000);  // 1 second delay
    }  // end of loop

The code for the slave basically does almost everything in the interrupt routine (called when incoming SPI data arrives). It takes the incoming byte, and adds or subtracts as per the remembered "command byte". Note that the response will be "collected" next time through the loop. This is why the master has to send one final "dummy" transfer to get the final reply.
In my example I am using the main loop to simply detect when SS goes high, and clear the saved command. That way, when SS is pulled low again for the next transaction, the first byte is considered the command byte.
More reliably, this would be done with an interrupt. That is, you would physically connect SS to one of the interrupt inputs (eg, on the Uno, connect pin 10 (SS) to pin 2 (an interrupt input), or use a pin-change interrupt on pin 10.
Then the interrupt could be used to notice when SS is being pulled low or high.
Slave (example)
// what to do with incoming data
volatile byte command = 0;

void setup (void)
  {

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= _BV(SPE);

  // turn on interrupts
  SPCR |= _BV(SPIE);

  }  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
  {
  byte c = SPDR;

  switch (command)
    {
    // no command? then this is the command
    case 0:
      command = c;
      SPDR = 0;
      break;

    // add to incoming byte, return result
    case 'a':
      SPDR = c + 15;  // add 15
      break;

    // subtract from incoming byte, return result
    case 's':
      SPDR = c - 8;  // subtract 8
      break;

    } // end of switch

  }  // end of interrupt service routine (ISR) SPI_STC_vect

void loop (void)
  {

  // if SPI not active, clear current command
  if (digitalRead (SS) == HIGH)
    command = 0;
  }  // end of loop

Example output
Adding results:
25
32
48
57
Subtracting results:
2
9
25
34
Adding results:
25
32
48
57
Subtracting results:
2
9
25
34

Logic analyzer output
This shows the timing between sending and receiving in the above code:

New functionality in IDE 1.6.0 onwards
Version 1.6.0 of the IDE has changed the way SPI works, to an extent. You still need to do SPI.begin() before using SPI. That sets up the SPI hardware. However now, when you are about to start communicating with a slave you also do SPI.beginTransaction() to set up SPI (for this slave) with the correct:

Clock speed
Bit order
Clock phase and polarity

When you are done communicating with the slave, you call SPI.endTransaction(). For example:
SPI.beginTransaction (SPISettings (2000000, MSBFIRST, SPI_MODE0));
digitalWrite (SS, LOW);        // assert Slave Select
byte foo = SPI.transfer (42);  // do a transfer
digitalWrite (SS, HIGH);       // de-assert Slave Select
SPI.endTransaction ();         // transaction over

Why use SPI?

I would add one preliminary question: when/why would you use SPI? A need for multi-master configuration or a very large number of slaves would tilt the scale toward I2C.

This is an excellent question. My answers are:

Some devices (quite a few) only support the SPI transfer method. For example the 74HC595 output shift register, the 74HC165 input shift register, the MAX7219 LED driver, and quite a few LED strips that I have seen. So, you might use it because the target device only supports it.
SPI is really the fastest method available on the Atmega328 (and similar) chips. The fastest rate quoted above is 888,888 bytes per second. Using I2C you can only get around 40,000 bytes per second. The overhead of the I2C is quite substantial, and if you are trying to interface really quickly, SPI is the preferred choice. Quite a few chip families (eg. MCP23017 and MCP23S17) actually support both I2C and SPI so you often can choose between speed, and the ability to have multiple devices on a single bus.
The SPI and I2C devices are both supported in hardware on the Atmega328 so you could conceivably be doing a transfer via SPI simultaneously with I2C which would give you a speed boost.

Both methods have their place. I2C lets you connect many devices to a single bus (two wires, plus ground) so it would be the preferred choice if you needed to interrogate a substantial number of devices, perhaps fairly infrequently. However the speed of SPI could be more relevant for situations where you need to output rapidly (eg. a LED strip) or input rapidly (eg. an ADC converter).

References

My page about SPI - also has details about bit-banged SPI, and using the USART to gain a second hardware SPI on the Atmega328 chip.

Serial Peripheral Interface Bus - Wikipedia

Arduino SPI library reference pages

SPI documentation at PJRC

SPI protocol - Sparkfun

Are you going to cover the weirdness that is the Due's SPI? Where the configuration of the SPI port is tied to the SS pin used, and there are (IIRC) 4 hardware SS pins assigned to the SPI port?

Other point about the selection: sometimes you really have no choice because the sensor you want/need to use is only available as I2C.

Are you going to cover the weirdness that is the Due's SPI? - I don't know anything about the Due's SPI (apart from presuming the overall protocol is the same). You are welcome to add a reply covering that aspect of it.

When is the audiobook of this answer coming out, and will you be reading it yourself ;)

@AMADANONInc. Perhaps a music video? Or an animation? I'm not sure if my Australian accent would be understandable. :P

@NickGammon, I live in NZ, and I've been learning from EEVBlog videos for some time, so I don't think I'll have any problems. A music video would be good, though - how's your circular breathing?

I think sub section "New functionality in IDE 1.6.0 onwards" should explicitly answer the question "What if I leave out SPI.beginTransaction?" (etc.). Similary, answer the question "Will old sketches work?" (backwards compatibility (with some fixed defaults?)) - I think they do; that is what I observed yesterday when trying with Arduino Uno, software version 1.6.5, and a DAC (MCP4901); but there could be caveats that I don't know of. "also" could maybe be "can also".

New SPI has SPI.transfer(buffer, size) https://www.arduino.cc/en/Reference/SPITransfer

@PeterMortensen using Arduino 1.8.8 setting SPI params the old way still works

Is the slave interupt function triggered by the clock leading edge?

No, it would be triggered by the complete transfer of one byte, as the ISR can immediately access that (SPDR), as in the code shown.

See my post https://www.fpaynter.com/2020/03/arduino-spi-data-exchange-between-two-arduinos-in-a-master-slave-configuration/ for a newbie's take on the problem

Someone tried to edit in a comment that the Leonardo and ProMicro don't expose the SS pin, so I have amended the answer to reflect that.

To the users that are rejecting edits about the SS pin, as the author I don't disagree with them.

I have amended the edit in question to remove the reference to "so people wondered" ... which people?

Thank you for the information.
Mr. Nick Gammon said

However the Leonardo and ProMicro don't expose the SS pin and thus cannot be used as an SPI slave.

but I could use ProMicro and Leonardo as SPI slave devides by wiring SS signal.
Reference: https://asukiaaa.blogspot.com/2023/05/atmega32u4-as-spi-slave.html


text:
How to read input pin on MCP23017?
I'm working to develop a simple code for MCP23017 that I want to use to run LCD128x64.
I was succeeded to set IODIRB as output and blink LED as a test.
Now I want to read the pin state, but I couldn't. Here's my code. I'm using the nice twi library that comes with Wire library.
uint8_t mcp23017_read(uint8_t add_reg){
    uint8_t data;
    twi_writeTo(MCP23017_ADD,add_reg,2,1,0);
    twi_readFrom(MCP23017_ADD,data,1,1);

    return data;
}

I've tried this version too:
uint8_t *mcp23017_read(uint8_t add_reg){
    uint8_t data[1];
    twi_writeTo(MCP23017_ADD,add_reg,2,1,0);
    twi_readFrom(MCP23017_ADD,data,1,1);

    return *data;
}

==================================================
Here's Arduino call function:
void loop() {
  // put your main code here, to run repeatedly:
  data = mcp23017_read(GPIOB);
  Serial.println(data);
  delay(100);
}

how do you know that you cannot read the pin state?

I'm connecting the pin with a resistor to 5V or GND.

here is an example about reading inputs https://tronixstuff.com/2011/08/26/arduino-mcp23017-tutorial/

Is there a reason why you use TWI but not Wire?

Yes, I can same like 300 bytes of the flash memory. And I want to learn how to study other people's code. The twi is a very good example. I learned how ISR work and how functions should handle buffered TX/Rx data.

I don't know how this lib works. But I'm pretty sure that you have to pass a pointer onto the data variable into the twi_readFrom method.
uint8_t mcp23017_read( uint8_t add_reg )
{
    uint8_t data;
    twi_writeTo( MCP23017_ADD, add_reg, 2, 1, 0 );
    // I inserted an & below
    twi_readFrom( MCP23017_ADD, &data, 1, 1 );

    return data;
}

Or in case of the second function:
// I removed the star operator
uint8_t mcp23017_read(uint8_t add_reg)
{
    uint8_t data[1];

    twi_writeTo( MCP23017_ADD, add_reg, 2, 1, 0 );
    // you pass the pointer to the array element 0
    twi_readFrom( MCP23017_ADD, data, 1, 1 );

    // I returned the element 0
    return data[0];
}

Update:
Just for completeness: The OP found also a failure on the write function. He had posted a separate answer, I voted up to mark it. Because this is the accepted answer, I also copied his post to here for completeness and the readers convenience.
Original post by R1S8K:

OK, I found a the answer and it was a good lesson in dealing with
  functions that receives pointers.
I forgot that the writeTo function also receives a pointer and I have
  to pass an array for both read/write functions.
void mcp23017_read(uint8_t *add_reg, uint8_t *buffer){
    twi_writeTo(MCP23017_ADD, add_reg, 1, 1, 1);
    twi_readFrom(MCP23017_ADD, buffer, 1, 1);
}

It isn't working ! I don't know what I'm doing wrong. Should I launch a repstart or not ... etc.

Yep, that's very nice :) Thanks for improving my thread.

OK, I found one little mistake in my coding.
I forgot that the writeTo function also receives a pointer and I have to pass an array for both read/write functions.
void mcp23017_read(uint8_t *add_reg, uint8_t *buffer){
    twi_writeTo(MCP23017_ADD, add_reg, 1, 1, 1);
    twi_readFrom(MCP23017_ADD, buffer, 1, 1);
}


text:
Why to store a function parameter value in a class private variable?
I'm just curious, I'm going through a C++ library for the mcu2.4 TFT display.
And this method I notice when I run through C++ libraries.
Which is when a parameter is passed through a function, it's stored in a private variable; like this one:
HCTFT::HCTFT(byte DisplayType)
{
    _Display = DisplayType;

What's the benefit of this method? What's the similar method when I want to do it in C code?

C doesn't have classes or private variables, so you can't do that in C?

You should read up on constructors.

@immibis I know, I just considering that the common methods in C++ and the equivalent in C.

The reason is that _Display will be used probably after its construction.
So you pass the byte during construction, and afterwards the value is available during the object's lifetime.
In C you probably will do this by:

Passing the variable (byte DisplayType) in each function where the value is needed (you can use this way in C++ too but it's cumbersome in both C/C++ to pass the variable in all functions needed).
Storing it in a global variable (static for that .c file); this is the typically C method.

* Added explanation *
Such a variable is called class variables and are mostly made private. The reason is that other objects cannot change the value directly. The only way to change a variable is:

By initializing it in the class constructor (like in your example).
Within the class itself (by any method).
By a typical Set method (like SetDisplayType). This method can check if the value passed is within a range, and there is only one entry point in this class to change it.

To retrieve the value, typically a GetDisplayType method should be created which is public. The variable itself is private.

OK, I understand, so it's a programming style. Hmm alright, I'm starting to understand C++ syntax. I'm just running through the library. Most of the time when I run through C++ libraries I encounter things; like, private, public, inline, virtual .. etc. There are also things I want to understand too, I'm just taking it step at a time to get to know C++ better, I'm thinking how C++ would be effective to me when I want to write a library.

Well in C++ (or actually an OO language) it's very normal to put information (data/variables) and functionality together, and in a class (private) variable you store data that belongs to that instance of the class.

OK, this one is clear to me now, so the class is just a complete object which has its own functions and variables and that's it. Then also there are other specifiers which provide the property to use this class functions or variable by other classes but of course it's much more advanced topic than my current knowledge.

It's better to read a book about OO design, than you will get to learn all the reasons behind it. The main idea is: keep data/functions together, keep data private, keep functions lean and public to others.

Michel Keijzers explained pretty well the purpose of that idiom. Just to
complement his answer, you can do exactly the same in C, only with a
slightly different syntax:
typedef struct {
    byte _Display;
    // ...
} HCTFT;

HCTFT_construct(HCTFT *this, byte DisplayType)
{
    this->_Display = DisplayType;
    // ...
}

Now, every function that receives a pointer to an HCTFT (a HCTFT
“method”) has access to that data as a member of the struct.

So you mean I have to store it somewhere whether in a class private member with C++, struct variable with C or a global variable. So I don't have to pass it again to other functions, and I just can call its value from any function without passing it to that function? Am I understanding it correctly?

@PerchEagle: You don't have to: there are always many ways to do one thing. What I say is that, if you need to store several pieces of data for managing a TFT display, it is convenient to bundle them together into a single data structure (a struct). Then, instead of passing all the pieces as separate arguments to every function that deals with the display, you just pass a pointer to that single struct. The code becomes better structured and more readable. The C++ classes and methods are basically syntactic sugar over this programming pattern.

Wonderful, I just have to dive into writing the TFT library to learn how to use these skills, I started to put the definitions in the header file. But what I'm considering now is that the process could be similar if I used my basic C skills to write a library hmmm. I found a good example like this piece of code. void HCTFT::SetFG(byte R, byte G, byte B) {  _FGR = R;  _FGG = G;  _FGB = B; } so now the result is that the underscore variables are declared in the private section. And now by passing them to this function then they can be used right away in other functions! Nice.

That is more Object Oriented Programing question than the Arduino related.
Encapsulation is one of the fundamentals of OOP and it's basically you'll provide some interface to the object and the outside world doesn't have to know anything about it's internals (so it's not possible to change it into inconsistent state).