How can i connect the Mics-5132 to Arduino Uno (Carbon Monoxide Sensor) hi. i don't know how can i connect Mics-5132 CO Sensor to my arduino.

plz help

That is a very skimpy data sheet for the MiCS-5132 .  (Shame on manufacturer for not including isolation information between heater and resistor output).

Connect 3.2 volts (3.3 volts is ok) to pins 1 and 3 (heater). Keep in mind the heater will draw about 32 mA.

Pins 2 and 4 are the output.  The output is a resistor, whose value changes with the degree of detected gases. And the resistance is about 160 k ohms.

Wire a resistor (call it R1) from VCC (positive power) to your input. Start out with R1 = 150k  (anything from 120K to 180K). .

Wire the sensor (pin2) to your input (use an input that can do A/D conversion).  Wire the other side of the sensor (pin 4) to your board ground.

This makes a resistor voltage divider to your input pin. Your input pin should be an A/D converter.  The A/D converter input should return a value dependent upon the sensor resistance.

Experiment with different values for R1, to get the input range that you desire.


flash read err, 1000 I know this question has been asked multiple times but solutions giving there hasn't been working,

I've got an esp32 soldered to my own designed PCB board with a UART to USB converter all that is working fine, I can get connected to my esp from the Serial monitor.

But it prints every about 0.5s:

rst:0x10 (RTCWDT_RTC_RESET)
boot:0x13 (SPI_FAST_FLASH_BOOT)
flash read err, 1000 ets_main.c
371 ets Jun 8 2016 00:22:57

Solutions have been to make sure to have 3.3v on the esp. I find it unlikely to have anything to do with it, 'cause its voltage range goes from 2.6v to 3.6v, but anyway I have tested it with an advanced transformer and a multimeter to check that there was 3.3v on the Vcc pin (didn't change anything).

All help would be appreciated.

Here is a bit more info:

I've also connected a 10uF capacitor (someone told me to try that).

If I pull IO0 to ground, it prints waiting for download in the serial monitor and I can almost upload the program, this is what I get:

  THERE IS NO CONNECTION BETWEEN NEIGHBORING PINS

(I have checked with multimeter)

PCB board:

Your PCB is lacking in the majority of things you need to get the module working. These modules are not "simple" in that you provide power and forget about it. You must add all the required support components. Those support components are NOT optional. For example: you aren't setting the boot mode properly with the right pullups. You lack a capacitor on the power pins (I told you to add one already. Where is it?). Also your power traces are too thin. The impedance is too high.


Arduino + IMU vs ArduIMU I am working on a UAV and we are currently exploring inertial measurement units or IMUs. The two options that we have come across are:

Using an Arduino Uno and a 9 DOF IMU like this one
Using an ArduIMU chip like this one

Ignoring the cost aspect and assuming the same microprocessor on board, what would be the pros and cons of either of these approaches?

Keep in mind that performance is very important for a UAV controller as ESCs require 60 Hz or higher refresh rates for stable flight.

Weight: marginal as the difference between one board (with everything on it) and two boards (Uno plus DOF) may be - for model airplanes every bit counts.

Size: the traditional "Uno" is much larger than the ArduIMU integrated boards.

Power: the integrated board PROBABLY will use less and thus get away with a smaller (lighter) battery.


Cannot enter programming mode on Arduino Uno I have an Arduino Uno that I've been programming with an AVR Dragon through Atmel Studio 7.

I did two things in close proximity, and I'm not entire sure which action is the culprit. I tried using the DebugWIRE interface (for the first time) instead of ISP in the tool select screen. I also hit the Arduino's reset button as Atmel Studio was compiling/uploading to the Arduino (stupid, I know.)

Now I cannot program with ISP the normal way, or do anything really.  If I try to upload to the Arduino I get:

I've tried to use the device programming feature using the Dragon and change the fuses as I've read about in other posts and get:

I've tried burning a new bootloader with the Arduino IDE and the IDE tries ten times, but it tells me that the programmer is not responding.

When I plug my AVR ISP mk2 into a different Arduino Uno I get a nice constant green light. If I plug it into the board I've been discussing it blinks red.

I'm not sure where to go from here...

I think either the chip or the board is fried. Try swap the chip (only the chip) to the other board and retry loading the program.


>=500Mhz microcontroller that works with arduino sketches? I'm looking for a decently beefier arduino, but from what I can tell by using google the best I can get is up to 80mhz clock speed. I need something closer to or higher than 500 with more ram, I found the Intel Edison but it runs linux, what I'm looking for is something that is bare metal like the arduino.
I need the higher clock rate for faster calculations and more ram for storing vertex information for a 3D renderer.
Thanks for your help everybody.

I would guess that the Teensy 3.6 is the beefiest Arduino available right now. It runs at 180 MHz. Now clock speed is not everything. This can be illustrated by Arduino-Scheduler and context switch time for the supported boards.

Cheers!


How should I decide the cut-off frequency for my low-pass filter? I'm trying to generate some basic thumping stereo sound using Arduino's PWM pins along with low-pass filters.
This is the frequency spectrum for the sound I want to play using Arduino UNO's PWM pins:

Based on this, I think (from what I understand) the cut-off frequency for the low-pass filter should be around 8900Hz. But, wouldn't the PWM function operate at a much higher frequency to generate the same wave? If that's how it'll be, how should I decide the cut-off frequency for my low-pass filter?
I understand that the fastest frequency one can get for 8-bit PWM on an UNO is 62.5 kHz. So, I might not be able to generate this wave using the UNO itself. Unfortunately, I won’t be able to use another microcontroller for this project. However, what I can do to solve this issue is - generate a different sound wave of lower frequency. If someone can help me with finding out by how much will the frequency of the wave increase if I use PWM to generate it, I’ll be able to generate an appropriate wave.

That looks like the spectrum of an 8-bit sound that is playing low bass notes only.  Most everything above that looks like noise floor.  (You can only get about 6 dB range per bit of resolution, so 8 bits gives about 48 dB max.)  If this is the case, you definitely don't want to reproduce the upper frequencies.  If you want to stick to your original PWM scheme, use pins 5 or 6 because they use 980 Hz PWM instead of 490.  I suggest you determine the filter by trial and error, since it comes down to how much PWM carrier you can tolerate.  You can make a simple RC filter using the formula F = 1 / (2 * pi * R * C) where F is the cutoff frequency in Hz, R is ohms, and C is farads (that's 10^6 microfarads per farad).  This type of simple filter will have a very soft cutoff frequency, about 6 dB per octave, so if you set it for 123 Hz (3 octaves below 980 Hz) the 980 Hz PWM will be reduced by 18 dB.  The R connects to the PWM pin, and the C goes from the other end of R to ground, as does the signal output.  The formula assumes that there is no output load, so you should connect an amplifier there.  If you are like most folks, you probably have fewer capacitor values on hand than resistor values, so pick the C value first.  Let's say it's 1 uFd.  Then if you use R=1K the cutoff will be 159 Hz.  Change R while listening to the output


Minimizing IR Detection Interference I'll start by saying that the goal here is to have a hand/distance detection device. Basically touch-less button.
I managed to get it working with a simple 2-pin IR emitter and 2-pin IR detector using analog read from the detector to trigger an event. The problem is that I get interference from the sun on bright days.
Is there a way to pulse the emitter at a specific frequency and have the detector activate only on that frequency and keep the 2-pin setup?
One solution I have been leaning towards is changing the IR detector to a IR decoder and basically treat it as a remote control but I can't see a way to detect distance using this method.
I am also open to any other ideas on getting something like this to work, without IR or ultrasonic.
Thanks.

This is actually something I have been meaning to try but never got around to it.
My idea is to drive the LED with PWM with a 50% duty cycle. The frequency isn't really that critical, but you don't want it too high for the next part.
Now you sample the receiver at a fixed frequency that is at least 2x the frequency of the PWM into a buffer.
Then you perform FFT on that buffer.
The bucket that contains the frequency of the PWM should have a power value that is proportional to the distance.
Other light sources will be unlikely to affect the same bucket as the PWM frequency - most will only affect the lowest (0Hz+) bucket.
Or that's the theory that I came up with. I have yet to try it in practice.


Modbus Communication protocol for Arduino as Slave I have an Arduino Uno board, with these components:

rs-485 Modbus module shield
Multiprotocol radio shield board for Arduino

In addition I have a level sensor which reads either 1 when it is above water, and 0 when it is below.

I need to be able to give the value of this sensor to a modbus master over rs485.

Cooking Hacks Tutorial

This page has a description of how to use the ModbusMaster485 library, but I can not find any information about the slave library.

I can not find any documentation for this library, and would really appreciate any pointers.

It's not very well documented for the slave but maybe that is because it only has two methods...

It looks like the slave library is contained in the same library as the master but with name ModbusSlave485.h

