I also use a Seeed Studio SD Shield, and used to have the same problem. To rectify this I have to insert the SD card into my PC and Format it. This almost always helped. If you have a card that has too large of storage, the Arduino will take too much time to check the full memory for information stored on it (initialize). Some SD card readers require a card of 2 gigabytes or less to work. Check the Data Sheet for this limit (if there is one). That should do it for you.


Attiny : Is it possible to analog read on PB1?

PB1 has no analog input. So no, you can't read analog with it.
For analog you must use any of PB2 through PB5.


SIM800C developer board "SIM not inserted"

The print on the PCB and product description at sellers site states it is GSM/GPRS board. The  module on the board comes from SIMCom. This particular SIM800 module seems to have following capabilities as per SIMCom:

Compliant to GSM phase 2/2+
GPRS multi-slot class 12/10
Quad-band 850/900/1800/1900MHz

I think at the best you can only use a 2G SIM card on this board. Any 3G/4G SIM will not work.

Thanks for those images in the problem description, it gave me relevant keywords to search.


The error has nothing to do with what readStringUntil returns. It has to do with what parameters it accepts.

The function expects a single character to look for. Instead you are passing it a string (C string) containing one character.

In C you represent a string (char *) using "", and a single character (char) using ''.

Since readStringUntil expects a char, not a char *, you need to use '':

String line = offline.readStringUntil('\n');


Setting up I2C with HTU21D, no response after beginTransmission

You forgot Wire.begin();.  You should add it in setup().

Wire.begin(); will configure the IO pins for I2C usage. Without that the signals don't get in or out of the MCU, so I2C functions that wait for an ACK signal never see it and don't complete.


How to connect a digital sensor through SPI

You're shifting your address too far.

Read should be 0b00000001 not 0b00000010.
Your address should be shifted one bit not two.

Also you need to turn it on. By default the device is in standby mode. You need to enable it by setting bit 0 of register 0x2D to 0.

byte readRegister (byte thisRegister){
    byte inByte = 0 ;
    digitalWrite(chipSelectPin, LOW);
    SPI.transfer((thisRegister << 1) | 1);
    inByte = SPI.transfer(0x00);
    digitalWrite(chipSelectPin, HIGH);
    return inByte;
}

void writeRegister (byte thisRegister, byte value){
    digitalWrite(chipSelectPin, LOW);
    SPI.transfer(thisRegister << 1);
    SPI.transfer(value);
    digitalWrite(chipSelectPin, HIGH);
}


Run function concurrent to server.available()

There is no “parallel” on a single core arduino. All you need to do is program both things in a non blocking fashion. Don’t use delay or while loops waiting on things and you can do both things so fast it seems like they are parallel. Put a call to server.available() in loop and then if it returns an invalid client object then the rest of the loop runs.  If it returns a valid client object then you can quickly do what you need with the server and then get back to everything else.
As noted in the comments, server.available is not blocking.  It doesn't wait for anything to come, it simply returns whether there is a connection available or not.


The {0} denotes an extra parameter (which you want to print), it seems you just want to print the string without any variable 'value' so you can remove the {0}.

I'm not so familiar with using {0} in C++, but in C# {0} means argument number 0 (after the initial string), since this argument is not given, probably an empty string is created ... it would be more intuitive if the compiler give an error or warning (maybe it gives a warning and you can check for it).

Also converting a string to String() does not do anything but I think it was just for debugging/checking purposes.

Also in Arduino to save SRAM space, normally it is wise to add before each string, the F function like:

Serial.println(F("Some string to print"));

This will create a memory in Flash and will not be copied to SRAM which is normally quite scarce.

To print out arguments you can simply use multiple print commands (which does not add a new line) and the last part of the line with println, like:

