If you have Arduino/Genuino Uno selected as your board in the Tools ► Board ► menu, then you get the error. If you select Arduino Leonardo it compiles correctly.

From Can't seem to be able use Keyboard.h library, this post states:

  Keyboard.h (and Mouse.h) only works on devices that use the ATmega32u4 processor, like the Leonardo or Micro.  See: https://www.arduino.cc/en/Reference/MouseKeyboard

This solution might help though

  I had the same problem using Flora

  This worked for me:

  Tools > Boards > Boards Manager
  Install TeeOnArdu (Then select that board from Boards Manager)
  Tools > USB Type > Serial, Keyboard, Mouse < Joypad
  Upload and run code again (might need to restart IDE)


Powering Arduino Uno from 5V pin, what exactly is the voltage range/tolerance?

Unfortunately there is no one "clear cut" answer for all you ask.

There are some hard limits, though, which you can get from the main chip's datasheet:

  Operating Voltage: 1.8 - 5.5V

But that's not the whole story. The minimum voltage depends on the clock speed of the chip, as shown in this graph:

But wait, there's more. The Arduino also contains a 3.3V regulator which is fed from the 5V supply. That will have a minimum voltage above 3.3V that it needs to maintain a 3.3V output. So if you want to use the 3.3V regulator then, according to the datasheet for the regulator (LP2985-33DVBR):

  3 Description
  The LP2985-N low noise linear (LDO) regulator delivers up to 150mA output current and only requires 300mV dropout voltage of input to output.

So a minimum of 3.3 + 0.3V, or 3.6V.

That gives you a usable range, clock frequency permitting, of 3.6V to 5.5V.

As to how to protect the Arduino from a power-on spike like you describe - you could:

Add your own extra regulation in the form of a 5.1V zener diode.
Add a dummy load which the Arduino can switch out of the circuit once booted up
Change your source to something with better regulation
Ignore it - the regulation with even a light load will be considerably better than open circuit.  Add a resistor across your supply that would draw much less than 60mA and measure the voltage. See how bad the regulation at low load is.


dutyCycle = analogRead (0) / 1023;    // dutyCycle potentiometer is at analong pin 0

Dividing a small integer by a bigger integer leaves you with 0. If analogRead() returns 1023 you will get a result of 1. Everything else will give you 0. You need to divide by a floating point number - either 1023.0 or 1023f.

analogRead() is slow. Because it is happening between every single cycle of your square wave you can expect to never get to anywhere near 100% duty cycle. There will always be a LOW period where the analog input is being read.

You should:

Fix your integer division problem
Make the ADC "free running" or interrupt driven so it doesn't interfere with your PWM generation

... Or ...

Fix your integer division problem
Make your PWM generation timer driven, either using the OC peripheral or manually with interrupts, so it doesn't interfere with the analog reading.

... Or ...

You could even do both. Make everything as asynchronous as possible leaving your loop() free to just do the heavy work of calculating the values.


Sure you can. This site isn't a great place for open-ended questions like this though. Since you have a serious real-world need I'll give you some guidance anyway.

You'd need to break it into pieces and solve each one in turn.

First create code that recognizes long and short presses (not using delay().) You'll probably want to respond on releasing the button, since at that point it's easy to tell if it was a long or a short press.

The pseudo-code might look something like this:

void loop()
   if button_is_pressed
      if !press_in_progress
         press_in_progress = true
         start = millis()
   else
      if press_in_progress //Button has been released
         elapsed = millis() - start
         press_in_progress = false
         if elapsed > long_press_threshold
            long_press_function()
         else
            short_press_function()

For controlling the relays, I suggest getting "digital" relays that are made to be controlled with 5V logic signals. Relays like this work well. (Link). Since you need to control 4 relays, a 4 channel model like this one would be a better choice. Note that you'll need a fairly high current power supply. A 2A 5V regulated supply should be plenty for both your Arduino and your relays, although it's more of a sure thing if you use separate power supplies for the arduino and the relays (that way the voltage to the arduino doesn't bounce around as the relays energize and de-energize.

You'll need a global variable for the currently active relay. The long press would increment that value modulo 4: (going from 0 to 3 and then back to 0)

relay_index = (relay_index + 1) % 4;

You'd need an array of 4 bools for the states of each relay:

bool relay_states[4];

The short press would toggle the state of the current relay

relay_states[relay_index] = !relay_states[relay_index];

Note that if you're more interested in solving your wheelchair problem cost-effectively than tinkering, this is the sort of thing that a maker space would be ideal for. There are lots of tinkerers there who love a challenge, and would likely pitch in and help you.


Sparkfun CCS811 sensor not interfacing with arduino

The problem was on the soldering part. SDA & 3.3V pin on sensor were slightly in contact. I modified it and started working fine.


What do I need to make fluffy toys move and talk?

You will need a processor board, motor driver, sensors, and audio amplifier.

Since you are asking on the Arduino forum, it would be natural to consider one of the Arduino boards or derivates - but beware they tend to be rather antiquated compared to alternatives now available.  The plus side of the classic ATmega boards is the wide variety of read-to-go example code available right within the IDE, and the wide supply voltage range (of the bare chips if not the boards) which is more compatible with AA-cell battery packs than competing device's narrower voltage range tends to be.  The one part of the functionality you describe that is a bit of an issue is the audio output - you can get it from an ATmega but it will be poor in quality and you will need to add storage for the "bark" data.  You might almost consider a separate module with an ATtiny and a small SD card for that (ironically the ATtiny while generally less capable has fast PWM better suited to audio).

For motor drivers, especially when using batteries steer clear of the older bipolar L293/L298 type of solutions, as these have very high internal loss which basically means that one cell in your battery pack exists just to generate heat in the driver IC.  A modern FET based driver (the TB6612FNG is quite popular) will be better.

For sensors you probably want one or more of microswitches extended with "whiskers", ultrasonic rangefinders, or short range IR reflectance.

Some dual wheel drive (or "tank steering") RC toys can be worth considering as platforms, but their gearing may be too fast for your purposes, particularly those designed to spin and tumble.  Continuous rotation servos are sometimes mentioned, but it can be hard to get them tuned to not rotate when commanded to stop, and mounting wheels can be tricky.  The small plastic gearboxes work well if you can get matching wheels but are hard themselves to mount.  Access to a 3d printer can be quite useful for creating missing physical components, though a block of wood and a router can make a nice chassis, too.  You can also buy ready made Arduino robot base kits with chassis, gearboxes, and wheels.

For audio output, you can accomplish something with an NPN transistor and base resistor driving a speaker, but best results would be with a small class D driver board as are now widely sold for a few dollars.  They tend to be stereo, but you can feed both sides with the same signal.  If you only wanted "robot beeps" you can drive a piezo disk directly from a processor pin with reasonable loudness at higher frequencies, but the low frequency response is quite poor.


How to use a precompiled library in a project with Arduino-IDE

See https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification

  library.properties file format
  [...]
  precompiled - (available from Arduino IDE 1.8.6/arduino-builder 1.4.0) (optional) set to true to allow the use of .a (archive) and .so (shared object) files. The .a/.so file must be located at src/{build.mcu} where {build.mcu} is the architecture name of the target the file was compiled for. Ex: cortex-m3 for the Arduino DUE. The static library should be linked as an ldflag.

So with the correct metadata and file layout the precompiled objects should be available.
You'll need to set the architectures property to indicate you're using esp8266 as your tag suggests.

More info on the library manager here https://github.com/arduino/Arduino/wiki/Library-Manager-FAQ including how to add to the public library list.


What have you selected as the analog reference? And if 'external', what is connected to the Vref pin?

For the LDR resistances of 10K and 1K, you  Vout should be ~ 1.8v at 10K, and ~ 4.2v at 1K, and giving A/D readings of somewhere around 370 counts and 860 counts, respectively, with a 5v analog reference.

If your analog reference selected to the 1.1v internal reference, either LDR resistance should give you the max reading, but an LDR = 20K could give just over a volt and pretty close to the reading you're getting.


Arduino function to fade from one RGB color to the next

There is no delay in there. It will fade very quickly, add a delay e.g. 5ms with n = 200 for a 1 second fade:

int n = 200;
for (int i = 0; i < n; i++)
{
    Rnew = Rstart + (Rend - Rstart) * i / n;
    Gnew = Gstart + (Gend - Gstart) * i / n;
    Bnew = Bstart + (Bend - Bstart) * i / n;

    // Set pixel color here.
    strip.setPixelColor(0, strip.Color(Rnew, Gnew, Bnew));

    delay(5);
}

The other thing is your last value of n in the loop is 199, not 200, and thus Rnew etc don't have the correct final value. Change the comparison to be <= not <:

for (int i = 0; i <= n; i++)


The biggest problem is that updating the LEDs is an intensive task.

Hand-crafted assembly is written to get the timing right
Interrupts are disabled while the update is running
88 LEDs take a (relatively) long time to update.

At about 1.2µS per LED plus 50µS for the reset pulse, you're looking at about 155µS that the Arduino can't be doing anything else at all. That includes receiving anything through serial.  And since you update for every note you receive, if there is a second note coming in with 155µS of that one, it will be missed.

You may get better results with the FastLED library instead of the Adafruit Neopixel library, but ideally you want to work with a board that is fast enough to not need to do such tight bit-banging for the protocol, so that interrupts can still be enabled for receiving data.


NRF24L01 integrated antenna exposed out of the box

In general no, this would make little or no difference. PVC has very little effect on RF signals.

After all, the antenna on your typical WiFi router is inside a PVC tube and it doesn't suffer from it.

Instead you would do better constructing a dipole antenna from a couple of pieces of carefully measured wire.

For instance this instructable tells you how.


Arduino UNO doesn't produce expected square waveform

As I explained in my comment, the reason for this glitch is the Timer 0
overflow interrupt kicking in every 1024 µs. This interrupt is used
by the Arduino core library for timekeeping. It is the basis of
millis(), micros() and delay(). The interrupt is enabled by the
init() function in
wiring.c.
There are several approaches to avoid that:

Avoid the Arduino core initialization

This may be overkill, but since it seems you are already familiar with
directly accessing the IO ports of the ATmega chip, it may well suit
you. You can use the Arduino IDE without the Arduino core initialization
simply by defining your own main():

#include <util/delay.h>

int main(void)
{
    DDRD |= _BV(PD2);        // PD2 as output
    for (;;) {
        PORTD |= _BV(PD2);   // PD2 high
        PORTD &= ~_BV(PD2);  // PD2 low
        _delay_us(0.625);    // 10 CPU cycles, loop time = 16 cycles
    }
}

Notice the extra delay: without it, the loop would complete in 6 CPU
cycles (2 per port access, 2 more to loop back). Not doing the Arduino
core initialization means you have no timekeeping and no analogRead()
or analogWrite(). Other Arduino functions should work normally but
some, like Serial.begin() will bring their own interrupts.

Disable interrupts

As suggested by Majenko, this may be the simplest way to have a steady
waveform:

void setup()
{
    pinMode(2, OUTPUT);
    noInterrupts();
}

void loop()
{
    PORTD |= _BV(PD2);   // PD2 high
    PORTD &= ~_BV(PD2);  // PD2 low
}

Without interrupts, you have no timekeeping, no serial communications
and, obviously, no attachInterrupt(). Most other Arduino functions
should work.

Use a hardware timer

This allows you to generate the signal without relying on the CPU. You
can keep interrupts enabled and do other work in the program while the
waveform goes undisturbed. The simplest way to generate such a waveform
is with analogWrite(). The resulting frequency is quite low though,
like 0.5 to 1 kHz. If you want 1 MHz, you will have to
configure the timer the hard way. For example:

void setup()
{
    DDRD |= _BV(PD3);     // OC2B = PD3 as output
    OCR2A = 15;           // period = 16 clock cycles
    OCR2B = 1;            // high during 2 clock cycles
    TCCR2A = _BV(COM2B1)  // non-inverting PWM
           | _BV(WGM20)   // fast PWM, TOP = OCR2A
           | _BV(WGM21);  // ditto
    TCCR2B = _BV(WGM22)   // ditto
           | _BV(CS20);   // clock at f_CPU
}

void loop() { }

The output is on pin PD3 = digital 3. This configuration will disable
analogWrite() on pins 3 (PD3) and 11 (PB3).


Unable to send SMS from interrupt routine

As mentioned in the comments Serial won't work in an ISR. Generally, you should do as little as possible in an ISR. Often an ISR will just set a flag to be handled in loop()

You will then need to refactor loop() to handle the flag set in the ISR. A common method is to use a finite state machine.


I understand your doubt. In a world where Uno WiFi i not Uno it is better to ask. And the Wawgat boards which are named Uno but use a different 8-bit MCU are a trap too.

The Nano in your link has Atmega 328p and interrupts are a feature of the MCU. There is no reason for the clone manufacturer to not use the standard Nano pinout as specified in Open Hardware Nano schematics. Then the board is compatible with Arduino Nano as defined in Arduino AVR boards package.

The clones usually use a cheaper chip for USB. You will maybe need to install a driver for the CH340.

In a few days Nano Every will be available and I expect clones of it in a short time because it is a very simple board. It will use the ATmega 4809 and Arduino advertises exact pin compatibility with old Nano. But I expect in details problems similar to Uno WiFi R2 versus classic Uno problems. One of the problems could be the mapping of interrupt pins.

And later this year Nano 33 will be released. It is a Nano format board with SAMD or nRF52 MCU so 3.3 V (the 33 in name).


I have three pushbuttons where only one can be pushed at a time and want to set a variable for this. How?

If you can only have one button pushed at a time, you can only end up with at most one of the if statements evaluate to true. In your code, you check button 2 and 3, even if button 1 is pressed. Your code can be a bit faster if you do this:
if(digitalRead(1) == 1)
{
  Variable = 1;
}
else if(digitalRead(2) == 1)
{
  Variable = 2;
}
else if(digitalRead(3) == 1)
{
  Variable = 3;
}


I am wondering about what voltage my external power will need to be to control all of them at 6v

Well that would be 6V then wouldn't it?

You're asking the wrong question. The question you should be asking is:

  How much current will I need from my 6V power supply?

And the answer is:

Add up the total current required by all of the devices and that is the minimum current the PSU has to provide

On top of that you need to consider how long the supply should last. The average current need to draw from the batteries, multiplied by the number of hours you need it to run for, is the minimum capacity of battery you need.

For instance, if you need to draw an average of 500mA for 6 hours then you need (0.5*6 =) 3Ah (or 3000mAh) batteries (or better).


Lifecycle hook in Arduino to know if Arduino is reset or powered down

EEPROM has a limit of 100,000 write/erase cycles, so we cant do more than that

You have 1k bytes of EEPROM and they survive a minimum of 100,000 writes. So that's 102,400,000 writes you could potentially do, if you are saving one byte. Even at one write a second that would be around 3 years.
However the EEPROM page size is 4 bytes, so that is actually 25,600,000 writes you could get away with (of 4 bytes at a time). Still, that is quite a lot of writes.
A while back I tested one of my chip's EEPROM and found that it greatly exceeded the 100,000 writes specified before it starting misreading the data back.
Also, if you refrain from writing if the value hasn't changed (hopefully that's a lot of the time?) then you could probably extend the life to 100 years.