You can see in the .h it only has two public methods. One is connfigure() and the other is update(). see below an extract from the .h which explains what each method does.

#include "ModbusSlave485.h"

mySlave = ModbusSlave485();

void setup()
{
  mySlave.configure(slave, baud, parity, txenpin);
}

void loop()
{
  //check for update from master
  mySlave.update(regs, regs_size)
}

extract from .h

/*
 * configure(slave, baud, parity, txenpin)
 *
 * sets the communication parameters for of the serial line.
 *
 * slave: identification number of the slave in the Modbus network (1 to 127)
 * baud: baudrate in bps (typical values 9600, 19200... 115200)
 * parity: a single character sets the parity mode (character frame format):
 *         'n' no parity (8N1); 'e' even parity (8E1), 'o' for odd parity (8O1).
 * txenpin: arduino pin number that controls transmision/reception
 *        of an external half-duplex device (e.g. a RS485 interface chip).
 *        0 or 1 disables this function (for a two-device network)
 *        >2 for point-to-multipoint topology (e.g. several arduinos)
 */
  void configure(unsigned char slave, long baud);

/*
 * update(regs, regs_size)
 *
 * checks if there is any valid request from the modbus master. If there is,
 * performs the requested action
 *
 * regs: an array with the holding registers. They start at address 1 (master point of view)
 * regs_size: total number of holding registers, i.e. the size of the array regs.
 * returns: 0 if no request from master,
 *  NO_REPLY (-1) if no reply is sent to the master
 *  an exception code (1 to 4) in case of a modbus exceptions
 *  the number of bytes sent as reply ( > 4) if OK.
 */
  int update(int *regs, unsigned int regs_size);

  // constructor
  ModbusSlave485()
  {
    myDevice = RS485();
  }


H-bridge with 2N2222 transistors - input voltage is chopped The H-bridge I put together works but not as expected unfortunately because the output voltage is limited to about 2.6V, regardless of the input voltage or resistors values.

I've already tried with 5V and 7.5V power supplies and nothing changed.

According to 2N2222's datasheet, Base-emitter Saturation Voltage (Vbe) is 2.6V and i have no idea if this is the problem or something with my setup.

Here's the 2N2222 datasheet: http://pdf.datasheetcatalog.com/datasheets/90/490358_DS.pdf

You have discovered the standard problem when building an H-bridge. If
you want to drive it with a voltage lower than its output voltage, then
you cannot directly control the high-side transistors.

There are several solutions to this problem. The simplest and most
reliable is to buy an already built H-bridge. If you really want to
build it yourself, then you will need extra transistors to drive the
high side.

Below is an example using only NPNs. It's a half-bridge which behaves
like an inverter. You would use two of those to build a full bridge.

simulate this circuit – Schematic created using CircuitLab

Here, the leftmost transistor is used to drive the high-side one.
I didn't label the resistors, as their values will depend on how much
current you want.

This is not the only possible schematic, and probably not the best.
There are many other options, including NPN/PNP combinations,
Darlingtons and MOSFETs.


Void value not ignored Why does this throw the error: "void value not ignored as it ought to be

returning = printTemperature(returnLine);"

void printTemperature(DeviceAddress deviceAddress)
{
  float tempC = sensors.getTempC(deviceAddress);
  if (tempC == -127.00) {
    Serial.print("Error getting temperature");
     return 0;
  } else {
    return tempC;
  }
}

void loop(){

   delay(2000);
   feeding = printTemperature(feedLine);
   returning = printTemperature(returnLine);
    mySql;
    feeding = 0;
    returning = 0;
}

Both 'feeding' and 'returning' are declared as a float too.

printTemperature() is declared void (i.e., nothing returned) but it contains a return statement, and you've attempted to assign the (void) value. You probably meant to declare the function as 'float'.


How to add additional millisecond delay to microsecond delay generator I am trying to make a delay generator. I already found an excellent example in Generating a short pulse after a delay that works in the range from ~5-32767 microseconds (it is limited by a 16 bit microsecond counter divided by 2).

How would I go about extending that range into the millisecond range (say up to 1s or so)? Since this example is interrupt-based, adding delay() statements do not really seem to work.

I have also tried changing the timer prescaler, but then the jitter is also scaled up in an unacceptable way.

This is the code I have now. Send commands via the arduino serial console, D500 for 500µs delay, L100 for a 100µs long pulse. Letters M and N change the prescaler.

uint16_t pulse_delay = 10; //half-microseconds
uint16_t pulse_length = 10;
String inputString = "";         // a string to hold incoming data
boolean stringComplete = false;  // whether the string is complete
long read_value = 0;
long ms_delay = 0;

void printvals() {
  Serial.print(F("Delay: "));
  Serial.print(pulse_delay / 2);
  Serial.println(F(" µs"));
  Serial.print(F("Length: "));
  Serial.print(pulse_length / 2);
  Serial.println(F(" µs"));
}
long getcommandvalue(String inputstring) {
  inputString.remove(0,1);
  return inputString.toInt();
}
void setup(){
  pinMode(8, INPUT);
  pinMode(9, OUTPUT);
  TCCR1A = 0;
  TCCR1B = _BV(ICNC1)  //input capture noise cancel
      | _BV(ICES1) //positive edge
      | _BV(CS11); // /8 prescaler
  TIMSK1 = _BV(ICIE1); //enable input capture interrupt
  Serial.begin(9600);
  inputString.reserve(200);
  Serial.println(F("RDY"));
  printvals();
}
void loop(){
  if (stringComplete) {
      switch(inputString.charAt(0)) {
        case 10: //\n (Newline; Line Feed)
          // previous line ending was CRLF, so now LF was carried to the next string
          break;
        case 63: //?
          //print current vales
          printvals();
          break;
        case 68: //D (Delay)
          read_value = getcommandvalue(inputString);
          if (read_value >= 1) {
            pulse_delay = 2 * read_value;
            printvals();
          }
          break;
        case 76: //L (Length)
          read_value = getcommandvalue(inputString);
          if (read_value >= 1) {
            pulse_length = 2 * read_value;
            printvals();
          }
          break;
        case 77: //M (additional prescaling)
          TCCR1B = _BV(ICNC1)  //input capture noise cancel
            | _BV(ICES1) //positive edge
            | _BV(CS10) // 64 prescaler
            | _BV(CS11); // /8 prescaler
          break;
        case 78: //N (8x prescaling)
          TCCR1B = _BV(ICNC1)  //input capture noise cancel
            | _BV(ICES1) //positive edge
              | _BV(CS11); // /8 prescaler
          break;
        case 79: //O
          ms_delay = getcommandvalue(inputString);
          // I don't know where to execute this ms_delay
          break;
      }
      inputString = "";
      stringComplete = false;
  }
}

void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    // add it to the inputString:Z
    inputString += inChar;
    // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
    if ((inChar == '\n') or (inChar == '\r')) {
      stringComplete = true;
    }
  }
}

ISR(TIMER1_CAPT_vect){
  TCCR1A = _BV(COM1A0) | _BV(COM1A1); //set OC1A on match
  TIFR1 = _BV(OCF1A);  // clear interrutp flag
  TIMSK1 |= _BV(OCIE1A); //enable match interrupt
  OCR1A = pulse_delay; //pulse begin time

  TCNT1 = TCNT1 - ICR1; //TCNT1 now contains time since input pulse, even if
                        //the interrupt isn't run immediately
}
ISR(TIMER1_COMPA_vect){
  TIMSK1 &=~ _BV(OCIE1A); //disable match interrupt
  TCCR1A = _BV(COM1A1); //clear OC1A on match
  OCR1A = pulse_delay + pulse_length;
}

You could count timer compare matches.  The following illustrates the principle, maybe not accurate as written but I am sure the counter loop will be precise enough for your needs, considering you want to use an Arduino.  Depending on the time resolution you want, you may be able to run other code while the software counter is active.

The following can count to several seconds, depending on values of OCR1A and counter_target.

unsigned int state, pulse_delay;
byte counter[3]={0,0,0}; // 24 bit counter, you can make it longer in principle

byte counter_target[3]={0,0,0}; // defines length of delay you want

void setup(){
state=0;
TCCR1A=0;
TCCR1B=0;
}