Serial.print(F("Test time: ");
Serial.println(test_time);


Some of the libraries you mention (iomanip, iostream, queue, string) are part of the STL - Standard Template Library. Whilst it does not ship with the IDE download, you can install it yourself. See The Standard Template Library (STL) for AVR with C++ streams - a port to the Arduino by Andy Brown.

I have some implementation notes here.

Be aware that a lot of Arduinos don't have much RAM, so you need to use libraries like this with caution.

Library download: AVR standard template library, version 1.1.1 - 197.29 kB


Do you have the same operating circuit that is shown on page 1 of the datasheet? do you have the 2K resistor they specifically from OUT to ground? Also, it may be worth adding the 1 uF capacitor they recommend from OUT to ground too
The other thing to consider is the actual voltage over the resistor. Check an see if the voltage over the resistor is 3.3 and that there isn't a voltage drop from the chip
If the voltage is fine, there may be a problem with the chip or the arduino


Example code and documentation on using Firmata communication in native Java

Maybe this can work for you.
Some months ago i used RXTXcomm library [1] to send Arduino data to a Program i made in java and store in in a file, it works fine with some issues:

I made the Java programm in linux but just works in java 6, so in the windows pc of the client i installed that version, i don't know if works with java7 or java8 in windows.
Java programm reads data from Arduino sketch with Serial.print() function, Arduino continously is using this function, i lose some data, so i had to put a short delay to java programm get all data send by Arduino.

[1] http://rxtx.qbang.org/wiki/index.php/Main_Page


How can you have two blinking leds and a fading one

While there are better ways to do this, as pointed out by other posters, for what you're trying to learn right now, your program (almost!) works just fine. You'll need the more advanced techniques as you progress to more complex programs. But for now, I made a couple of edits to your program to get you going:

The most important one was to use analogWrite() for the PWM LED (LED 9). That makes it fade in and out instead of turn on and off (with a long period).
I turned one LED on and one off at the same time, getting rid of the dark periods and 400ms of combined delay.
I doubled the fadeAmount to fade in and out a little faster; it wasn't very visible with an increment of 5.

Here it is with those changes:

int led = 9;
int brightness = 0;
int fadeAmount = 10;

void setup() {
  pinMode(11,OUTPUT);
   pinMode(12,OUTPUT);
    pinMode(led, OUTPUT);
}

void loop() {
  digitalWrite(11, HIGH);
  digitalWrite(12, LOW);
  delay(200);
  digitalWrite(11, LOW);
  digitalWrite(12, HIGH);
  delay(200);

 analogWrite(led, brightness);

 brightness = brightness + fadeAmount;

if (brightness <= 0 || brightness >= 255) {
  fadeAmount = -fadeAmount;
}
 delay(30);

}

Update:

  what if i wanted to add a a second led

I'm assuming you mean a fading LED, that it's pretty clear where you'd a blinking one?

Blinking in-phase is easy - write the same brightness to both. To fade them out of phase, you'll need a second brightness-variable (and possibly a second fade-amount), and an increment/decrement and limit test for each LED.

But note how your code starts getting more complex as you add components and try to manage them in a single loop, with delay()s? That's when you'll want to try the Blink Without Delay example, and compare adding new LEDs that way, to adding new LEDs to your current program.


Help a noob, no idea on Programming, only started 2 days ago Help please

I presume you got some errors, like this:
/tmp/arduino_modified_sketch_836883/sketch_oct30a.ino: In function 'void setup()':
sketch_oct30a:13:3: error: a function-definition is not allowed here before '{' token
   {
   ^
sketch_oct30a:37:17: error: expected '}' at end of input
       delay(500);
                 ^
exit status 1
a function-definition is not allowed here before '{' token

You have to read those. At the end of a function you need a closing brace. So, setup for example would look like this:
void setup()
{
  pinMode(EMagnetPin, OUTPUT);     // assign pin type
  pinMode(solenoidPin, OUTPUT);   // assign pin type
  pinMode(ReedPin, INPUT);        // assign pin type
  Serial.begin(9600);             //serial port open
}   // <------- ADD THIS

Ditto for the end of the loop function.
The next problem is this line:
    if (digital REad(ReeddPin) == 0 ) {

The function "digitalRead" is spelt like that, not as two words. Also you misspelt "ReedPin" as "ReeddPin".
You have to go carefully through your code, look at the error messages, and fix them one by one. C++ is case-sensitive, you can't just thrown in extra spaces in the middle of words, and you have to be consistent with your variable names (ie. not misspell them).

I suggest you do a C++ tutorial, or find an Arduino tutorial. These are basic coding mistakes made by beginners. With a bit of practice, and some working through examples, you will stop making them.


Should BLK and GRN of Pro Mini be connected to upload sketch?

If you look at the picture in your link, you would see that BLK is ground (GND) and GRN is DTR, that is used to reset the board and enter the bootloader for programming.

As Majenko said, without DTR you will need to press the reset button at the right time, to enter the bootloader.


UART error can not compile on Arduino Yun (ATmega32u4)

Those register names are for a different chip (maybe the ATMega328P of the Uno).

Instead you need to use the right register names.  Start by reading the datasheet for the ATMega32U4.  You might find that the register names are UCSR1A etc, or UCSRA or something like that instead of UCSR0A.


How do I send data to an Arduino via light flashes

I can't yet make a comment, too much a newbie yet, so am submitting this as an answer.

I have been using this Instructable as my entry point into All Things Arduino and there is src code you may be able to use.

http://www.instructables.com/id/Programmable-LED/

This uses an ATTiny to detect and record changes in a photoresistor, and use the result to play back the same flash sequence that was received.

Other than the pin mapping being different, and lack of reliance on higher-level Arduino core functions : ) it could be useful to you.

the big thing I see is that we and you may not know the delta in resistance a photoresistor might see from your screen flash.  However, the src available from the link does contain a configurable delta in measured resistance (so even a dim flash could work, if you change the threshold in the code).

There are also code snips in the comments that help measure the "background" light level, before enabling the sensor to "record".
This could be useful for low- or high- background light levels as you may find in a lit (or poorly lit) room.


Is it possible to change pin operation from output to input within the Arduino loop (event-driven)?

Yes.

Just call pinMode([pin], [mode]) whenever you want to change from input to output or output to input.

How to decide when to do that is entirely up to you. You can do it any time you choose using any stimulus you like.


I'm not using a 220 Ohm resistor or any kind of resistor that time.

Well, there you go then. If you abuse an LED you can expect it to die.

  When I plugged the green LED into a 220 Ohm resistor, it did as expected. It lowered its brightness, of course, because the resistor is resisting some of the electricity to pass on the LED.

And the LED was so much happier when you weren't abusing it.

  I'm expecting that the green LED should also be burned, because I think, that's the way how LED's work.

It was probably tinged with yellow. And if you left it a while it would get yellower as it got hotter, and then started to fade out, and eventually die.

Different LEDs use different combinations of elements to make the different colours. Different types of the same colour also use different elements. Old fashioned green LEDs are more reliable, though dimmer, than newer ones. They withstand more abuse. But they will still complain after a while.


First, check to see if the printer itself yields this information, either on LCD display if present, or by reporting it to a host computer upon connection (ie, try enabling verbose output in your printing software).

While it's not guaranteed to be supported, in practice many Arduino Mega based 3d printers have bootloaders capable of readback of the flashed contents, and the chips themselves are unlocked.  Even if the bootloader does not support this, an ISP connection might.

If you are able to read out the contents, you can have avrdude write them to a flat binary file, and examine it with the strings program or a hex editor.  If you end up with a hex file instead, there are tools for converting this to a flat binary.

Your goal would be to look through the file for version strings, and other messages which might indicate specifics, especially on which side of various points of change or configuration options it falls.

Making such a backup is a good idea before loading a new firmware anyway.  Ideally after verifying that you obtained meaningful contents, you would also readback a few distinct copies of the file and use something like diff to verify that they are all the same.  You can grab the EEPROM contents too, if your firmware may be storing things there.


Identifying Arduino-compatible board signatures in code

In the boards.txt file each board has a board type definition, such as:

uno.build.board=AVR_UNO

When you compile your sketch that is adapted into a "board" define by prepending -DARDUINO_ to it and adding it to the compilation command line - so that one becomes the same as #define ARDUINO_AVR_UNO.  You can, of course, test for it with:

#ifdef ARDUINO_AVR_UNO
....
#endif

The location of the boards.txt file varies with different versions of the IDE, but every installed core will have one.  Look around in your Arduino program folder in the hardware subdirectory.


Boolean Logic With Chars For Motor Input Selection

It's screaming on you:

sketch_jun13a.ino:7:11: warning: invalid conversion from 'const char*' to 'char' [-fpermissive]

 char  x = "0";

           ^~~

sketch_jun13a.ino: In function 'void loop()':

sketch_jun13a.ino:21:36: warning: comparison with string literal results in unspecified behavior [-Waddress]

   if (Serial.available () && (x == "0")) {

                                    ^~~

sketch_jun13a.ino:21:36: warning: ISO C++ forbids comparison between pointer and integer [-fpermissive]

sketch_jun13a.ino:26:36: warning: comparison with string literal results in unspecified behavior [-Waddress]

   if (Serial.available () && (x == "a"))

                                    ^~~

sketch_jun13a.ino:33:9: warning: invalid conversion from 'const char*' to 'char' [-fpermissive]

     x = "0"; //reset x, goes back to input selection

         ^~~

sketch_jun13a.ino:34:38: warning: comparison with string literal results in unspecified behavior [-Waddress]

   } if (Serial.available () && (x == "b"))

                                      ^~~

sketch_jun13a.ino:41:9: warning: invalid conversion from 'const char*' to 'char' [-fpermissive]

     x = "0";

         ^~~

sketch_jun13a.ino:43:36: warning: comparison with string literal results in unspecified behavior [-Waddress]

   if (Serial.available () && (x == "c"))

                                    ^~~

sketch_jun13a.ino:50:9: warning: invalid conversion from 'const char*' to 'char' [-fpermissive]

     x = "0";

         ^~~

sketch_jun13a.ino:52:36: warning: comparison with string literal results in unspecified behavior [-Waddress]

   if (Serial.available () && (x == "d"))

                                    ^~~

sketch_jun13a.ino:52:36: warning: ISO C++ forbids comparison between pointer and integer [-fpermissive]

sketch_jun13a.ino:58:9: warning: invalid conversion from 'const char*' to 'char' [-fpermissive]

     x = "0";

         ^~~

Basically this is char variable with assigned character literal: char x = '0';

And this is C string: char str[] = "0"; or its equivalent: char str[] = {'0', '\0'};. Where '\0' is so called NUL Terminal character.

Everything about C strings you need to know

EDIT:

Simple demo for the "parser" - it's not perfect but should be enough:

char  x = '0';

int inpSpeedS[4]; // An array to determine the speed of each individual input

void setup() {
  Serial.begin(9600);
  Serial.println("Select channel [a..d] and speed [0..255]: ");
}

void loop() {

  if (Serial.available() > 1) { // wait for more characters in buffer
    switch (Serial.read()) {
      case 'a': inpSpeedS[0] = Serial.parseInt(); break;
      case 'b': inpSpeedS[1] = Serial.parseInt(); break;
      case 'c': inpSpeedS[2] = Serial.parseInt(); break;
      case 'd': inpSpeedS[3] = Serial.parseInt(); break;
      default : return; // skip invalid characters like line endings
    }

    Serial.print("Speeds: ");
    for (auto spd : inpSpeedS) {
      Serial.print(' ');
      Serial.print(spd);
    }
    Serial.println();
    Serial.println("Select channel [a..d] and speed [0..255]: ");

    /*
      analogWrite(motinp1, inpSpeedS[0]);
      analogWrite(motinp2, inpSpeedS[1]);
      analogWrite(motinp3, inpSpeedS[2]);
      analogWrite(motinp4, inpSpeedS[3]);
    */

  }
}

And the result:

-> Select channel [a..d] and speed [0..255]:
<- a547
-> Speeds:  547 0 0 0
-> Select channel [a..d] and speed [0..255]:


How to check if all pins are connected on my board to make sure Arduino sends the correct pattern number on my tool

As mentioned in a comment, your code has some fundamental flaws. Do not call loop() from within loop()! Aside from the code errors, your question has a legitimate element.

Testing the tri-state behaviour of an input pin will let you know if it is genuinely high, genuinely low, or floating (disconnected). The technique was given in this answer to similar problem I was encountering.

In short:

Connect a large (1MOhm) resistor to each input between the pin and ground, then for each pin:

Turn off internal pullup;
Read value of input pin;
Turn on internal pullup;
Read value again.

If the value changes from the first to the second digitalRead(), the input was not connected to anything. If the value remains the same then it is a genuine value from a connected device.


Have the MFRC522 objects remember where you want them to send the output
by adding a data member to the class like this:

private:
    Print &output;

This is a reference to a Print object, i.e. any object where you can
print() or println() to. This reference should be initialized in the
constructor, like this

MFRC522:MFRC522(...other arguments..., Print &my_output = Serial)
: ...other initializations..., output(my_output)
{
    ...constructor body...
}

Notice that, by default, the output is initialiazed as a reference to
Serial. Thus, unless you explicitly ask for the output to go
elsewhere, the class will behave as before.

Last step is to change, in the implementation of the class, every
reference to Serial by output. This is just a global find and
replace.

At this point, the MFRC522 class can be used exactly as before, and it
will behave identically. This means that every user of the library
should be able to use your modified version with no issues. I thus
encourage you to submit the changes to the original author, so that they
have a chance to be incorporated into the canonical version of the
library.

Now, if you want this debugging output to be sent elsewhere, just
provide the destination as the last argument of the constructor:

MFRC522 my_RFID_module(...other arguments..., my_SD_card_file);

As long as the destination is an instance of the Print virtual class
(basically anything you can print() to should be OK), it should work
as expected.


What's taking up so much RAM in an almost empty sketch?

First off, a sketch that uses Serial cannot really be considered an empty sketch as Serial drags along a lot of function definitions, at least one Serial class instance (more on Arduino Mega, for instance), plus probably some more global variables...

sizeof Serial may be interesting to display as Serial is not limited to the TX and RX buffers, as you seem to believe. Its class also has a couple of additional data members on its own, plus members inherited from its superclasses, Stream and Print.

In addition, the Arduino IDE comes with the various "utilities" which you normally can't get rid of, like the millisecond timer that uses at least 9 bytes (see reference in wiring.c file).

So in the end, even an empty sketch (even without Serial) takes some SRAM space for global variables.

I think there is some way, with avr-size, to check out, with fine details, the size of data (not accounting for the runtime stack) after the sketch has been fully built.

Arduino IDE already displays some of this static memory information (at the end of "verification").

For example, on my IDE (1.5.8) for Arduino UNO, a really empty sketch, once compiled is mentioned to use 9 bytes of SRAM. Actually those 9 bytes are for 3 global variables, used by the millisecond timer. This number, of course, does not account for runtime memory usage, in particular the stack.

Then, just adding Serial.begin(9600); makes it use 182 bytes (ie 173 more bytes than an empty sketch). So you get the culprit.


Arduino Mega 2560 RFID Serial Communication

First of all, try testing 1 functionality at a time to isolate the issue.
Now you do not know if the LCD is not working correctly, or if the serial communication with the RFID module is not working correctly. Connect it to a computer and test both independently.

When getting gibberish from a serial line, usually it means the baudrate doesn't match. Both devices have to send the same amount of bits per seconds in order to communicate with each other.

This is the Arduino example to test 2 serial lines (for Arduino Mega) at the same time: http://arduino.cc/en/Tutorial/MultiSerialMega


Mega attachInterrupt on pins 18 or 19 require EIFR bit set first (to clear it)?

It's not that pins 18 or 19 are faulty, you are just lucky the other ones worked.

As I mention on my page about interrupts* you are recommended to always write 1 to the appropriate EIFR bit before enabling interrupts because it (the interrupt condition) may have been set in the past.

I checked the source for attachInterrupt in the file WInterrupts.c and there is no mention of the EIFR register, therefore attachInterrupt never affects that register.

* Also see my answer: How do interrupts work on the Arduino Uno and similar boards?


Serial.print changes serial output before it is called

Your string needs to end with a null character '\0'.  I think yours does not because of the way that you filled the buffer, so you're getting whatever junk is in memory next to your array printed in addition to the array itself.


Sender:

SoftwareSerial mySerial(10, 11);  // Rx, Tx

Receiver:

SoftwareSerial mySerial(11, 10);  // Rx, Tx

  I have the 'sending' Arduino's D10 pin connected to the 'receiving' Arduino's D11 pin, and vice versa.

So you have the sending Arduino's Rx connected to the receiving Arduino's Rx. Therefore it won't work. You need to connect Rx to Tx.

  mySerial.listen();

You don't need that in this simple example.


How to program Fio v3 without MicroUSB port

The board runs at 3.3V, so you can provide 3.3V directly into the 3.3V pin on the side. Also the black connector next to the USB socket is a battery connection for a Li-Ion battery or similar. It will take any voltage between 3.6V and 5V. Any higher and, according to the schematics, you need to remove the solder link that's just below the battery connector (silver blob). With that link removed you can theoretically go up to 20V on the battery input.

Yes, you can program through the 6-pin header below the main chip if you have a suitable hardware programmer (e.g., USBASP). That is a normal ICSP header like most Arduino boards have.


Why the LED freezes? when I am adding a delay?

Your Arduino does nothing during the delay(5000). So pressing the button during the 5000 mSec that the led is off won't do anything. Or you must be very lucky to press the button in the very small time between one loop and the next.

I learned a lot about timing and delays with this tutorial: Blink Without Delay


This is likely a permission problem.  The user likely does not have permission to read from and write to the port created when plugging in the Arduino.  This can be temporally fixed using the following command:

sudo chmod 666 /dev/ttyACM0

However, this procedure is only temporary as the port is recreated every time the Arduino is reconnected to the computer.  And upon recreation the permissions are reset to their defaults for security reasons.

A better solution is to determine the group which the port belongs to and to add the users expected to access these connected devices to that group.

Plugin and list the port to determine its group:

ls -l /dev/ttyACM*

or

ls -l /dev/ttyUSB*

The group the ports belong to will likely be "dialout".  Add the user to that group:

usermod -a -G dialout user_name

...where user_name is replaced by the name of the user who needs access to the port.  If you don't know the name of the current user you can use this command:

whoami


Using L298N bridge to control smart lock

You really don't want an L239D to control that lock. It's overkill.  The L239D is a H-bridge that is designed to drive loads in two different polarities (forward / backwards on a motor for example).

That lock is merely a spring-loaded solenoid. You give it power and it pulls the lock back. You remove power and the spring closes it again.

All you need is a simple transistor circuit just like you'd use for a relay.

Since you insist on using an L239D, here's a schematic for you:

simulate this circuit – Schematic created using CircuitLab


Has anybody seen/created a gps guided vehicle with arduino?

Yes, someone (not me) has: https://www.youtube.com/watch?v=3-r2Jk0uA6U

I doubt it would work very well with non-flying vehicles - in the air, a 3 meter margin of error is fine, on the ground it's the difference between the sidewalk and the middle of the road.


How do I send MIDI properly with ESP8266?

NOTE : Probably not the answer you're looking for, but it works for me.

Solution : Move the jumper from 5V to Vin.
Why? I don't know. It just works.

Please notice that this is Wemos D1 Uno, which has adaptor input, which can receive 9-24V.
If you're going to use the adaptor, IT MAY BROKE YOUR MIDI DEVICE!
As far as I know, Vin stands for Voltage Input, and everything from the adaptor is routed there. That means if you use 24v adaptor, Vin is 24v!

I'm only planning to use USB as power supply, so yeah. it works for me.
If you're going to use Vin with external power supply, please use voltage regulator to 5v. Better safe than sorry.

Anyway, since I'm planning to use 6N137 to receive MIDI also on this board, here goes :

  Input voltages greater than 7 V must be avoided to preclude damage to
  the gate oxide of the input stage. This damage is not necessarily
  permanent, but will adversely affect the expected lifetime of the
  circuit. The gate oxide of AHC devices is only 200 Å thick. An input
  voltage of 7 V corresponds to a field strength over the gate oxide of
  350 kV/cm. Although breakdown of the oxide is expected only at input
  voltages above 10 V, electrons tunnel increasingly into the gate oxide
  at field strengths greater than 350 kV/cm, influencing characteristics
  of the transistors and causing failure.

Source : this question on electronics stackexchange.


HC-05 bridge using Arduino Nano and GNU Screen

Based on the above comments I provide here the full answer in the hope it will be useful in the future.

HC-05 has two modes. The Communication Mode and AT Command Mode. In the latter mode, HC-05 responds in kind of "config" way and many default settings of the communication mode can be change here. While the baud rate of the communication mode, and many other settings can be changed, the baud rate of the AT command mode is always fixed 38400 to avoid any confusions and mistakes. On the other hand, the default factory baud rate of the communication mode, i.e. before any change, is set to 9600. So the solution to my problem was to set the baud-rate to 9600 on my newly purchased HC-05 and I was able to make an echo bridge between HC-05 Bluetooth and serial. Here is the code:

/*
 * echo script
 */

byte incomingByte;

#include <SoftwareSerial.h>

SoftwareSerial BTSerial(3, 2); // RX | TX

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

void loop() {
  if (Serial.available()) {
    incomingByte = Serial.read();
    BTSerial.print((char)incomingByte);
  }

  if (BTSerial.available()) {
    incomingByte = BTSerial.read();
    Serial.print((char)incomingByte);
  }
}

After pairing HC-05 with OSX, I was able to open two OSX Terminals with one of these commands in the first terminal:

screen /dev/cu.wchusbserial1410 9600

and in the other:

screen /dev/cu.HC-05-SPPDev 9600

Everything worked properly, i.e. typing in one terminal produced characters in the other and vice versa. For changing the default baud-rate in the communication mode, I found a very good tutorial which can be found here.


Increasing number of iterations not increasing time

The compiler has realized that your loop doesn't do anything useful and therefore optimized the whole thing away. Thus you are just timing how long it takes to do nothing. (You didn't get a result of zero, because calling micros will itself take time).

BTW, the granularity of micros is 4 µs, so you won't get a reading of 1 or 2. The code actually probably only took a couple of microseconds.

You need to do something that the compiler thinks "does something", like this:

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

volatile byte b;

void loop() {
    unsigned long a = micros();
    for (unsigned long j = 0; j < 100; ++j)
      b++;
    Serial.println ((micros() - a));
    delay(1000);
}

By making b volatile the compiler cannot decide that b isn't doing anything useful, so now the timings make sense.

I got 72 for 100 iterations and 144 for 200 iterations.

  Is there a function which I can use to measure time properly in arduino?

Your time measurement is fine. Your interpretation of the results indicates you didn't realize how smart the compiler is. :)

You can see what the compiler did if you examine the generated code:

    unsigned long a = micros();
  d8:   0e 94 d2 00     call    0x1a4   ; 0x1a4 <micros>
  dc:   6b 01           movw    r12, r22
  de:   7c 01           movw    r14, r24
    for (unsigned long j = 0; j < 100; ++j);
    Serial.println ((micros() - a));
  e0:   0e 94 d2 00     call    0x1a4   ; 0x1a4 <micros>
  e4:   ab 01           movw    r20, r22
  e6:   bc 01           movw    r22, r24

As you can see, between the two calls to micros there isn't any sort of loop.

To find the assembled code you can follow the steps documented here.

Basically, turn on "verbose compiling" which will show near the end of the verbose output the full pathname of the ".elf" file. Then use a command (terminal) window to enter this command:

avr-objdump -S xxx.elf

You may want to redirect the output to a file:

avr-objdump -S xxx.elf > myfile.txt

Depending on how the Arduino IDE was installed you may have to find the pull pathname of avr-objdump and use that instead of just the program name.


A proper way to get the roll, pitch and yaw values

In some sources there is something going on as the importance of order of the application of roll,pitch and yaw. But I cannot understand why this is related.

Take your right hand: point your thumb upwards, your index finger away from you, and your middle finger to the left. You now have a righthanded coordinate system: your thumb is the x axis, your index finger the y axis, and your middle finger the z axis.

First rotate +90° around the x axis (thumb). Your index finger now points to the left, and your middle finger towards you. Next, rotate +90° around the y axis (index finger). Your thumb now points away from you, your index finger to the left, and your middle finger upwards.

Now, move back to the initial position, and apply the same two rotations in a different order, first around the y axis and then the x axis:
Rotate +90° around the y axis (index finger). Your thumb is now pointing to the right, your index finger away from you, and your middle finger upwards. Next, rotate +90° around the x axis (thumb). Your thumb now points to the right, your index finger upwards, and your middle finger towards you.

This is different from the last result: order of rotation matters.

  I have used accelerometer values by inputting them into some formulas on the internet(those arctangent formulas, which everybody uses but nobody explains well)

When the aircraft is moving at a constant velocity, the accelerometer just measures the acceleration due to gravity, which is a vector pointing exactly downward, (0, 0, -g) in the global coordinate system. This is always true, regardless of the orientation of the sensor.
If the sensor is perfectly level, the sensor's local coordinate system is aligned with the global coordinate system, so the sensor also measures (0, 0, -g).

When the sensor is tilted, the measured vector also has an x and y components.
To keep things simple, imagine the case where the sensor is tilted around the positive y axis.
The sensor now measures an x component as well as a z component: (x, 0, -z).

As you can see from the following image, the angle of rotation θ = atan2(x, z).

The black arrow is the acceleration due to gravity, and the red and blue arrows are the x and z axes of the coordinate system of the (tilted) sensor.

However, accelerometer measurements are not useful for determining the orientation when the sensor is accelerating, because then the measured vector no longer points exactly downward (in the global coordinate system).

Gyroscopes measure angular velocity. By integrating the angular velocity, you get the angle.
There's one caveat: it is impossible to integrate exactly, because we only have measurements at discrete points in time. This means we have to use something like Euler's method, which is known to result in drift of the orientation estimate. To make matters worse, the measurement is noisy, and this noise is integrated as well, resulting in an even larger error.

Luckily, you can combine both imperfect measurements into a single, better orientation estimate using a sensor fusion algorithm. I've successfully used Sebastian Madgwick's algorithm for my quadcopter.
It uses the measurements of the accelerometer to minimize gyro drift.

Note that this algorithm uses quaternions instead of Euler angles (roll, pitch, yaw), because the latter suffer from gimbal lock, and because quaternions geneally require less processing power.

Also note that you cannot determine the yaw angle using the accelerometer, so you'll get some drift on that measurement.

It's a good idea to do all of your calculations using quaternions. You probably won't need Euler angles for your quadcopter, except maybe for debugging purposes.

If you want to, you can also get the quaternion from the acceleration vector directly:

    Quaternion quaternionFromDirection(Vec3f v) {
        /*
         * Formula:
         * q = cos(ϑ / 2) + sin(ϑ / 2)·(x·i + y·j + z·k)
         * where (x y z) is a unit vector representing the axis about which
         * the body is rotated; ϑ is the angle by which it is rotated.
         *
         * Source:
         * https://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#Using_quaternion_as_rotations
         *
         * The rotational axis (x y z) can be calcuated by taking the normalized
         * cross product of (0 0 1) and the given vector. The angle of rotation
         * ϑ can be found using |A×B| = |A||B|·sin(ϑ).
         */

        // First check the edge case where v == (0 0 z), i.e. vertical
        if (v.x == 0 && v.y == 0)
            return {1, 0, 0, 0};

        // Calculate the cross product and its norm.
        Vec3f cross     = {v.y, -v.x, 0};
        float crossNorm = cross.norm();
        cross /= crossNorm;

        // Calculate the angle ϑ.
        float angle = std::asin(crossNorm / v.norm());

        // Calculate the resulting quaternion.
        return {
            std::cos(angle / 2),            //
            std::sin(angle / 2) * cross.x,  //
            std::sin(angle / 2) * cross.y,  //
            std::sin(angle / 2) * cross.z,  //
        };
    }


Can anybody advise what type of connector this is?

The board uses a JST PH connector, with 2.0mm spacing. The battery has a JST XH connector, with 2.5mm spacing. You will need to replace the battery connector or put a XH socket on the board.


Power supply affecting sensor readings ESP8266 and JSN-SR04T-2.0

The JSN-SR04T-2.0 ultrasonic range finder is rated to 5Volts. giving it 3.3 volts may not be enough. from my limited knowledge it should work if you give it a separate power supply and not depend on the 3.3 volts of the ESP.


I think you are making a mistake initializing cs_5_7.

CapacitiveSensor   cs_4_2 = CapacitiveSensor(4,2);
CapacitiveSensor   cs_5_7 = CapacitiveSensor(4,6);

You are using same pin 4 for both Capacitive sensors. Try using different pins. I am quite sure that, this would help.


How to read 6 RC remote channels using Attachinterupt for every channel

I am not sure what you are asking but you can have as many interrupt sources on a single interrupt pin as you want.  When the interrupt happens in your ISR (Interrupt Service Routine) you simply check each one and process the ones that are valid.  Be sure to do one final check before exiting as another could happen while servicing the first one.

Gil


Do you want i and x to increment at the same rate 0-255 then x to remain 255 while i increases to 500?

this should do what you want. i and x increase together until x reaches 255 then it wont increment.

int x=0;
for (int i=0; i<500; i++) {

  digitalWrite(DIR,LOW);
  digitalWrite(PUL,HIGH);
  Serial.print("i = ");
  Serial.println(i);
  Serial.print("x = ");
  Serial.println(x);
  delayMicroseconds(x);
  digitalWrite(PUL,LOW);
  delayMicroseconds(x); }

   if(x<=255){
        x++;
   }

}