Like a function would be called before the Arduino gets switched off.

No, that's impossible. How would it possibly know it is about to be switched off? Once it is switched off, functions are hardly going to be able to run.

Is there a way to know if an Arduino is getting switched off or being reset?

Once you hit Reset the processor starts again. It doesn't run any functions "just before" or "just after" being reset (using the original variables). That would mean that the reset doesn't actually reset it.

If you are designing some gadget that lets you configure it (eg. with a volume control) then simply save the new setting to EEPROM when it is changed. This is hardly going to happen 24 hours a day.


Properly using separate tabs with Arduino IDE

This question is more about C/C++ header basics rather than Arduino. Anyways, you should have the following file structure: Code in .cppfiles, Header in .h files. Main sketch either .ino or .cpp (for cpp remember that you must explicitly write out the function prototypes!)

So for your small example that would be:

main.ino:

#include "driver.h"
void setup() {
  Serial.begin(500000);
  PrintMessage();
}

void loop() {
}

driver.cpp

#include "driver.h"
byte PrintMessage () {
  Serial.println("printin");
  return 0; //previously had no return although returning 'byte'.
}

driver.h

 //Always use include guards
 #ifndef DRIVER_H
 #define DRIVER_H

 #include <Arduino.h>
 //All function prototypes from driver.cpp.
 byte PrintMessage();

 #endif /* DRIVER_H */

Also corrected a typo from PrintMessge to PrintMessage. This is the "professional" way to do it, seperate implementation and header files.


You do not appear to be configuring the slave as an SPI slave. Merely changing the pin modes won't achieve this. Example code at SPI - Serial Peripheral Interface - for Arduino - however that does not specifically mention the Attiny88.

In my example in reply #1 on that page I have this code:

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

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

This sets SPCR bit MSTR to zero (by not mentioning it). If you call SPI.begin() it will be activated in master mode.

It looks like the Attiny88 has the same register.

So in my opinion your code merely has two SPI masters.

Also, you seem to be doing 3 transfers in the master, but only 2 transfers in the slave.


"Why was the Due retired?" - It is quite interesting that Arduino.CC never explained that. One would think, that a professional company or organisation places a notice in advance with at least a short explanation as to why.

Most of the Arduinos, that have been available on both projects (CC and ORG) have suddenly and without further notice or explanation been retired on CC (the exceptions being Uno and Mega 2560, the cash-cows), but are still alive on ORG.
It would seem, that either the "divorce" is proceeding or that the copyright case at the US court is not going as smoothly as Banzi hoped. Well, he could repeatedly "bend the truth" by claiming Arduino being completely his idea and design in front of the press (that never bothered to check the obvious facts), but laying such a claim at court is borderline criminal. (see also: arduinohistory.github.io and make your own opinion)
CC has still the biggest chunk of the overall community and also serves as the central nexus for developers. But it seems there is a lot of movement... some people move to Wiring (from which the Arduino IDE was forked), others to 3rd Party sites and yet others try out different  and newly emerging products (eg. Adafruits MCUs and Pi or the Renesas GR series).
ORG on the other hand seems to become the bigger (Arduino branded) hardware supplier and developer. CC has apparently out-sourced this to Intel and tries to live of royalties and "certification" fees (which is the central point where Banzi and Martino started to heavily and openly disagree).

"Why was the Due retired?" - Unless CC doesn't give an explanation, there is no real answer. A lack of interest is certainly not the reason.


Alternative to delay() when using Ticker in ESP8622

use the ticker callback to increment a value. this value can be used as millis() substitute. actually the "millis" is made that way.

write a simple function to give you a delay. this code assumes the callback function is interrupt/event driven like a systick timer in ARMs.

uint32_t ticks;

void callbackFunc()
{
   ticks++;
}

void myDelay(uint32_t del)
{
   uint32_t tempTime = ticks;
   while (ticks < tempTime + del);
}


Arduino Editor: Monitor menu show "Serial port unavailable"

type "tail -f /var/log/kern.log" into a terminal window. This will show you the messages that the kernel produces. Hit enter a few times so you can easily see when something new is added.

Now remove (hmm. easier if you do that before typing the command above).  and insert the arduino. Now your kernel should produce a few messages stating it found a new device. Linux has drivers for all popular USB chips so no driver issues expected.

With a bit of luck you'll see something like:
   Aug 27 18:53:23 kernel: usbcore: registered new interface driver ch341
   Aug 27 18:53:23 kernel: usb 3-3: ch341-uart converter now attached to ttyUSB0
What comes after "now attached to" is what you need to use for the serial port....


Using external power supply to power leds on multiple pins (A0-A5)

Caveat: I too am new to this. The answer below is my understanding and I need an expert to confirm.

Current in your Arduino:

A single digital pin on a Uno will provide 40mA -- and could conceivably power two of your LEDs.
The VCC pin outputs 200mA and could therefore conceivably power ten.

So all you need to do is power your LEDs from your VCC, but use your digital pin as a switch. One idea, which you had, was to use a relay. But a relay is an inductor so don't connect it directly to the Arduino. Make sure it's on a shield. But that shield will essentially do exactly what you need to do, but to drive the relay rather than drive your LEDs: It will use the digital pin to switch the VCC and activate the relay.

Luckily this isn't hard. All you need is the most magical of all components: the transistor. A transistor can be used as a switch to turn on a higher current. In your case, the transistor can switch the VCC connection to the LED array when the digital pin is high.

This question was answered nicely over at the electronics stack exchange.
Here's a PDF tutorial on using transistors as switches.
Found a nice reference on figuring out the transistor / resistor relationship.

Here's the circuit I believe you need based on my understanding. Note that the values of the resistors and transistors are just made up. Read the docs above to get the correct values.


ArrayList implementation fails for string object

In theory, there's no reason why you shouldn't be able to call it by using toCharArray(). You would need to call it like this:

String str = "text3";
char * buf = new char[str.length()+1];
str.toCharArray(buf, str.length()+1);

list->add_string_item(buf);

