Your conclusion is correct. The servo motor is asking a lot of current.

You need a power supply that is more than 2amps. Connect the grounds (the servo black wire to the Arduino GND). Don't let the current for the servo motor go through the Arduino board. Use wires for the servo motor that can handle high currents. Don't let the power for the servo motor go via a breadboard, because the small metal contacts of a breadboard are not for high currents.

Can you get a smaller servo motor?

Could there be something wrong with the 2 A power supply? Is it a certified and good quality power supply?

Tower Pro does not tell what the stall current of the MG90S is: www.towerpro.com.tw/product/mg90s-3/


Set the wall clock time or change GMT offset without ntp server?

The functions configTime and getLocalTime are from ESP32 core file esp32-hal-time.c. This wraps the ESP32 SDK functions. You can use the SDK functions to set the time and zone. They work with the RTC peripheral of the ESP32.

You can use setTimeZone to set the time zone.

The time.h is standard C time library. The ESP32 SDK makes it to work with the built in RTC (reference). To set the time it gets complicated. You would have to use undocumented SDK time functions.


Problem with serial driver for CH340G board

Using different search criteria I found http://kiguino.moos.io/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html

This indicated a newer driver for OSX 10.9 and above at:-
http://kiguino.moos.io/downloads/CH34x_Install.zip

It is now working OK.

PS This was probably a Mac question, but I will answer as it is mainly of interest to Arduino users.

PPS The board worked on my Raspberry Pi which had the driver installed.

WARNING

The driver worked on OS X 10.11 but after upgrading to OS X 10.11.2 when I plug the USB cable into the Mac it causes a crash. This may or may not be related to the upgrade but after this happened twice I gave up.


delay() runs super fast unless I remove a while loop that never runs

I will add an official answer just so that others can see it if they run into similar problems.

The issue is with the int sequence[1000] array, which eats up 2,000 bytes of data memory. The Uno only has 2,048 bytes of data memory so the instability is due to this memory hog of an array. Use a smaller number of array entries or switch to char (if you can) to use half the bytes of an int.


DC motor makes noise but does not rotate

For the benefit of anyone reading Jeremy Blum's Exploring Arduino book who is having the same issue- he has labelled the transistor wrong in the book so the collector and emitter are back to front. Turn the transistor around to face the other way and your issue will be resolved.


Strange artifact in writing to serial while executing loop

In your code colors is declared as

rgb_color colors[ledCount];

This means that the very first iteration of this cycle in shiftLED

for (uint16_t i = ledCount; i > 0; i--)
{
  // access colors[i]
}

will access ledCount[ledCount] which is obviously out of bounds (and will actually write into that location!). The behavior is undefined after that.

Using unsigned types for "backward" array iteration requires a bit of skill. The common idioms are

for (uint16_t i = ledCount; i > 0;)
{
  --i; // do this ASAP

  // access colors[i]
}

or

for (uint16_t i = ledCount; i-- > 0;)
{
  // access colors[i]
}

or

// Careful: this technique is not usable with unsigned types
// narrower than `unsigned int`
for (uint16_t i = ledCount - 1; i != -1; --i)
{
  // access colors[i]
}

This is assuming that you want to iterate over the whole array: from [ledCount - 1] all the way back to [0].

But if you intended to iterate back to [1] and stop short of [0] (which is apparently the case), then a simple fix for your cycle would be

for (uint16_t i = ledCount - 1; i > 0; i--)
{
  // access colors[i]
}

I.e. simply start from ledCount - 1, not from ledCount.


Opening webpage using ESP8266 in Arduino

First things first: never use a delay when reading from serial.

You are just blindly trying to read data and send it out to another port. That's not going to work unless you know how much data you need to read.

And that information is handed to you on a plate - you just need to interpret it.

You are required to read the serial data as it comes in and decide what it means, then do different things depending on that data.  For instance, when you read the characters +IPD you know you have an IP Data response to be interpreted.  Just after that comes a comma, and following that a number. That number is how many bytes you then have to read to get your data. So you keep looking and reading until you have received all the data you should be receiving.


The arrays need to be tagged with the keyword const.  It is possible that the original sketch was written using an earlier version of the IDE that you are using (or a later version?) and your version requires the const keyword whereas the author's doesn't.

Basically any arrays that are PROGMEM need the word const adding to them.  For instance, lines that start:

static unsigned char PROGMEM ...

need changing to:

static const unsigned char PROGMEM ...


Can the 'Adafruit Non-Latching Mini Relay FeatherWing' be used with an Arduino microcontroller such as an Arduino Mega 2560?

Yes.

There's not a lot more to be said really.

It's a relay, and they provide a MOSFET and associated circuitry to drive it cleanly.

Just connect power and ground to the Arduino, along with the "Signal" pin to the GPIO pin of your choice, and away you go.

Note that the relay is a 3.3V relay, so you must power it by the 3.3V pin, not the 5V pin.


Problem with running 2 DC motors with ultrasonic sensor

How (acoustically) loud are the motors?  If they're the typical RC car motors, they can screech harmonics right up into the 40 KHz range typical of ultrasound ranging sensors, interfering with the sensor's ability to work at all.

How (electrically) loud are the motors?  If RC as above, they throw all sorts of transients onto the power lines (and everything else within electrical pickup range).  You might want to put some ceramic capacitors across the motor leads to absorb some of those transients.

Kudos for the suggestions to provide separate power supplies for the motors and the Arduino / sensor combination.  I'd go even further, and provide separate power for all three, and use opto-isolators for the connection between the ultrasound and the Arduino.

Some years ago I used two Novak Super-Rooster motor drivers for a battle-bot competition.  They were driven by PWM outputs of an Arduino, where 50% duty cycle was off, 0% was full speed reverse, and 100% was full speed ahead.  These were powered by a sealed lead acid battery, and driven full-out, the motors got +/- 12VDC at about 40 amps.  There was a common ground with the Arduino, going to the Super Roosters, but not the motors, and the drivers took care of the electrical shielding, with a little help from the ceramic bypass capacitors I mentioned.  Worked great!


Using all ten capacitive touch inputs on the ESP32

is there a way to change the pinmode from digital-in to touch-in once normal boot has completed?

You already are. However it will make no difference since that pin is connected to external hardware - namely the button and a pullup resistor.

You cannot have touch inputs connected to anything else.  The only way to get the touch to work on that input is to physically remove the pullup resistor and even maybe the button. Touch inputs are "touchy" about what else is connected since even a button that's not connected to anything else can effect the capacitance on the pin.


Measuring Battery level with ADC already in use

As @dandavis rightly says in the comments, you can't measure the battery voltage from a power bank.  This is because the power bank typically includes a step-up converter to turn the batter voltage (3.2 to 4V) into a stable 5V.  That 5V will alwaye be 5V (or thereabouts) until the battery runs out and the power bank shuts itself off.

To measure the battery state you will have to directly interface with the batteries (disassemble the power bank) and tap into the battery terminals themselves.

Some power banks also have LEDs in them to display the power remaining. It could be possible to interface directly with these as well.

One thing to note, though, is that using a power bank for an ESP8266 board is pretty silly.  You are taking nominal 3.6V, stepping it up to 5V, then linearly dropping it back down to 3.3V again.  Both stages involve power wastage - the 5V to 3.3V most of all (a linear regulator turns the waste voltage into heat).

You would be better removing the batteries from the power bank and wiring them directly to the power input - or better still, feed them through a high efficiency switching regulator to get a stable 3.3V and feed that directly into the 3.3V pin.  be sure to include some way of monitoring the battery voltage and shutting off the power when it gets too low. Since your ADC input is already in use the simplest way is to add an external ADC chip to your design.


Arduino Ethernet Shield on Arduino Mega Pin Usage!

Those 4 pins D50 to D53 are the ICSP pins which appear twice on the MEGA; the Ethernet Shield uses the second set of connections located in the middle of the Mega board.

The header files gets told (by the Arduino IDE) that the board is a MEGA so the compiler uses those pin numbers to connect.


How can I clear the memory of my Arduino in this case?

Do the "button dance" - hold the Arduino in reset, releasing just you see the download start in the IDE. This may (will!) take a little practice to get just the right timing.

or

Use an external programmer connected to the ICSP connector. This could be a commercially made one, a DIY, or another Uno programmed and connected as an ICSP programmer. How-to's abound on the web.


Arduino New Optiboot Bootloader on custom ATMega328p board, ATMEL Studio and AVRdude

Since I am not so familiar with bootloaders, I would skip for now writing my own, so I would like to use the newest Arduino Bootloader for ATMega328p to support the firmware updates.

Even people who do know about bootloaders rarely bother writing their own when there is a perfectly good one with good support and good cross-platform tools available.  Why would you?

  The question here is, do I need to make any linker modifications or modifications in the code in Atmel Studio projects in order to be able to "transform" my code into application code so that can coexist with the bootloader?

No. The bootloader resides at a high memory address, and your code at address 0x0000 just like normal.  A fuse is set to say "Boot at the bootloader address", and another lets you set the size of the bootloader area (and thus the bootloader address).

  Since the optiboot bootloader used by Arduino uses the STK500 communication protocol and functionality, could I use AVRdude to communicate with the bootloader and flash the applications code only through UART?

Yes. This is what the Arduino IDE does. It just runs avrdude to communicate with the bootloader.  If you turn on verbose mode in the preferences you should be able to see what the exact command is that it runs so you can replicate it in your own program or script.


How do I know if a board fits my requirements?

Things to consider when picking an Arduino board:

Do I want native keyboard/mouse support? If yes: you'll need the Leonardo (or it's breadboard mountable equivalent) or the TRE (not released, dual MCU board).
Do I want a small form factor and/or have it breadboard mountable? If yes, choose a board like the Mini/Micro/Nano/etc.

If you want to make it even smaller, either get a board without USB built in or try using an ATTiny

Am I computing large numbers with it? If yes: use the Due, Galileo, or TRE (not released yet)
Do I want video/audio? If yes: TRE is the only way to go as of now (but it's not released yet).
Do I need a USB host (and not want to have an external shield)?  If yes, use the Mega ADK (limited support), Yun, TRE (again, not released yet), or Galileo.
Do I need WiFi/ethernet built in? If yes; use the Yun, TRE (still, not released yet), Ethernet board, or Galileo.
How many pins do I need (and how many of each type)?

Digital: simple ON or OFF. Use these for buttons, simple lights, some communication, etc.

Stay away from the Due if you don't want to mess with 3.3V logic. Most other boards are 5V. You can work around this with either voltage dividers (doesn't always work) or level shifters. As far as I know, you can't really do much if a sensor provides max 5V; level shifters AFAIK only work with digital signals.