In short, there aren't any substantial differences.  But it makes sense to use the one that actually matches what you have.
My KICAD symbols are out of date, so I downloaded and unpacked the current archive for MCU Module symbols.  These things are defined in text files, so doing this allows you to employ the usual diff tools to them, if you break the parts of interest out into separate files, which is what I did to produce the below images.
Index Entries
Besides the name, they're different in what datasheet they refer to:

Definitions
In the below, on the left you'll see in dark blue background that both the Nano v2.x and v3.x are actually defined in the same file.  So, they are in fact sharing a definition; so, no differences there at all.  The original Nano boards varied in that some had ATMega168P and some had ATMega328P.  These are practically but not quite the same chip.  The significant difference is sizes of the various memories.  And they had different bootloaders.  Nothing that would make their symbols or footprints significantly different.
On the right is the Nano-Every, which is a fairly different beast from the older Nanos in that it's an ATMega4809, one of the new-series AVR parts, and different significant ways greater than just memory sizes.  But, it was designed to have the same layout as the prior Nano boards.  They even went so far as to make classes and objects to try to "emulate" the more traditional style GPIO ports of the Nano for Nano Every users.
As you can see there's really no differences besides the names of the pins and a few changes in drawn locations between the v2/v3 symbol on left and the "Every" symbol on the right.  Some of the pin names are different, but it's the pin numbers that matter when mating it to a footprint in Kicad, and those are the same between the two.
For whatever reason pin number 29 changed from W (in 2/3) to N (in "Every"), which according to their documentation is a change from power input to not connected.  I suppose this might make a difference between whether or not you need to add a PWR_FLAG symbol somewhere in your design to satisfy electrical rules check (ERC).  In the "Every", for whatever reason when they (slightly) rearranged the pins locations in the symbol, they stuck pin number 29 right on top of pin 4.  So, if you're having a hard time seeing pin 29, that (and the light gray text) are why.