void loop(){
switch (state){
case 0: // idle state machine // you other code here
counter_target[0]=0; // For example
counter_target[1]=0;
counter_target[2]=1; // corresponds to (1+65536)*pulse_delay/clock_scaler
// when you are ready to start counting
state=1;
break;

case 1: // setup timer
counter[0]=0; // Zero the 24-bit counter
counter[1]=0;
counter[2]=0;
OCR1A = pulse_delay; // number of pulses to count = 1+OCR1A
OCR1B = OCR1A+1;
ICR1  = OCR1A+1;    // Just to make sure these don't cause compare match
TIFR1 |= (_BV(ICF1) | _BV(OCF1A) | _BV(OCF1B)); // Clear match flags
state=2;
TCCR1A = B00000011; // Fast PWM mode 15 on UNO, OCR1A=TOP
TCCR1B = B00011001; // Clock prescaler 1
break;

case 2: // Counting up
loop_until_bit_is_set(TIFR1,OCF1A);
TIFR1 |= (_BV(ICF1) | _BV(OCF1A) | _BV(OCF1B)); // Clear match flags
counter[0]+=1; // Increment counter by 1
if(counter[0]==0x00){counter[1]+=1;
if(counter[1]==0x00){counter[2]+=1;}} // etc

if(counter[0]==counter_target[0] && counter[1]==counter_target[1] && counter[2]==counter_target[2]){state=0;}  // Check if we have reached the target delay
break;

}
}


can i use bluetooth from a speaker as a bluetooth module? i have a Bluetooth speakers that i don't want,and i was wondering if i can use its Bluetooth as a Bluetooth module to use it with Arduino.
if so how what pins should i use. here is a pin diagram for the module.

Bluetooth actually uses many different protocols to support many different Bluetooth applications.  For 2 channel good fidelity music with high latency and a very low bandwidth return only suitable for short infrequent commands like PAUSE and PLAY, most use A2DP or Advanced Audio Distribution Profile.
As most Arduino platforms use very low powered processors, good fidelity sound manipulation is not possible or is very difficult.  This only leaves the very low bandwidth return channel only suitable for short infrequent commands.  If you can imagine a use case for this channel it may be possible to use a low powered Arduino to send these PAUSE, PLAY, STOP type commands.
That said, you may want to buy a new well supported (in the Arduino community) Bluetooth module which uses the HID (Human Interface Device) protocol so you can build a keyboard for example or which uses the SPP (Serial Port Profile) protocol so you can build something that sends arbitrary data.
Added later...
I see in the diagram that there may be an "microphone in pin".  If true this hints that the module also supports the Bluetooth HFP (Hands Free Profile) protocol.  This is a lower fidelity 2 directional low latency audio channel with a very low bandwidth return only suitable for short infrequent commands like ANSWER and HANGUP.  Instead of music this is used to make phone calls.  This might be of more interest to Arduino project builders as this might be made into an intercom.


Is there a relationship between RSSI and Power? If so, how are they connected and does it have a formula to extract one from the other? I have searched on Google but to no avail. Perhaps you guys can help.

-Aj

Is there a relationship between RSSI and Power?

Yes

  If so, how are they connected and does it have a formula to extract one from the other?

RSSI is in relation to the square-root of the power. See below references for the actual formula.

Holiday extra: RSSI for an RF433 module can be estimated by the time from end of transmission and noise. This is the time for the AGC circuit to increase gain from the received signal to the noise level. Please see Cosa RF433 library for an example.

References:

https://en.wikipedia.org/wiki/Received_signal_strength_indication
https://en.wikipedia.org/wiki/Signal_strength_in_telecommunications


Burning a Uno bootloader into a Nano I bought some cheap Arduino Nanos from ebay, but the watchdog does not work in them.

So I removed their old bootloader and burnt a new Nano bootloader from the Arduino IDE. Same problem, the watchdog didn't work.

Then, I burned a Uno bootloader to the Arduino Nano and now the watchdog works properly. The only issue here is that in Arduino IDE I now have to tell it that I am programming an Arduino Uno instead of a Nano. So far everything seems to work just fine.

Are there other problems that may arise from using a Uno bootloader in a Nano? I notice that there are some extra analog pins in Arduino Nano, but I will still be able to use them with the Arduino Uno bootloader right?

Assuming they're based on the more recent Arduino Nano 3.x series or later, the microcontroller in your Nanos is probably an ATmega328 running at 16 MHz. That's the same as the Uno, so there should be no major problems hopefully.

It might be worth checking that you've got the latest version of the Arduino IDE though. I seem to remember there was a problem in some older bootloaders which prevented the watchdog from working properly.


I2C TinyWireS SEND: How to convert unsigned long to uint8_t array? How do you convert an unsigned long to a uint8_t array? I am interested in sending an unsigned long integer from an ATTiny85 to an Arduino Uno via I2C. The issue is with TinyWireS.Send() which can only send a var of type uint8_t. I believe the solution would be to use TinyWireS.Send() in an array?

This might not be politically correct code, but it is pretty simple to just cast a pointer to uint8_t like this:

long data = 5;
uint8_t *rx = (uint8_t*) &data;

You can still use array subscripts even though its a pointer, and you can pass it to a function like an array. Just don't go past rx[3].

Alternately, you could also make a union like this:

union{ long data; uint8_t bytes[4]; } convert;
convert.data = 5;

And then use convert.bytes as your array to send.


Arduino Hello World in Serial monitor Hi we were asked to program something which when i enter something in the serial monitor it prints Hello world but the catch is it only prints hello world under the conditions that your input in the serial monitor is a 3 bit input and after that i need to have a code which then stops it from printing over and over again.
my only problem is that i don't really know how to count the number of bits of an input and also to stop it from printing continuously.

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

}

void loop() {
  String readSerial;
    String input;
    while(Serial.available() > 0){// put your main code here, to run repeatedly:
    delay(2);
  input.concat(String((char)Serial.read()));
  return input;
  }
  Serial.println("HELLO WORLD");
}

Judging from the comments, you lag some basic knowledge. To really learn, what you are supposed to learn in this assignment, you should review your learning material or C/C++ and Arduino Tutorials on the web. Here I will only give you some hints with reasoning, that may help you in solving the assignments task. (Unfortunately it is not really clear, what exactly the task is here)

The Serial interface of the Arduino (an UART interface) sends the data in bytes, one at a time and one after another (hence the name serial). 1 byte is a series of 8 bits, each of them with a value of 1 or 0. Together the 8 bits form a value, that can also be expressed as a decimal value from 0 to 255. For example 01001011 is the binary equivalent of the decimal number 75. (For further explanations google the binary number system) The byte data can also be expressed as characters, as they are defined in the ASCII standard. Every binary value refers to a specific character. This is what happens in the serial monitor of the Arduino IDE. (For more explanations google ASCII)
Since the data is send serially, there may appear some delays in the transmission, which are unnoticeable by humans, but the Arduino is fast enough, so that the Serial.available() command may return 0, because at that moment a little delay in the transmission occurred. Hence it is important to catch the whole message, before trying to work with it. You can do this by either counting bytes (waiting until at least 3 bytes are available in the buffer) or by marking the end of the message with a special character (for example the newline character '\n'). There are a lot of tutorials on the web how to do both. You can start with Majenko's blog.
You can get the number of bytes, that were received, with the return value of Serial.available(). It will return 3, when there are 3 ready to be read bytes in the buffer.
If you define a variable inside the void loop(), it will be thrown away when the function ends and redefined, when the function starts again (In the Arduino world the void loop() function is called again and again forever). You will loose all content, that was written to this variable. If you want to persist data over the executions of the void loop() function, you can define the variable outside of any function at the top of your program. This variable is then global and will be defined only once at the start of the program and hold for the whole lifetime of the program.
As wrote in the comment you should not return a value from a void function, since void mostly means, that there is no return value. And returning from the void loop() function will only restart this function (since we are in the Arduino world).
You can ditch the delay(2). There is no need for it. And if it only works with the delay, then something else is not correct and you are just working with the symptoms instead with the real issue.

Also you should not try to build everything on your own and reinvent the wheel. Instead try to look at the examples, that come with the Arduino IDE. For example the SerialEvent example, which shows how to receive a serial message (which is ended by a newline character '\n'). Also have a look at the other related examples. If you understand, how they work, you will be able to do the assignment without any problem.


Calling I2C functions inside an ISR I have an Adafruit 2.8" cap touch display, which has an interrupt pin (IRQ). I tried to use this with my Arduino Nano, but encountered a problem:

When trying to get the touched point from the display during a display triggered interrupt, it would not work because the touch screen is connected via I2C and according to this post, it is not possible to call I2C functions inside an ISR on an Arduino. Therefore the IRQ pin does not make much sense to me, as I would have to poll if the screen is touched inside the main loop.

My question now is: is this a problem specific for the AtMega 328p? I am thinking about getting an ESP32 based board. Would it be possible to get the I2C data inside an ISR on this chip? Or is it just not possible at all?

Here is an analogy for you to help you understand why using the IRQ is a good idea.

Imagine you are at a conference. There's hundreds of you in the audience, and you are in a question and answer session with the person on the stage. Maybe their presentation has just come to the end and they're fielding questions from the audience.

Lots of people have questions, and any member of the audience can raise their hand at any time to ask a question.

Now there's three ways of the presenter handling it.