UART Pins: these are the pins that you can use the serial library on. (Note: this doesn't include the software-serial library). One of these on most boards is connected to a USB chip.
SPI Pins: These are pins which are used by a form of communication (like on the Ethernet shield).
Inturupt Pins: These can trigger an event when the signal getting sent to the board changes. There are a couple of different settings, but this can be used for near-instant response time when low latency is critical.
PWM Pins: pins that go on and off to simulate a lower voltage. It does this by turning it on and off very rapidly. This is used often for dimming LEDs and controling the speed of a motor.
Analog pins: pins that can read a voltage and convert it into a number.

The Arduino Due has a much higher precision rate, as it has more possible values and it has less voltage, thus much more accuracy.

All of these types of pins can act as a digital pin. All of these, except the analog pins, are under the "digital pin" section of your Arduino board. I didn't go into the technical aspects of the pins; I explained then in the simplest way I could.

I left a lot of boards out of this list, but this should give you some things to think about when choosing a board. There's a lot of weird quirks with this list, so it's incomplete, especially with the types of pins. You'll just have to do research and figure out what you need and if a board can meet your needs. Just make sure to not plan two things on the same pin, especially when mixing different shields and sensors! Shields do take up pins.

Shields: they are pretty much compatible with every board except for if the board is 3.3V (newer shields can adapt automatically) OR if it's a breadboard mounted board, like the Nano. There are ways to work around this problem, but it's very difficult.


I2C communication between arduino and raspberry pi breaks under stress for unclear reasons. Why?

Use a logic level conversion IC.

picture source http://msx-elektronika.pl/en/logic-level-converter


What happens if you write >10000 times to the flash memory of an ATmega?

What will happen?

it may not pass parity check. so uploading code wouldn't be possible.

with that said, I have never had one flash-based mcu failure due to endurance. that's countless mcus since as far as I can remember.

to give you some sense of design headroom, I wrote-to and then read-back from eeprom on a pic over several hours @ 10ms per read/write, without a failure. that eeprom is rated 1M in endurance.

so unless you get some weird parts or you write to it repeatedly over a long period of time, flash failure is unlikely a practical issue.


Summary:

Your transistor is the wrong way round.
Rotate it 180 degree (so that collector and emitter are swapped) and it should work.

There are much better transistors available for this job, but this one should work when correctly connected.

Swap, test, report back.

The blue wire goes from emitter (right hand lead) to Arduino ground.

Longer:

The transistor is almost certainly "backwards" as above. More on that below, but first some comment on the actual transistor used and a superior alternative.

While it should work better than you describe, the BC548 is not a very good transistor for motor driving. It's maximum collector current is 100 mA. While you do not state the required motor current, within sensible limits a good guide is that the more a transistor can handle the better it will work, all else being equal. A 500 mA rated part would work better. An excellent pair of small transistor for "playing" are the BC327-40 (PNP) and the complementary BC337-40 (NPN). These have guaranteed current gains (effectively current amplification factor) of 250 and typically of 400. They are typically rated at 45V and 500 mA.
The Fairchild versions data sheet here from Digikey have an absolute maximum 800 mA rating. While the part was originally a European one it is widely available in the US and Asia and is usually about the same price as transistors with substantially inferior specs. eg see Digikey pricing below for BC548B and BC337-40 in 1, 10 and 100 quantity. The BC337 costs 1 cent more per transistor in each case. The BC337 comes in 3 versions with suffixes -16, -25 and -40. This relates to the current gain. The -40 part has an average Beta or current gain of 400. This is better (higher) than most alternatives and costs little or no more than the lower gain -16 and -25 parts.

BC548B datasheet here
BC337-40 datasheet here

BC548B pricing
1 10 100 prices are 22 / 20 / 11 cents each.

BC337-40 pricing
1 10 100 prices are   23 / 21 / 12 cents each.

According to that the pinout is CBE (collector base emitter) left to right looking at flat front with pins down. There are occasionally variations between manufacturers (but should not be) but if the datasheet matches your transistor it is "in backwards".

Swap C & E by rotating 180 degrees and report back.
With C&E swapped it acts like an NPN withj very low current gain.

Note: Presumable where you saay digitalWrite you meant analogWrite?


Reading multiple pins via registers on the Arduino Due

You will find a good introduction on using port registers here. It also mentions some cons and pros of using port manipulation.


Sending PUBX commands to GPS Board (Ublox NEO-6M) through SoftwareSerial

I've tried your code sending those PUBX commands to a ublox module and they work successfully for me.

There are a lot of fakes about on the internet using AT6558 chips repackaged as ublox. Check the GPTXT messages that are output when the GPS module is powered up to see if its really a ublox module or a fake one like this:

$GPTXT,01,01,02,MA=CASIC*27
$GPTXT,01,01,02,HW=ATGM332D,0080113573899*18
$GPTXT,01,01,02,IC=AT6558-5N-31-0C500000,J7M911C-B2-008827*50
$GPTXT,01,01,02,SW=URANUS4,V4.3.0.5*18


blah reported:

  So I was just hacking around and I finally figured out what went wrong! Apparently, there's a switch "XBEE/USB" that needs to be switched to XBEE for BOTH shields. After that, everything works as planned.

Can someone vote this up please to remove it from the unanswered queue?


Initialize and read from a PROGMEM array of pointers to PROGMEM arrays

const byte* const message[] PROGMEM =

to use an item, load it in RAM

strcpy_P(buffer, (byte*)pgm_read_word(&(message[i])));

source Arduino reference - PROGMEM


Arduino NRF24L01+ arduino to netmf transmit issue

I have a couple of projects that use the NRF24L01+ and the RF24 Library.

As I mentioned in my comment, the examples provided is not asynchronous. I am not sure if the library supports asynchronous operations. Nevertheless, in your example, one radio should be in transmit mode and the other receive. If you look at the examples, the author uses modes (role_ping_out and role_ping_back). Basicly, the author wrote the code so you can both send and receive. But you can't do send and receive at the same time.

If you look at the example cope in the library, you can see where you need to stop receiving and start sending:

radio.stopListening();

// Send the final one back.
printf("Sent response.\n\r");
radio.write( &got_time, sizeof(unsigned long) );

// Now, resume listening so we catch the next packets.
radio.startListening();

And on the other radio stop sending and start receiving:

radio.startListening();

// Wait here until we get a response, or timeout (250ms)
unsigned long started_waiting_at = __millis();
bool timeout = false;
while ( ! radio.available() && ! timeout ) {
__msleep(30); //add a small delay to let radio.available to check payload
  if (__millis() - started_waiting_at > 200 )
    timeout = true;
}

// Describe the results
if ( timeout )
{
  printf("Failed, response timed out.\n\r");
}
else
{
  // Grab the response, compare, and send to debugging spew
  unsigned long got_time;
  radio.read( &got_time, sizeof(unsigned long) );

  // Spew it
  printf("Got response %lu, round-trip delay: %lu\n\r",got_time,__millis()-got_time);
}

If this is a bit confusing, I would suggest you load the Getting Started example on both your radios. Once you get that working, you can get a better idea on how it works.

Good Luck


How to control a Nema 17 stepper motor with an arduino? (too much current / heat)

The stepper motor does not directly control or limit its own current.  When using the L298n for stepper control, the motor current control is performed by a PWM signal to the L298n ENABLE pin.  If you have ENABLE high (100% duty), current will be a factor of only the DC resistance of the stepper winding and the power supply voltage.  Here you are trying to drive a 1.2A@3.3V-rated stepper from 12V, so naturally the current will be ~3 times greater.

To adjust the motor current to a safe range for the driver, use analogWrite() from a PWM-capable pin on the Arduino connected to the ENABLE pin on the L298n, and set it to something less than 255 (50% is usually a good starting point).  Even then, the instantaneous current draw on the L298n will likely be stressing it outside of its operating envelope.

EDIT: I reviewed the info at the link, and this is the relevant area of the code:

// set speed to 200 out of possible range 0~255
analogWrite(enA, 200);
// set speed to 200 out of possible range 0~255
analogWrite(enB, 200);

Here is where the code is setting PWM of the two ENABLE pins to 200 (~80% duty cycle).  Drop this to 50 (~20% duty cycle) and you would likely resolve your overcurrent issue.  Reading further still, even the author gives you your first hint at what is happening:

  This is not a speed value, instead power is applied for 200/255 of an
  amount of time at once.


Ignoring the first high output from the sensor

One simple solution could be:
Start by noticing the first time you get the HIGH input whit a simple if statement:
if (digitalRead(sensor) == HIGH) {
}

where sensor is the pin of the sensor according to your code.
When this statement is True, you are interested in remain here until one of two things happens:

either you interrupt some kind of loop with another HIGH input,
or the time you have set is passed.

One way of knowing elapsed times will be with the millis() function, that returns the milliseconds since the board began running.
We should get the elapsed time the first time we enter the loop:
if (digitalRead(sensor) == HIGH) {
  long startTime = millis();
}

Then, as I have said, we need to remain here for a specific amount of time. We could use the while loop, but, which condition needs to be true?
So we have a start time, lets said x and you need to stay in the loop for, let's say, y milliseconds. This is the same as saying that you want to stay in the loop until the time we enter the loop and a specific amount of milliseconds, x+y. When the millis() function gives us a greater number, we should exit the loop:
if (digitalRead(sensor) == HIGH) {
  long startTime = millis();
  while (millis() <= (startTime+1000))
//                              ^ The second you are interested, 1000 milliseconds.
}

Now, we have to check if there is another interrupt during this time, by using the same statement of the beginning:
if (digitalRead(sensor) == HIGH) {
  long startTime = millis();
  while (millis() <= (startTime+1000)) {
    if (digitalRead(sensor) == HIGH) {
      // 2 interrupts in less than 1000 millis!
    }
  }
}

Summarizing is nicer to declare a global with the specific time we want, instead of the 1000 value we are using now:
const long maxTimeInterval = 1000;

And changing it in our code (that is inside the loop())
if (digitalRead(sensor) == HIGH) {
  long startTime = millis();
  while (millis() <= (startTime+maxTimeInterval)) {
    if (digitalRead(sensor) == HIGH) {
      // 2 interrupts in less than 1000 millis!
      digitalWrite(LED, HIGH);
    }
  }
}

Hope this helps!


Normal servos have a speed. It's their speed, and you can't change it. You can make it appear slower by moving in small increments, but you can't actually change the speed it moves.

With constant rotation servos the "angle" dictates the rotation speed, but even with those there is nothing you can do to change the relationship between "angle" and rotational speed.

Other than buying a different servo with a different degrees-per-second rating.


ESP-01 does not run code after Deep Sleep

What sasso is describing is classic Deep Sleep Zombie mode. There's someone else here with ESP-01 boards with the same issue.  I'd bet you got your boards in blister packs from Inland.  I didn't see any ESP-01 boards from Inland at my local computer store, only ESP-01S, and that one works with Deep Sleep just fine.  I only bought the one for a test.  I believe it's the Flash chip, but we haven't proven that yet.  I have plenty of Winbond flash in case I find a board that goes zombie, and can prove or disprove my theory.  I have 8 different types of boards and modules, and all come out of Deep Sleep correctly.
edit: If the pic at Ali is correct, the Puya Flash shouldn't be causing an issue, presuming it's real and not a clone.  Half the time the pics are only 'representative examples' of what they ship.  The ESP8266 Arduino core has supported Puya for a while now.  Also, on sober reflection the Inland package I bought said ESP-01S, and it's actually an ESP-01 (false advertising).  I looked closer and didn't see the pull-up resistors. :-(
If you're powering it from that USB programmer board, it should work.  If you have a separate 3.3V supply, I'd be suspicious of the supply.  The current spikes as the ESP is booting will cause many switching supplies to drop below 2V briefly, and the ESP goes insane.  Without having a zombie in front of me, I'm at a loss to go a lot further as my 'scope leads aren't that long.


5v, 4ohm, >1amp from a pin rated for 0.04amps; this isn't safe!
You would need a driver, but it would suffice to add a small transistor & a couple of resistors to drive it; here is a slightly more complex layout, there are many examples on the web.


How can I stop a loop when using a servo with a Key input?

Here is a quick and dirty solution, where each loop() iteration
corresponds to one “start sweeping”/“stop sweeping” cycle:

wait for the “start” command
then sweep back and forth in an infinite loop
stop at any point if you receive the “stop” command

void loop() {
    // Wait for the 'start' command.
    while (Serial.read() != 't')
        continue;

    // Repeatedly sweep back and forth.
    for (;;) {
        for (int pos = 0; pos <= 180; pos += 1) {
            myservo.write(pos);
            delay(3);
            if (Serial.read() == 's') // check for 'stop' command
                return;
        }
        for (pos = 180; pos >= 0; pos -= 1) {
            myservo.write(pos);
            delay(3);
            if (Serial.read() == 's') // check for 'stop' command
                return;
        }
    }
}

Note that this approach has a couple of drawbacks:

As this is blocking code, you cannot easily extend the program to do
other things.
The sweeping runs always start at position 0, instead of resuming
from the position that was current on the last “stop” command.

If you need anything more sophisticated, you should go to a non-blocking
approach based on a Finite State Machine (c.f. jsotola's
comment). Note that you can get away with delay(3);, as it is a quite
short delay, but you would have to break the sweeps into one step per
loop() iteration.

I suggest you give the FSM approach a try: read the tutorial I linked
to, then try to implement it. If you cannot get it to work, you can
always post another question here.


The board which you are using is operating on 3v3. Even if you try to run the relay using the D5 or any other pin on the board, you may not be able to run it successfully at all times. In this case, you can go for either MOSFETs or Pull-up resistors so that you can hold the voltage to 5V for triggering the relay. I would personally suggest to go for a PNP type.

As requested by Sachith, here is the circuit suggested for the problem stated. Just note that the voltage source should be +5 V (which is +1 V in the schematic). Also, the MOSFET is not the specific one, it is just for the schematic purpose.

simulate this circuit – Schematic created using CircuitLab


I've rewritten the code entirely. Not that yours was terrible, it was just easier for me to start from scratch. You are left with a very empty loop(), which I always prefer.

The code contains three 'colours' and an OFF state. You can add as many other colours as you wish: add an enumeration to _LED_STATE and then add a corresponding case(<NEW_COLOUR>) statement in LEDcontrol(). I haven't included any analogWrite() functions - or in fact any declarations for the LED pins at all - because I'm a little too lazy but it should be obvious where to put them within the case statement.

Note that in the final case() statement, the LED state is changed from green to off. This means that a short press will turn the LED off after it has cycled through all the other colours, but will stay off until a long press. If you only want long pressed to switch off/on, change line 103 to eLED_STATE = _LED_STATE_RED;, or whichever the first colour is.

#define btn 3   // button pin

#define SHORT_PRESS 100     // useful for debouncing, can be changed
#define LONG_PRESS  2000    // defines how long a 'long press' is
#define CYCLE       false
#define SHOW        true

//--// You can add new colours in this enum block
enum _LED_STATE
{
    _LED_STATE_OFF,
    _LED_STATE_RED,
    _LED_STATE_BLUE,
    _LED_STATE_GREEN
};

_LED_STATE eLED_STATE = _LED_STATE_OFF;

void setup()
{
    pinMode(btn, OUTPUT);
    LEDcontrol(SHOW);
}

void loop()
{

    if (digitalRead(btn))
        btnPressed();
}

void btnPressed()
{
    unsigned long tStart = millis();

    //--// Loop continuously while button is pressed
    while (digitalRead(btn))
    {
        //--// If LONG_PRESS is exceeded...
        if (millis() > tStart + LONG_PRESS)
        {
            //--// If LED is off, turn it on
            if (eLED_STATE == _LED_STATE_OFF)
                eLED_STATE = _LED_STATE_RED;        // Choose 'starting' colour
            //--// If LED is on, turn if off
            else
                eLED_STATE = _LED_STATE_OFF;
            //--// Update LED to display new eLED_STATE
            LEDcontrol(SHOW);
            //--// Now loop here until button is released
            while (digitalRead(btn));
        }
    }

    //--// If button is released in between the two press times
    if ((millis() > tStart + SHORT_PRESS) && (millis() < tStart + LONG_PRESS))
    {
        //--// Ignore if LED is off         ////// REMOVE ////////////////////
        if (eLED_STATE == _LED_STATE_OFF)   ////////// IF ////////////////////
            return;                         ///////////// NECESSARY //////////

        //--// Change the LED colour
        LEDcontrol(CYCLE);
        //--// Update LED to display new eLED_STATE
        LEDcontrol(SHOW);
    }

    //--// This helps to debounce; experiment with it
    delay(10);
}

void LEDcontrol(bool SHOW_OR_CYCLE)
{
    switch (eLED_STATE)
    {
        case(_LED_STATE_RED) :
        {
            if (SHOW_OR_CYCLE)
            {
                // paint it red
                return;
            }
            eLED_STATE = _LED_STATE_GREEN;
            return;
        }
        case(_LED_STATE_GREEN) :
        {
            if (SHOW_OR_CYCLE)
            {
                // paint it green
                return;
            }
            eLED_STATE = _LED_STATE_BLUE;
            return;
        }
        case(_LED_STATE_BLUE) :
        {
            if (SHOW_OR_CYCLE)
            {
                // paint it blue
                return;
            }
            //--// What happens after last colour? Next colour or OFF?
            eLED_STATE = _LED_STATE_OFF;
            return;
        }
        case(_LED_STATE_OFF) :
        {
            if (SHOW_OR_CYCLE)
            {
                // paint it black
                return;
            }
            eLED_STATE = _LED_STATE_RED;
            return;
        }
    }
}


I found out my solution. Actually I was connecting Rx to Rx and Tx to Tx.


Can the atmega328 return remainder during integer division?

If using optimization, the compiler is smart enough to recognize this.
Since your example is so short, it could be optimized away entirely.
To ensure that doesn't happen, the results in c and r have to be used in some way.
Also, if a and b could never change, the values of c and r would be calculated during compilation.
Therefore, I put the calculation in its own function.
From godbolt.com, using AVR-GCC 9.2.0:
#include<stdint.h>
#include<stdio.h>

uint8_t a = 0;
uint8_t b = 2;
uint8_t c = 0;
uint8_t r = 0;

void calculate() {
    c = a / b;
    r = a % b;
}

int main() {
    a = 7;
    b = 2;

    calculate();

    printf("%d %d", c, r);
}

compiles the calculate() function into
calculate():
        lds r24,a
        lds r22,b
        rcall __udivmodqi4
        sts c,r24
        sts r,r25
        ret

The results, stored in r24 and r25 respectively, are re-used from the same division operation.


Alternative to patching core library source and header files

Unfortunately there really isn't any way of doing that other than modifying those files. The good news is that it is perfectly viable to make the modifications under a different "core" and then amend boards.txt with the core containing the modifications.


Speed of built in DAC/ADC in Arduino Due

See sections 43, Analog-to-Digital Converter (ADC), and 44, Digital-to-Analog Converter Controller (DACC), in the Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf specsheet.

In particular, subsection 43.2, Embedded Characteristics, says: “1 MHz Conversion Rate”.  Some time diagrams appear quite a few pages later that suggest 10-bit conversions can be done more rapidly than 12-bit.

For the DAC (or DACC, per the specsheet), section 44.6, Functional Description, says:

  The DACC uses the master clock (MCK) divided by two to perform conversions. This clock is named DACC Clock.
  Once a conversion starts the DACC takes 25 clock periods to provide the analog result on the selected analog
  output.

AIUI, the Due's master clock frequency is 84 MHz, so DACC Clock frequency is 42 MHz, whence 25 cycles take 575 ns, which is an update frequency of about 1.74 MHz.

For more details about the ADC, see eg
Analog performance, particularly of Due's 12 bit ADC at djerickson.com.


How can I make an H-bridge using NPN transistor?

I am posting this as an answer so I can show the diagram.
But, my answer proper is in my comments above - your diagram is badly wrong. If what you have built is the same as the diagram then it is not what you are trying to build.  And, if the diagram is wrong, you should fix it.

Fritzing can do an OK job of showing layouts when used well. But your diagram is unable to be interpreted with certainty. It is not a matter of  you "not being good with Fritzing" as you say - it is a matter of putting in enough effort to show what you are trying to show. If it is wrong you MUST fix it - it is pointless to show people absolute rubbish which cannot be correct.

You say " ...I did exactly the same, [as the example]..." BUT your diagram and his are different and half your diagram cannot work in any way.

You MUST compare the two and not just keep pretending that yours and his diagrams are identical.

Look at the diagram below - copied from your diagram.
Inside the orange ellipse - how do the blue wire, green wire, diode and transistor really connect.
Why do your wires not end on "holes" in the breadboard - if a wire end is between two holes, which is it really meant to connect to?
Follow the red and blue lines that I have added to show current flow through one motor. The current MUST go THROUGH the diode in your example. In his example the motor current does NOT go through the diode.
FWIW - your diodes can not pass current in the direction shown - but that's not your main problem. FIRST fix the wiring so it is the same as his and the same as what you have built/ THEN your main question may be able to be answered - or may answer itself.

LOOK at his diagram and yours.
Compare them.
Follow the current pars.
Realise that your one is wrong.

If you refuse to take advice and continue to insist that what you have shown on your diagram is the same as the example then you will be unhelpable. Or, take advice and learn as you go and you will find it a rewarding hobby.


GSM library , sendSMS, string instead of char

OK, i found access to SIM card and tested this myself.
I can confirm it's working!

So, if anyone wants to use the standard GSM library for SMS, you can use both chars and strings.


How do I set a continuous servo to turn on until a switch is flicked?

Your are not debouncing your input buttons, which means that digitalRead(Closed) (and Open) will be HIGH in one execution of loop and in the next pass, 3 millis later, it will be LOW.

The servo probably need over 50ms to complete the action (you don't said what servo are you using).

You need to wait for the action to be completed before trying to move it in another direction.

You didn't post your schematic, so may be you wired things wrong. How can we know?

Usually the first step when you find a problem is add Serial.print to know what is working and what not, and then correct the problem.


Circuit diagram interpretation and electrical flow

Should the Resistor be Placed Before or After the LED?

The important thing to remember is that the direct current electricity must flow through the circuit to be useful. Since the resistor is part of the circuit (meaning that there isn't another path for the current to take) it resists the overall flow, thereby helping to protect the LED. Whether before or after the LED, it would still be in the circuit, and would therefore still reduce current flow.

Visualizing the Flow of Water

Think of it like a water hose, where the LED is a flow meter and the resistor is your foot. If you step on the hose before the flow meter it will cause the overall flow to slow down. Stepping on the hose after the flow meter but before the nozzle will have the same result, as the water must pass through the entire length of the hose before being released.


Are there ultrasonic transducers which are able to produce a "chirp" sound wave?

Piezoelectric speakers, the kind commonly found in ultrasonic transducers generally operate in a narrow frequency range when operating at ultrasonic range (a resonate frequency of the metallic diaphragm). This is very true once you get above about ~60 kHz. However if the ultrasonic "chirp" you are looking for can be in the range of say 20-60 kHz you could be in luck, i.e., http://www.conrad-electronic.co.uk/ce/en/product/710991/KEPO-piezo-element-25-60-kHz-515-mm

You could use the Tone function (which goes up to 65535 Hz) to produce the frequency sweep you desire. However if you want to go up to frequencies in the 100+ kHz range you will be delving into research territory and hence extremely expensive equipment.

Having said that, technologies change very quickly and I my knowledge may already be out of date. Hope this helps.


An ISR should be kept as short as possible, since while it runs, no other interrupts can be handled (including the one powering the delay() function. Thus you cannot delay that easy inside an ISR and you shouldn't do it either.

Instead you should set a simple flag variable in the ISR and then check this flag inside your loop() function. If the flag is set, you can execute the corresponding code inside the main code instead of inside an ISR.

A typical flag definition is a single byte (since then every read/write action is atomic and cannot be interrupted by an ISR). Be sure to set it volatile, so that the compiler knows, that this variable may change any time.

volatile byte interrupt_flag = 0;

In the ISR you can set this variable to 1 for example and then in your main loop() function:

if(interrupt_flag){
    // Do whatever you need to do here
    interrupt_flag = 0; // reset the flag variable
}


You should split your problem in pieces. Like you cannot get communication with your Arduino again, so check first:

If you plug in the Arduino / USB, do you get a message on your computer?
Is it visible in the systems manager?
Is it visible by the IDE?
If you connect an adapter (12 or 9V), does it make a difference?
If you try another Arduino, does it work like it should be?

If you are a beginner, always make sure:

Never change any wiring with the Arduino on
Never have dangling wires, if you do not need a wire for the time being, either remove it completely or put it in a breadboard hole that is not used
Never change components with the Arduino on
After rewiring/adding/changing components, double check first

Update for comment below because it does not fit as comment:
To buy a cheap/fake (but working) Arduino uno, e.g.
Arduino Uno from Aliexpress


How to switch on an AC bulb using arduino as well as regular switch?

This can be done (to a certain extent) using a SPDT (Single-Pole-Double-Throw) relay and an SPDT switch.

The basic principle is the same as when you have two light switches controlling the same light (such as on a staircase - one switch at the top and one at the bottom).  The two switches alternate between one of two different paths for the current. When both switches are routed to the same path the light is on.

Both the Arduino and the switch can turn the light on and off at will. The only problem, though, is that the Arduino has no clue if the light is on or off. To know if the light is on you will need some kind of feedback mechanism.  That might be a simple LDR that looks to see if it's light or dark, or some kind of current monitoring system (current transformer, hall effect current monitor, etc) which the Arduino can use to see if current is actually flowing through the lamp circuit or not.


Convert serial value into hex using in Genuino zero

There are several issues with your sketch. The most important is the lack of understanding for the difference between internal and external representation.

The sketch reads a single character from Serial and prints the value as a hexadecimal number. The character is ASCII; a number that represents symbols in our alphabet.

Your goal is to read characters into a string and then convert the string to a number assuming that the string represents a hexadecimal number ('0'..'9' and 'a'..'f' or 'A'..'F').

The sketch should be 1) scan string, 2) parse and convert string to number, 3) print the number.

Scanning the string requires skipping whitespace and then collecting characters until a whitespace.

The sketch could look something like this:

void setup() {
  Serial.begin(57600);
  while (!Serial);
  Serial.println(F("Serial started..."));
}

void loop() {
  const size_t BUF_MAX = 16;
  char buf[BUF_MAX];
  char* bp = buf;
  char c;

  // Skip whitespace
  do {
    while (!Serial.available());
    c = Serial.read();
  } while (c <= ' ');

  // Scan token until whitespace
  *bp = c;
  do {
    while (!Serial.available());
    c = Serial.read();
    *++bp = c;
  } while (c > ' ');
  *bp = 0;

  // Print scanned token
  Serial.println(buf);

  // Convert to number and print
  const int BASE = 16;
  long val = strtol(buf, &bp, BASE);
  if (*bp == 0)
    Serial.println(val);
  else
    Serial.println(F("not a number"));
}

This allows scan of hexadecimal numbers with possible sign (as defined by strtol). By changing the BASE to zero strtol will use the notations for base definitions (prefix '0' for octal, '0x' for hexadecimal). Last, please observe the parse error handling provided by strtol(*bp != 0).

Cheers!


How can the Arduino Uno support up to 12 servos if it only has 6 digital PWM pins?

Although I haven't looked at the source myself, in these types of situations they usually use interrupt timer 1, which in PWM mode would have been associated with pins 9 and 10. This would explain why you can't use pulse width modulation on those pins. In fact, you can use any of the three timers for PWM on any digital pin, although it's not as good as the built in PWM options.

(source: bansky.net)

(Source)
The above image accurately describes how the signals are sent to the servo motor. Such a waveform is similar to a standard PWM. The servo library can translate a degree to a waveform that the servo's IC will be able to use to adjust the motor's position with it's motor and potentiometer.


ESP8266 error: espcomm_upload_mem failed while uploading sketch

Well, first of all you should make sure that the voltage on both Tx and Rx pins of the ESP8266 is 3.3V (the Tx and Rx voltage on Arduino is 5V). Personally, I've never succeded in using an Arduino to program the ESP (even though there are plenty of examples of this setup in the web). After a while, I just gave up and bought a converter to do the job for me (it's totally worth it).

Even so, I got this error a few times. You must keep two things in mind:

In operation mode, the CH_PD pin must be connected to 3.3V, but it won't do any harm to let it connected during the flashing, so I just soldered a wire between these two pins to make things easier.
In flashing mode, GPIO0 must be connected to GND. It won't work otherwise. I strongly recommend you using a usb converter for this, and only connect it to your computer once GPIO0 has been set to GND. This has solved this issue for me, in fact I even soldered a switch on my converter between GPIO0 and GND.

Hope this answers your question.

EDIT: Here are some photos of the setup


byte and char are the same. If you set 0 as string terminator after last character in the buffer, you get a zero terminated string. If you really must use String, you can create an instance with a constructor that takes zero terminated string.

buffer[tam] = 0;
String str((char*) buffer);

Let in the buffer a place for the zero. (char*) is cast that says that the byte array is a char array.

Note: Don't use String class in a MCU, use zero terminated character arrays.


Why ATMEGA328P U-TH doesn't answer to USBasp but work fine with Arduino as ISP?

If you want to upload a sketch via any other interface than ISP, the atmega needs a bootloader.
The bootloader basically is a piece of software which is stored in a dedicated flash section, the "bootloader section". Code stored in this bootloader section has the special ability to write to parts of flash memory where the actual program is stored (this is called the "application section").
In general, a program can not overwrite its own flash section, so the bootloader and the application need to be stored in different sections/partitions.
In principle, a bootloader can do whatever a normal sketch could do: toggle pins, access eeprom, read UART/I2C/etc... and as it can also write to the "application section", you can make it read data from any interface and transfer it to the application section.
This is what happens if you upload code via USBasp (Arduinos have a USB-to-UART converter on board).
But of course, this requires that a bootloader is installed.
avrdude: error: program enable: target doesn't answer. 1 - this might sound misleading, what it actually means is, that the bootloader doesn't answer. That makes sense, as the device doesn't have a bootloader.
When there is no bootloader, the only way to upload code is to use ISP, which doesn't need any software to function. It's a hardware functionality that Atmel implements in silicon.
A code upload via ISP works in (almost) any case.


how to create a specific buffer when there is no buffer message in the data packet?

That read method just retrieves bytes that have already been received from an internal buffer.

The buffer is pre-allocated to a specific size (64 bytes) and that is how many bytes can be received before you start to lose data as it gets overwritten.  You have to be sure to read your data from the buffer before it overflows.

The function that actually receives each UART bit from the IO port, builds them into bytes, and stores them in the internal buffer, is this one:

void SoftwareSerial::recv()
{

#if GCC_VERSION < 40302
// Work-around for avr-gcc 4.3.0 OSX version bug
// Preserve the registers that the compiler misses
// (courtesy of Arduino forum user *etracer*)
  asm volatile(
    "push r18 \n\t"
    "push r19 \n\t"
    "push r20 \n\t"
    "push r21 \n\t"
    "push r22 \n\t"
    "push r23 \n\t"
    "push r26 \n\t"
    "push r27 \n\t"
    ::);
#endif

  uint8_t d = 0;

  // If RX line is high, then we don't see any start bit
  // so interrupt is probably not for us
  if (_inverse_logic ? rx_pin_read() : !rx_pin_read())
  {
    // Wait approximately 1/2 of a bit width to "center" the sample
    tunedDelay(_rx_delay_centering);
    DebugPulse(_DEBUG_PIN2, 1);

    // Read each of the 8 bits
    for (uint8_t i=0x1; i; i <<= 1)
    {
      tunedDelay(_rx_delay_intrabit);
      DebugPulse(_DEBUG_PIN2, 1);
      uint8_t noti = ~i;
      if (rx_pin_read())
        d |= i;
      else // else clause added to ensure function timing is ~balanced
        d &= noti;
    }

    // skip the stop bit
    tunedDelay(_rx_delay_stopbit);
    DebugPulse(_DEBUG_PIN2, 1);

    if (_inverse_logic)
      d = ~d;

    // if buffer full, set the overflow flag and return
    if ((_receive_buffer_tail + 1) % _SS_MAX_RX_BUFF != _receive_buffer_head)
    {
      // save new data in buffer: tail points to where byte goes
      _receive_buffer[_receive_buffer_tail] = d; // save new byte
      _receive_buffer_tail = (_receive_buffer_tail + 1) % _SS_MAX_RX_BUFF;
    }
    else
    {
#if _DEBUG // for scope: pulse pin as overflow indictator
      DebugPulse(_DEBUG_PIN1, 1);
#endif
      _buffer_overflow = true;
    }
  }

#if GCC_VERSION < 40302
// Work-around for avr-gcc 4.3.0 OSX version bug
// Restore the registers that the compiler misses
  asm volatile(
    "pop r27 \n\t"
    "pop r26 \n\t"
    "pop r23 \n\t"
    "pop r22 \n\t"
    "pop r21 \n\t"
    "pop r20 \n\t"
    "pop r19 \n\t"
    "pop r18 \n\t"
    ::);
#endif
}

To show you how the timing of the routine works, here is a little diagram:


Unless the FSi6 (whatever that is) uses an nRF27L01+ as its transmitter, then no - you can't.

The nRF24L01+ chip will only communicate with other nRF24L01+ chips.  It contains its own custom protocol within the chip and it can only talk that protocol and no others.


Reducing lag between the arduino and a processing sketch on my computer

As already pointed out, your Arduino is saying too much too fast. Adding delay() will slow it down, but still it keeps yelling at Processing. Ideally, you want Processing to ask for the value when it's convenient, and then receive one answer from your Arduino.

Enter SerialEvent().

As opposed to loop() on your Arduino and draw() in Processing, everything inside serialEvent() only excutes when there is something new in the serial buffer. So instead of Processing asking questions as fast as possible and your Arduino yelling back even faster, they can have a nice, polite (asynchronous) conversation.

Both Processing and Arduino have a serialEvent. This is serialEvent() on the Arduino and this is serialEvent() in Processing. Using serialEvent on both sides, this is what would happen:

Processing sends a character to the serial connection. This could be any character, but if we predetermine one we can filter out any unwanted requests caused by e.g. a noisy signal. For this example, let's send a V every time we want a new reading of your potmeter. After the character is sent, we continue our business as usual. Not waiting around for an answer here!
On the Arduino side nothing is happening, until it receives data in the serial buffer. It checks whether the incoming character is a V, and lucky us, it is. The Arduino reads the potmeter's value once, outputs that value to serial once, and goes back to chilling out, maxing relaxing all cool. Protip: terminate the value with a character (* in our case). This will help you in the next step.
Processing is doing its regular interfacey pixel business when all of a sudden there's a disturbance in the force new data in the serial buffer. It switches to serialEvent(), and starts reading the serial data, until our terminating * is encountered. Knowing for sure this was the last character worth reading, we can now store the incoming value in a variable that stores the Arduino's reading.
That's it. Processing now knows the new sensor value and carries on with whatever we tell it to do. Meanwhile, your Arduino is enjoying the weather or contemplating its existence until there is incoming serial data.


"Pseudo-code" isn't a programming language. It is just a term that we use when we write code that looks like code but can't be compiled, because it's half-English, half-code. You write pseudo code when you want to communicate to another human how code is supposed to work without getting bogged down in the details.


I would use a single transistor rated at minimum 1A continuous (a MOSFET by choice), and have both LEDs switched in parallel with their own resistor.  By having them in series as in your second schematic you are limiting the input voltage to a minimum of 2×Vf which could be as high as 5.2V, and thus more than your power source can provide.

simulate this circuit – Schematic created using CircuitLab

This gives the same result as your first circuit, but only uses one transistor for the switching. You can add more LED+Resistor pairs in parallel as you like as long as the total current is below that which the chosen MOSFET can handle.

You should rate the MOSFET to handle the maximum continuous current, not the pulse current, in case the output of the Arduino should be set continuously HIGH instead of sending PWM.

You should also note that the pulse current of an LED is usually rated at 1% duty cycle.

Also note that as the voltage of your power source drops, so will the voltage across the resistors, and thus the current flowing through them (and your LEDs) making the LEDs dim.  It may be beneficial to first pass your battery power through a high-efficiency 3.3V switch-mode regulator to keep the voltage stable whilst wasting the minimum amount of power in the regulation.


Power suply for MicroSD card breakout board

Yes you can give power supply to MICROSD CARD BREAKOUT BOARD from a 3.7V battery It has Onboard LP98x Voltage regulator winch provide 3.3V regulated power supply.

Take reference from here Schematic of MICROSD CARD BREAKOUT BOARD


How to properly construct objects on ATmega2056?

I tried working constructing in the global scope, but I get garbage values printed to serial ...

Constructors in global scope are called before init and setup and thus are probably executing too soon for you. This would account for the garbage printed to serial, because your constructor is printing before the Serial.begin() call.

You can put constructors in global scope, however they should do fairly trivial things (eg. setting a counter to zero, or a pointer to NULL). Do not rely upon the system being initialized, thus do not call functions like millis, nor should you be using dynamic memory allocation at this point.

Most classes defer their "real" initialization to a begin function (eg. Serial.begin) because it is safe to do that, usually in the setup function.


I think that  AcX, AcY, AcZ, GyX, GyY, GyZ are raw acceleration and gyroscopic values recieved from mpu6050 in the corresponding directions. in order to recieve them a procedure is followed.

 Wire.read();

means two registers are read and stored in the same variable

   accelerometer_x = Wire.read()<<8 | Wire.read();

reads registers: 0x3B (ACCEL_XOUT_H) and 0x3C (ACCEL_XOUT_L) that is ,
it deals with bitwise operation to shift the values 8 bits left (multiplying it by 256).
This enables addition ("|" or "ored") of two datas in order to continuously output the accelerometer data !! Without this you would not be able to see the increasing and decreasing sloping values .
Further, the print just displays the instantaneous values on screen.

If you want to go in deapth of the code, you can visit this site for line to line description !!

https://www.mschoeffler.de/2017/12/09/example-application-gy-521-module-mpu-6050-breakout-board-and-arduino-uno/

 delay(500);

Totally depends on your project, i don't see any forecoming issues if you will make 333 go 500 !! It will just stablize the output on screen there for a bit longer (for .5 seconds)


Receiving partial messages when using VirtualWire and ServoTimer2

If msg1 is of type char* (as is implied by the cast in msg1 = (char*)buf1;), then it seems to me that that statement will copy the address of buf1 to msg1.  Then, when you fill buf1 with ascii zeroes (ie, characters '0') msg1 ends up being a string of ascii zeroes.

On the other hand, if msg1 is of type String (to go along with your comment about buf1 being of type String) the cast should be unnecessary.

Note, if you don't give the source for the vw_get_message() routine and the declarations for all of the constants and variables used in the code extract, it's unlikely anyone can definitively answer your question.

Note, the while test, msg1 != sweep_term, may not be well-defined on entry to the while loop.  Or, if msg1 is left over from a previous use, you won't enter the loop at all.  Consider writing the loop in the form do { ... } while (msg1 != sweep_term); instead.

Note, if (as said in a comment) buf1 is of type String, then the statement memset(buf1,'0',VW_MAX_MESSAGE_LEN); is a line of code I'd recommend against, because it treats buf1 as a simple array rather than as an object.  (In this case it should make no difference, but it requires some research to be sure of that. [1,2,3,4,5])


Serial not declared in this scope, newbie mistake most likely

Case matters in C/C++. You should write Serial rather than serial.


I just read that it can't. It's a shame:

https://forum.arduino.cc/index.php?topic=441328.0


It sounds like a power-to-ground short circuit, either a fault in the Ultrasonic sensor or in the connection to the Arduino.

Check your connections, and if you have an Ohm-meter, check the resistance between the sensor's power and ground pins.

Current consumption is a function of the device being powered, not of the power-supply, unless the supply lacks the capacity to provide as much current as the device needs.

Note that 9v batteries (the small brick aka a "transistor battery") is not well suited to supplying much current and probably will not power your Mega, or not for long, anyway. They are much better suited for long-term powering of very low current devices, such as a smoke detector.


What pins can be used for chip select (CS, CC) on the Arduino nano every?

The following answer assumes the Arduino is the master.

You can use any pin for that (at least any GPIO pin).

Multiple SPI devices can be connected to a SPI peripheral on an Arduino (in principle).

Every SPI device should have their own CS/CC pin, and is mandatory when you use multiple SPI devices.

For this reason, there is no single pin the SPI can define for being used as CS/CC pin. However, it should give a GND or VCC value, thus a CS/CC pin should typically be configured as a digital input pin (as master) for each slave.
(See remark of KIIV too); as slave the CS/CC pin should be a digital output pin.

For the other pins (MOSI, MISO, CLK), the Arduino uses a fixed set of pins because all SPI devices will be connected to these pins.

So the CS pin is configurable, and the other spi pins are fixed.


What maximum length of wire can I use to connect a push button to an Arduino?

Majenko's answer is probably the safest option. There is, however,
something simpler that you can try:

Use a strong pull-up (or pull-down). Something around 1 kΩ will
make it quite difficult for the noise to pull your signal low, at the
cost of increased current consumption.
Connect each push button to the Arduino using a twisted pair of copper
wires. This will minimize the inductive pickup effect.


NTP Client Library. Set sync provider pointing to public class function. Possible?

What could I do to allow registering this function as sync provider to hide NTP internals to my sketches?

The function should be a static member function. A "normal" member function does not have the right prototype as there is a hidden parameter ("this").

static time_t getNtpTime();

To solve this you need a single-ton (an instance of the client class) that the static function can use.

class NTPClient {
public:
   NTPClient() ...
   {
     ...
     s_client = this;
   }
   time_t getNtpTime();
   ...
   static time_t getNtpTime() ( return (s_client->getNtpTime()); }
   ...
protected:
   static NTPClient* s_client;
   ...
};
...
NTPClient::s_client = NULL;
...
NTPClient ntpClient;
...
setSyncProvider(NTPClient::getNtpTime)

Alternatively a global function and a known instance:

class NTPClient { ... };
extern NTPClient ntpClient;
...
time_t getNtpTime() { return (ntpClient.getNtpTime()); }
...
setSyncProvider(getNtpTime)

Cheers!


here there's a nice tutorial on how to obtain it.

Basically it sets the registers so that a pin outputs a PWM signal at 800 kHz and then modulates that signal in code by just switching the pin and off (pinMode set to INPUT or OUTPUT). If you plug a cable (20 cm and on) to pin 8, and tune your radio to 800Khz you'll hear some noise going on and off.

If you read down the forum you'll see people suggesting how to actually send tones, by putting a very small delay (delay(1)) between the on/off of the pin.

In this link they guys have ogn further and they even implemented a morse code library.

Now I am trying to figure out a way to do the same for a receiver.


It sounds like you need a debouncing circuit.
You can do it in code, but you are then trying to execute more code in you interrupt handler.
I would go for a hardware version.  I don't have the circuit to hand but if you search for a 'Schmidtt Trigger' based debouncing circuit.  You can implement it with 5 resistors, a capacitor, a LM386 OpAmp and a CMOS XOR IC (Inverts the signal which the inverting Schmidtt trigger inverts).

What happens is the Schmidtt trigger goes low when the input passes a certain voltage.  It remains low until the voltage passes the low voltage threshold at which point it goes high.  The CMOS XOR IC (I think its a 4004??) takes two inputs and inverts them.  It also adds extra hysteresis which further damps the bouncing.

The values of your resistors affect the thresholds, but there are plenty of calculators on the web that will solve the values for you.

The LM386 has two channels and the CMOS usually has 4 so it becomes quite easy to debounce multiple signals.

Hope that helps.


Arduino on breadboard Tension is 4.4V instead of 5 V,looking for some guidance

The yellow-boxed 5V and Gnd buses on the freetronics.com.au ProtoShield Basic for Arduino [like you used] already have copper strips connecting the holes.  The strips run on both sides of the board and the holes are plated-through, so there's no need (for this kind of circuit) to have additional bus wire running along above the boxes.  Having that extra wire there gets in the way of making changes, whether for debugging the circuit or for adding or replacing components.

From the frontside picture, it appears you may have a voltage regulator on board.  (However, I don't see the connections to 5V and Gnd, so might be misinterpreting things.)

If your board input is 5 VDC from an external supply, feeding that 5 V into a regulator will lose half a volt or so, which may account for what you are seeing.

However, let's instead suppose you are putting 7 to 12 VDC into an on-board 5V regulator and then measuring 4.4-4.6 V out.  One possibility is the regulator isn't working.  This can happen if the regulator's input or output capacitors are the wrong sizes or wrong kinds, and cause oscillation.  Diagnosing that kind of problem is straightforward if you look at the 5V line with an oscilloscope.  Another possibility is something drawing a lot of current (eg a couple of amps) and taking the 5V line out of regulation.  That's usually easy to diagnose because of all the resulting smoke and heat.

Drawing a good schematic is an excellent step to take to allow better problem debugging.

Other steps to take:

Measure the amount of current the whole board is drawing, or that the NRF24L01 is drawing.  (For the latter measurement, you might need to lift your ground lead off the NRF24L01 board and put the ammeter into the ground circuit.  In general you want all the grounds to be at the same voltage, so the voltage drop across the ammeter is a problem, but not much of one.)
Pull the '328P chip and see if that makes any difference.  In general, it's a good idea to work out a prototype board's power supply problems – such as shorts, reversed electrolytics, incorrect resistors – in advance of installing a microcontroller chip onto the board.
Remove the NRF24L01, if feasible, while debugging the power supply.  If you can't easily remove it, check your schematic and see if all of its pins except 5V and Gnd are open when the '328P chip is pulled.  If so, you can detach the NRF24L01  ground lead to take it out of the circuit.  If, during testing, you unsolder and remove the NRF24L01 board, consider making a socket for it from two 5-pin female header strips.


CAN for the Phy (physical) layer would be good for several thousand feet. You can use whatever baud and protocol on the CAN layer you like within reason. I am assuming (maybe in error) that they all communicate on the same bus. This CAN Phy was designed for this. It would be possible for you to write your own protocol and simply address each by a unique number or whatever. There is also the option of using a CAN controller but I think that would be a lot of time not needed to design your solution. By placing a Atmega8 at each sensor opens up a lot of possibilities for you.


Send Arduino data to Database using ESP8266

Since you mention you operate on a battery (standalone), what exactly do you mean by "the database"? Do you have online connectivity? Do you have any peripherals like an sdcard or other storage?

In case you don't have a permanent online connection, you would need to use some writable memory (like EEPROM) to store your data in some organized form. Since the ESP8266 doesn't seem to have any EEPROM built in, you would need to use its flash memory, like described in those answers.

A database could be as simple as a fixed length string list (essentially how string arrays look in memory). For example if the string data you want to save always has 32 bytes, you could just divide your available storage (e.g. 4096 bytes) to have a "database" wich can store 128 entries (4096/32). Your "database entries" will then be addressable in multiples of 32, you would find the 1st entry at byte 0, the 2nd at byte 32 and so on.

Once you are online, you could send the data out for further processing. Getting the data into a database can be as simple as a https request.


You planning to use multiple servo, but only declare one.
I still don't get about the pattern, but maybe this will give some image:

Servo myservo[5]; // assuming you have 5-servo
                  // servo[0]--> pin 0
                  // servo[1]--> pin 1
                  // servo[2]--> pin 2
                  // servo[3]--> pin 3
                  // servo[4]--> pin 4
pos = 0;

void loop() {

BUTTON = digitalRead(button);
Serial.println(BUTTON);
 if(BUTTON == LOW){
  randomNumber = random(1,4);
  delay(275);
  pos+=randomNumber;
  Serial.print("Random Number ");
  Serial.println(randomNumber);
  Serial.print("Current pos ");
  Serial.println(pos);

 for (x = 0; x < randomNumber; x++) {
  myservo[x+pos].attach(x+pos);
  Serial.print("attach servo-");
  Serial.println(x+pos); }

//open (move from 0-180 degrees)
 for (x = 0; x < randomNumber; x++) {
  myservo[x+pos].write(180);
 }
 delay(2000);

//close (move from 180-0 degrees)
 for (x = 0; x < randomNumber; x++) {
  myservo[x+pos].write(0);
 }
 delay(2000);

//detach servo
 for (x = 0; x < randomNumber; x++) {
  myservo[x+pos].detach();
 }
 delay(2000);
}
}


Use a gyro, it will give you the angle. Gyros are difficult to find spare, so you should buy an IMU like MPU6050 that contains also an accelerometer.


Is this a common problem?

Yes it is. The drift is a common problem.

  Why is this happening?

The drift results, in general, from the fact that to calculate the angles it is made an integration. The errors and noises present in the inicial variable before integration (in this case angular velocity) will be "summed" over time.
For simplicity, let's say your gyro is perfect with noise free but it has a small offset , and lets considere only rotation in one axis, meaning:

Ang_Velocity(x) = Real_Ang_Velocity(x) + offset_x

if this was the case, the sensor standing still should output only:

Ang_Velocity(x) = 0 + offset_x

now using the integral over time results in an output of:

Angle(x) = int[Ang_velocity(x)] = offset_x * t

For example note that using a simple 0.01 offset over axis x, causes the sensor to output 1rad angle after 100 seconds and in fact the sensor didn't move at all.

Taking this as example the sources of errors I'm aware of are:

offset: already talked
scale factor:  is the relation between input and output
scale factor linearity: sometimes the scale factor at slow speeds are not the same as speed increases.
temperature: (not 100% sure!) this changes the sensitivities of axis. Majority of digital sensores already come with an integrated temperature sensor. If not auto compensated, there will be probably information on the datasheet to guide you how to compensate for this. If your application will not take high temperature variations, it is common sense to let the sensor achieve thermal internal stability and then do a simple calibration.
Random Walk: This is probably the hardest to process. In general is assumed that the noise is a normal distribution with mean of zero and a certain variance (white noise). If that was true, the integral over time, as time increases would go to zero (because the mean is zero). However, the noise is usually not evenly distributed in the spectrum, causing the integral to not tend to zero (Brownian noise).

  way to solve it?

The first two are simple using calibration. You must do a series of tests at diferent rotation speeds to determining the non-linearities, offsets (at zero speed) and scales factors for each axis.
Then your sensor equation of the module should take acount for this facts. Usually the sensor datasheets describes the equation to be used.
Take a look at IMU_Zero in the repository you gave.

As for the other two, it depends on the application. Typically the temperature will be considered stable after a few working minutes. If temperature is important datasheet will probably be your best friend.

As for random walk. The most common use to take into account corrections of this is to use an accelerometer (and in some cases magnetometer) and apply a sensor fusion algorithm generally denoted as AHRS.
Some examples go as:

Sebastian Magdwick - Open source IMU and AHRS algorithms
Extended Kalman Filter
Direction Cosine Matrix filters
Complementary filters

If you really want to model the noise of the sensor to improve the result, you probably should search for Allan variance but you will need a lot of basis in stochastic processes and statistical theory

Some devices like yours already have an Motion processor built-in, that makes a similar application of (probably) one of these filters. See examples MPU6050_DMP6.ino

If you just want an implementation, just google for AHRS arduino. Github as a lot of examples used by other sensors that are easy to adapt. For instance and this

More information on IMU errors


yes there is. power will be drained from external source(altough 7 volts is around the limit and arduino may switch to usb power) and arduino will still operate at 5v, same as usb. in any case your arduino and usb will be safe.


There are lots of circuits for charging a SLA battery from a solar cell.  You need 14.4V input, so you need to ensure that the output of you solar cells is going to be at least 14.4 for enough hours to charge your battery. This means you will need to know the output current of your charging circuit and do a fair bit of maths.

Charging a lipo battery will probably be more tricky.  I would look at using a USB to LiPo charge regulating circuit and then generate a constant 5v from you solar cells.

You could also look at getting a COTS solar charge regulator, that allows you to connect the cells, load and battery and it does all the hard work for you.


You supplied 5V to a device that only takes up to 3.6V. Heat generated by the excessive power did the rest.


ATmega328P of Arduino Pro Mini not responding

Does the MCU get bricked/locked?

Yes, it's possible. The chip requires a valid clock to run, even when programming, so if the clock settings are corrupt or were set wrong it will no longer be programmable through ICSP.

  How can I recover this?

Depending on what has actually happened you can either supply an external clock signal to the chip to get it working again, or you may need to reprogram the chip through the parallel programming interface, also known as HVP (High Voltage Programming).

  Is there any way to solve this problem using AVR Dragon board?

Yes, the Dragon can do parallel programming. You can read more about how to fix fuses with it here.


How to Sort Elements of Array in Arduino Code?

As mentioned in the comments, qsort is a good option:

// qsort requires you to create a sort function
int sort_desc(const void *cmp1, const void *cmp2)
{
  // Need to cast the void * to int *
  int a = *((int *)cmp1);
  int b = *((int *)cmp2);
  // The comparison
  return a > b ? -1 : (a < b ? 1 : 0);
  // A simpler, probably faster way:
  //return b - a;
}

void setup() {
  // The array
  int lt[6] = {35, 15, 80, 2, 40, 110};
  // Number of items in the array
  int lt_length = sizeof(lt) / sizeof(lt[0]);
  // qsort - last parameter is a function pointer to the sort function
  qsort(lt, lt_length, sizeof(lt[0]), sort_desc);
  // lt is now sorted
}

void loop()
{
}


bitRead(x, y) takes a value x, and looks at bit number y.

So, if:

y is the number 2;
x is 53 (binary number 0 0 1 1 0 1 0 1)

                                       ^

it looks at bit #2. Bits are counted from the right starting at 0 - I have indicated the bit in question above.

So, bitRead(53, 2) would return 1, since bit #2 in 53 is a 1.

In the above program, the clever programmer has coded whether to light or not light the LED for each segment of the display in a single byte for each possible number to display. The digit 8 has all seven of its LEDs lit up, so you'd expect the encoding for 8 to have lots of binary 1s in it - and sure enough, it does (B11111110)! And the digit 7 has only three segments lit up, so you'd expect only 3 bits to be set. Sure enough, B11100000.

The comment at the top describes what each of the bits represent - the last bit is the decimal point, which is never set...


How to send characters to Arduino serial using Linux command line without tail -f?

Arduinos have auto-reset circuit to reset the board if new connection is initiated on USB. It is good for convenient upload or to reset for debugging at Serial Monitor open. But it causes troubles if you want to communicate with MCU from computer over USB from command line tools, scripts, python, C++, C#, Java. Always on new connection the board resets.

One solution is to disable the auto-reset circuit. Other option is to wait a second after the connection while the board resets.


Interrupt on Analog Port - ESP8266 w/ Arduino

Interrupts are a tricky concept to get, you have to be mindful of so many things (in bigger projects).

Have a quick look on youtube for some tutorials, there are a heap out there.

Having said all that, your code above isn't using interrupts at all. And you have these big delays, does the code work as published?

I would suggest you rework the code into more of a state machine and have a single loop. ditch all the delays (except for your setup, that's fine) and go along the lines of:

setup

set a variable for current timer value and have a constant defined for your update interval

loop

read sensor (consider constantly reading, or reading it more often than the information is sent, and average it out)
anything on the serial port?

go read it

check timer against old timer and interval
interval exceeded

send averaged value

using interrupts

You could use interrupts but the thing to consider is that they can be run AT ANY TIME. your code must be interrupt-able which whilst isn't too hard, needs special consideration in relation to delays, reading 16bit values, not having delays in the interrupt, status register changes, a whole host of others.

There are two types of interrupt, those that are driven by a change in input and those that are time based. You don't really want the change in state on this one because you would normally want to monitor it constantly anyway, but it is certainly doable.

In both time based and external input, you would have the interrupt set a flag that gets acted upon in your main loop.

sorry for not providing more info at this time, screaming kids :(


The most common (not sure what others are used) carrier frequency is 38khz. You need an IR receiver tuned to that frequency to get the signal from the remove. See this page for way more information.

There is no encryption or special receivers needed as long as the carrier frequencies match.

That's really all the hardware you need. On the software side of things, you read this signal and decode it. There's a neat little library for doing exactly that. It's called Arduino IRemote.

It even has an example sketch which tells you just what the decoded value is of whatever button you pressed so you can use that in your other programs.


I am playing on a Arduino UNO, you would have to compare the datasheets to determine differences.
For my research on this answer I am looking at:

Code/PwmFrequency (for a quick rundown)
Tutorial/PWM
TimerPWMCheatsheet (explains the prescaller and resulting frequencies)
varying the pwm frequency of timer0 and timer2
feature request: adjustable pwm frequencies
pwm frequency library (this is the one you REALLY want)
and the datasheet for the ATMega328

Also:

we know PWM pins are D3, D5, D6, D9, D10, D11
I am using D11 for this since I can attach my oscilloscope to the MOSI pin of the ISCP
D11 maps to PB3 (MOSI/OC2A/PCINT3) (see datasheet or this cool gfx)

Normal usage
First, let's see what happens when we set an arbitrary PWM on pin 11
int DUTY = 25;
analogWrite(11, DUTY * 256 / 100);

results in:

Freq: ~487Hz
Duty: ~25%
Time: ~2.05ms

This first point I will make is that with the given 490Hz the PWM duration is actually 2ms which seems to be close to what you want (you said between 1-2ms), maybe my misunderstanding there.

Playing with pre-scalers
From several of the links posted above, you will see that you have different pre-scalers available depending on which timer you are using: eg.
Pins 5 and 6: controlled by Timer 0 in fast PWM mode (cycle length = 256)
Setting     Divisor     Frequency
0x01        1           62500
0x02        8           7812.5
0x03        64          976.5625
0x04        256         244.140625
0x05        1024        61.03515625

TCCR0B = TCCR0B & 0b11111000 | <setting>;

Pins 9 and 10: controlled by timer 1 in phase-correct PWM mode (cycle length = 510)
Setting     Divisor     Frequency
0x01        1           31372.55
0x02        8           3921.16
0x03        64          490.20
0x04        256         122.55
0x05        1024        30.64

TCCR1B = TCCR1B & 0b11111000 | <setting>;

Pins 11 and 3: controlled by timer 2 in phase-correct PWM mode (cycle length = 510)
Setting     Divisor     Frequency
0x01        1           31372.55
0x02        8           3921.16
0x03        32          980.39
0x04        64          490.20
0x05        128         245.10
0x06        256         122.55
0x07        1024        30.64

TCCR2B = TCCR2B & 0b11111000 | <setting>;

(All frequencies are in Hz and assume a 16000000 Hz system clock.)

These are relatively simple to setup and use (the setting is at the bottom of each of the above code blocks), but you have to be mindful of playing with the pre-scaler of timer0 (which controls millis() and delay()). So if you have a choice, steer clear of timer0, or pwm pins 5 and 6.
Example of using just the inbuilt pre-scalers without any additional libraries:
#define PIN 11
void setup(){
    pinMode(PIN,OUTPUT);  // not absolutely required
    int DUTY = 20;
    TCCR2B = TCCR2B & 0b11111000 | 6;
}

void loop() {
  static long counter = 0;
  if(millis()%10==0){
      counter++;
      analogWrite(PIN, counter%255);
  }
}

I know you can manipulate the frequency better than that, and I have been playing with this for hours and then I finally stumbled upon the final link (which believe it or not, I found via YouTube!).

Using an External Library
To use the PWM library you will need to download it from Google Code, save/import/get it into your library folder, and restart the IDE. Once you do that, you can explicitly set the frequency (within limits, 333Hz is within those limits), and you should be set.
Code example:
#include <PWM.h>
int32_t frequency = 333;

#define PIN 10

void setup(){
    pinMode(PIN,OUTPUT);
    int DUTY = 20;
    InitTimersSafe();                    // won't touch timer0
    SetPinFrequencySafe(PIN,frequency);  // again, not timer0
    pwmWrite(PIN, DUTY * 256 / 100);
}

There is even a pwmWriteHR which allows for higher resolution, but that does not work with timer2 (which is only an 8-bit timer).
The matching, non-safe (ie initialises and uses timer0 as well) functions are:
InitTimer();  // and
SetPinFrequency(PIN,frequency);

The only limitation I have found so far is that it doesn't work with PWM pin D11. I have tested D3, D9 and D10 (they all worked fine), but I did not get around to testing D5 or D6.
Good luck, I hope this helps.


Arduino board not recognized by Linux (dmesg, lsusb, etc.)

So, to summarise the comments trail; the blinking lights at power-up are the normal boot sequence for the Leonardo,  indicating the processor is good, and that power is reaching the board; the device seen should be /dev/ttyACM0 or some other number; dmesg wasn't recording a plug-in event as the cable was not good.

We still don't quite know why the IDE thought it had sent a program to /dev/ttyS0, but presumably the level of interaction is much less (ie, none) via RS232 serial? Which explains why it said it had uploaded a test program when, in fact, it hadn't!

And replacing the USB cable has solved the problem - excellent news!


difference between the nano and the nano every

The classic Nano has ATmega 328p MCU, same as Uno. The 328p is classic AVR ATmega as used in Arduinos from the start and before in many AVR MCU projects for over 20 years now. There is large knowlege base for this MCUs, many ready codes in form of libraries, snippets, tutorials.

The Nano Every and Uno WiFi Rev 2 use a modern version of the AVR based MCU a so called megaAVR_0-series, an ATmega4809. It uses the same AVR CPU architecture in core of the MCU so the compiler is the same as for 328p and co., but the MCU peripherals configuration is very different then in the classic ATmegas. So the old knowledge base about AVR MCU peripherals doesn't help here.

The lower price is not related to manufacturing costs. The possible reasons are:

better price by MCU manufacturer at introduction of the new MCU family to market
higher price of classic Nano because it is popular and together with classic Uno founds Arduino as company
getting the new chip to Arduino power users to build up the knowledge and code base for the new MCU

To mention some more differences of classic Nano and Nano Every: Nano uses a bootloader for sketch upload and an external USB chip for USB communication. Nano Every doesn't use a bootloader, it has an on board UPDI programmer in form of a small SAMD MCU which serves as USB adapter for serial communication too.


Traffic lights: gpios against 5V or ground

I have 3 standard LEDs (red, yellow and green) connected in parallel to GPIO pins 10, 11 and 12. I also have one resistor, to which they are all three connected.

BAD BAD BAD!!!

What's the difference between connecting the resistor to ground (so that the leds are high active) or to the 5V output pin of the arduino (so that the leds are low active)?

Nothing, other than the reversed logic. AVR GPIOs (and most GPIOs in modern MCUs) are balanced - i.e., they have the same current limit for both sink and source.

Moreover: how many ohms should the resistor have? My understanding is: each of the 3 standard LEDs needs 20mA, so, if all three are lit, there is 60mA on the circuit. The 3 parallel LEDs need 2 V. So, the resistor should be chosen such that it has a voltage drop of 3V at 60mA, hence 3V/60mA = 50 Ohm. If only one is lit, I need 3V/20mA = 150 Ohm.
But, if its possible that every possible subset of the LEDs is lit at once, wouldn't it be better, to place a resistor in front of every LED, so that I have 3 LED-resistor pairs in parallel? The value of each resistor is 50 Ohm then, allowing for a voltage drop of 3V in each of the 3 branches, so that each LED only gets the needed 2V?

Yes. That is how you should wire LEDs - and you have already identified why.
For each LED calculate the resistance as R=(5-Vf)/0.02. You need to find the correct Vf for each LED from the datasheet to get the best results - but if you can't then a rule of thumb is: Red, Green and Yellow are about 2V, Blue and White are about 3V.


You seem to lack the basic understanding, how Serial (UART) communication works. So I will explain the basic principles. From there you should be able to implement, what you want.

Serial (aka UART) transmits the data serially, byte after byte (thus it's name). When you type in a text in the Serial Monitor of the Arduino IDE and send it, you have no influence, when exactly each byte will be transmitted. As the UART interface doesn't know messages or "chunks of data", only bytes, it will transmit each byte, when it is ready. There might be a short pause inbetween the bytes. This is an important fact to know, if you want to implement commands longer than 1 byte.

The normal Serial interface is mostly implemented in the Uno's hardware, thus it doesn't depend on the running software that much. SoftwareSerial does all the hard communication work in software, thus it comes with some caveats (blocking write operations, more limited baudrate, only possible to receive on one SoftwareSerial interface at once, ...). But both mostly share the same code interface.

Serial.available() returns the number of received bytes, that are still in the internal buffer. You are already using this to only read from the buffer, when there is actually data to read in it (with the if statement). Then you read one byte from the buffer by Serial.read(). Currently you are giving the return value (the read data) directly to the other serial interface for sending. Thus the value is not saved anywhere in your sketch. Doing a Serial.read() will remove the read byte from the buffer and return it. Thus the read byte will no longer be in the buffer.

The code with the 2 if statements and serial functions is mostly used to forward the data between the two serial interfaces. For your use case you don't need this. Instead you should read the data into a local variable like you did in your first sketch:

if (btSerial.available())
{
  a= (char)btSerial.read();

  if(a=="b")
  {
    btSerial.println("Turning LED blue");
    leds[0] = CRGB::Blue; // Turns 1 LED to blue
    FastLED.show();
  }
}

Here you are first checking, if there is data to read in the btSerial buffer. If yes, you read it into the variable a. This variable now holds a single character. If you also want to forward this character to Serial, you can now use Serial.write(a); to do so. Then you want to check the value of the received character. Here we are doing a little excourse:

In C/C++ 2 different kinds of quotes are used: The double quotes " and the single quotes '. Double quotes mark string literals, which consists of a series of characters. Single quotes mark single character values - only one character. In your if statement you check for equality. If you think about it, you see, that checking if 2 single characters are equals is a lot easier, than checking if two strings are equal (checking 1 character on each side versus checking multiple characters on each side). Thus it is a difference, if you compare string literals or single characters. Comparing a single character variable with a string literal doesn't work - they are two completely different things. Instead you should compare the character variable to a single character:

if( a == 'b' )

As you are adding more commands for your project, you will see, that if statements don't order the code very good. In this case a switch statement is better:

switch(a){
    case 'b':
        // Doing what you want to do with the LEDs here
        break;
    case 'c':
        ...
        break;
}

This will execute the corresponding code part depending on the value of a. You can read more about this construct on the web (google something like "C switch").

Now you should be able to implement simple 1 byte/character commands in your code. Also review and understand the examples from the Arduino IDE about Serial.

If you need more complex commands (maybe with some payload data in addition to the command), you have to introduce a communication protocol onto the Serial interface. The simplest way is to define whole messages by using a delimiter character at the end of every message. Mostly the newline '\n' character is used for this purpose. You basically read the data from Serial and save it on a char-array/string until you received the newline character. Then you know, that you have received a complete message, and you can start to process it as a whole. When finished, you clear your message buffer and again wait for a new message. For this to work, you of course have to ensure, that the delimiter character is never part of your send data (as the code would think, that it marks the end of the message).

You can see this in the SerialEvent example in the Arduino IDE. Try to understand, what happens there. There are also many tutorials on the web.

I hope, I could enlighten you a bit. Good luck with your project.


Oops.

You let the Magic Smoke™ escape from your Arduino.  Your Arduino is now somewhat dead.  Depending on what died it may be repairable by replacing components, or it may be beyond resurrection and it'll be easier to buy a new one.

Now - why did it happen?  Looking at the board in your link it should have been OK with the 12V power you provided, since it has its own regulator on board that can supposedly take up to 12V.  So one of two things may have happened:

What you thought was 12V was actually higher than 12V and the regulator didn't cope with it.
You connected the power backwards, so -12V was pumped straight through everything.

There seems to be no polarity protection on the board as far as I can see, and many regulators, if connected backwards, will just pass the power straight through with little or no change to it.  So my money is on having connected the power backwards.  Now, that might not be your fault, since on that site I can see no mention of which polarity the power connector uses - whether it is pin-positive or pin-negative.  The normal way (the way the Arduino board uses) is pin-positive, but that is not always the case.

Either way, the Arduino is now dead, and the GSM module may be dead as well. In fact the whole lot may be dead.


How to use 3 digital input pins on Arduino Uno for frequency inputs and total the output?

Assuming that only one sensor will trigger each time then (as jsotola suggested) tie them together and connect the common output to an interrupt pin. Arduino UNO has interrupt functionality on pins 2, 3.
As an example for counting the pulses using pin2 on falling edge (modified from https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/):
const byte interruptPin = 2;
volatile int numPulses = 0; // change type of variable according your needs

void setup() {
    pinMode(interruptPin, INPUT_PULLUP);
    attachInterrupt(digitalPinToInterrupt(interruptPin), sumPulses, FALLING);
    Serial.begin(9600);
}

void loop() {
    Serial.println(numPulses);
    delay(500);
}

 void sumPulses { // keep the ISR as short as possible
    numPulses++;
 }


Arduino protecting analog input with internal voltage reference

Yes, it is safe.  The reference voltage is only used as a comparison. The ADC is still powered by, and limited by, the chip's supply voltage (5V).

The AREF voltage has no bearing on what limits there are on voltages you can apply to a pin. All that will happen is that voltages above 1.1V will register as 1023. You can go right up to 5V safely.


Get pin input status without using the arduino library

For reading, e.g., PB2, you would test

PINB & _BV(PB2)

where PINB is the port input register and _BV(x) is a macro defined as
(1 << (x)).

C.f. the datasheet for the relevant port names.

See also the Arduino tutorial on
port manipulation.


send more than one integer on serial between Mega and nodeMcu

I'd suggest some kind of character before each int so that the receiver knows which one it is getting.


I am working on similar project that uses internet to communicate with external device (mobile). I am reading data from sensors and passing them over the web with web sockets. I am using Arduino Yun for this project and Spacebrew (for web sockets communication). It's very interesting approach but quite a challenge in some cases. You will probably run into asynchronous/synchronous problem, which in my case lead me to running some Python scripts on Yun triggered from Processing code. I am currently running Spacebrew server on my VPN, so I can connect my Yun left at home and use my iphone from everywhere to get the readings.

It's also worth mentioning Yun comes with pre-installed Temboo library, which is great starting point for web communication. The configuration is really easy and quick. You will also find official documentation very handy and easy to understand. It's really great starting point for experimenting with web-like applications integrated with Arduino Yun.

Spacebrew

http://docs.spacebrew.cc/

Spacebrew is an open, dynamically re-routable software toolkit for choreographing interactive spaces. Or, in other words, a simple way to connect interactive things to one another. Every element you hook up to the system can subscribe to, and publish data feeds.
http://github.com/Spacebrew/pySpacebrew

This repo contains the Spacebrew Library for Python along with documentation and example apps.
http://github.com/julioterra/yunSpacebrew

The Spacebrew Yun library features two main components - a set of python scripts that run on the linino, and a library that runs on the atmel chip. You find there information how to install both of these components so that you can connect to Spacebrew from an Arduino sketch.

Temboo

Yun has also build in Temboo library, it's a great way to start experimenting, once you prove the concept you can start narrowing your environment and moving away if you don't want to use 3rd parties software.

http://www.temboo.com/arduino

The Temboo Library makes it easy to connect to over 100 web-based resources and services with Processing. Currently you can find libraries for Android, Arduino, iOS, Java, Node.js, PHP, Processing, Python, REST API, Ruby, Twyla

Node.js

You can also run node.js on the Yun itself, here's good article and some packages ready to install:

http://giorgiocefaro.com/blog/installing-node-js-on-arduino-yun
https://github.com/giorrrgio/nodejs-linino

This is an openwrt package for node. It probably only works on mips (not mipsel, or arm). It runs an outdated v8 as well.

What is Bridge library for Arduino Yun?

You also asked about Bridge library. As you know Yun has two processors on board, one is running your Processing code, the other one has Linux on it (Linino). Bridge basically simplifies communication between them so they can "talk" to eachother, more information here:

http://arduino.cc/en/Reference/YunBridgeLibrary

(Taken from arduino.cc documentation:)

The Arduino Yún has two processors on board. One is an ATmega32U4 like on the Arduino Leonardo. The other is an Atheros 9331, running Linux and the OpenWRT wireless stack, which enables the board to connect to WiFi and Ethernet networks. It is possible to call programs or custom scripts on the Linux system through the Arduino to connect with various internet services.

The Bridge library simplifies communication between the ATmega32U4 and the AR9331. It inherits from Stream, and many of the methods should be familiar from Serial and other derivatives of Stream.

Bridge commands from the 32U4 are interpreted by Python on the AR9331. Its role is to execute programs on the GNU/Linux side when asked by Arduino, provide a shared storage space for sharing data like sensor readings between the Arduino and the Internet, and receiving commands from the Internet and passing them directly to the Arduino.

Bridge allows communication in both directions, acting as an interface to the the Linino command line.

Where to start?

I would start with Temboo if I were you, it's a great learning curve and quite simple step to start. You will also learn and understand how the board works and how you can communicate with "external world". Once you have proof of concept, start experimenting with different libraries and improving the approach. Perhaps you will find Spacebrew more handy later or even discover different solutions.