Help with code. Fade in LEDs from off (shift register)

I was mistakenly thinking that setting the brightness variable to 255 would mean that the LED is full on. This is wrong, 255 is actually off.

So with a little change in my code.

for (byte b = 255; b > 0; b--) {
  setBrightnessUp(b); //calls the brightnessup function
  delay(30);
}

The loop now works. I am still not sure why 255 is off and not on though.


Can we detect a magnet using Arduino? If so how?

I can't comment yet but you probably are looking for a hall effect sensor.

Something like this is a simple version of the sensor. https://www.sparkfun.com/products/9312

You can then do a digitalRead on the DO pin to detect if a magnet is near the sensor.

You would connect the Vdd to 5v arduino supply and GND to the GND of the board.


Splitting a string read from Serial into parts

The first thing you should do is to collect your serial input into a string.

If your incoming data use a separator, then you can take advantage of the useful function "readStringUntil".

For example, if your separator is comma (,):

while (Serial.available() > 0) {
  var1 = Serial.readStringUntil(','); // writes in the string all the inputs till a comma
  Serial.read();
  var2 = Serial.readStringUntil(',');
  Serial.read();
  var3 = Serial.readStringUntil('\n'); // writes in the string all the inputs till the end of line character
}

At this point you have your data in 3 different variables and you can use the standard eeprom library to store. Don't forget you will need to declare the variables and to initialize the Serial.

A faster way is to save the whole input in string and process it when ready.

Much better it will be if you use interrupts attached on the Serial input, so you can keep free your loop from waiting data. This can't be done with the standard Serial library but you can use this library:

https://github.com/SlashDevin/NeoHWSerial

It works really well, we use it to collect data from GPS receivers at very high speed and it's fast.

N.B. eeprom is limited in the numbers of reads and writes it can support before risk a failure. Even 100,000 reads/writes sounds a big numnber, if you write the data once every second your eeprom will die in just 27 hours, a day of life. Try to write data only when it's strictly necessary and read data as well only when you start the procedure that uses those data, once.


A relay is just an electromagnet, and the same circuit that can drive a relay can drive an electromagnet. You just need to make sure it can handle the power.

The simplest circuit is to use an N-channel MOSFET:

simulate this circuit – Schematic created using CircuitLab

Just make sure that the MOSFET can handle the required power dissipation and switches on fully at below 5V on the gate (a gate threshold voltage of less than 3V is ideal).


TWI Wire.setClock() on non arduino AVR MCU issue

Looking to get 100 kHz clock. What am I missing?

Calculations are int (16-bits) by default in AVR GCC. Try 100*1000L. Or even better:

#define F_TWI 100000L

and use:

TWBR = ((F_CPU/F_TWI)-16)/2;

or:

Wire.setClock(F_TWI);

Cheers!


Compiling for Wemos D1 mini with Visual Studio Code

Intellisense reports "Problems" - these are distinct from compile time errors. Just because Intellisense can't resolve a literal or something doesn't mean it won't be resolved in the compiler; thus it's possible to have the IDE report a problem but still be able to have a successful compile. In the case described above, two changes to the c_cpp_properties.json file provided Intellisense with the information it needed. A header file was added to the forcedInclude section to provide pin definitions. A literal "ESP8266" was added to the defines section to indicate the processor type. This define is used in lots of header files so it must be know to Intellisense when reading the headers. Here are the relevant sections of that .json file:
        "forcedInclude": [
            "C:\\Users\\David\\AppData\\Local\\Arduino15\\packages\\esp8266\\hardware\\esp8266\\2.7.1\\variants\\d1_mini\\pins_arduino.h"
        ],
        "defines": [
            "USBCON",
            "ESP8266"
        ],


There is confusion about what is and what isn't possible with this board. This is because there are different versions with different power arrangements.
NodeMCU 0.9
In this board the USB's 5V and the 5V pin are directly connected together. The combined result is then fed through a diode before entering the 3.3V voltage regulator.
With this arrangement the 5V pin will provide the exact same voltage that the USB port feeds the board. However it is dangerous to connect that pin to any power source - it may kill (or at the very least disable) the USB port in your computer - when the board is also connected to a computer through the USB port.
NodeMCU 1.0 and 1.1
On this version the USB's power is first fed through the diode and then to the 5V pin and the 3.3V regulator together.  This means that the 5V pin will show about 0.5V below whatever voltage is fed in through USB. This isolates the USB from the 5V pin so it becomes safe to provide power through the 5V pin whilst at the same time having the board plugged in to the computer - at the cost of having a slightly lower output from the 5V pin.

Original answer:
The VIN pin not directly connected to the USB's 5V supply (at least on the LoLin v3 board). this means the pin cannot be used as a 5V supply output.

You cannot control that voltage. It is always on, and always 5V (or whatever your USB port happens to provide - 4.75v - 5.25v).
You must never ever connect VIN to a power source and connect the USB socket. That can destroy the USB port in your computer. There is zero back-powering protection on that board.
Drawing more than 500mA from the VIN pin could cause the USB port of your computer to be shut down.


Broken Arduino Uno, works over USB but cannot take DC in

As you have noticed, measuring voltages is the first step. Here's some voltages for you and what they mean if they aren't there. These are all assuming precisely 12V in through the barrel jack. They are in order of "priority" - start at the top and work down, the first one that fails is your culpret (i.e., the barrel jack feeds VIN through the diode, VIN feeds 5V through the 5V regulator, and 5V feeds 3.3V through the 3.3V regulator).

Roughly 11.4V on VIN - if it's not there the input protection diode has blown
5V on the 5V pin - if it's not there the 5V regulator has blown
3.3V on the 3.3V pin - if it's not there the 3.3V regulator has blown

Fixing it may be as simple as replacing the faulty component identified above - although they are all surface mount and some are more tricky to replace than others.  That said, if it is (as it sounds) the 5V regulator that has gone, that is one of the larger components (SOT-223) so should be eaiser to replace. Also it's dirt cheap - I get them for a few cents each in bulk.


How can I communicate from Arduino to MATLAB