That allocates a char buffer, copies the string data into it, then passes that buffer pointer to the list to be stored. Note that the buffer is one character larger than the string, as it needs to add a null terminator at the end.

However, there is a major problem with the rest of your code, which could eventually cause your Arduino to crash or do other strange things (depending on how much you use the list object).

Unlike Java, C++ is not a garbage-collected language, meaning it won't automatically clean-up memory for you. If you call new or malloc() to allocate heap memory, you have to call delete or free() (respectively) when you're finished with it to deallocate it.

Simply overwriting a pointer with another call to malloc() is not enough; it results in a memory leak. This means the block of memory it was previously using is lost, and cannot be reused again as long as the program is running. On a platform like Arduino, which has limited memory, you can very quickly run out.

Fixing the design of your class is probably beyond the scope of an answer on this site. I would strongly recommend working through some C++ tutorials (of which there are hundreds online).

As a side note, you should generally use new/delete instead of malloc()/free(). It doesn't make much difference when you're using arrays of char or char*, but it's important if you want to allocate class instances.


You have a timer conflict.

Pin 9 is OC1A which is the Output Compare Channel A pin of Timer 1. However the Servo.h library also uses timer 1.

So you can't use servos and still use pins 9 (OC1A) and 10 (OC1B) as PWM.

However, you can still use pins 3, 5, 6 and 11 as PWM since they are on other timers.


How can I use a transistor to "press" a button?

A glance at the TIP22 datasheet shows that this is a Darlington pair transistor, which means that it has very high DC gain (good), but at the cost of a very high Vbe_ON (bad).  The datasheet shows that the Vbe_ON is 2.5V, which means that the voltage across the 1K is only 2.5V max, which limits the base current to around 2mA.  This is probably not enough for good saturation.  In addition, the Vce_SAT for this device is about 2.0V, which may or may not be enough to look like a good GND to the button circuit.

I think a MOSFET like the IRF540N, connected as shown here (substitute button circuit for motor) might be a better choice
YMMV


Cannot convert 'int (*)[size]' to 'int**'

According the prototype of f and the usage pattern for its x
argument, the function expects this argument to be a pointer to the
first element of an array of pointers to the first elements of arrays of
int. However, the matrix in main() is defined as an array of arrays
of int. If you try to pass this to a function, the matrix will decay
into a pointer to an array of int. That's not what you want.

If you want both dimensions of the matrix to be variable, the only
simple solution I see is to build an extra array of pointers (pointing
to the matrix rows) and pass that array to the function

int main() {
    int x[16][128];

    // Build an array of pointers to rows.
    int *px[16];
    for (int i = 0; i < 16; i++)
        px[i] = x[i];

    f(px, 16, 128);
}

For more information on this, see the section Arrays and Pointers in
the C FAQ, and more specifically the questions 6.16 (How can I
dynamically allocate a multidimensional array?) and 6.19 (How do I write
functions which accept two-dimensional arrays when the width is not
known at compile time?).


I would recommend using multidemnsional arrays for both your contacts and your light states.

//------------------------------------------------ declare variables

char* titles[] = {"RELATION", "FIRST NAME", "LAST NAME", "LOCATION", "PHONE NUMBER"};

char* econs[][5] = {
  {"SELF", "JOHN", "SMITH", "FLORIDA", "999-888-6666"},
  {"BROTHER", "MICHAEL", "SMITH", "FLORIDA", "999-888-5555"},
  {"WIFE", "EMILY", "SMITH", "FLORIDA", "999-888-4444"},
  {"SISTER", "SOPHIA", "ADAMS", "NEW YORK", "888-777-3333"}
};

uint8_t lights[][4] {   {HIGH, LOW, LOW, LOW},
  {LOW, HIGH, LOW, LOW},
  {LOW, LOW, HIGH, LOW},
  {LOW, LOW, LOW, HIGH},
};

int ledPinOne = 2;
int ledPinTwo = 3;
int ledPinThree = 4;
int ledPinFour = 5;
int buttonPin = 6;
int state = 0;

//------------------------------------------------ setup - set pins
void setup() {
  Serial.begin(9600);

  pinMode(ledPinOne, OUTPUT);
  pinMode(ledPinTwo, OUTPUT);
  pinMode(ledPinThree, OUTPUT);
  pinMode(ledPinFour, OUTPUT);
  pinMode(buttonPin, INPUT);

  Serial.println("Emergency Contact");
}

//------------------------------------------------ main
void loop() {

  if (digitalRead(buttonPin))
  {
    if (state > 3)
      state = 0;

    {
      for (int y = 0; y <= 4; y++)
      {
        Serial.println(" ");
        Serial.print(titles[y]);
        Serial.print(" ");
        Serial.print(econs[state][y]);
      }

      Serial.println(" ");
      setLights(lights[state][0], lights[state][1], lights[state][2], lights[state][3]);
    }

    delay(1000);
    state++;

  }

}

//------------------------------------------------ function to turn LEDs on/off

void setLights(int one, int two, int three, int four)
{
  digitalWrite(ledPinOne, one);
  digitalWrite(ledPinTwo, two);
  digitalWrite(ledPinThree, three);
  digitalWrite(ledPinFour, four);
}

I haven't tested the above, but it should provide the same result.

As for the second part of your question, there is an autoformat tool in the Tools menu that will auto-indent your code. Ctrl-T will do the same.


SPI between Master arduino and Slave arduino

Feel free to take a look at my YouTube videos. They are not monetized so I'm not self-promoting. You can even skip the videos and checkout my GitHub repo with the Master and Slave sketches.
https://youtu.be/A9oSX_dwJKQ
https://youtu.be/PSUzhCtNRRQ
https://github.com/linhartr22/Arduino_SPI_Master_Slave_Demo


How do I pass an Int Array into void for a foreach loop?

What you want will not work the way you think: in C++ (just like in C), arrays and pointers are almost the same, and the compiler won't be able to make a distinction between

void f(int* array)

and

void f(int array[])

In particular, inside f() the compiler won't be able to know the actual size of array: for the compiler sizeof array will always be the same as sizeof(int*), i.e. just the size of a pointer, always 2 bytes on Arduino UNO, whatever type it points to.

If you want your foreach macro to work correctly, you have to pass it the actual array count of items as an additional argument:

#define foreach(item, array, size) \
    for(int keep = 1, \
        count = 0;\
        keep && count != size; \
        keep = !keep, count++) \
    for(item = (array) + count; keep; keep = !keep)

And also pass the count of items in Words:

void Words(int w[], size_t size) {
    foreach(int *v, w, size) {
        Serial.println(*v);
        delay(500);
    }
}

In loop() you can use sizeof example, because the compiler knows what its size is, from its initialization (an array of 5 integers, i.e. 10 bytes):

void loop() {
    Words(example, sizeof example / sizeof example[0]);
}

You could even define a macro to compute the count of items in an array:

#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))

It will work as long as you use it with an argument that is completely known by the compiler:

void loop() {
    Words(example, ARRAY_SIZE(example));
}

Important comments on your original code

You mentioned that you want to "save space", but defining a macro will not help in this regard, as a macro is NOT a function, hence its binary code will be repeated everywhere it is used. It can just help make your source code shorter and possibly clearer.

The way you defined your macro seems weird and overly complex to me: why use 2 for loops when you need only one?
It would have been possible to define it in a simpler way, for example:

#define foreach(type, var, array, size) \
    for(type* var = array; var != array + size; var++)

It would be used as follows:

void Words(int w[], size_t size) {
    foreach(int, v, w, size) {
        Serial.println(*v);
        delay(500);
    }
}

Using C++ templates may probably help too, but this is an advanced topic. I'd recommend reading first some good book about C++ before digging into templates.


It looks like the 0.9 uses the SPX3819 regulator. That can run with up to 16V on the input, so 9V on the 5V pin (as long as USB never gets connected) should work fine.

Except: 9V PP3 batteries are useless. If it can even provide enough power to run the board (which is doubtful) it won't last more than a few hours.  You would have to ensure that you use very very deep sleep mode to get any semblence of longevity out of it.

The 3.3V regulator will be throwing away half to two-thirds of the power as heat. So wasteful. You would be better off investing in a 3.3V switch-mode ("buck") regulator circuit (cheap on eBay) to directly power the 3.3V pin of the board instead of 9V into the on-board regulator.


You can combine the Streaming library with a wrapper class that sends data to multiple serial destinations.
Here's a little example:
#include <Streaming.h>

class DualSerial : public Print {
    private:
        Print *_dev1;
        Print *_dev2;

    public:
        DualSerial(Print &s1, Print &s2) : _dev1(&s1), _dev2(&s2) {}

        size_t write(uint8_t c) {
            _dev1->write(c);
            _dev2->write(c);
        }
};

DualSerial remote(Serial, Serial3);

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

void loop() {
    // Both Serial and Serial3 will receive this
    remote << "The time is: " << millis() << endl;
    delay(1000);
}

The Streaming class will work with anything that inherits from the Print class, which includes the SD card's File class, so you can also use it for writing to the SD card:
logfile << eOilTempF << ","
        << checkEngine << ","
        << engineOilStats.maximum() << ","
        << engineOilStats.average() << endl;


1) Which Arduino board is the best fit? 2) Is it an option to use Chinese boards for the sake of cost optimization? 3) Do I need separate RS232 and USB shield or it's ok to leverage built in USB and data pins?

When communicating with Android you need to make sure that there is software available for doing the communication. That's really down to the application more than the operating system, and because of that it can be quite restricted what boards will work and what won't.

Personally I would go for either an ATMega32U4 based board which provides a standard CDC/ACM interface. This also has the advantage that the (often single) UART on the board is not used by the USB communication.

Then you need to convert the UART into RS232 using (for example) a MAX232 board.


http.POST is not sending data to local web page

Your URL has localhost as the host name. That cannot work. localhost means “self”, the computer initiating the request. In this case it would mean the ESP8266, if it even understood it. You need to use the name or the IP address of the computer running your spring boot app, not localhost.


With no active cooling, most ATmega328P will run at 30MHz but you will need to up the supply voltage to ~6V. I have never done this on an Arduino board, just an ATmega328P.

I provided an external clock from a signal generator.

The only way to achieve a speed faster than 16MHz is to change the crystal/oscillator/clock input for one faster than 16MHz.

As this was just an experiment, I didn't alter f_cpu in boards.txt, so all timers etc. would be incorrect. Baud rates would also be incorrect - the only way to upload code was to change back to 16MHz.


Monitoring Power Down Using Arduino UNO and ZMPT101B

Got a answer for the issue,

Attaching code for anyone interested.

/*
   Design by Vinod Amarathunga 26.08.2018
   FSSG R&D Team
*/