The first way is your way of using an interrupt and responding to the interrupt within the interrupt handler itself.  This is like the presenter stopping what he is saying mid sentence to answer the new question. That's just nasty, and both confusing for the presenter and the audience.

The second way is for the presenter to continue until the current question has finished being answered, then pick someone at random from the sea of hands. While the question is being answered people are getting antsy waving their hands around to get noticed, and there's no guarantee that it will be first come first served. People may then not be paying attention to what is a good answer to an important question because they are fixated on theirs.  That's just the same as you polling the interrupt line, or polling the screen directly. If the interrupt line isn't active at the time you poll it you'll miss it.

The third, and best way, is if the presenter sees a hand go up while he's answering a question, and acknowledges that person with an "Ok, I'll come to you next.". Everyone else knows that waving their hand around is pointless, so don't bother - and the next question can be asked immediately after the current question has been answered. Everyone is happy.  That's the proper way of handling a system like this - when the interrupt triggers you remember "Ok, I'll come to that interrupt signal in a moment when I'm ready". Then in your loop, when you have the time, you act on the interrupt that you remembered earlier. You get to respond at your speed to a signal that you may otherwise have missed.

So to sum up: using an interrupt to remember that something is pending and then act on that remembered state is how you should use interrupts to manage communication.


Deep Sleep Reset with Shock Sensor I am trying to design a circuit that wakes my ESP8266 (Wemos D1 Mini) from deep sleep using a shock sensor. I can achieve this using the reset pin but I need
it to ignore further requests to reset to give it time to run the code in my sketch. Provided there is still motion it will just continue to reset meaning the code only gets run after the 'shock' stops. I have tried all kinds of things with capacitors and transistors to delay subsequent resets but with very limited success. Can someone please point me in the right direction or suggest an easier way to do this? Many thanks in advance.

This is actually somewhat more tricky than you would at first thing.

First off, the "shock sensor" is merely a spring inside a tube.  This will create lots of triggers while it's being "shocked", which really is messy.

Secondly, you only want those shocks to make it through to the ESP when you are in deep sleep.

Thirdly, you don't want whatever you connect to adversely affect, or be affected by, other circuitry that is connected to the reset pin.

So you first really need to "condition" the output of your sensor so that it gives a clean pulse that can reset the ESP8266. Then you need to "gate" that signal so it can only get through while the board is asleep.

For conditioning the shock sensor signal I would be inclined to use a 55 timer in monostable mode.  You can find a good circuit and description here which looks like this:

Now to gate that signal (which is active high) you need a signal to gate it with.  Since all the GPIOs of the ESP8266 are "dead" while it's asleep you need it to be in a "default on" state and have the ESP8266 drive an "I am awake" signal to disable the output.  So you'd have a pullup resistor on a GPIO to make it default HIGH (to match the trigger pulse for simplicity) and then use pinMode() and digitalWrite() as the first things after waking up (and at the start of setup()) to indicate it's awake by driving it LOW.  Then you combine those two signals:

If the trigger is HIGH and
If the gate signal is HIGH
Then pull reset LOW
Otherwise don't affect reset

So you make a truth table:

Trig | Gate | Res
-----------------
  L  |  L   |  HiZ
  L  |  H   |  HiZ
  H  |  L   |  HiZ
  H  |  H   |  L

The tricky one here is the "HiZ" - This means "High Impedance" - or in effect "Don't affect the reset pin at all".

Apart from that the truth table is that for a NAND gate - if both inputs are HIGH then the output is LOW - otherwise the output is HIGH.  Except we want HiZ not HIGH.

To make that HiZ there's two things you can do:

Use a NAND gate that has an "Open Collector" (or "Open Drain") output, or
Use an AND gate and create your own "Open Collector" that inverts the output by adding a transistor.

For option 1 you can use the 74AC01 which is a "Quad 2 input NAND gate Open Collector".  For option 2 you can use the 74AC08 and any NPN transistor (or N-channel MOSFET with a suitable threshold).

simulate this circuit – Schematic created using CircuitLab


Arduino - Print file name I need my sketch to print the name of the original INO file at the beginning of execution (during setup).

Is it possible?  If so, what is the resource which should be used?

You can use the macro __FILE__ to get the filename that is being compiled.  That may not be your INO file, but may be some derivative of it.

Serial.println(__FILE__);

You also get some other handy macros:

__DATE__
The date the sketch was compiled

__TIME__
The time the sketch was compiled

__LINE__
The line number where __LINE__ is being used

The combination of __FILE__ and __LINE__ is commonly used for debugging:

Serial.prinln("Error 23 at line " __LINE__ " of " __FILE__);


ATmega328p - ISC00 with INT1? I was reading about external interrupts using the ATmega328p, and I saw in the chip datasheet under the paragraph "Bits 3:2 – ISC1n: Interrupt Sense Control 1 [n = 1:0]" the following table:

Value | Description
------+------------------------------------------------------------
00    | The low level of INT1 generates an interrupt request.
01    | Any logical change on INT1 generates an interrupt request.
10    | The falling edge of INT1 generates an interrupt request.
11    | The rising edge of INT1 generates an interrupt request.

From what I understand from the table title and the definition in the datasheet that ISC1n where n=1|0, is dedicated for INT1. And that ISC0n where n=1|0, is dedicated for INT0. However, in the table above, the value 00 is described as "The low level of INT1 generates an interrupt request.".

What I don't understand is how can ISC0n where n=1|0 be dedicated for INT0 but in the table above the value 00 (or ISC00) is used for INT1 ? I could totally be missing something but I would appreciate any guide.

It's a typo. My revision of the datasheet (revision G) properly says "INT0".


PubSubClient - MQTT_MAX_PACKET_SIZE How is it calculated I'm using an ESP32, and I want to rule out a probable MQTT error. In PubSubClient , MQTT_MAX_PACKET_SIZE is set to 256. Is 256 the size for message only ? if not, what is left for message only ?