MATLAB Support Package for Arduino (aka ArduinoIO Package) allows you to do it fairly easily.

  Sample usage:

  %-- connect to the board

  a = arduino('COM9')

  %-- specify pin mode

  a.pinMode(4,'input');

  a.pinMode(13,'output');

  %-- digital i/o

  a.digitalRead(4) % read pin 4

  a.digitalWrite(13,0) % write 0 to pin 13

  %-- analog i/o

  a.analogRead(5) % read analog pin 5

  a.analogWrite(9, 155) % write 155 to analog pin 9


You have to add use your user to the dialout group, as explained in the installation instructions for Linux.

sudo usermod -a -G dialout $USER

Then log out and back in again.


What is the maximum length an Interrupt Service Routine?

As already explained by jwpat7, interrupts are, by default, not
interruptible. Thus, if another interrupt fires while your ISR is
running, it will no be serviced until your ISR completes. This delay you
impose on other interrupts is called latency. So your question boils
down to “how much latency can the other interrupts tolerate”.

There is no simple answer: it all depends on the timing requirements
of whatever those interrupts are servicing. For example:

The millis() counter is updated by interrupts. Any latency longer
than 1024 µs (on the Uno) can make it loose tics.
If you are using the serial port to receive data, a latency longer
than one byte time (1040 µs at 9600 pbs, less at higher baud
rates) will make you loose data.
If you are using the Servo library, any interrupt latency will
create jitter in the drive signal, and at some point this may become
visible as mechanical jitter.

Then, if you really need a precise answer, you will have to check the
timing requirements of every piece of hardware and every library you
are using. And then check the latency already imposed by the ISRs in
those libraries, as your latency can come in top of that.

If your program relies on loop() looping fast enough, you should also
keep in mind that interrupts also slow that.


How to get data from 9DOF razor IMU directly to arduino mega

sscanf should be enough. There is also other options, String class for example with substring method.

Take a look at the example:

#include <stdio.h>

char myString[] = "#YPR=72.13,1.74,-16.38";

void setup() {
  // put your setup code here, to run once:
  float yaw = 0;
  float pitch = 0;
  float roll = 0;

  sscanf(myString, "#YPR=%f,%f,%f", &yaw, &pitch, &roll);
  Serial.println(yaw);
  Serial.println(pitch);
  Serial.println(roll);
}

void loop() {

}


Seeking to measure back EMF of an electric motor via Arduino

There is no need to measure the windings of the motor... please see the great write up for full details using an Arduino to sense the back EMF on a PWM driven motor to control the speed. This can be applied to a 3 phase motor as well, see Back EMF.

This person uses the analog input and a voltage divider to sense when the EMF happened, basically he gets the motor running, then periodically grounds one side of the motor through the H-Bridge he is using to drive it, and the other side of the  motor goes to a voltage divider into the Arduino... and it is also an open circuit at this time so the voltage generated is from the collapsing of the coil field so if it is 12V it becomes a safe 4V at the Arduino Analog input.

Now your question says "measure the back EMF", what I provided senses the back EMF... to measure it you just need to sample the Analog pin a bunch of times, and that will give you a reference of the max amplitude.


Don't worry about the current limit. The board will only draw what it needs. The spec is telling you that the board can draw as much as 1 amp, so in general the power supply should be able to supply that – more is no problem, but less could be if you have a lot of devices attached to the board that are drawing power as well.