#include <OneWire.h>
#include <DallasTemperature.h>
#include <SoftwareSerial.h>
#define ONE_WIRE_BUS 2
SoftwareSerial mySerial(11, 10); //SIM800L Rx Tx
char msg;
String textMessage;

bool D7_alarmSent = false;
bool Temp_alarmSent = false;

OneWire oneWire(ONE_WIRE_BUS);

DallasTemperature sensors(&oneWire);

void setup()
{
  mySerial.begin(9600);   // Setting the baud rate of GSM Module
  Serial.begin(9600);    // Setting the baud rate of Serial Monitor (Arduino)
  delay(100);
}

void PowerSMS()
{
  Serial.println("Warning!! Server Room Power Down");
  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No1\"\r");
  delay(1000);
  mySerial.println("Warning!! Server Room Power Down");
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  mySerial.println("AT+CMGD=2");

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No2\"\r");
  delay(1000);
  mySerial.println("Warning!! Server Room Power Down");
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  mySerial.println("AT+CMGD=2");

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No3\"\r");
  delay(1000);
  mySerial.println("Warning!! Server Room Power Down");
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  mySerial.println("AT+CMGD=2");

}

void SendMessage()
{

  Serial.println("Warning!! Server Room Temperature is Critical");

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No1\"\r"); // Replace x with mobile number
  delay(1000);
  mySerial.println("Warning!! Server Room Temperature is Critical");
  mySerial.println(String("Reading : ") + sensors.getTempCByIndex(0) + String("*C"));
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  mySerial.println("AT+CMGD=2");

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No2\"\r");
  delay(1000);
  mySerial.println("Warning!! Server Room Temperature is Critical");
  mySerial.println(String("Reading : ") + sensors.getTempCByIndex(0) + String("*C"));
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  mySerial.println("AT+CMGD=2");

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No3\"\r");
  delay(1000);
  mySerial.println("Warning!! Server Room Temperature is Critical");
  mySerial.println(String("Reading : ") + sensors.getTempCByIndex(0) + String("*C"));
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  mySerial.println("AT+CMGD=2");

}

void loop()
{
  sensors.requestTemperatures(); // Send the command to get temperature readings
  delay(1000);
  Serial.println(String("Temp Reading : ") + sensors.getTempCByIndex(0) + String("*C"));
  Serial.println(String("Voltage Digital: ") + digitalRead(7));
  Serial.println(Temp_alarmSent ? "True" : "False" );
  Serial.println(D7_alarmSent ? "True" : "False" );
  Serial.println("***********");
  ReceiveMessage();

  if (digitalRead(7) == 1 || sensors.getTempCByIndex(0) > 29 || D7_alarmSent == true || Temp_alarmSent == true ) {
    if (digitalRead(7) == 1 ) {
      if (!D7_alarmSent) {
        D7_alarmSent = true;
        PowerSMS();
      }

    }

    else if (sensors.getTempCByIndex(0) > 29 ) {
      if (!Temp_alarmSent) {
        Temp_alarmSent = true;
        SendMessage();
      }

    }

    else {

      if (D7_alarmSent){                  //alarmSent == true means that previous state was "Power Down"
          SendMessage_After_Power_Down();          //Send message
          D7_alarmSent = false;
          Temp_alarmSent = false;             //Reset alarmstate
        }

    }
  }

}

void SendMessage_Normal()
{
  Serial.println("Temperature and Power is OK");

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No1\"\r");
  delay(1000);
  mySerial.println("Temperature and Power is OK");
  mySerial.println(String("Reading : ") + sensors.getTempCByIndex(0) + String("*C"));
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No2\"\r");
  delay(1000);
  mySerial.println("Temperature and Power is OK");
  mySerial.println(String("Reading : ") + sensors.getTempCByIndex(0) + String("*C"));
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No3\"\r");
  delay(1000);
  mySerial.println("Temperature and Power is OK");
  mySerial.println(String("Reading : ") + sensors.getTempCByIndex(0) + String("*C"));
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);

}
void SendMessage_After_Power_Down(){

  Serial.println("Power Back Online");

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No1"\r");
  delay(1000);
  mySerial.println("Power Back Online");
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No2\"\r");
  delay(1000);
  mySerial.println("Power Back Online");
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);

  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"No3\"\r");
  delay(1000);
  mySerial.println("Power Back Online");
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);

  }

void ReceiveMessage()
{
  if (mySerial.available() > 0)
  {
    mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to recieve a live SMS
    delay(1000);
    textMessage = mySerial.readString();
    Serial.print(textMessage);
    delay(10);
  }
  if (textMessage.indexOf("Status") >= 0) {
    SendMessage_Normal();
    mySerial.println("AT+CMGD=2");

  }
}


Arduino Saint Smart Chapter 7 Tri Color Module

This line pinMode(i, OUTPUT); should probably be replaced by pinMode(ledPin[i], OUTPUT);
Otherwise it won't make sense.


Servo Driven Through Custom Library Not working Properly

In C++, when an object is declared as a member of another object, the constructor method of the inner object must be called explicity (see constructors and member initializer lists).

In your code, properties of Servo type can be constructed within the header of the MotorControl constructor:

MotorControl::MotorControl(int north, int south, int west, int east)
    : _north(), _south(), _west(), _east()
{
  _north.attach(north);
  _south.attach(south);
  _west.attach(west);
  _east.attach(east);
  _northVal = 0;
  _southVal = 0;
  _westVal = 0;
  _eastVal = 0;
}


Problems with Hardware Serial (UART) on Nano 33 BLE Sense

You can't make calls to IMU if you haven't initialised it with IMU.begin()


Can I have two separated serial monitor for the same arduino board connected to PC?

If you want to have two Serial Monitors, start the IDE twice. Use your desktop shortcut or start menu entry to start the second instance of the IDE. In the second instance you can select a different port. It will not work for Upload of course, but when you open the Serial Monitor, it will work at the selected port.

Other option is to use some terminal program to see the output of the com port.

The other answers cover the fact that you need an USB to TTL Serial adapter to connect to USB and in sketch SoftwareSerial as your second serial interface or use some board with two or more hardware serial ports like the Mega on the picture.


What is the pinout of the Arduino MKR motor carrier when using external power supply, not the Li-Po battery

Vin means "Voltage Input". That's where you provide your power. That is the input to the voltage regulator.
5V and 3.3V are what the board uses internally and are provided for you to also use should you want to. These are outputs from the voltage regulators.
It's exactly the same (though more efficient and higher current) as almost every other Arduino.


Cheap weatherproof ultrasonic range sensor?

Those modules are just the ultrasonic transducers. You can see the two pin connector. You can probably get those cheap boards, de-solder the two transducers, and connect the wires from two of the water-proof ones.


Arduino AT not working (Arduino UNO and HC-06)

Use a macro like this to send AT commands:
 #include <SoftwareSerial.h>

 SoftwareSerial btSerial(2, 3); // RX, TX
 /*
  * Connect pin 2 Arduino to pin TX HC-06
  * Connect pin 3 Arduino to pin RX HC-06
  */
 void setup() {

 Serial.begin(9600);

 Serial.println("Enter AT commands:");

 btSerial.begin(9600);

 }

 void loop()

 {

 if (btSerial.available())

 Serial.write(btSerial.read());

 if (Serial.available())

 btSerial.write(Serial.read());
 delay(1000);
 //btSerial.print("AT+PIN4321");
 //btSerial.print("AT+NAMEAlibaba");
 //btSerial.print("AT+BAUD4");

 }

You may have another port set on the HC 06 instead of 9600, like I had.
If so, try this code with all the possible port numbers and changing something like the password, and everytime you run the code - go check if it worked, this way you will find in wich port number you have your module.

good luck


Problem burning bootloader on ATmega328P using internal clock

If your ATMEGA328P has already been used with a crystal or already has a bootloader on it, then the fuses will be set to expect a crystal oscillator. In this case, you must initially have a crystal & the associated 2 capacitors connected. Once you have succeeded in burning the bootloader (this process also sets the fuses) you can dispense with the crystal.


Can anyone point out my mistake?

Your mistake is in thinking that it's possible to do more than you can within a 10uS period.

At 16MHz each instruction takes 63ns (for single-clock instructions). 10nS gives you a maximum of (10,000 / 63) 156 assembly instructions.  Into that you have to fit the preamble and postamble to store the registers to the stack and retrieve them again.

The remaining clock cycles (maybe no more than 100) won't give you much time to do complex things. And given that many of the Arduino API calls are quite heavyweight, even just something as "simple" as a digitalWrite() can overflow that many times over.


Accelerometer readings on a moving object

A few things to consider.

First. An accelerometer isn't that great here. Low output frequency is one issue. Noise is another. A pot or an optical encoder would be better.

Secondly. Even if output frequency isn't an issue. You will need some sophisticated math to reconstruct the instantaneous tilt, as the measurements are essentially a sine function, but with an acceleration away from the center of the rotation.  Getting to the max tilt is easier mathematically.

Just for starters.


Do I need to run an expand drive sketch if I update the Yun Firmware subsequent to expanding?

After upgrading the firmware and rebooting:

Log in to your Yun through your browser and use the LuCI interface.
Navigate to "System" > "Software" and observe the "Free space" meter. You will see that the total space shown is between 800KB and 1MB, instead of the size of your flash drive. This indicates that the system is that of the memory available on the board.

Yes, you will need to run the expander sketch again and reinstall software that was previously there. (You might want to back up the contents of the drive beforehand, using a PC running GNU/Linux.)


Creating an array of structures which store bitmaps to work with u8glib

That still wouldn't solve the issue with struct!
I think I have found a glitch in GCC compiler where if you define your struct in dynamic memory rather than PROGMEM, even if you use a buffer and fetch the data using memcpy_P, it will return the correct value while printing, but when you copy it again to allChars[0].bitmap , the wrong value is copied! the thing that solved the issue was adding PROGMEM to the struct like below:

typedef struct {
  unsigned int ascii;
  int size[2];
  const PROGMEM unsigned char *bitmap;
} chars;

I have not yet encountered any compilers that are this specific and don't even allow transfer between memory spaces correctly. (Not to mention other issues with GCC linker that are brought up by david from eevblog like stack overflow without warning, etc). They really need to solve issues like this as this compiler is one of the most frequently used on different platforms.

anyways, here is the final code if anyone finds it useful (I will probably end up making a youtube video about it later):

#include "U8glib.h"
//U8GLIB_SH1106_128X64 u8g(U8G_I2C_OPT_NONE);
U8GLIB_SSD1306_128X64 u8g(U8G_I2C_OPT_NONE|U8G_I2C_OPT_DEV_0);