It is the maximum size of an entire packet.  In publish() this check is done:
if (MQTT_MAX_PACKET_SIZE < MQTT_MAX_HEADER_SIZE + 2+strlen(topic) + plength) {

So the maximum length of a message payload will be
MQTT_MAX_PACKET_SIZE - MQTT_MAX_HEADER_SIZE - 2 - strlen(topic)

MQTT_MAX_HEADER_SIZE is defined as 5, so if you have, for example, a 20 character topic you would have 256 - 5 - 2 - 20 = 229 bytes left for your payload.


Will enabling parity bit actually decrease corruption? I have an Arduino Mega communicating with a Bluetooth adapter through one of the auxiliary hardware serial ports. It works, but there appears to be a corruption rate of approximately 1 in 200 small packets. In other words, about 0.5% of the packets are being corrupted, it seems. I have the option of configuring the serial mode on both ends. While I cannot decrease the baud rate for bandwidth reasons, I do have enough room to enable parity or a larger stop bit if that would help.

Granted the corruption is on the serial line and not on the Bluetooth, if I enable parity, will this actually decrease the corruption rate? Or will the corrupt bytes simply be dropped without being re-sent? In other words, what happens when the hardware detects a bad byte?

Parity doesn't, and was never intended to, decrease corruption.

All parity does is allow you to DETECT errors. If you detect errors, you still have to handle them.

Parity in memory is usually fatal - your code or data is corrupt, the solution is to halt the box, to stop this corruption (in memory) getting on to disk.

When used in communication (as it is here), parity errors usually mean you have to request a re-transmit (or, if acknowledgements are sent back, fail to send an acknowledgement and wait for an automatic re-transmit).

Also, be aware that the relevant error rate is per bit, not per packet. If a small packet (very small!) is 20 bytes, and there is corruption 0.5% of those packets, this indicates a 0.5% / 20 bytes per packet / 8 bits per byte (assuming 7 data bits, 1 parity bit, for example). This comes out to 0.003% errors.

Note that parity checks only work for 1-bit errors - in fact, a 2-bit error (in the same byte), the parity change will cancel out, and it will look ok.

An alternative to requesting re-transmits, is to use forward error correction - send redundant data (reducing your bandwidth). A very easy scheme is to send each packet twice (halving your bandwidth). You still need error checking (or some checksum) - if two packets are different, you still need to know which one was right. Checksums, on a more complex device, could let you try each combination, but for an Arduino, this would probably be too expensive (the code would take up sizable space, which an Arduino may, or may not, have spare).

All of this is usually written into higher level protocols (TCP, used for most internet file transmission, ZModem file transfer used for modems prior to the Internet). Other protocols, such as internet radio, will use either forward error correction, or will accept the occasional glitch.


How to use while loop in arduino for infinte loop I am doing code of esp while switching hotspot for connecting esp i am getting some problem .
I am using this line of code:

while ((!esp.find("WIFI ")) || (!esp.find("+CWJAP:3")));

but it is not working. Anybody please give me alternate how to use this type of looping.

The find method reads the characters until the searched string is found or a timeout interval is passed.

In your case if the connection is not successful, the first find will not find "WIFI" and will read all the input including the "+CWJAP:3", then on timeout it returns false. The second find will wait until timeout and then return false.


What current is safe for Wemos d1? I've got 12V / 400mA power supply for my Wemos D1 R1, and I'm using VIN output(I need 12V for led strip). I need to change this power supply because of color, and I can't find similiar with the same parameters. The question is - Is power supply with 12V / 1A - 2A safe to use?

With very few exceptions, electronic devices only draw as much current as they need, limited by their resistance.

The current rating on a power supply is the MAX current it can provide before the voltage drops. Having a higher current power supply may waste energy, but won't hurt anything.

According to Ohms law, V = IR

Where V = Voltage
I = current, in amps
R = resistance, in ohms

(voltage = current times resistance.)

Or, solving for current:

I = V/R

current = voltage divided by resistance.

So if you have a 12 volt power supply, and a 100 ohm resistor, you'll get 12/100, or 0.12 amps, flowing through the resistor.


How to produce rolling count per minute? I have a counter attached to ISR:
void ISR_impulse() {
  CNT++;
}

and I want to calculate rolling count per minute with arbitrary update rate.
However I can only get it to update every minute:
void loop() {
  if (t - t0 > 60000) {
    CPM = CNT - CNT0;
    t0 = t;
    CNT0 = CNT;
  }

  t = millis();
  delay(100);
}

I'd appreciated if anyone can help me to create a rolling count with a window of 1 minutes that works with arbitrary update rate like 1 second ?
Thanks in advance !

If you want to update every second a one minute running average, you
have no choice but store in memory the counts you got the previous
60 seconds. You store them in a ring buffer, so that every new
reading replaces the oldest one. Then, every second:

you add to the CPM count the number of counts you got this second
you subtract the number of counts you got on the second that just got
out of the sliding window.

I would implement that logic this way:
const uint32_t ONE_SECOND = 1000;

uint16_t counts_per_minute;
uint16_t previous_counts[60];
size_t counts_pos;

void loop() {
    static uint32_t previous_second;
    if (millis() - previous_second >= ONE_SECOND) {
        previous_second += ONE_SECOND;
        noInterrupts();
        uint16_t CNT_copy = CNT;
        interrupts();
        static uint16_t CNT_previous;
        uint16_t second_count = CNT_copy - CNT_previous;
        CNT_previous = CNT_copy;
        counts_per_minute += second_count - previous_counts[counts_pos];
        previous_counts[counts_pos] = second_count;
        if (++counts_pos >= 60) counts_pos = 0;
    }
}

Note that:

The timing variable is updated with previous_second += ONE_SECOND
rather than previous_second = now in order to avoid the accumulation
of small timing errors.
The counter that is updated in the ISR has to be read only once,
with interrupts disabled. Otherwise the interrupt may change it while
you are in the middle of reading it.


How do I accelerate a stepper motor? I have a 24BYJ48 stepper motor, and my main problem is that I cannot make it rotate quickly. I've understood that in order to achieve a high speed I must start at a low speed and carefully accelerate the motor to higher speeds.

I'm not quite sure how this acceleration ought to be done, though. My idea is to execute the control sequences with an initially long delay, and then decrease the delay between each time I change the sequence for the motor wires.

Below is the code I have written. When I run it, the motor accelerates for a little while, but then all of a sudden it just stops and makes a high pitched noise.

The basic technique is as you have tried to program. The time between stepper pulses if shortened to cause acceleration and lengthened to slow down. A real solution typically uses an "S" curve type acceleration profile that starts out with a slow ramp up to the acceleration rate and then as it nears the target rotational speed it slows the acceleration rate back down.

In your case you may be getting to the point where you have increased the acceleration rate too much and the motor cannot respond to it.


Arduino port not showing serial USB Mac OS El Capitan I don't see serial USB as an option under ports when my Arduino is connected to my Mac. I have used this Arduino on the same computer before without any issues on Yosemite OS. However, I was trying to run a servo motor and I don't think I was getting enough power so I decided to use an external power supply. 12V 500mA DC and connected it while still keeping the USB connection. Since I already had the servo program loaded, the motor did work. Then I tried uploading the program again, that's when I realized that there was no serial connection. I am not sure if the problem is because of the power supply that I connected.

I tried the following approaches without success:

Upgraded the OS to El Capitan (which might have been a bad decision in hindsight).
Tried connecting the Arduino to another Mac with new Arduino IDE download, same issue.
Tried downloading the FTDI drivers as suggested by other folks.

I searched for a few hours for a solution online, but nothing so far has helped. Please provide suggestions.

Change USB ports
Check your Tx and Rx pins aren't connected to ANYTHING.
Reboot your Mac.
If you're really desperate, change OS.


Parallel shift registers I'm having trouble with using parallel shift registers, I've studied example codes and I've come up with this function to set the pins to on or off. The problem is the first time the function runs all the output pins are set to HIGH regardless of the values in the array.

    void updateRegister(int ClockPin,int DataPin,int LatchPin){
      int pinState;//Holds the state of the data pin
      pinMode(ClockPin, OUTPUT);//Sets the pinmode of the pins
      pinMode(DataPin, OUTPUT);//Sets the pinmode of the pins
      pinMode(LatchPin, OUTPUT);
      digitalWrite(LatchPin, 0);//Turns latch off to prevent bleedover while shifting

      digitalWrite(DataPin, 0);//clear everything
      digitalWrite(ClockPin, 0);//clear everything

      for (int i=1; i<=16; i++){//Repeats 16 times with i increment from 1 to 16
          if (Qout[i]){pinState= 1;}//Checks the array for the value and if it is true sets the pinstate to 1, HIGH
          else{pinState= 1;}//If it equals false set it to 0, LOW

          digitalWrite(DataPin, pinState);//Sets the data pin depening on the pinstate
          digitalWrite(ClockPin, 1);
          digitalWrite(DataPin, 0);
          digitalWrite(ClockPin, 0);
        }
      digitalWrite(LatchPin, 1);//Turns latch pin back on
    }

I'm storing the boolean values of the each pin in an array called Qout which is defined and all set to false like this

    boolean Qout [17];//Holds the state for each pin
    for (int i = 1; i < 17; i++ ) {Qout[i]=false;}//Sets all output to off

I know I should start at Qout[0] but it just makes it way more confusing.

Can someone help me fix my function so that it actually works.

This is what I based it on ShftOut23

First of all, fix the following part of your code:

if (Qout[i]){pinState= 1;}//Checks the array for the value and if it is true sets the pinstate to 1, HIGH
else{pinState= 1;}//If it equals false set it to 0, LOW

into:

if (Qout[i])
{
    //Checks the array for the value and if it is true sets the pinstate to 1, HIGH
    pinState = 1;
}
else
{
    //If it equals false set it to 0, LOW
    pinState = 0;
}

Of course, if you always set pinState to 0, it won't work as you expect :-)

Note that you should rather use HIGH and LOW constants (more readable) instead of 1 and 0.

Finally, you could make the code much simpler this way:

pinState = (Qout[i] ? HIGH : LOW);


Include Adafruit_RGB LCD Shield library in class I'm trying to make a class to expand on the functionality of the Adafruit-RGB-LCD-Shield-Library I'm creating this based on what I see from this post.
class LcdMenu
{
 #include <Adafruit_MCP23017.h>
 #include <Adafruit_RGBLCDShield.h>
 public:
 Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();
     void Setup()
     {
      lcd.begin(16, 2);
     }
     void Write(int line, char text[17])
     {
      lcd.clear();
     }
};

LcdMenu *LcdM;
#define VIOLET 0x5

void setup()
{
  LcdM->Setup();
  LcdM->lcd.setBacklight(VIOLET);
}

However, I'm getting the following error:

C:\Users\jschere2\AppData\Local\Temp\ccUzvCmX.ltrans0.ltrans.o: In function `main':
ccUzvCmX.ltrans0.o:(.text.startup+0xf0): undefined reference to `LcdMenu::Adafruit_RGBLCDShield::begin(unsigned char, unsigned char, unsigned char)'
ccUzvCmX.ltrans0.o:(.text.startup+0xf8): undefined reference to `LcdMenu::Adafruit_RGBLCDShield::setBacklight(unsigned char)'
collect2.exe: error: ld returned 1 exit status
exit status 1
Error compiling for board Arduino/Genuino Mega or Mega 2560.

Move your #include statements outside the class definition.

You declare a pointer, but never allocate space for it with new. I see no need for a pointer.

#include <Adafruit_MCP23017.h>
#include <Adafruit_RGBLCDShield.h>

class LcdMenu
{
 public:
     // default ctor will be called here.
     Adafruit_RGBLCDShield lcd;

     void Setup()
     {
      lcd.begin(16, 2);
     }
     void Write(int line, char text[17])
     {
      lcd.clear();
     }
};

LcdMenu LcdM;
#define VIOLET 0x5

void setup()
{
  LcdM.Setup();
  LcdM.lcd.setBacklight(VIOLET);
}

Also note: you are not extending the Adafruit_RGBLCDShield class as in the example you linked. To do that:

#include <Adafruit_MCP23017.h>
#include <Adafruit_RGBLCDShield.h>

class LcdMenu : public Adafruit_RGBLCDShield
{
 public:
     void Setup()
     {
      begin(16, 2);
     }
     void Write(int line, char text[17])
     {
      clear();
     }
};

LcdMenu LcdM;
#define VIOLET 0x5

void setup()
{
  LcdM.Setup();
  LcdM.setBacklight(VIOLET);
}


How to use code for OV7670 on Arduino Uno I want to interface my OV7670 camera (without FIFO) to my Arduino Uno. I have browsed internet quite a lot about it and found people either saying it's not possible or they just give me the link to this github repository (As this guy has done exactly what I want). As the author of this repository is a man of few words, he did not help me very much. I just want to know how to use this to get image sent to my PC serially. I only know how to use Arduino IDE in windows platform and no other platform.

I am ComputerNerd. I read this post and realized the real problem and why I am having difficulty helping you. You are asking the wrong question. What you should be asking is "how do I compile it using GNU Make and Avr-Gcc on Windows?". Instead you are asking "how can I use this code in the Arduino IDE?".

The answer to what you should be asking is simple. Use what you already have. The Arduino IDE ships with Avr-gcc and (maybe) GNU Make. Just run the programs directly. Better yet download MinGW and compile GCC to target the AVR yourself.


Custom Arduino board beeps and process freezes while I'm uploading a sketch to it. Why? The strangest thing is happening to a standalone Arduino board that I designed and built. The board (whose schematics are below) has the following features:

It has a ATmega328P with a 5V voltage regulator and usual circuitry when set up as a standalone controller.
It controls a scoreboard with several 7-display digits linked through the connectors on the right (JP1 through JP12).
It has cursor buttons decoded using a voltage ladder through ANALOG_0 (A0).
It has a Real Time Clock to keep time when it's turned off.
It has an RF receiver module.
It has a UART header (JP17) so I can program the board using a serial port.
It has a speaker attached to digital pin 3 (D3).

I upload sketches to it using a RS232-to-TTL adapter that I've also built (schematics also below) and a Serial-to-USB cable. When programming it, the board behaves much like a Severino board.

What's strange is that, when I upload a sketch, the process is paused in the middle and then the speaker starts to beep continually. It pauses with the following avrdude messages:

avrdude: Version 5.11, compiled on Sep  2 2011 at 19:38:36
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

     System wide configuration file is "C:\arduino-1.0.3\hardware/tools/avr/etc/avrdude.conf"

     Using Port                    : \\.\COM1
     Using Programmer              : arduino
     Overriding Baud Rate          : 115200

When I press reset on the board, avrdude continues outputting its messages (such as below), the beep stops, the upload continues and the sketch is uploaded successfully to the board.

avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
... messages and upload continue and completes successfully.

I don't have the rest of the messages handy here, but I hope you get the idea.

So, my questions are:

What is making the upload process pause?
Why is the buzzer beeping when the process pauses?

What is making the upload process pause?

Well, given all the comments made under your question, this is definitely a tricky one. You might want to try to add a decoupling capacitor as suggested by @jfpoilpret, though your schematics look alright to me… (maybe ask a review of it on EE SE).

I'd also advice you to copy the avrdude command from Arduino IDE output (you'll find it at the top), and run it in the command shell with lower bitrate:

avrdude -v -v -v -v -C "C:\arduino-1.0.3\hardware/tools/avr/etc/avrdude.conf" -P COM1 -patmega328 -U… -B3 -b115200

the higher the -B value is the lower your bitrate is. and -b to the correct baudrate for your bootloader (are you sure this is 115200? it's more common to see 57600).

Did you also set fuses correctly? You might as well want to check the values of the fuses to see if the clocks are correctly set up:

avrdude -U lfuse:r:-:i -U hfuse:r:-:i -U efuse:r:-:i

which will output the values of the fuses. Then to make the values readable, put the values at the bottom of the form on the fuse calculator site, after choosing the Atmega328P MCU from the dropdown list.

Double check that:

you have enough size for the bootloader (usually the more you give it the better it is) ;
you have correctly set up the cristals configuration for your design (which may not be compatible with default Uno settings as setup by the Arduino IDE), checking if you correctly set up the external crystal at 16MHz…

  Why is the buzzer beeping when the process pauses?

It's because when the processor does not have the output set up, the values within the registers are in an undefined and unpredictable state. Which means that usually it keeps the last value it had before a reset, or changed state because of some electrostatic weirdness, or is giving some weird PWM output because of the influence of a clock nearby.

So basically, there's something wrong happening when you're uploading your code and that wrong thing has an indirect effect on the audio. I wouldn't worry much about that stuff, but more about the cause of the pausing.

Sadly, I don't have a direct answer for you, but at best a few paths you should investigate more. HTH


I don't know why this type of come in my program expected initializer before 'if' #include <iostream>
#include <stdlib.h>

using namespace std;

void  menu(){
    cout<<"1 : First Grade"<<endl;
    cout<<"2 : Second Grade"<<endl;
    cout<<"3 : Third Grade"<<endl;
    cout<<"4 : Fourth Grade"<<endl;
    cout<<"5 : Fifth Grade"<<endl;
    cout<<endl;

}
int main

    if (k=1){
        mindigit=10;
        maxdigit=99;
    }
    else if(k=2){
        mindigit=100;
        maxdigit=999;
    }
    else if(k=3){
        mindigit=1000;
        maxdigit=9999;
    }
    else if(k=4){
        mindigit=10000;
        maxdigit=99999;
    }
    else if(k=5){
        mindigit=100000;
        maxdigit=999999;
    }
}
char randomOperator()
    return "+-"[rand() % 2];

int main(){

    menu();
int i,question,maxdigit,mindigit;
cout<<"Please select grade, user numbers 1 to 5:  ";
cin>>i;
    if (i=1){
        mindigit=10;
        maxdigit=99;
    }
    else if(i=2){
        mindigit=100;
        maxdigit=999;
    }
    else if(i=3){
        mindigit=1000;
        maxdigit=9999;
    }
    else if(i=4){
        mindigit=10000;
        maxdigit=99999;
    }
    else if(i=5){
        mindigit=100000;
        maxdigit=999999;
    }
        cout<<"Enter number of questions you want to generate:  ";
        cin>>question;
    cout<<endl;
    for (int j = 1 ; j <= i ; j++)
    {
        int firstNum  = rand() % (max - min + 1) + min;
        int secNum  = rand() % (max - min + 1) + min;
        char opr = randomOperator();

    }
        if(opr == '+'){
            cout<<"("<<firstNum<<opr<<secNum<<") = ________ \t";
            if(i= 5){
                cout<<"\t";
            }
        }else if(opr == '-'){
            if(firstNum > secNum){
                cout<<"("<<firstNum<<opr<<secNum<<") = ________ \t";
                if( i= 5){
                cout<<"\t";
            }
            }else{
                cout<<"("<<secNum<<opr<<firstNum<<") = ________ \t";
            if( i= 5){
                cout<<"\t";
            }
            }
        }

    }

Your if statements are also incorrect, in your code you're assigning values if(i=1){ rather than testing for them if(i==1){ see Arduino If reference


Reading from 2 serial ports I have 2 Arduino Nano, they are connected via ports 2 and A2

While I use only one port to receive, it works properly. But if I activate the second port, system crash (and even first port don't work properly)

Code of first Arduino:

#include <SoftwareSerial.h>
SoftwareSerial SerialPort2(2,A2);
SoftwareSerial SerialPort3(3,A3);

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

void loop() {
  delay(500);
  SerialPort2.listen();
  if(SerialPort2.available()){
    char value = SerialPort2.read();
    Serial.print(value);
    Serial.print(" First port\n");
  }
  // IF YOU REMOVE PART BELLOW, THE 'SerialPort2' WILL WORK PROPERLY
  SerialPort3.listen();
  if(SerialPort3.available()){
    char value = SerialPort3.read();
    Serial.print(value);
    Serial.print(" Second port\n");
  }
  // END OF THIS PART
}

Code of second Arduino:

#include <SoftwareSerial.h>
SoftwareSerial SerialPort2(2,A2);

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

void loop() {
  SerialPort2.write('a');
  delay(1000);
}

PS in real system I need to listen 6 ports

SoftwareSerial can only listen to one port at a time. You cannot listen to both, no way. To really listen to both, you need an Arduino with more hardware Serial ports, where most of the protocol is done in hardware, thus can receive without CPU intervention. The Arduino Mega has 4 hardware Serial ports.

Or you could impose a protocol on the Serial stream to make the listening Arduino the master. You would listen to the first serial interface, send a start byte over this interface, that tells the slave Arduino to start sending. It sends and the listening interface receives (The transmission has to be delimited by either a time limit, e.g. listen for a specific time, or by a stop byte). Then you listen to the next interface, send again the start byte and receive. And so on.

With such a protocol, you could even use a single serial interface. The protocol makes sure, that only one slave is transmitting at a time. Though you should add resistors to every slave to protect their TX pins.

  in real system I need to listen 6 ports

Serial (UART) is really not the best interface type for such topology. You should consider using interfaces like SPI. It doesn't need additional electronics and is better fit for multiple slaves.


Homebrew Arduino using ATMEGA328P, ISP or ICSP? I plan on creating a homebrew Arduino breakout board using the ATMEGA328P smd version. I'm geeting confused by the wealth of information out there as to whether I should be using ICSP or ISP to program it. It is a blank chip, aka no Arduino bootloader on it yet. I'd rather not have to buy a specialized programmer to burn the bootloader, I do have another Arduino I could use to burn the bootloader and upload sketches to it with.

So the question is; Do I use ISP or ICSP, or both?

ICSP is used for PICs, not AVRs. Use ISP, which can be performed either by an Arduino via ArduinoISP or by a dedicated programmer.


How can I deal with rapid fluctuation of Anemometer readings? In my little weather station I collect temperature, humidity, MQ-2 smoke sensor, and wind speed readings for display on a 20x4 LCD display, every 500 ms.
The Anemometer readings jump up and down by quite a bit.

Initialization of variables before Setup is like so:

// Wind Speed Anemometer
const int sensorPin = A3;
int sensorValue = 0;
float sensorVoltage = 0;
float windSpeed = 0;
float voltageConversionConstant = 0.004887586;  // (5/1024)
float voltageMin = .33;   // 0.4 in the documentation
float windSpeedMin = 0;
float voltageMax = 1.5;   // 2.0 in the documentation
float windSpeedMax = 32;

// 20 x 4  LCD Display
#include <LiquidCrystal_I2C.h>
// set the LCD address to 0x3F for a 20 chars 4 line display\/ Set the pins on the I2C chip used for LCD connections:
//                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
LiquidCrystal_I2C lcd(0x3f, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

Then in Setup I initialize the LCD and flash the backlight.

lcd.begin(20,4);
lcd.clear();
for(int i = 0; i< 3; i++) {
  lcd.backlight();
  delay(250);
  lcd.noBacklight();
  delay(250);
  }
lcd.backlight(); // finish with backlight on

In Loop, I paint the initial screen then take readings and display them

void loop() {
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Weather");

  ...etc... to display time and show temp and humidity

  // Wind Speed
  sensorValue = analogRead(sensorPin);
  sensorVoltage = sensorValue * voltageConversionConstant;
  if (sensorVoltage <= voltageMin) windSpeed = 0;
  else windSpeed = ((sensorVoltage-voltageMin)*windSpeedMax /(voltageMax-voltageMin)*2.23694);
  lcd.setCursor(0,3);
  lcd.print(windSpeed);
  lcd.print(" MPH  ");

  ...etc... to display smoke detection...

  delay (500);
  }  // end loop

So the question is:  How can I slow down the Wind Speed fluctuations?  It jumps up and down quite widely.

A:  Use a running average

In the initialization I include an array to hold 10 values

// Wind Speed Anemometer
const int sensorPin = A3;
int sensorValue = 0;
float sensorVoltage = 0;
float windSpeed = 0;
float voltageConversionConstant = 0.004887586;  // (5/1024)
float voltageMin = .33;   // 0.4 in the documentation
float windSpeedMin = 0;
float voltageMax = 1.5;   // 2.0 in the documentation
float windSpeedMax = 32;

float ws[10] = { };      // (initializes all to zero)
int wsIndex = 0;
float wsTot = 0.0;
float wsDisplay = 0.0;

Then in the Loop I fill the array with values and display the average of the 10 readings stored there

  // Wind Speed
  sensorValue = analogRead(sensorPin);
  sensorVoltage = sensorValue * voltageConversionConstant;
  if (sensorVoltage <= voltageMin) windSpeed = 0;
  else windSpeed = ((sensorVoltage-voltageMin)*windSpeedMax /(voltageMax-voltageMin)*2.23694);

  if (wsIndex<9) {
    ws[wsIndex] = windSpeed;
    wsIndex++;
    }
  else {
    wsTot = 0.0;
    for (int i=0;i<=9;i++) wsTot = wsTot + ws[i];
    wsDisplay = wsTot / 10.0;
    lcd.setCursor(0,3);
    lcd.print(wsDisplay);
    lcd.print(" MPH  ");
    wsIndex = 0;
    ws[wsIndex] = windSpeed;
    }


SPI MOSI receive error I have a master and a slave (both are arduino UNO) connected through SPI connected. I want to transmit a character to the slave and receive true or false to the master. The transmission is working perfectly. If I send '2', slave is receiving '2'. When I try to transmit an integer from slave to master, the master is always receiving some arbitrary number like 128 or 255.

Master Code:

void setup() {
  Serial.begin(9600);
  Serial.println("Master");
  digitalWrite(SS,HIGH);
  SPI.begin();
  SPI.setClockDivider(SPI_CLOCK_DIV8);
}
void loop() {
  digitalWrite(SS,LOW);  //  Slave select to low
  received1 = SPI.transfer(test);  // test is a variable which is '2'. The data received by master is stored in received1 variable which is char.
  Serial.println(received1);
  digitalWrite(SS,HIGH);
}

Slave code:

void setup() {
  Serial.begin(9600);
  Serial.println("Slave");
  pinMode(MISO,OUTPUT);
  SPCR |= _BV(SPE);
  process = false;
  SPI.attachInterrupt();
}
ISR(SPI_STC_vect){
  received = SPDR;  // the data received by slave is slored in **received** variable(the variable is char type)
  Serial.println(received);
  process = true;
}
void loop() {
  if(process){
    SPDR = jj;  // Updating SPDR to send data from slave. jj is char type
    process = false;
  }
}

I have found a solution for this problem in a blog.

Link: http://www.gammon.com.au/forum/?id=10892

I modified my master code and got my desired result.

Master code:

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

void loop() {
  digitalWrite(SS,LOW);
  transferAndWait (10);
  received1 = transferAndWait (11);
  digitalWrite(SS,HIGH);
  Serial.println(received1);
}

The response will be "collected" next time through the loop. That's why we need to keep a dummy transferAndWait() function first and then the result of that transfer will be stored in received1 variable.


LCD Display Flicker When Arduino Main Board Supply Voltage to GSM Shield Board I have a 16x2 LCD display that is connected to an Arduino microcontroller.
It is working fine but the LCD display flickers when I connect the Vin and GND of the main board to its slave GSM Shield.

I used main board Vin and GND to power up the GSM Shield so I only have one power supply. I was able to power up GSM Shield by adding jumper to Vin and GSM +Vin.

In additional question, is there any other way to power up Arduino GSM Shield without connecting it to another power source to still keep having only one plug for power?

This sounds like either your GSM Shield is drawing to much power (from time to time) and thus your Vin drops resulting in flickering or your GSM Shield induces ripple on top of your Vin.

To debug this I would recommed to have a look at Vin with an oscilloscope and see how stable Vin is. Additionally some capacitors between Vin and GND (100nF and 10-100µF) and a ferrit between Vin and the GSM Shields Vin might help.


Problem with Arduino and INA226 power meter module I am new to the use of Arduino in general, and to the INA226 Module for power metering.

I first got everything set up WITHOUT anything plugged to the INA226 module metering pins (V+, ISens+, Isens-, V- not connected to any power source) and running a sample code that gets data being read by the INA226, of course, all values return 0, but at least I know the program runs and the arduino can connect to the INA226. Now, the problem comes when I try to get some reading such as 5V or even 3.3V from the Arduino pins.

I connected the circuit as follows:

simulate this circuit – Schematic created using CircuitLab

(I noticed that I wrote A6 instead of A4, sorry about that)

But when I do this, there is no reading at all from the serial console. I tried connecting the V+ and Isens+ directly to the 5V pin leaving everything else as shown in the diagram, but the Arduino board doesn't even turn on.

I tried referencing other sources, but their tests use external power supplies or other equipment I don't have.

I would be really thankful if someone could lend me a hand here or help me understand why am I having this problem and how can I make it read something basic such as 5V or 3.3V directly from the Arduino board.

Thanks!

There is a discrepancy in pin terminology between your schematic & what TI uses in their datasheets. I don't see anything in their datasheets using I+ or I-. I only see V+ & V-. These 2 pins perform all your voltage & current measurements depending on the "mode" you tell the IC to use.

As near as I can tell based on your schematic, you should be seeing the voltage reading based on what is applied between V+ & V- (In your case, 3.3vdc) if you've told the chip to read the bus voltage channel.

You should also be getting a current reading between the V+ & V- pins if you've told the chip to read the shunt voltage channel. Since the part is designed for a full scale voltage differential of 36v between the V+ & V- pins, I suspect a reading of about 10% of max (based on a 3.3v differential).

I confess to not knowing the board or its operation but having looked it up on the TI website, it does appear to have a few jumper settings & a calibration routine to follow. There's a user guide on TI's website as well as the usual technical data pages. Perhaps those will assist in setting the jumpers correctly. ina226 data sheet & eval board user guide
bc


KY-022 IR receiver, LED always on, no output I've been trying to use a KY-022 to read IR signals. However no output is being produced and the LED on the board is constantly on.

Board: Arduino Uno R3

I followed the procedure found here.

The code:

#include <IRremote.h>

int RECV_PIN = 11;

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup() {
  Serial.begin(9600);
  // In case the interrupt driver crashes on setup, give a clue
  // to the user what's going on.
  Serial.println("Enabling IRin");
  irrecv.enableIRIn(); // Start the receiver
  Serial.println("Enabled IRin");
}

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    irrecv.resume(); // Receive the next value
  }
  delay(100);
}

The output:

Enabling IRin
Enabled IRin

The LED is constantly on, it should come on when there's a signal received. However this is not shown in the output. :/ I don't know what to do.

Pictures:

The first thing to look at is the circuit board. Are they using the resistor and LED to indicate the board is receiving power? The data sheet has a schematic showing several passive components in the "3. ApplicationCircuit" section. Here is a copy of the schematic I have used that worked with the IRremote library (Version 0.1 July, 2009 - Copyright 2009 Ken Shirriff).


ARDUINO IDE debug level for stack trace only (nodeMCU 1.0) What is the minimum debug level (TOOLS tab) which will display the stack trace on crash?

I would like to reduce information clutter in the serial monitor.

I understand that debug port must point to my serial monitor.

In case it makes a difference, it is a NodeMCU, running C++, in Arduino IDE on a Ubuntu 16.04 machine.

The crash report is printed to 'standard output' by __wrap_system_restart_local in core_esp8266_postmortem.c in esp8266 Arduino core.

The standard output is considered as debug output in esp8266 Arduino core. Debug output to hardware Serial can be enabled in runtime by Serial.setDebugOutput(true);.

At compile time the initial debug output is controled by -DDEBUG_ESP_PORT=, for example -DDEBUG_ESP_PORT=Serial1. The Tools menu "Debug port" sets the DEBUG_ESP_PORT define. The crash report is not controlled by "Debug level" setting.


How to program the Robotdyn Mega 2560 PRO MINI? I want to program the Robotdyn Mega 2560 PRO MINI which has no USB port.

How do I connect the pins to an FTDI?

Which setting do I have to use in the Arduino IDE?

Connect the Arduino to the FTDI in the following way:

FTDI - Arduino
VCC - VCC
GND - GND
RX - TXD
TX - RXD
DTR - 100nf capacitor - RST
CTS is not connected

Use the following settings in the Arduino IDE

Board: Arduino/Genuino Mega or Mega 2560
Processor: ATMega2560 (Mega 2560)

The image shows the Arduino with colored connectors and with 4 extra rows of connectors. These are not part of the original Arduino. I added them to make it easy to connect lots of I2C devices for testing.


How to use H3LIS331DL 3-Axis Linear Accelerometer with arduino to detect Harsh braking of vehicle I am a newbie here, Recently I was working with H3LIS331DL 3-Axis Linear Accelerometer I²C Mini Module

Here is code for the X, Y, Z-axis.

 #include <movingAvg.h>
 #include <Wire.h>

// H3LIS331DL I2C address is 0x18(24)
 #define Addr 0x18

       movingAvg xAxisAverage(5);

       int readingIndex=0;
       int readingArray[10];
       int firstFiveReadingAverage;
       int lastFiveReadingAverage;

    void setup()
   {

      // Initialise I2C communication as MASTER
         Wire.begin();
     // Initialise Serial Communication, set baud rate = 9600
        Serial.begin(9600);

    // Start I2C Transmission
       Wire.beginTransmission(Addr);
   // Select control register 1
      Wire.write(0x20);
  // Enable X, Y, Z axis, power on mode, data output rate 50Hz
     Wire.write(0x27);
  // Stop I2C Transmission
     Wire.endTransmission();

// Start I2C Transmission
   Wire.beginTransmission(Addr);
// Select control register 4
   Wire.write(0x23);
 // Set full scale, +/- 100g, continuous update
  Wire.write(0x00);
 // Stop I2C Transmission
  Wire.endTransmission();
  delay(300);

   }
 void loop()
 {

   unsigned int data[6];
   for(int i = 0; i < 6; i++)
  {
    // Start I2C Transmission
    Wire.beginTransmission(Addr);
    // Select data register
    Wire.write((40+i));
    // Stop I2C Transmission
    Wire.endTransmission();

    // Request 1 byte of data
     Wire.requestFrom(Addr, 1);
    // Read 6 bytes of data
    // xAccl lsb, xAccl msb, yAccl lsb, yAccl msb, zAccl lsb, zAccl msb
     if(Wire.available() == 1)
       {
       data[i] = Wire.read();
      }
    }
   delay(300);

     // Convert the data
       int xAccl = ((data[1] * 256) + data[0]);
       int yAccl = ((data[3] * 256) + data[2]);
       int zAccl = ((data[5] * 256) + data[4]);

    if(readingIndex<10)
  {
     readingArray[readingIndex]=xAccl;
     readingIndex++;
     if(readingIndex == 10)
  {
    firstFiveReadingAverage=(readingArray[0]+readingArray[1]+readingArray[2]+readingArray[3]+readingArray[4])/5;
    lastFiveReadingAverage= (readingArray[5]+readingArray[6]+readingArray[7]+readingArray[8]+readingArray[9])/5  ;
   if(lastFiveReadingAverage>firstFiveReadingAverage)
    {
     Serial.print("Hardbrake Pressed");
     Serial.println();
    }
     readingIndex=0;
    }
    }

  //int avg = avgAccl.reading(xAccl);
  // calculate the moving average

     // Output data to serial monitor
        Serial.print("Acceleration in X-Axis : ");
        Serial.println(xAccl);
        Serial.print("Acceleration in Y-Axis : ");
        Serial.println(yAccl);
        Serial.print("Acceleration in Z-Axis : ");
        Serial.println(zAccl);
        delay(300);
        Serial.println();

     int average=xAxisAverage.reading(xAccl);

    if (average < -1000)
    {
     Serial.print("Hardbraking: ");
    //Serial.print(average/100.0);
      Serial.print(average);
      Serial.println();
        }
       }

I have changed the code, but values are keeps on repeating when I trigger the hard braking and it keep on repeating even I released the brake.

Here is the output

A harsh braking is nothing more than a strong negative acceleration, so you could compare your accelaration values to a threshold. Let's assume, that the positive x-axis is the moving direction of your vehicle. This means, that braking will give an acceleration in the negative x direction. Then you first define a specific threshold for the acceleration. An acceleration in the negative x direction above this level means, that it is a "harsh" braking (you will have to test yourself, what value you want for this). Then you test, if the read values are below the negative of our threshold (since acceleration in the negative direction will be presented by negative number).

int braking_threshold=1000;
...
void loop(){
    ...
    // Convert the data
    int xAccl = ((data[1] * 256) + data[0]);
    int yAccl = ((data[3] * 256) + data[2]);
    int zAccl = ((data[5] * 256) + data[4]);

    if(xAccl < -1*braking_threshold){
        // Do whatever you want to do at a harsh braking here
    }
    ...
}

Note, that often the accelerometer data is rather noisy, especially, when mounted on a vehicle, that will vibrate during the motion (due to motors and such). You might need to apply some filter to the read values, before you can use them. That can be as easy as averaging some values, but can also go on to more complex filter algorithms, depending on how noise free you need the data. You will have to test, what values you realistically get in your application and how noisy they are. But data noise reduction is a complete different topic and thus off-topic for this question.

Also note, that your accelerometer measures a range of 200g. That's quite much I would say. When measuring relatively low accelerations the signal to noise ratio will be rather bad. So I hope, that you really want to measure accelerations, that fill this range, rather than only using a very small percentage of the range.


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.

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