As is pointed out in the comment above the higher the input voltage the more power the on-board regulator will need to dissipate (as heat). If you are using the barrel jack (which you should if you aren't providing power through an external regulator or other stable source) there is a diode (D1 in the reference design) in the input path and the MC33269D-5.0 regulator is spec'd with a max dropout voltage of 1.25 V so you will need an input voltage of at least 6.95 V (assuming a 0.7 V drop across the diode).


The backslash escape encoding for special characters is a feature of double quotes in some programming languages, shells, and other parsers.  It is not normally a feature of live text input - an "end user" human typing a backslash is assumed to mean it literally.

"Live" input of a carriage return or newline is more traditionally done with the return/enter key, or with the corresponding control codes - CTRL-J for newline and/or CTRL-M for return.  I don't know that the Arduino IDE's Serial Monitor supports either of these, at least once you select "no line ending"


Sensor that detects when metal sieve is clogged with debris

I would tackle this not from the point of view of the filter, but from the point of view of the water itself.
The water will be impeded by the filter. As the filter gradually clogs that impediment will increase.  The net result will be a slower flow of water through your filter.
There's a number of things you could do to detect that:

Measure the incoming water flow rate and the outgoing water flow rate and calculate the difference.

This would mean having all the water flowing through two flow meters which would complicate your design as the filter will no longer be able to deposit directly into the tank. But when the difference in flow between the in and out sensors gets above a certain point (to be determined by you) then you can safely say that the filter is blocked.

Measure the "backlog" of water. To do this the input portion of the filter will have to be sealed (or largely sealed). Again the filter will impede water flow, and the more it's clogged the more it impedes. Once the impediment becomes too high the water will start "backing up" up the input pipe as it can't get through the filter fast enough. At this time you can detect that rise in water level with a float switch.

You'd have a simpler design now, as the filter can deposit straight into the tank. Whether you want to detect the rise in water level in the incoming pipe itself or in the gap between the filter and where the pipe comes in depends largely on the size of your filter. With a large filter it may be better to have a smaller space at the top and measure in the pipe. That will "amplify" the level rise and make it easier to detect.


Arduino leonardo. Encoder mouse movement

That's a quadrature encoder implemented using photo interrupters. Use a DMM to suss out which half of each is the diode and which is the phototransistor, connect both halves as you would were they independent, and decode the quadrature output.


Allocate object memory statically; intialize it dynamically?

You can use placement syntax to specify an existing allocation in which to instantiate the class.

FOOOBJ foo(0);

 ...

  FOOOBJ *f = new (foo) FOOOBJ(3);


How can I have two Arduino Uno's communicate wirelessly?

ESP8266 is also a good choice. these little guys are really useful and give you a Wi-Fi connection between your Arduino boards.

Also, the cost of one ESP8266 is about $3.. super cheap!


There is no library, and there physically cannot be one. IPv4 is built into the Ethernet shield itself. (It has a Wiznet 510 chip.)

  Shields based on the MicroChip ENC28J60 chip (such as those sold by Ekitszone and Nuelectronics) are suitable for the implementation of an IPv6 or dual IPv4/IPv6 stack. This approach requires the TCP state machine to be implemented in software and results in more complex arduino code.

Source: this tutorial. (You may find it useful, I'd recommenced reading it.)

There is this library for IPv6 on other hardware, not for the official Ethernet shield.


How to change Multiple variable values through Serial Monitor

You are setting the input string's base to 16 instead of 10 in your strtol conversions, which is why you are getting 1280 when you expect 500.


Triggering an SPI transfer with an interrupt in Arduino Due

In general, it's best to do as little as possible in your interrupt service routine (ISR).

resetPhase is your ISR here, and typically it would set a flag or semaphore to signal lower priority code that certain work needs to be done and, in this case, probably nothing more. Then your loop code on noticing the flag is set would clear the flag and do its work.

I imagine the library authors thought SPI.usingInterrupt would ease use of SPI, but performing I/O in an ISR seems a bit contrary to best practices. These concerns are echoed here, along with some other caveats regarding interrupts and ISRs. Possibly not the answer you're looking for, but I hope it helps.


Your code, simplified, is:

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

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

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

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

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


What do symbols like UCSR0C, UMSEL01, etc. means?

Take a look in the datasheet under the "20. USART0" section:

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

I will list the names of the registers, what they are called, and then what your code is doing specifically:

UBRR0H and UBRR0L together form the baud rate divider.  Your program probably uses F_CPU and <util/setbaud.h> to calculate a divider and set the baud rate.  For more information see Table 20-12.
UCSR0A  "USART Control and Status Register n A"  --  This line is enabling the U2X0 which doubles the transmission speed
UCSR0C  "USART Control and Status Register n C" --  This line is enabling the UCSZ01 and UCSZ00 bits to set parity check to "Enabled, Odd Parity".  See Table 20-9.  This line has extra information, all the statements with 0<< actually do nothing.
USCR0B " USART Control and Status Register n B" -- This line is setting the UCSZ02 bit which is described here: "The UCSZn2 bits combined with the UCSZn1:0 bit in UCSRnC sets the number of data bits (Character SiZe) in
a frame the Receiver and Transmitter use. "  This basically allows you to select 9 bit wide serial if you would like (8 bit is more common)
The final USCR0B line enables tx and rx


How to run multiple DC motors in different patterns?

Why not generate a psuedo random number from 0 to 255 and use it as a code for which motors are to be activated - bit 0 == viboutputpin0, etc.? Then one function can look at each bit in turn and activate that motor if the bit is set, delay, and stop the motors.
You'll probably want to test your code with a few pre-defined test patterns instead of the random ones, and once you're satisfied that it works, randomly seed the random number generator so your project will generate a different pattern each time. One way to do that is to ask via terminal for the operator to click the 'Send' button (or tap the space bar if you're using a separate terminal emulator that sends key by key). Measure the time from the request to the response in microseconds, discard the 2 or 3 least significant bits of the result and keep the next 8. The micros() function's resolution is 4 usec at 16 MHz, is the reason for discarding those 2 lower bits.


What precision can I expect by syncronising DS3231 with PC serial?

Transmission time will certainly not be negligible. To estimate it, you could use the roundtrip delay calculation, which is (roughly) how the NTP protocol is implemented in the first place.

at PC time T1, PC sends current time T1 to Arduino via UART
Arduino sets the time T1 in DS3231 via I2C
Arduino reads the time T2 from DS3231 via I2C
Arduino sends the time T2 to PC via UART. This happens at time T3 from PC's point of view.

Now the PC can estimate the half-roundtrip delay R as (T3-T2)/2. See the following chart which denotes current time form POW of PC and RTC

        |--UART--|--I2C--|--------|--I2C--|--UART--|
PC      T1              T1+R     T2+R           T3=T2+2R
DS3231  -                T1       T2              T2+R

Next, at time T4, the PC sends the value (T4+R) via UART. This will result in  DS3231 to be set to (T4+R), which happens exactly R time after T4, so that both clocks are now set to the same value.

Estimation of R can be repeated several times. In this case you can calculate the standard deviation which tells you how much "jitter" your clocks have.


pulseIn() is a blocking function: it waits until it gets a complete
pulse, or until it times out. While it's waiting, the Arduino cannot do
anything else, and it will miss pulses on other channels.

The RC receiver sends the pulses sequentially. Then, if you try to read
them in the right sequence, it may work. If you read them out of
sequence, you will miss some pulses, and the corresponding pulseIn()
calls can timeout, returning zeros.

For this kind of job I would use the pin change interrupt on pins 2 – 7.
This should allow reading the six pulses continuously without blocking
the whole program. But it's low-level (AVR-level) programming, probably
not doable with the standard Arduino libraries.

Edit: Here is what I had in mind when suggesting the use of the pin
change interrupt. Notice that the pin numbers are “hardwired” into the
code and cannot be changed easily. This is because:

Pins 2 – 7 share a single pin change interrupt request
(PCINT2_vect), thus a single ISR is needed to time the six channels.
They also share a port (port D), meaning they can all be read by the
ISR in a single instruction.

The other possible choices having these nice properties would be pins
8 – 13 (PCINT0_vect, port B) or A0 – A5
(PCINT1_vect, port C).

/*
 * Read 6 PWM signals from an RC receiver.
 *
 * Channels 0-5 are on digital pins 2-7 (i.e. PD2-PD7 = PCINT18-23).
 */

// This always contains the last length measured on each channel.
volatile uint16_t last_pulse_lengths[6];

// Interrupt triggered on every change in pins 2-7.
ISR(PCINT2_vect)
{
    static uint8_t last_pin_states;
    static uint16_t start_times[6];  // start time for each channel
    uint8_t pin_states = PIND >> 2;  // shifted to bits 0-5
    uint16_t now = micros();

    // Check every changed bit of the port.
    for (int i = 0; i < 6; i++) {
        uint8_t mask = _BV(i);

        // Record start time on rising edge.
        if ((pin_states & mask) && !(last_pin_states & mask))
            start_times[i] = now;

        // Record pulse length on falling edge.
        if (!(pin_states & mask) && (last_pin_states & mask))
            last_pulse_lengths[i] = now - start_times[i];
    }
    last_pin_states = pin_states;
}

// Return the pulse lengths avoiding race conditions.
static void get_pulse_lengths(uint16_t lengths[6])
{
    for (int i = 0; i < 6; i++) {
        noInterrupts();
        uint16_t tmp = last_pulse_lengths[i];
        interrupts();
        lengths[i] = tmp;
    }
}

void setup()
{
    // Setup the pin change interrupt.
    PCIFR  = _BV(PCIF2);  // clear pin change interrupt flag
    PCICR  = _BV(PCIE2);  // enable pin change interrupt
    PCMSK2 = 0xfc;        // sense changes on pins 2-7 (i.e. PD2-PD7)

    Serial.begin(9600);
}

void loop()
{
    // Report the pulse lengths on the serial console.
    uint16_t pulse_lengths[6];
    get_pulse_lengths(pulse_lengths);
    for (int i = 0; i < 6; i++) {
        Serial.print(pulse_lengths[i]);
        if (i < 5) Serial.print(", ");
        else Serial.println();
    }

    delay(1000);
}


Arduino SoftwareSerial - can't get data from NEO 6M-GPS module

RX of the Arduino (pin 4, according to the SoftwareSerial statement) goes to the TX of the GPS.  Arduino pin 3 (ss TX) goes to the GPS RX.

And you should use pins 8 & 9 instead.  That would let you use AltSoftSerial, the best choice when you can't use HardwareSerial (i.e., Serial).

If you can't use pins 8 & 9, then NeoSWSerial is a better choice than SoftwareSerial.

And while I'm promoting NeoSWSerial, I'll mention a library I wrote, NeoGPS...  It's faster and smaller than all other GPS libraries, and very configurable.  It also has several diagnostic programs and a Troubleshooting section in the docs.


Is the DHT.h library compatible with ESP8266 Arduino IDE compiler?

As far as I see, the DHT sensor library does bit-banging, which is kind of expected given the ad-hoc nature of the protocol that DHT type of sensors utilize. It should be compatible, as the library doesn't use any Atmel-specific features of the MCU.


Servos stop after a while in case of 8 servo motor control

If Adafruit say to use the kit to drive multiple servos you need to add a cap and without the cap you can't drive multiple servos, then yes your first port of call should be to add the cap.

However that's probably not all that's wrong.  If it runs for a bit before dying then it could be a number of causes.

Not enough power.
Something is overheating.
Code problem.

Use a decent transformer with more than enough amps to power your motors.
Use your nose, does something smell hot?  If you use your fingers you will get burnt!
We can't fix invisible code.


Problem with code for IR remote controlled robot

Try replacing you loop function with this one.  It won't fix it.

void loop()
{
    if (irrecv.decode(&results))
    {
        Serial.println(results.value, HEX);

        switch (results.value)
        {
        case Straight:
            moveForward();
            break;
        case Right:
            turnRight();
            break;
        case Left:
            turnLeft();
            break;
        case Back:
            moveBackward();
            break;
        default:
            Stop();
        }
        irrecv.resume();
    }
    else
    {
        Serial.println ("Nothing received");    // This message will annoy you so comment it out as soon as you are happy with what is happening.
    delay(100);
}

The switch statement is just a neater way of doing your ifs.  The Nothing received message will show you if decode is ever returning.  If it is returning you need to work out why it is returning false, by looking in the library code.  If it isn't returning then you need to look in the library code and see why.  If it is returning, but not giving you an expected value, you need to look in the library code and see why.

Sorry but from what you describe it seems to be an issue with the library or your use of it, could be anything, but when you can get some more info post it back here.


How can I connect H-Bridge motor driver (using four 2n222 transistors) to Arduino?

I am not an electronics guru yet either so others might give you a better answer, but this is one circuit I have messed with a lot because I keep trying to build robots, so I will take a shot at an answer.

Normally you need both NPN and PNP transistors for an H-bridge:

The 2N222 is NPN so you'd want to pair two of them with two equivalent PNPs such as the 2N2907.

I've see diagrams that have all NPNs but I have never gotten a circuit to work that way. There is a distinction about where the load goes, before or after the transistor, that makes you chose to use an NPN or a PNP in order to make it all flow properly.


How to setup Uno + xbee shield 1.1 + wee wifi chip?

As far as the Wi-Fi and Uno is concerned, it's not too difficult. You should download its library for Arduino, which is available on Github and then try its example named Wifi Client.

In this example, change your SSID and password, and run serial terminal. It will show you that your Arduino is connected to Wi-Fi and it will also display your IP Address.

Now enter this IP address in your browser and it's like you are pinging your Wi-Fi shield.  Soon it will display your analog values. Just make sure your computer and your Wi-Fi chip are connected to the same Wi-Fi connections.


unexpected primary-expression before ';' token

1) You should be using:

myservo.write(pos);

instead of

servo.write(pos);

for all of your  methods.

2) Change:

include #include<Servo.h>

to

#include <Servo.h>

This code only verifies when it is run on certain boards*, so make sure you are using one of those boards.Good luck and welcome to the Arduino world!:)

*Verify that your board will work, I know Mega, Uno and Nano will function properly.

P.s. Here is the whole code in correct format:

#include <Servo.h>

int pos = 0;

Servo myservo;
void setup() {
 pinMode(2, INPUT);
 pinMode(3, INPUT);
 myservo.attach(9);
}
void loop()
{
  if ( (digitalRead(2) == HIGH) && (pos < 180)) {
    pos++;
    myservo.write(pos);
    delay(15);
  }
  if ( (digitalRead(3) == HIGH) && (pos > 0)) {
    pos--;
    myservo.write(pos);
    delay(15);
  }
}


Maximum power rating for Arduino UNO revision 2 (SMD)

The Arduno UNO SMD R2 uses an MCP33269 not an LM1117.  What you have is probably some cheap Chinese clone of the Arduino, and in that case the regulator will be the cheapest Chinese copy of the LM1117 available.  It's impossible to tell what the specs of that specific chip are.  Suffice it to say, though, that the specs of the chip are pretty much irrelevant since they rely on good heatsinking, which you most certainly don't have on a little Arduino board.

500mA, though, is a lot to push through a linear regulator like that, and when running from batteries the excess power loss imposed by the regulator will be a major factor in longevity.

You are better off investing in a proper switching regulator (such as a UBEC from a model aircraft supplier like Hobbyking).


Cannot display a chr string using Wire.read() and u8g2.drawStr()

This is kind of convoluted to put as a comment and it is sort of an answer, so I'm making it an answer.  Just to warn you, I have not tried to compile any of the code snippets here.
Wire.onReceive(receiveData); registers your function so that it can be later called back in the context of the interrupt service routine used for handling I2C ("Wire") data.  Or at least this is how it usually works.  So when your receiveData function is running you are in the middle of handling an interrupt associated with the I2C peripheral.
Using Serial.print(), .println(), .write(), and many other things, including non-serial related things like delay() inside of an interrupt service is usually a no-no.  On the AVR Arduino core, if the outbound serial buffer happens to fill, your code will deadlock with the underlying .write() waiting for there to be room in the outbound serial buffer and the serial transmit interrupt waiting for .write() to get done waiting for it.  I don't know how the Teensy LC and its MCU are configured, whether or not it prioritizes interrupts, etc, but it is likely that you're still not supposed to call functions like these inside the interrupt context.
There's really not a lot you're supposed to do in an ISR except:

communicate with hardware (which is being done for you here)
manage the non-volatile variables that belong to the ISR itself.
set global volatile qualified variables to communicate with the main line of execution.
call functions that have no shared state with the main line of execution.
call functions that have shared state but are carefully designed to be called from both ISR contexts and main line of execution.

That said, I don't know precisely why you're seeing what you're seeing, but I'm not overly surprised either.  The above may be related to it, but I haven't drawn that connection yet.
The way you currently have receiveData, it may overflow buf.  All that's required for that is for the sending side to send more than 15 bytes.  Any number of weird things can happen if you manage to overflow.  Is it related? Maybe.
For communicating between the receiveData running in the ISR context and the main line of execution in loop, buf should be volatile qualified.  Without that the main line of execution can behave as though buf never changes after it is first seen.  Because of how you're using it and familiarity with the compiler, I'm going to guess that this isn't manifesting as a bug, but I don't know that; it could be related.
So I'd recommend updating something like your buf declaration to volatile qualified and removing the Serial print calls from the receiveData function, and preventing overflow:
volatile char buf[16];

/// ...

void receiveData(int byteCount){
  static const size_t room_for_non_null_chars = sizeof buf - 1;
  const size_t read_amount = min(byteCount, room_for_non_null_chars);

  int i;
  for (i = 0; i < read_amount; ++i) {
    buf[i] = Wire.read();
  }

  buf[i] = '\0';
}

If it weren't for the fact that we need to read into something volatile qualified the above loop could really just be a read call taking the buffer and size.  You can see that's updated to prevent overflow.
Part of loop would then become something like:
void loop() {
  char non_volatile_buf[sizeof buf];
  size_t write_index = 0;

  noInterrupts();
  for (char c: buf) {
    non_volatile_buf[write_index++] = c;
  }
  interrupts();

  // U8G2 setup code snipped
  // This line doesn't output anything on the screen:
  u8g2.drawStr(0, 0, non_volatile_buf);

  // ...

We're turning off interrupts while copying the data into a local buffer so that the onReceive handler cannot interrupt the use of the buf, updating while you're in the middle of using it in drawStr.
If you care about losing messages there's more that would need to be done.  Surrounding what to do if you've got a call to receiveData while there's a message currently in buf.  The way the above is written it just drops whatever is in there whether it's been seen by loop() or not.


Selected board depends on 'arduino' core (not installed)

I needed to install the boards package for:

Arduino AVR Boards

Under Tools -> Board -> Board Manager


Can I use 1 clock module for multiple Arduinos?

The LCD is connected over SPI. The MCU can be an I2C slave and the SPI master. There is no conflict.


How to connect the 3.3v pin of arduino mega to multiple sensors

You can connect all of them as long as the total current draw is not over 50mA as described here. If you need more than 50mA, you need to create your own 3.3v supply or use something like a breadboard power supply for instance (keep in mind to make a shared ground line).


As explained in Michel Keijzers' answer, you cannot use the = operator
to assign something to a string (a character array). However, you can
initialize a string using =. There is an important distinction
between assignment, which you can do anywhere in a program, an
initialization, which can only be done at the time you define a
variable.

For example:

int i = 2;  // initialization

void setup() {
    i = 4;  // assignment
}

In your specific case, you can initialize fields as follows:

struct s_field_def fields[2] = {
    {"HALTED", FALSE},  // displays the current run state
    {"@", TRUE}         // displays indicator of system running
};


First Serial.print voltage is wrong, way too low. Ruins average calculation

The code at the link is mediocre – it has dozens of unnecessary casts or declarations, dozens of superfluous statements, and numerous unused or unnecessary variables.  Also, the code shown there has nothing about any averages, so evidently does not show whatever code you actually are running.  You could revise your question and include the actual sketch within it.

Nevertheless, the code at the link looks like it will take a reading ok.  Possibly your modifications, whatever they are, incorrectly initialize variables for the running average calculation, or incorrectly initialize some other variable not shown.  Or there may be some hardware glitch that spoils the first reading.

Several fixes are possible.  You could discard the first reading.   You could discard the first reading of each set of readings.  You could take readings in sets of three or five and only keep the median reading.  You could take sets of readings and discard the highest and lowest readings.  You could apply exponential smoothing or some other form of smoothing to the readings.

Note, the formula you show for averaging – ((count-1)/count)*volt_mV + (1/count)*volt_V – has a number of problems.  First, if count is an integer, both of ((count-1)/count) and (1/count) will compute to zero values.  Secondly, as count becomes large, you will be adding a tiny value to a much larger value, which is ill-conditioned arithmetic.  Third, although the formula computes a running average, it does not compute a moving average.  That is, your formula computes the average of all readings taken so far, with all readings equally weighted.  A moving average, on the other hand, typically will weight recent readings more heavily than old readings, for example via a window technique or via an exponential smoothing formula like movingAverage = (15*movingAverage + newReading)/16.


Yes, you can do that by cross-connecting the transmit and receive pins on the Arduino. But then your devices sits there silently murmuring to itself (or not...) and you can't really tell what it's saying, or if it's doing anything unless you can observe some other hardware - LEDs, a 'scope, f/ex.

But why not hand-type or script some messages to it on your PC? If the Arduino sketch would make some brief, coherent replies you could confirm what it's doing and debug it if necessary.

I've done just this in your situation: Two of us defined a serial protocol - the ASCII (for human readability!) commands and replies that either end could make or expect. Then each of us wrote the communication code for one of the two devices and proved that it met the protocol. Once both of us had finished and were confident in our respected communication code, we plugged the two devices together, and - they played! Nicely! :)  And if they hadn't we could have eavesdropped on the serial line and printed their attempted conversation to discover where it went wrong.


ESP-12e, Arduino IDE, NeoPixel Strip - Flickering

Have a google for (WS2812 or Neopixels) and ESP, it should give several good hints on how to wire it up reliably. Also really read this: https://learn.adafruit.com/adafruit-neopixel-uberguide/overview .

But some things to consider:

WS2812 requires 5V, so you do want to use a 5v source, not 3.3v.
Make sure all your grounds are connected together, especially if you have a separate power supply for the leds.
The data input on the WS2812 needs a 5v high signal, especially when the WS2812 is (correctly) powered by 5v. This means you probably need some kind of level shifter, which needs to be able to switch fast as well, cause it's a pretty high frequency signal.
224 WS2812's can chew up a lot of power, so make sure your 5v source can handle that. When all are set to full white, it's 20ma per color per led, that's 60ma per led, so 13,44 AMP maximum. Your average USB charger isn't gonna cope with that :) You can use a power supply which provides less power if you make sure you only turn on a few leds/colors at a time, but if you accidentially turn on more, voltage is gonna drop and stuff will stop working :)