typedef struct {
  unsigned int ascii;
  int size[2];
  const PROGMEM unsigned char *bitmap;
} chars;

chars allChars[1];

const unsigned char pat[] PROGMEM = {
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x01, 0xfc, 0x00,  //.......%%%%%%%.......
  0x0f, 0xff, 0x00,  //....%%%%%%%%%%%%.....
  0x1f, 0xff, 0xc0,  //...%%%%%%%%%%%%%%%...
  0x3f, 0xff, 0xe0,  //..%%%%%%%%%%%%%%%%%..
  0x3f, 0xff, 0xe0,  //..%%%%%%%%%%%%%%%%%..
  0x7f, 0xff, 0xf0,  //.%%%%%%%%%%%%%%%%%%%.
  0x7f, 0xdf, 0xf0,  //.%%%%%%%%%.%%%%%%%%%.
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0xff, 0x8f, 0xf8,  //%%%%%%%%%...%%%%%%%%%
  0x7f, 0xdf, 0xf0,  //.%%%%%%%%%.%%%%%%%%%.
  0x7f, 0xff, 0xf0,  //.%%%%%%%%%%%%%%%%%%%.
  0x3f, 0xff, 0xe0,  //..%%%%%%%%%%%%%%%%%..
  0x3f, 0xff, 0xe0,  //..%%%%%%%%%%%%%%%%%..
  0x1f, 0xff, 0xc0,  //...%%%%%%%%%%%%%%%...
  0x0f, 0xff, 0x80,  //....%%%%%%%%%%%%%....
  0x01, 0xfc, 0x00,  //.......%%%%%%%.......
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
  0x00, 0x00, 0x00,  //.....................
};

void charToBitmap(int x, int y, char chr){
  for(unsigned int i=0; i<sizeof(allChars);i++){
    if (allChars[i].ascii=chr){
      u8g.drawBitmapP( x, y, allChars[i].size[0], allChars[i].size[1], allChars[i].bitmap);
      break;
    }
  }
}

void draw(void) {
  charToBitmap(0,0,'0');
}

void setup(void) {
  allChars[0] = (chars) {48,{3,54},pat};
}

void loop(void) {
    u8g.firstPage();
  do {
    draw();
  } while( u8g.nextPage() );
}


Because M(3 + 2, 4 + 2) gets replaced to 3 + 2 * 4 + 2 and then the normal priority of operations does the multiply before the addition.

This is one of the many reasons why you should prefer functions over macros. The inliner of the compiler will negate any call overhead.

If you truly want to use a macro then surround each use of the macro arguments in parenthesis, surround the macro itself in parenthesis as well.

#define M(x, y) ((x) * (y))


There are two issues here:

The "L" LED lighting. On the R3 Uno this is driven by an op-amp and if pin 13 is "floating" the op-amp may, or may not, turn the LED on. So this is normal.
The 8-pin chip near the power plug getting very hot. This is definitely not normal. You must be consuming a lot of current to do that. You could try measuring it. A Uno running an "empty" sketch should be consuming around 50 mA. Note that this chip is the op-amp mentioned in my first point. Possibly you have damaged it. Did you connect an LED (or motor) or similar to pin D13? If so, what current-limiting precautions did you take?

Try running an empty sketch (or the Blink sketch) with no hardware connected to the board, to see if it still happens.
Try measuring the power consumption, if possible, with a meter measuring the input through the 5V pin, if you have a 5V power supply you could use for this.
Are these genuine boards, or cheap clones from eBay?


You don't want an array of strings containing the (badly formatted) names of variables. Instead you want an array of 32-bit integers containing the values held within those variables.

const uint32_t colors[] = {
    CRGB::White,
    CRGB::WhiteSmoke,
    CRGB::CadetBlue,
    CRGB::SteelBlue,
    CRGB::Teal,
    CRGB::SlateGray,
    CRGB::MediumPurple,
    CRGB::Purple,
    CRGB::PapayaWhip,
    CRGB::LightPink,
    CRGB::Crimson
};

Since colours are just numbers, in the (hexadecimal) form of 0xRRGGBB you just store them as 32-bit unsigned integers.  The names you have there are just such (constant) variables used for easy reference (CRGB::White is 0xFFFFFF).


Stuck making multi, many button, joysticks

Each ShiftIn instance handles just one connection. You need to make multiple instances.

ShiftIn shift1<3>;
ShiftIn shift2<3>;
ShiftIn shift3<3>;

Then you begin each of them:

void setup() {
    shift1.begin(8, 9, 11, 12);
    shift2.begin(7, 6, 5, 4);
    shift3.begin(3, 2, 1, 0);
    ... etc ...
}

Each shiftx is a completely separate entity. You can just repeat your block of code for each shift object:

if (shift1.update()) {
    for (int i = 0; i < shift1.getDataWidth(); i++)
    Joystick[0].setButton(i, shift1.state(i));
}

if (shift2.update()) {
    for (int i = 0; i < shift2.getDataWidth(); i++)
    Joystick[1].setButton(i, shift2.state(i));
}

if (shift3.update()) {
    for (int i = 0; i < shift3.getDataWidth(); i++)
    Joystick[2].setButton(i, shift3.state(i));
}

You could arrange the ShiftIn objects into an array like you do with your Joystick objects and then loop through them, but that is pretty pointless for just three of them.


How can I handle micros() double rollover?

If you want to measure times longer than 70 minutes with
micros(), you will have to use uint64_t, and there is nothing
wrong with that.

  The code needs to run with as little interruptions as possible [...]

You don't need to do the 64-bit arithmetic within the ISR. You could
very well implement an interrupt-driven 32-bit version, and then extend
it to 64 bits in non-interrupt context. Example:

// Your ISR-based implementation.
uint32_t micros32();

// Extend to 64 bits.
uint64_t micros64() {
    static uint32_t low32, high32;
    uint32_t new_low32 = micros32();
    if (new_low32 < low32) high32++;
    low32 = new_low32;
    return (uint64_t) high32 << 32 | low32;
}

This should work as long as you call micros64() often enough.
Presumably, you will have something like
if (micros64() - lastTime > period) { ... }
within your loop, so this should be no issue as long as you never block
your loop.

Actually, you can push this idea even further. If you can guarantee that
micros64() will be called at least once every 65.5 ms, then you
could have your ISR increment only a 16-bit counter.


Problem in getting the output (language: Processing and Arduino IDE)

If you read the documentation for Serial::read() at https://processing.org/reference/libraries/serial/Serial_read_.html

it says:
"Returns a number between 0 and 255 for the next byte that's waiting in the buffer. Returns -1 if there is no byte, although this should be avoided by first cheacking available() to see if data is available."

Either before calling "Draw" function, or inside "Draw", you should first check:

if(port.available()){
  //do your checking for X value and set text as you are doing before

}

IMPORTANT - you are only ever sending the lower byte (values 0-255) from Arduino when you do Serial.write(x). That is only 1 byte. The "int" return from an analogue read is 10 bits, and needs 2 bytes to store the information from 0-1023.

You should use the Arduino function Map() to scale it down from 0-1023 to 0-255. It looks like your application should be okay with this, in terms of resolution.

  int val = analogRead(ldr1);
  val = map(val, 0, 1023, 0, 255);
  Serial.write(val); //now you will not lose information

On the Processing side, you would then look at values from 0-255 to determine daylight/times of day.


How can I identify, debug or fix a faulty IMU?

In theory you must use a level shifter for SDA and SCL. The Arduino Mega 2560 board has internal pullup resistors of about 50k for SDA and SCL and extra 10k pullup resistors of 10k to 5V and according to the datasheet the ATmega2560 requires 3.5V to detect a high level for the I2C bus.

Those pullup resistors might damage the LSM9DS1.
5V-3.3V / 50k//10k times two (both SDA and SCL) = 400nA that might be pushed into the sensor (I assume there are protection diodes, and the maximum voltage is 3.6V, therefor the 400nA is just an indication).
I assume the 10k pullup resistors to 3.3V on the sensor module are enabled. They will take away some over-voltage.

The current by the pullup resistors (to 5V) is a very small current, and I don't know if the sensor is in sleep mode during startup.

To be sure you need to buy another LSM9DS1 and a level shifter. Or even better: buy a 3.3V Arduino board, like the Due or the Zero, M0, and so on.

Have to compared the raw sensor data with others ? Those sensors are very noisy. That is why there is so much to do about filter algoritms to get data that can actually be used. The LSM9DS1 does not do processing or smart filtering with the raw data. All you get is the raw data. Did you assume that the values would be zero ? They never will be, because such sensors are far too noisy and too sensitive for that.


Is there an advantage to set pinmodes via bitmask and register?

I can name a few:

1) speed - I benchmarked the arduino pin ops vs. direct register ops here;

2) size - the code size is considerably bigger with the arduino library;

3) portability - the bitmark approach is supported by any C-compiler;

4) convention - i'm used to the bitmask approach and wrote all of my libraries around it;
...

as i'm sure others have their reasons to use the bitmasks.


Creating formatted String (including floats) in Arduino-compatible C++

The Adafruit_GFX class has two methods named print() and
println(). These behave exactly like Serial.print() and
Serial.println(). Specifically, when printing a float, you can provide
a second argument telling it the number of decimal places you want after
the decimal point:

display.print(temp1, 1);  // 1 digit after the decimal point
display.print(", ");
display.print(hum1, 1);  // ditto
display.print("%");

Background: the reason these methods behave like the ones of
Serial is that both Adafruit_GFX and HardwareSerial inherit them
from the Print virtual class.


Always HIGHT line on Oscilloscope when UNO's Fast PWM TOP ICR1

You might want to set the TCCR1A and TCCR1B registers to 0 before your code as the Arduino library sets the WGM10 bit. Or change the first |= to a =. By leaving the WGM10 bit set, you get fast PWM mode, with TOP set to OCR1A. Combined with your other code, this would result in both pins having a 100% duty cycle.
So use
TCCR1A=(0<<WGM10)|(1<<WGM11);
TCCR1B=(1<<WGM13)|(1<<WGM12);

or
TCCR1A=0;
TCCR1B=0;
TCCR1A|=(0<<WGM10)|(1<<WGM11);
TCCR1B|=(1<<WGM13)|(1<<WGM12);

Other than that, you code looks fine, and should give you a 800Hz signal.
PS "I assumed that my UNO works on 1 MHz"; no, the UNO runs at 16Mhz.


How do I set up a multi-file project in the Arduino IDE?

You have two options with ArduinoIDE.

First Each module in a module directory

So the structure looks like

  main_routine
     main_routine.ino
  --module1
      module1.ino  #test routine
      module1.cpp
      module1.h
 --module2
  .....