Driving single-character alphanumeric (16-segment) displays

If you need additional IO lines, a typical “LCD backpack” supplies at most eight additional lines of IO; 16-channel TLC59116 LED Driver Board as mentioned by Majenko would be more elegant than using several backpacks.

You might try an approach like the following to see if it works well enough.

Use 16 IO lines to pull down 16 segment lines.  Use three IO lines to drive three digit-select PNP or PFET transistors for digit multiplexing.  Use pin-change interrupts on two IO lines to read rotary encoder (RE) data.  Use one input to read the RE pushbutton.  Use one IO line to notify the bigger unit of success.  Total 23 IO lines.

In operation, your code will need to implement a state machine that frequently refreshes the multiplexed digits while keeping track of digit values, selected digit, etc.  Each time you click the RE have your sketch go on to the next digit.  To tell the user which digit is working, blink the selected digit a couple of times after the RE press.  Each time that selection wraps around to the first digit, check if the combination is correct.

If you feel it's necessary to have three different digit-setting knobs, vs clicking through to each digit, you could use one less IO line by using three pots instead of one RE.  The pots would be read in analog.  A6 and A7, IIRC not usable for output lines, could be used as analog inputs for two of the pots.


It would appear that the output of the power regulator pin has been vaporized.

From the Arduino R3 schematic we see this part as U1 which is an NCP1117ST50T3G power regulator.  Here is that data sheet for that part. From that data sheet we see the physical image of the part.

It appears that pin 2 has been vaporized.  If we look at the schematic of the Arduino R3 we see where pin 2 supplies the regulated power to the rest of the Arduino board and likely any connected electronics.  Note the red "X" indicating the vaporized pin 2.

The schematic and the data sheet both indicate the regulator's TAB is also an output.  If true it is difficult to explain why pin 2 vaporized.  Perhaps this particular version of the regulator does not use the TAB as an output.  Or perhaps the Arduino R3 PCB and schematic do not agree.

Added later...

There has been a comment that U1 (the NCP1117ST50T3G power regulator) may sometimes be manufactured with out the center pin.  Still, if you can power the Arduino R3 using the USB port and unable to power the Arduino R3 using power through the barrel jack, the likely suspects are U1 and D1.  However, to be sure, you would have to check the voltage before D1 and after U1.


AM (Amplitude Modulation) varies the amplitude of the carrier based on the input signal. So, assuming you had some circuitry (LC circuit) to receive a particular carrier frequency and managed to boost the voltage so that it was in the range 0-5v then you would able to feed this to an analog input on the Arduino.

AnalogRead requires around 100uS per sample, so your max sampling rate would be 10K/s, which might just cut it for voice (up to 3.4Khz, sampling at least 2 * the highest freq).

However, you then need to do something with the sample value (in code) and depending on how long that 'something' takes, your actual sample rate will be reduced.


Recognize peak in specific frequency area

You can filter the signal and look at the power that lies within the
frequency range you are interested about. You could use an FFT for that,
but it is quite computationally expensive. If you go for the FFT, you
would probably end up sampling the mic in small bursts (a few
milliseconds sampled every few tens of milliseconds), as the Arduino
would spend most of its time processing the data.
A better option is probably to work in the time domain, rather than the
frequency domain. If you do not need to know exactly how much power lies
in each frequency bin, and are only interested in the total power within
the window of interest, then the FFT is computing too much stuff you do
not need. A less computationally expensive option would be to run the
samples through a digital band pass filter tailored to the band you
want. You can then compute the power from the output of the filter and
low-pass it:
raw_sample = sample_the_microphone_somehow();
filtered_signal = bandpass_filter(raw_sample);
instantaneous_power = filtered_signal * filtered_signal:
smoothed_power = low_pass_filter(instantaneous_power);

But you would still need a beefy Arduino if you want to be able to
acquire and process the samples at a reasonable rate: at least twice the
highest frequency that comes out of the microphone.
A still better option could be to do the filtering in the analog domain,
before the signal reaches the Arduino. If you can at least remove the
frequency components above 5 kHz, then the Arduino would only need
to sample at 10 kS/s, and run a digital high pass filter to remove
the part of the signal below 1 kHz. This should be easy enough even
for an AVR-based Arduino.
For the implementation of the filters, you may want to try this online
filter builder


Why am I only receiving the first address byte? (I2C Protocol)

(Acknowledging this is an old question.) The TI article "Troubleshooting I2C Bus Protocol", suggests several common reasons for no ACK:
1. Timing
2. Missing / Unexpected SCL pulses
3. Incomplete 8 bit block
4. Missing Bytes
5. False slave address
6. Unsuccessful address change


You do not need an RTC to build a clock: the ATmega chip has all the
hardware needed to perform the duties of the RTC itself. Here is how:

Get a 32768 Hz watch crystal: either buy it or disassemble an
old clock. These crystals, specifically designed for time keeping,
have an extremely small temperature drift. You would also need one
of those if you wanted to use an RTC chip.
Configure the fuses of your ATmega to run off the 8 MHz RC
oscillator. This will make your millis() function horribly
inaccurate, and also free the XTAL1 and XTAL2 pins.
Connect the watch crystal to the TOSC1 and TOSC2 pins. These are the
same pins as XTAL1 and XTAL2 (9 and 10 on the 328P). The different
names are used to mean different functions.
Configure the Timer/Counter 2 for asynchronous operation, normal
counting mode, prescaler set to 128, and enable the timer overflow
interrupt.

Now you will get a TIMER2_OVF interrupt at a very steady rate of once
per second. You only need to advance the clock display by one second in
the ISR. In between the interrupts, you can put the MCU in very deep
sleep (power-save sleep mode: nothing runs but Timer/Counter 2) and run
for years on a couple of AA cells. Unless the display is power-hungry,
obviously.

I did exactly this to build my 24-hour one handed wall
clock.
This link points now to the English translation of the original
documentation in French.

Quartz calibration

If you do not calibrate your quartz, you can expect a significant drift,
typically a few seconds per week. The drift rate depends on the
stray capacitance of the traces that connect the crystal to the MCU. In
principle, it could be removed by adding some extra, finely tuned
capacitance. It is worth noting that you would have the same drift
problem with an RTC.

If you are satisfied with this kind of accuracy, then live with it and
be happy. However, if you care to measure the drift, you will notice
that it is very stable. You can then easily compensate for it in
software, and achieve an accuracy of a few seconds per year.

The algorithm for correcting the drift is very simple. From the measured
drift, you figure out the precise delay between the interrupts, which
should be very close to 109 nanoseconds, then:

#define ONE_SECOND    1000000000  // in nanoseconds
#define ONE_INTERRUPT  999993482  // for example

ISR(TIMER2_OVF_vect)
{
    static uint32_t unaccounted_time;

    unaccounted_time += ONE_INTERRUPT;
    while (unaccounted_time >= ONE_SECOND) {
        advance_display_by_one_second();
        unaccounted_time -= ONE_SECOND;
    }
}

In the above example, the quartz is slightly too fast, and the software
compensates by “missing” a tick every few days. If the quartz was too
slow, the same code would instead double-tick once every few days.

This kind of calibration could also be done for an RTC, but it would be
significantly more complex because the RTC reports the time in a
broken-down form that does not naturally lend itself to arithmetic
operations.


You only have two external interrupts on the Uno, so a simple solution would be to call an "intermediate" routine, which remembers the button number. eg.

  attachInterrupt(digitalPinToInterrupt(2),this->int_handler2,RISING);
  attachInterrupt(digitalPinToInterrupt(3),this->int_handler3,RISING);

Those two functions could then call your main function passing down 2 or 3 depending on which one was called.

eg.

void int_handler2 ()
  {
  int_handler (2);
  }

void int_handler3 ()
  {
  int_handler (3);
  }

If you have more switches than that you can use pin-change interrupts. The typical way of detecting which one fired is to see which bits are different this time, compared to last time.

See my page about interrupts.


How to control low power devices when implementing Low Power Mode strategy?

Yes, MOSFETs are what you want.

The temptation is to just insert any old logic-level N-channel MOSFET in the ground connection to the device like you would when driving a relay, etc. However that method is fraught with danger. You get such issues as ground-level offsets (where ground isn't actually ground but some mV above ground) which can result in logic level mismatch problems. You get the possibility of power trying to make its way to ground through the device's IO pins and your MCU, etc.

So it is best to instead use a P-channel MOSFET to switch the positive power rail to the device. If the voltage you are switching is the same as the voltage you are doing the switching with (i.e., you are switching 5V using a 5V-level GPIO pin such as on an Arduino) then that is really all you need. However if the voltage you want to switch is higher then you will need to switch the P-channel MOSFET with an N-channel MOSFET, or an NPN BJT.

Here's two schemes:

simulate this circuit – Schematic created using CircuitLab

In the left schematic M1 is kept off by R2, and pulling the control GPIO low it turns M1 on allowing the current to flow.

In the right schematic M1 is kept off by R2 in the same way, but M2, when turned on by the GPIO being driven HIGH. R3 keeps M2 off while the MCU is not ready to drive the GPIO pin yet (in the bootloader, etc).

One thing to remember when switching the power off on either schematic is to first set all the GPIO pins that communicate directly with the device to INPUT mode. That will prevent them trying to power the target device through the IO pins (which will typically have ESD diodes that would feed current to Vcc).

All MOSFETs should be logic level (except M1 in the right schematic which can have a higher threshold depending on the voltage you are switching - best to keep it all logic level though as a rule).


Not directly. The standard Arduino Uno doesn't have the hardware/software necessary to act as a USB host, which means it can't talk directly to other USB devices.

You might be able to get it work via a USB Host Shield. I don't know how compatible that is with GSM dongles though because I assume you can't install drivers on it. Additionally, if you're using a shield anyway, you might as well use a GSM shield.

If you're able to get an alternative board then another possibility might be the Arduino Yún. It has a USB host built-in which is operated by the Linux part of the board. I don't know for certain that it would handle a GSM dongle, but it may be worth looking into.


Your best strategy would be to write your own bootloader.

The existing bootloader receives data through the serial port and writes it, a page at a time, to the flash.  Your custom bootloader, instead, would receive the data through the nRF module and write it to flash, a page at a time.

You could use the source code for the existing bootloader (maybe use optiboot?) as a starting point and remove the UART code, replacing it with nRF code.

Of course, you still need a way to enter the bootloader when you want to program it - the easiest way is to ensure that is added into any sketch you upload so you can send an instruction to that sketch to enter the bootloader.

You would also need to create a program on the Pi to do the programming over the air - or modify an existing one like avrdude.

It may, in the long run, be simpler to have a pair of other Arduinos (maybe something small like an ATTiny based board) to act as bridges between UART and the nRF modules so they become a transparent wireless serial link.


Can the Arduino Eclipse plugin v2.2 be used with Arduino 1.5.8?

V2.2 is pretty old by now.
As far as I recall it should work fine.

V2.2 of the Arduino eclipse plugin should work fine with the Arduino IDE version 1.5.8.
What that phrase wants to say is: the plugin V2.2 was released before Arduino IDE 1.5.8 was released; as such the code can not make a statement on the compatibility.

But again V2.2 is old. We hope to release V3.0 end of February 2016


Is it safe to power Arduino project using a power bank and wall charger?

Yes you can.  A promini will run very well on 5V from a wallwart.  Connect 5V to VCC (not RAW or VIN).  You can also find wallwarts with 2.1mm/5.5mm plugs, and a mating barrel jack adapter that ends in screw terminals so you don't have to try hacking up a USB cable.

Power bank, you will have to play games to convince it that something is connected and drawing sufficient current to keep it turned on.

Wallwart example  https://www.mpja.com/5-Volt-DC-Plug-Power-Supply-4A-Regulated/productinfo/18520+PS/

Barrel jack to screw terminal adapter example  https://www.mpja.com/55_21mm-Power-Jack-Screw-Terminals/productinfo/19454+PL/


`.readFileCounts()` not working on DFPlayer mini module

These DFPlayer modules are more difficult to drive than the examples suggest. Whenever you send a command to the DFPlayer (such as player.setVolume(30)) the module will return some sort of acknowledgement or a status command.  You need to be calling the player.available() method and then player.readType() and player.read() continually in loop() to keep the SoftwareSerial buffer free before you try sending commands. So calling player.setVolume(30) and then player.readFileCounts() in setup() may be overfilling the buffer before you start clearing it and the buffer will contain unread messages that are not the expected file count reply thus confusing the library. The other thing to consider is that it takes the module a second or two to initialise the SD card after .begin() and you really need to wait for the DFPlayerCardOnline status message to come in before you can ask for file counts.

I've written a more comprehensive library to drive these but it's not mature enough to share yet.


How to detect patterns in an FFT output?

It depends.

First you need to break the problem in steps:

If you can make a static analysis, than there is a chance. Meaning, if you can record a snapshot of the howl, and than spend some time processing it.
If you need to process it (almost) real time, than I am almost sure the Arduino is way too slow for that. In the next steps will be clear why, and otherwise you can use the next steps to get some idea how to do the analysis.
Assume you can do a snapshot of the sound, than you have to store it. The Arduino has only 2 KB of SRAM which is way too small. I assume you want a decent frequency (let's say 40 KHz) of mono (1 channel) samples, which is 40 KB of memory.
You need to record this (probably any sound sensor will be fast enough), and store it to some device, either external SRAM (fastest, most expensive), external EEPROM (somewhere in the middle) or SD card (might be slow). EEPROM/SD cannot be written 'forever' so if you want to process a sample every second, you might run in trouble.
Than you need to run your algorithm over the static data. I do not know this algorithm, if you have to iterate many times, forget about using SD, use SRAM or EEPROM.
Otherwise, read a few blocks (typically 2 or 3, to get 1 or 1.5 KB) and process it. I hope you can store the result also in the Arduino, otherwise write it (if you write much, probably SRAM is the only well feasible solution).

As you can see, you have to break your problem into smaller pieces, and check how the algorithm works (does it need a lot of data, or a snapshot), can it be processed in pieces, or does it need to iterate over the entire sample data a lot, are there intermediate results need to be stored etc.

Note there might be other solutions:

If you need more speed, try an Arduino Due
If you need more (internal) SRAM, try a Mega (8 KB) or Due (48 KB)


How to print a line with a variable in it?

I use:

Serial.println("The temperature is " + String(temperature) + " degrees C");

With this solution you can't format the variable's value but I find this quick and dirty for debug messages.


Arduino receives no external UART comms after Serial.begin(9600)

Solved. I double crossed the rx/tx connection which made it wrong again... stupidity attacks


Trouble uploading sketch / error in sketch

I am guessing you have connected 2 arduinos together using their hardware serial ports while uploading. This cause uploading to fail as those ports are getting two signals at the same time.

Break this connection before upload and then it should work. You can reconnect them after upload.

If you want to avoid this you can use different pins with software serials for communication.

Also consider using Serial.available() on the reading end to see if there is data to be read.


The ESP8266 just doesn't have sufficient CPU power to do this reliably.

It is possible, since the EPS8266 SDK docs have an "SSL User Manual" which describes this scenario.

In my experience, using the Arduino core for ESP8266, it doesn't work reliably.

Consider using an nginx reverse-proxy and having that proxy handle SSL negotiation. Understand that this is more for situations where the ESP8266 is local, in a network sense, to the nginx proxy, and you consider your WLAN secure enough.

On the plus side, you have room to grow in key sizes and/or complexity.