included in main_routine.ino

   #include "module1/module1.h"
   #include "module2/module2.h"

So you have everything in your master dir and in module specific subdirs below - Nothing is or will be copied by the ArduinoIDE (v1.8.12)

The second (more hacky way) is to have everything in one dir and for development testing working with include guards in the main_routine.ino

 // for production comment all MODULEX_TEST and uncomment PRODUCTION
 //#define PRODUCTION
 #define MODULE1_TEST
 //#define MODULE2_TEST
.....
#if defined (PRODUCTION) || defined (MODULE1_TEST )
   #include "module1/module1.h"
#endif

#if defined (PRODUCTION) || defined (MODULE1_TEST )
   uint8_t myModule1Var = 0;
#endif

setup(){
.....
#if defined (PRODUCTION) || defined (MODULE1_TEST )
   myModule1setup someInit(1,2,3);
#endif
.....
 }

loop(){
.....
#if defined (PRODUCTION) || defined (MODULE1_TEST )
   void mymodule1Func(){....};
#endif
#ifdef MODULE1_TEST
   void mymodule1Test(){....};
#endif

Pros and cons

+This approach gives you the possibility to test two modules together.
-Its harder to read, but
+easier to document with tools like doxygen
~Only the active includes are compiled and so no overhead in the compiled code

Be aware that with some tool chains there are at the moment problems when using special templates (works if everything is in one module file - I use an "extended header" file as momentary work around) or arrays as initializer (open issue in esp8266)


Simple GET request with ESP8266HTTPClient

As Musa said, I needed to suply the website certificate footprint to http.begin.

void loop() {
  HTTPClient http;
  String thumbprint="08:3B:71:72:02:43:6E:CA:ED:42:86:93:BA:7E:DF:81:C4:BC:62:30";
  String path = "https://calm-falls-41696.herokuapp.com/api/v1/cards.json";
  http.begin(path, thumbprint);
  int httpCode = http.GET();
  Serial.println(httpCode);
  if(httpCode == HTTP_CODE_OK) {
    Serial.print("HTTP response code ");
    Serial.println(httpCode);
    String response = http.getString();
    Serial.println(response);
 }
  http.end();
  delay(1000);
}


Sending Float values from Python to Arduino via serial communication

It would seem you managed to solve your problem with
Serial.parseFloat(). This is probably the easiest solution, but it has
one serious drawback: it is a blocking function. Which means, during
all the time needed by the serial port to transfer the number, your
Arduino does nothing but wait for the incoming characters. This is an
issue if your program has other task to do like, e.g., manage a PID
regulation.

I suggest you consider reading the serial port in a non blocking
fashion instead. This should make your PID happier, as it won't feel
neglected while you read the incoming data. Look Alterno's answer is a
good example of a non-blocking function that combines reading and
parsing. However, I would like to point out that you do not need to
implement your own number parser if you don't want to. A very common
pattern is to instead store the incoming characters in a buffer and,
when you see the character chosen as a terminator (e.g. ASCII LF), you
parse the buffer at once using either strtod() or atof(). For
example:

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

void loop() {
    static char buffer[32];
    static size_t pos;
    if (Serial.available()) {
        char c = Serial.read();
        if (c == '\n') {  // on end of line, parse the number
            buffer[pos] = '\0';
            float value = atof(buffer);
            Serial.print("received: ");
            Serial.println(value);
            pos = 0;
        } else if (pos < sizeof buffer - 1) {  // otherwise, buffer it
            buffer[pos++] = c;
        }
    }
}


Arduino program to scan two different rfid cards in same program ? Im using nodemcu- esp8266 , rc522 reader and Firebase

also look into sprintf to get hex formatting
(I dont have these libraries so I cannot test, this is all written in stackexchange editor, so I might have a typo somewhere)

unsigned long startScanTime;
bool GotBookId = false, GotUserId = false;
void loop() {
GotBookId = false;
GotUserId = false;

  if ( !mfrc522.PICC_IsNewCardPresent() ) {
    delay(50);
    return;
  }

  if ( !mfrc522.PICC_ReadCardSerial() ) {
    delay(50);
    return;
  }
String book;

  for ( byte i = 0; i< mfrc522.uid.size; i++ ) {
    Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
    Serial.print(mfrc522.uid.uidByte[i], HEX);
    book.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
    book.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
    book.toUpperCase();
    if(book != "")
       GotBookId = true;

    Serial.println("Got Book");

startScanTime = millis(); //timeout look to get user card
  while( !mfrc522.PICC_IsNewCardPresent() && (millis() - startScanTime < SCAN_TIMEOUT) ) {
   //do nothing but wait
  }

  if(!mfrc522.PICC_IsNewCardPresent())
  { //did not get the user id, return from loop
      return;
  }
  if ( !mfrc522.PICC_ReadCardSerial() ) {
    return; //should never hit this if library works correctly
  }
  String user;

  Serial.print("Scan your id: ");
    for ( byte i = 0; i< mfrc522.uid.size; i++ ) {
    Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
    Serial.print(mfrc522.uid.uidByte[i], HEX);
    user.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
    user.concat(String(mfrc522.uid.uidByte[i], HEX));}
    user.toUpperCase();
    //Serial.print(F("Card UID: "));
    GotUserId = true;

   if(GotBookId && GotUserId){
       Firebase.pushString("Issued_Books/Book_rfid",book);
       Firebase.setString("Issued_Books/Book_rfid/user_rfid",user);
   }
}


How do I hook up a 3V device to a 74AHCT125 (Quad Level-Shifter)?

It's not a level shifter. It's a buffer chip that can be used to level shift in one direction only.

It is good for shifting from a low voltage logic signal (3.3v, say) up to a 5V logic signal. It can't shift down from 5V to 3.3V.

Basically it works by having a fixed voltage that it considers to be a logic HIGH, and any voltage above that will be output as 5V. Any voltage below will be output as 0V.  This is the "TTL Logic Level" specification in the datasheet.

So if you have a sensor that emits a 3V logic signal the HIGH logic value will be above its fixed threshold and will trigger a 5V HIGH on the output.

In contrast "CMOS" logic uses a percentage of the supply voltage to set the thresholds (usually > 0.6 x Vcc), and a 3V signal is less than that (3.3V is about bang on it, so is "iffy"), so won't work (or not reliably).


your code makes copies of Serials into items in the array of HardwareSerials. To use the original Serial objects, store and use pointers.

HardwareSerial* Serials[]={&Serial,&Serial1,&Serial2,&Serial3};

void setup(){
    for (int i=0;i<=3;i++){
        Serials[i]->begin(38400);
        while (!*Serials[i]);
    }
}

void loop(){
    for (int i=0;i<=3;i++){
        if (Serials[i]->available()){
            char s=Serials[i]->read();
            Serials[i]->write(s);
        }
    }
}


Do I need a full Arduino board hardwired to a sensor to send data via Wi-Fi?

There are small packages out there with built in WiFi.  Node MCU is one of them, however its analog to digital conversion isn't up to the task of measuring bridges.  If you go that route you'll need to add a ADC to the Node MCU which will increase the total package size.


Do I need to worry about voltage, coming from ground, and effecting an analog input?

The arduino has build in pull up resistors, it is not a residue voltage coming from ground more than a "not 100% 0 volt" resistor.

Even though there is built in pull-up resistors one can add additional resistance to the arduino to make sure it will not show a false positive.

From what i have learned, you cannot experience voltage comming from ground (if everything is properly wired), if you want to make sure. Place a diod in the direction of the power flow, to prevent this.


BOUNCE 2
Basically, the mechanical part of buttons and switches vibrate slightly when closed or opened causing multiple undesired false states (similar to noise). This library filters out these undesired state changes. More about debouncing:
John Errington's Experiments with an Arduino : Using digital inputs: Switch bounce and solutions to it
Wikipedia article : http://en.wikipedia.org/wiki/Debounce#Contact_bounce
See the bottom of this page for a basic usage example and the "examples" folder for more.
The library is composed of three classes:
Debouncer : The code that does the actual debouncing. Only advanced users should play with this class.
Bounce : This is the general use library. It links the Debouncer to a hardware pin on your board.
Button : A special version of Bounce for buttons that are pressed.
https://github.com/thomasfredericks/Bounce2


The reset is basically jumping to the reset vector address 0x0000 (if you don't have the bootloader, or you don't want to start it).

There is also the MCUSR register, indicating which reset source caused the reset. It won't be set if you do simple jump to the reset adress.

The memory is also preserved, but C/C++ init code takes place and initialize your global variables. This can be ommited by placing variable/variables into the .noinit section. But it's not defined, what is there after the reset. With combination with MCUSR register you can init the variables for regular reset sources and keep it unchanged if you jump to the reset vector address.

Also the regular reset sources jumps to the bootloader, so it can use the same memory locations as your .noinit variables and trash them.


Reading from a pin Arduino Uno (assembly)

You are simply reading the state of the input pin - this won't work.

Study the datasheet for the DHT22, available from Sparkfun or eslewhere.

To get data from the DTH22, you must first send a start signal, wait a specified time, then watch the level of the data line, measuring the time of each bit to determine whether it is a 1 or 0, and store the bits in five 8-bit variables.  You can then examine those variables to determine the temperature and humidity.


How do I use a 3 legged phototransistor?

A reasonably generic data sheet is HERE
That is for an AT156 but yours may be an AT138/HT138 based on an ad some years ago from the same seller when they said they had 10,000 for sale.

Basic information here and more in the data sheet.


How can I hack my intercom system to buzz people in remotely?

3 possible solutions:

Connect the 2 contact for the button to a relay and control that relay from the arduino (example) But the kit you have doesn't include a relay.
Use a transistor to trigger the switch -- I would not recommend this option as your first project.  It would be easy to damage the intercom and/or your arduino.
Use the servo in the kit to physically press the button.  You will need to figure out the mechanical linkages but you don't need to attach wires to the intercom.

For a beginner project I would probably go with the third option.


"return" not working to break out of a loop

Your second outermost if() clause in StartScreen(), the one that begins with if (frametype == 0 || frametype == -1), contains an infinite while loop. That loop contains no break statements, and calls StartScreen() -- it recurses into itself!

Without my trying to follow the program logic, I can at least posit that the code is in a second or higher recursion when it calls return, thus returning to where it had called itself. So, yes, if that is correct, it will still be executing within StartScreen() after the return statement. The return statement wouldn't have "failed" in that case; it would have resumed the at the point where the its prior instance called itself.

If that sounds convoluted, it's because it is! There can be good reasons to recurse, if you intended to, your know in what circumstances the code will recurse, and you know that recursiing will stop before you run out of stack space. Carefully review your program logic; this may not be one of those instances....


Serial print message results in gibberish

This "weird" result usualy happens when you select then wrong baud rate or a different one then the one you beginned the serial communication with in the program. Thus by using Serial.begin(9600);, you have to make sure that the serial monitor is actually set to a baud rate of 9600.


when I attach pin 16 or pin 10 of the 74HC595 to the 5V pin on the Uno ... the entire arduino shuts off

This sort of thing usually happens to me when I have made a mistake in the wiring.
This is easy to do as the 595 needs a lot of connections in a small space and it is easy to make a mistake.
In your case it seems you have a wiring mistake that is pulling Vcc low and the ATmega328 IC etc can't run.

I would

Re-check the orientation of the 595
Re-check each wire paying particular attention to the ground wires, especially the one that pulls 595 OE to ground (it's pin 13 on the 595).
If necessary, pull everything off the breadboard and start again with things in a completely different position (turn the IC's round etc) to make me re-think everything.

For fun, I set this up on a Uno clone. I made some mistakes in the wires linking the 595 to the Uno but careful inspection found the problem. I found it easy to mix up the pin-number on the 595 with that on the Uno. Using the same wire colours mentioned in the guide may help.
Here's it working


Turning an LED on when an error occurs, then turn it off after 2 seconds

When you turn on the led, record the time.

After that, turn off the led if

The led is on and
Sufficient time has passed.

edit: this is what I would do.

//detect if sufficient time has passed
//1. turn on the led on button high -> low transition
//2. turn off the led after certain time (LED_DLY)
uint8_t led_ctrl(void) {
    static uint32_t led_timeoff=0;                              //time to turn the led off
    uint32_t time_now = millis();                               //take time now

    //if sufficient delay has passed, turn the led off
    if (isLED_ON() && (time_now >= led_timeoff)) {              //if led is already on
        LED_OFF();                                              //turn off the led
    }

    //if the button has experienced a the falling edge, turn on the led and set up the time to turn the led off
    if (btn_pressed()) {
        LED_ON();                                               //turn on the led
        led_timeoff = time_now + LED_DLY;                       //set up the time to turn off the led
    }

}

it is almost a literal implementation of what I wrote above.

here is the code in action, responding to button's falling edge with a 150ms delay turn off for the led: the button is on D12 and the led on D8.

fairly straight forward, isn't it?


How can I see if volume buttons of Apple earphones are pressed?

Here is an article that explains the inner working of the Apple headphones:

http://tinymicros.com/wiki/Apple_iPod_Remote_Protocol


Using ps2 mouse (PAW3402 / PAW3412) as a distance sensor for arduino

Assuming under normal conditions a relative pointing device such as a optical mouse always reports relative position changes with out regard to speed.  If true, then consider that the speed of the robot is faster than the mouse can process.  Also, consider that the mouse's optics is out of focus with respect to the surface it is supposedly taking its positioning cues from.  Lastly, consider the surface may not be ideal for an optical mouse.  Attempt the same experiment using a sheet of paper or a "not-shiny" wood surface.

All surfaces have to be flat.  For example, a ceramic tile floor will likely not work as the surface will come in and out of focus during travel.  Make sure the elevation of the robot with respect to the surface is constant.  Inspect the wheels to make sure they are perfectly round and rotating around their center point.

Check and make sure you are not suffering from a integer calculation or type size problem.  Examine your code and make sure you are handling all cases including the expected maximum and minimum values properly.  And that your variables are large enough to handle these expected values.


Consider using loops of length specific to the desired number of transactions.  For example, using this pseudo code create a sketch which follows this pattern:
initialize i to zero
loop 2 times for each row using the variable x
  loop 3 times for each element in first array using the variable y
    long array [i] = first array[x][y]
    increment i
  loop 2 times for each element in a second array using the variable z
    long array [i] = second array[x][z]
    increment i


I haven't found the source of the problem by reading through the code, and will limit my comments to advice about debugging the problem.

With the code as it stands, there are half a dozen points where the missing character might have dropped out.  With just a final result, the problem location is difficult to narrow down.  Modify your code to display intermediate data.

For example, in the sending code, print the read-in string and its length to Serial.  Eg, if you #include <Streaming.h> you can say:

Serial << message << ' ' << message.length() << endl;
Serial << msg << ' ' << strlen(msg) << endl;

and so forth.

[Note, msg actually occupies strlen(msg)+1 bytes, the last byte being a null-byte terminator, which your code doesn't send or receive.]

In the receiving code, besides the lcd.write of msg, do an lcd.print with msgLength.

You can also do some code clean-up in the sender.  Remove the line

while (Serial.available() > 0) {,
and its corresponding }, because  Serial.readString() already contains a character-wait loop with timeout.


Arduino I2C communication between Raspberry Pi

Its a long time since I used a Pi, but isn't it a 3.3V device and the Arduinos are 5V devices.  I think you may need a logic level shifter (not a resistor divider).  I suspect that's the reason I2Cdetect isn't working and without that working, nothing else will.


Which is faster, Serial or DigitalWrite?

Using digitalWrite() is the slowest by far.

Using PWM could be the fastest.

Using Serial could be the fastest.

PWM:

You have to filter the PWM output to be a smooth analogue signal for it to be of any use. The filtering adds an inherent sluggishness, or response time, to the system - the harder the filtering the slower the reaction to changes in the PWM duty cycle. Adjusting the filter component's values will give an optimum point between smoothness and response time. Bear in mind that the motors may respond erratically if there is insufficient damping of the signal. This will probably give the Sabertooth a hard time, too. The datasheet recommends are filter response time of greater than 1ms.

Serial:

If you are considering the 2x 60Amp version (thanks for adding plenty of information in the question, by the way) then the fastest baud rate is 384kbps - or 48k commands per second. The Arduino will of course not be churning data continuously because it'll be busy running the rest of the program, but using serial it is theoretically possible to send commands faster than the motor controller's output PWM.

So which is faster?

No idea. Only you can determine this, and I doubt you'll be able to determine the answer without wasting your time on some experiments.

The motors will have an inherent mechanical dampening thus creating an overall bottleneck in the whole system response time. I can almost guarantee that both PWM and Serial methods will be much faster than the response time of the motors themselves.


I have solved this.

The problem was with the pinout indeed.

attachInterrupt(0, myISR, FALLING);

will use the DIGITAL PIN 2

I was using attachInterrupt 2, that's all.


I get fairly accurate values most of the time however, at times I suddenly get a junk value.

if you use the ebay board, it has the incorrect grounding, which may contribute to the sporadic values you saw.

  For example, I call the weight function every 3 seconds

poor quality libraries could be another possibility.

I have used the board quite extensively and aside from its tempco, it is fairly reliable. you can see here: https://dannyelectronics.wordpress.com/2015/10/25/a-hx711-based-milliohm-meter/

when everything is done right (and in a constant temperature environment), it has very good consistency.


The Arduino Pro Mini has a row of connections at the small end that align with the connections on the USB-to-Serial board you have.  They are marked GND - VCC - RXI - TXI and should be in the same order as the connector on the FTDI board. I think that the pin marked GRN on the Arduino will align with the connector marked DTR on the USB-to-Serial board, but please make sure that VCC aligns with 5V!

With the FTDI board plugged into the Arduino, you can plug your computer into the FTDI board's USB port and when you run the Arduino IDE programming tool, that USB port should say that it's connected to a serial port.  Pick the "Arduino Pro or Pro Mini" as your board, then pick your processor (most likely the "ATmega328 (5V, 16MHz)" and finally your port (that serial port you found).

Now when you upload your Arduino program to the Arduino, it will know the board your have and the port to use.

As for programs to use, start simple and get the onboard LED to blink.  From there, you'll have the basics down for creating a program and getting it to the Arduino.  You'll find tons of example programs (called sketches in Arduino land) that will help you connect all your fun wireless gizmos!

As noted above - Google is your friend.  There are many places to go for examples and help.  Start with some of the commercial sites like Adafruit and SparkFun. Their staff really supports the Arduino community with how-to videos, libraries, examples, etc.


TPIC6B595 Output Unable to Allow Supplied Power to 7-segment Display

You are getting confused. The pullup resistor is only needed on open drain when you are using it to generate logic levels. It turns the OD output into an RTL output.
You don't want that.
Instead you want your open drain outputs to act like a low-side switch transistor - which is infact what they are.
You can do that by simply placing your LEDs in series with your "pullup" resistor, thus:

simulate this circuit – Schematic created using CircuitLab
I have only shown two elements there (everything inside the dashed box is inside the shift register), but you can see now how when an output is "on" the transistor conducts, and the current flows through the LED, through the resistor, through the transistor, and down to ground.
Your resistor value is then calculated as simply
    9 - Vfled
R = ---------
      Iled

For 20mA and a 2V forward voltage that comes out as 350Ω - so your 390Ω resistors are perfectly fine.


How to make sure Arduino's PWM pulses are phase shifted?

This (short) code below will achieve what I think you are asking for, on the Atmega328 (eg. the Uno, Duemilanove, etc.).

byte dutyCycle = 80;

void setup()
 {
  pinMode (3, OUTPUT);    // Timer 2 "B" output: OC2B
  pinMode (11, OUTPUT);   // Timer 2 "A" output: OC2A

  // Set OC2A on Compare Match when up-counting.
  // Clear OC2B on Compare Match when up-counting.
  TCCR2A = bit (WGM20) | bit (COM2B1) | bit (COM2A1) | bit (COM2A0);
  TCCR2B = bit (CS21);         // phase correct PWM, prescaler of 8
  OCR2A = dutyCycle;           // duty cycle out of 255
  OCR2B = 255 - dutyCycle;     // duty cycle out of 255
  }  // end of setup

void loop() { }

How it works

The code uses Timer 2 (an 8-bit timer) to count up to 255 in phase-correct PWM mode. Outputs are to OC2A (the "A" output - pin D11) and OC2B (the "B" output - pin D3). The duty cycle is in variable dutyCycle which must be in the range 0 to 255. The timer counts up to 255 and sets OC2A on compare-equal to the dutyCycle number, and it also clears OC2B on compare-equal, when counting up. The second half of the phase-correct cycle does the reverse. Thus the two cycles are of opposite phase.

Frequency

The frequency of the timer is 3.9 kHz. This is because the timer has a prescaler of 8, then it counts up to 255, then it takes two cycles per period (one up, one down):

16000000 / 8 / 255 / 2 = 3921.56 Hz

As Edgar Bonet pointed out in the comments, phase-correct PWM counts are not zero-relative, unlike other counting modes. Thus you divide by 255 to work out the frequency, not 256.

You could select other frequencies by choosing different prescalers.

Proof of operation

The oscilloscope screen here shows the two outputs, out of phase with each other by 50%.

You can see from the circled cursor measurement that the OC2B pin is off for exactly the requested duty cycle (80 µs).

 1/ 16000000 * 80 * 8 * 2 = 8e-005 (0.00008)  --> 80 µs


SPISettings was not declared in this scope

If fixed this by deleting this built-in library

/usr/share/arduino/libraries/SD

but then I received the error:

/usr/share/arduino/libraries/Robot_Control/ArduinoRobot.cpp:25:2: error: 'Serial1' was not declared in this scope
  Serial1.begin(9600);

so I deleted these libraries as well:

/usr/share/arduino/libraries/Robot_Control
/usr/share/arduino/libraries/Robot_Motor

which appear to be buggy in the 1.6 Arduino release. It's still unclear why any of these libraries were being used, since I wasn't including any of their files.


Is it possible to get which pin generated interrupt?

It is not possible to know which interrupt caused the ISR to be called. The INTFx flag gets cleared when the interrupt routine is called, so you lose that information (which is a shame).
The closest you could do is to have a separate ISR for each pin which just calls the common routine with a parameter to say which ISR it was executed via. That will add some extra latency though as it has to make an extra function call, but that can be somewhat mitigated by having the common function marked as always_inline, which means the compiler will duplicate it and place it within the code where it's being called from. This reduces latency but increases code size.
static ISREncoder(uint8_t pin) __attribute__ ((always_inline)) {
    // Do stuff with the `pin` variable
}

void ISR0() { ISREncoder(2); }
void ISR1() { ISREncoder(3); }


You can use FTDI cable with your board on the last row of pads as you have highlighted.

Unfortunately your board designers do not publish a pdf version of the schematic so I opened the provided schematics in EAGLE and exported the FTDI connector diagram.

Here is the FTDI connector connections from the schematic:

Here is the pinout of the FTDI cable

So you can solder a 6 pin header on the bottom row and use the standard FTDI cable.

The FTDI row on your board indicates "BLK" on the left so orient your FTDI connector's black wire with the "BLK" pad on your board.

EDIT:

As per your edits you are using hardware serial on your arduino board to monitor and you are using one instance of "SoftwareSerial" to interface with bluetooth.

As SoftwareSerial library says, you can define any digital pins for Tx and Rx. In the example they have used Arduino pins 10 (pin 14 of the ATMEGA) and 11 (pin 15 of ATMEGA) for Rx and Tx respectively. In your non-standard arduino board, the micro-controller pin 14 is labeled as PWM1 and pin 15 is labeled as MOSI and they are brought out on connector JP7.

So in a nutshell you can use pin 4 of JP7 as SoftRx and pin 5 of JP7 as SoftTx.

If those pins are in use, you can always use other digital pins that are unused in your design. Just refer to the schematic of your board, ATMEGA328 datasheet and arduino libraries.


Timer2 "Clear OC2B on Compare Match" not working as expected in CTC mode

The PWM modes manage pin at both ends of the cycle.

The point of the CTC modes is that they manage the pin only at one end of the count, but allow you to manage the other end explicitly.

To manage both ends explicitly, you use normal mode.

To set the OC2B bit with FOC2B in the TCCR2B with your interrupt:

ISR(TIMER2_COMPA_vect)
{
  TCCR2A |=  (1 << COM2B0); // Set OC2B on Compare Match
  TCCR2B |=  (1 << FOC2B ); // Force Output Compare B OC2B
  TCCR2A &= ~(1 << COM2B0); // Clear OC2B on Compare Match
}


This module is designed to be "plug in and go" without access to anything except the connector pads at the board edge. While there are a number of pads on the face of the board these are for "experts only" access and are unneeded for normal operation.

The only soldering required should be the addition of a 9 pin row of pins to allow the CC3000 module to be plugged into a solderless breadboard or a socket. If this is all you do then the module will work directly and interchangeably with  Arduino Uno, Leonardo/Micro & Mega. These are the only Arduino versions that a full library is available for so far. ADAFruit promise more versions will be supported "sometime".

Additional information is available from
 WIRELESS / WIFI / ADAFRUIT HUZZAH CC3000 WIFI BREAKOUT WITH ONBOARD ANTENNA

Solder on connector and go ...

Larger version of photo here makes pin use clear - + see link above

Example use weather station

Low power use tutorial

Example use wireless lamp

Library


2 way communication between Arduino with XBee and Computer

You don't need to declare an extra (software) serial port because the wireless shield connects the Arduino TX and RX on pins 0 and 1 directly to the TX and RX of the Xbee. So, Serial.available, Serial.read and Serial.write directly addresses the xbee. Just leave out the software serial from your code and it should work.


Arduino Mega Shield Library for Eagle CAD

Since you're new user, perhaps it's easier to take an existing project and modify it for your need.
For Eagle, examples can be found on Github.

https://github.com/zortness/rocket-mega-shield
https://github.com/practicalarduino/ProtoShieldMega

However, due to recent developments in the PCB EDA world I would suggest you take a look at Circuit Maker. It's more fit for sharing an collaborating designs and libraries. You can easily fork an existing board and use their community parts repository.


How can I calculate approximate cycles per second from pulsed pin on Arduino MKR Zero?

It is unclear exactly what you are trying to do, however the frequency generated by the code would be ~5Hz - corresponding to a period of 200mS


Trinket Pro 5V red light flashing when battery attached

Please consider reading the "https://learn.adafruit.com/trinket-gemma-servo-control/wiring" tutorial.

It says

  It is suggested you use an external wall or battery supply and not
  power the servo via the regulator. servos can draw up to 500mA and the
  Trinket regulator can only source 150 milliamps (USB power generally
  500 milliamps).

No matter what power supply you hook to the "Bat+" battery pin, if you hook the servo power to the "5V" pin on the trinket, the trinket's on-board 5V regulator will temporarily collapse under the load of the servo, which typically causes the system to reset over and over again.

Instead, please hook the servo power directly to the battery.
Alas, a typical partially-drained 9V battery has enough internal resistance that the battery's voltage will temporarily collapse under the load of the servo, which typically causes the system to reset over and over again.

Instead, use a better power source.

Many people, even when they intend to eventually run their system on batteries, start out using a wall-wart power supply, so they don't have to keep wondering "Is this glitch because of a bug in my software, or is the battery just going dead?".

The "Adafruit 16-Channel Servo Driver with Arduino" tutorial says:

  Good power choices are:

  5v 2A switching power supply
  5v 10A switching power supply
  4xAA Battery Holder - 6v with Alkaline cells.  4.8v with NiMH rechargeable cells.
  4.8 or 6v Rechargeable RC battery packs from a hobby store.

You might also want to look at other Battery holders that hold lots of AA batteries in a convenient package.

Related:
"How to get high current from 9 volt batteries"
and
"What is the max current I could draw from a 9V battery?".


DC motors not running using PWM and L298N motor driver

According to the Servo reference page it's not possible to use Servo library and PWM outputs on the pins 9 and 10.

  On boards other than the Mega, use of the library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins.


Next update with 3.1 of the library, you need to call irrecv.decodedIRData.decodedRawData to get the data. This code worked for me:
#include <IRremote.h>

int IRpin = 11;
IRrecv irrecv(IRpin);

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop()
{
  if (irrecv.decode())
    {
      Serial.println(irrecv.decodedIRData.decodedRawData); // Print the Serial
      irrecv.resume();   // Receive the next value
    }
}


Integrating an analog signal using Arduino Uno SMD

There are a couple of issues with your code.

First of all, 10^-3 is not a valid constant in C/C++ code. The correct syntax would be 1e-3, which means 1 × 10-3. But you have the further problem that you're working with integer variables, and 0.001 rounded to the nearest integer is just zero. You'll probably want to use float variables for this math.

Also, the values you get from AnalogRead() are all non-negative integers, so your summation will quickly overflow unless you subtract a constant from each reading in order to get both positive and negative values.

The second issue is about the delay() function, and trying to use it to determine the sample rate of your system. The delay() function is not all that precise. It really is just guaranteed to produce a delay of at least the number of milliseconds specified, but it can be more — sometimes much more.

Furthermore, the other operations in your loop take much longer than 1 ms anyway. For example, you're printing on the order of 25 to 30 characters to a serial port on every iteration, which is an overall rate of 25,000 to 30,000 characters per second. Unless you're running your serial port at an insane baud rate (430.8 kbaud or more), it simply won't be able to keep up, and it will end up increasing the period of your loop to whatever time it needs.

All of this means that the sample period of your loop is NOT 1 ms as you want, and in fact, it can vary quite a lot based on other things that are going on in the system, such as interrupts. For doing this kind of DSP, you will want to learn how to use a timer interrupt to control the sampling of the analog input, and you'll need to trim the amount of data transmitted for each sample to an amount your serial link can handle.


Transmit/Receive data Nodemcu(V3) + Bluetooth Module HC-05

I had the exact same problem and got it to work doing these changes:
I had to add this under my library include statements
#ifndef D5
#if defined(ESP8266)
#define D5 (14)
#define D6 (12)
#define D7 (13)
#define D8 (15)
#define TX (1)
#endif
#endif

and changed
SoftwareSerial BTserial(3, 1); // RX, TX
to
SoftwareSerial BTserial(D5,D6);
I used D5 and D6 on my esp8266 instead of D1 and D3 but shouldn't matter


What is the difference between serial begin() and wire.setClock() for I2C communication?

Serial has nothing to do with Wire/I2C communication. The examples only have this, because mostly they use Serial out- and input for interaction in the example codes (like showing the data of an I2C sensor on the Serial Monitor).
If you don't want to use the Serial Montior/Serial communication, then you can leave all the calls to Serial out.


DHT 11 temp. And hum. Sensor always 0 values

You haven't bought a DHT11 module but the Grove - Temperature&Humidity Sensor (High-Accuracy & Mini) / TH02 module.

Thus you should use the example code here or follow the guide at seedstudio wiki.

Datasheet of the sensor: https://www.silabs.com/documents/public/data-sheets/Si7005.pdf


If you are handling interrupts then you need to keep the code as quick and simple as possible.  I suspect that in this case calling blueToothSerial.println is what's causing the problem. It may well be calling an operation that an ISR can't call and so it fails and your code doesn't write the data you expect it to.

All I ever do in ISRs is set flags and then get the 'normal' code to handle changes to the flags. Personally I wouldn't do the digitalWrites within the ISR. Have two volatile variables, one for the pin state and one when sending a message is required and handle those in your loop().