text:
Program Arduino Mega Adk on linux
for a project my supervisor gave me a Arduino Mega ADK board (https://store.arduino.cc/arduino-mega-adk-rev3) and the usb-cable.
I only programmed a Atmega32 8 bit controller on linux ubuntu. I have no possibility to use windows (i heard it's easy to program the arduino using atmel studio). I can only use ubuntu 16.04. Is there a convient way to program the Arduino like a microcontroller?
I'm not aloud to use the highlevel Arduino libraries. I have to do a cascaded control for a dc-motor and sensor-fusion.
Thanks in advance.
If it's offtopic, could you transfer me to a suitable board?

You can still use the Arduino bootloader even if you don't use the Arduino libraries and development flow.  Easiest approach is to install the Arduino IDE, put it in verbose mode, use it once, and copy out the avrdude command line it generates, then adapt that to your own project.  You can use their avr-gcc install, too.

You can use Eclipse, along with AVR-GCC and AVRDude and an AVR plug-in for Eclipse. Debugging may be a little painful since you don't have all the tools that Atmel Studio gives you. I'd question your employer if you aren't allowed to use the best (free) tools even if they do run on Windows.
Really all you need is the avr-gcc and avrdude to write software for it, you can use any text editor (although it isn't really convienent).  Seems like they are pigeon-holing you into a difficult job. Good luck.

the thing is that unfortunately no windows computer is available

i can use the atmega libraries i think

Eclipse runs on Linux Ubuntu, as well as all the other tools I linked to...

yes i know, i just explained the the supervisors behaviour. Thank you, i'll take a look at it :)


text:
How to read a specific amount of data via serial?
I'm trying to send data via serial from my Arduino nano to my ESP. Its an integer from 1 to 4 digits
so something like 0, 13, 1234, 123, ...
Every thing works fine but when the data comes too fast it stopps the output and  then it print all the data on the screen.
I use this method to recieve data.
void loop() { // run over and over
        if (Serial.available()) {
                incomingByte = Serial.readString();
                Serial.println(incomingByte);
        }
}

how does it print data to screen when the output is stopped? ... it is not clear what you are saying

What stops?  The Arduino or the ESP?   And how do you know?  You haven't told enough for people to help.

https://majenko.co.uk/blog/reading-serial-arduino

From what you have posted, assuming this is the ESP code in the question, it is clear that for every character the Arduino sends the ESP the ESP will send 3 back. So at some speed this will likly stop working

source: Stack Exchange

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

sort: votes


text:
Nth-Light LED Strip power connections
Based on this question on the Adafruit forum for Nth-Light Narrow LED Flexible Strip Light (https://www.adafruit.com/product/3683) and the image below is it safe to connect from the 12v source + a wire to the Vin (orange wire) or it is better to connect to another DC barrel?

If your 12V power supply has enough current to drive your LED strip at its maximum power, plus the Arduino's power supply, plus about 10-20% of "wiggle room" you should be fine. As the LED strip draws spikes of current the voltage from your power supply might bounce around a little, but the Arduino's voltage regulator would be fine with as little as 7.5V input.
Note that your Arduino's voltage regulator will get hot if you use much current from the Ardunio's 5V rails, since it has to regulate 12V down to 5V and the linear regulator on the Arduino converts the extra voltage to heat.

Thanks. any alternative solution in order to avoid the heat issue? The LED is intend to be in a close space.

If you aren't driving much load from the Arduino's 5V pin it might not be a problem. Total power converted to heat will be ≈total_current • (12V-5V)

If you're really sensitive to heat, drive the Arduino with a separate switching 5V supply fed into the USB port. That bypasses it's regulator entirely

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


text:
Powering a Sim800L Module
I am trying to use a DC power supply. I am thinking whether I can use this power supply to provide power for Sim800L module. After some research, I gathered that the Sim800L module requires a max current of 2A during GPRS transmission at 3.8-4.2 V (4.0 recommended). With the power supply I can easily configure the voltage at 4.0V. My question is: for this setup, do I need a DC-DC Buck Converter as in this one for regulation/step-down (not sure which)?

Li-Po batteries blow up very easily and require specific hardware to charge (check drone power supply issues).  please  be VERY CAREFUL charging Li-Po batteries (if you are following https://lastminuteengineers.com/sim800l-gsm-module-arduino-tutorial/#supplying-power-for-sim800l-module).  Li-Po ba

The lab power supply you linked is serious overkill for your needs. It shouldn't need a separate voltage regulator or buck converter, since I assume that it provdes a voltage and current regulated supply.
A regulated, fixed voltage 4V power supply that can provide 2A is what you want. That will probably cost < 1/10 of the amount of the lab supply you linked. The challenge is to find a 4V supply. (Most regulated power supplies are either 3.3V or 5V, since those are common voltages for solid state electronics.)
That said, the linear voltage regulators are usually adjustable with a decent voltage range using a resistor.
You could always build your own voltage regulator using a linear voltage regulator rated for 2A, plus a resistor and a couple of capacitors. You could either feed it from an unregulated 6V power supply or use a transformer, bridge rectifier, and capacitor to provide an unregulated DC input to a voltage regulator.
Edit:
With a little googling I found a few 4V 2A power supplies online. This one, for example:
https://www.alibaba.com/product-detail/US-AC110-220V-To-DC-4V_62155516966.html?spm=a2700.7724857.normalList.14.a5e64009aUU1ln&s=p
(That link is to a wholesale manufacturer that sells them in volume, but you may be able to find the same supply for single unit sale. A 2A switching 4V supply would meet your needs as well)


text:
DS3231 RTC module and battery problem
I have a CR2032 battery connected to a DS3231 module as backup battery. When the module is connected to 5V the battery voltage is at 4.3V and without power 3.7V.
That means the module is trying to charge the nonchargeable battery. I couldn't find a rechargeable (LIR23032) battery to buy and after some research someone in forums suggested to remove the diode from the module...

If I keep using the CR2032 battery for long run 24/7, how long will it last? Is there a risk of explosion?

Is there any other way than modifying the module itself?

Most modules have a bad charging circuit design. I'd advice to modify the board and use non-recharchable batteries, even if you had LIR2032 batteries available. What is the problem with removing the diode? Are you unsure how to do this? Or are you reluctant to permanently change your module?

@Gerben i removed the resistor.

If i keep using the CR2032 battery for long run 24/7, how long will battery last? is there a chance of explosion?

Yes. Recharging a non-rechargeable battery is dangerous. It should be avoided at all costs.

is there any other way than modifying the module it self?

You have to prevent the power getting to the battery. That power is fed through a diode (hence 4.3V, which is 5V minus 0.7v for a silicon diode forward voltage).  Without knowing what the module is, I can't tell you if there is any other way that modifying it - however I would guess that no there isn't. You need to stop that power getting to the battery, and that can only be done at some point between where the power comes in to the module and the battery itself - and the simplest method is to remove the diode.
The purpose of that diode is to prevent power from the battery from trying to power the rest of your circuit when you remove the main power. Removing the diode will have no adverse affect.  You just won't be able to charge a rechargeable battery in future.

i removed the 200 ohm resistor and kept the diode, the voltage is now dropped to 3.8V which is 0.05V more than battery voltage. is that 0.05V gonna be a problem?

I don't know what resistor you are on about. If you are going by the voltage that is printed on the battery: that is only a "nominal" value and is less accurate than the 0.05v difference you are measuring anyway.

i'm using a multimeter to measure the voltage, and i removed THIS resistor.

That looks like it's in series with the diode to limit the charge current. It has the exact same effect as removing the diode - it breaks the circuit.

So the 0.05V is the difference between "no power connected to the Vcc pin" and "5V connected to the Vcc pin"? In that case the 0.05V drop when no power is applied, is most likely due to the battery voltage sagging a bit because a bit power is being drawn from it. I wouldn't worry about that.

You can remove either or both the resistor and diode. The battery in the Amazon DS3231 clock modules is already connected to the DS3231 IC. I just removed the resistor- by the way, it isn't 200 ohms, it is 200 mega ohms, but that still allows way too much current into a non rechargable CR2032 battery. I tried using it with the charging circuit, and the non rechargeable battery swelled up over the course of 2 days!


text:
Rotary encoder using interrupt
This is my first time working with a rotary encoder and interrupts.  I am using a Pro Micro which has interrupt pins at pin0 and pin1.  The code below works as expected.
My question: do I need to use an interrupt pin for PinB as well, or can I use any digital pin?
It does not seem to work when I choose PinB = 9, for example.
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2); // set the LCD address to 0x27 for a 16 chars and 2 line display

// Used for generating interrupts using CLK signal
const int PinA = 0;

// Used for reading DT signal
const int PinB = 1;

// Used for the push button switch
const int PinSW = 8;

// Keep track of last rotary value
int lastCount = 50;

// Updated by the ISR (Interrupt Service Routine)
volatile int virtualPosition = 50;

// ------------------------------------------------------------------
// INTERRUPT     INTERRUPT     INTERRUPT     INTERRUPT     INTERRUPT
// ------------------------------------------------------------------

void isr ()  {
  static unsigned long lastInterruptTime = 0;
  unsigned long interruptTime = millis();

  // If interrupts come faster than 5ms, assume it's a bounce and ignore
  if (interruptTime - lastInterruptTime > 5) {
    if (digitalRead(PinB) == LOW)
    {
      virtualPosition-- ; // Could be -5 or -10
    }
    else {
      virtualPosition++ ; // Could be +5 or +10
    }

    // Restrict value from 0 to +100
    //virtualPosition = min(100, max(0, virtualPosition));

  }
  // Keep track of when we were here last (no more than every 5ms)
  lastInterruptTime = interruptTime;
}

// ------------------------------------------------------------------
// SETUP    SETUP    SETUP    SETUP    SETUP    SETUP    SETUP
// ------------------------------------------------------------------
void setup() {
  // Just whilst we debug, view output on serial monitor
  //  Serial.begin(9600);

  lcd.init();                      // initialize the lcd

  lcd.backlight();

  // Rotary pulses are INPUTs
  pinMode(PinA, INPUT);
  pinMode(PinB, INPUT);

  // Switch is floating so use the in-built PULLUP so we don't need a resistor
  pinMode(PinSW, INPUT_PULLUP);

  // Attach the routine to service the interrupts
  attachInterrupt(digitalPinToInterrupt(PinA), isr, LOW);

}

// ------------------------------------------------------------------
// MAIN LOOP     MAIN LOOP     MAIN LOOP     MAIN LOOP     MAIN LOOP
// ------------------------------------------------------------------
void loop() {

  // Is someone pressing the rotary switch?
  if ((!digitalRead(PinSW))) {
    virtualPosition = 50;
    while (!digitalRead(PinSW))
      delay(10);
    //    Serial.println("Reset");
  }

  // If the current rotary switch position has changed then update everything
  if (virtualPosition != lastCount) {

    lcd.clear();
    lcd.print(virtualPosition);

    // Keep track of this new value
    lastCount = virtualPosition ;
  }

  //delay(100);
}

think about how the code works now, with just a single interrupt ... then think about what would happen if you had interrupt on both data pins of the encoder ... one thing to note is that you would have twice as many interupts per revolution of the encoder, but they would not be symmerical if you are interrupting on only one edge ... i am assuming that you are using a quadrature encoder

attachInterrupt(digitalPinToInterrupt(PinA), isr, LOW); I think you mean FALLING, otherwise the ISR will continuously get called when the pin is LOW, leaving barely any CPU cycles for you main code.

Let me rephrase:  The code above works perfectly fine as is (yes it could be optimized per @Gerben).  It uses a single interrupt on PinA.  When I try to assign PinB to any other physical digital pin (other than Pin1), it no longer works.  I cannot understand why.

I don't see why it won't work. There is nothing special about pins 1 and 9. 1 indeed is a interrupt pin, but you don't use that here. Pretty strange.

How would I use this as a subroutine instead of a main loop?  For example, setting a max val, then running another sub until max val is hit.  I'd assume we'd use another input for the break trigger.

Found my error... on the ProMicro, the pins are not arranged 0, 1, 2, 3, 4, 5 etc instead they arranged 1, 0, 2, 3, 4, 5 etc... On the board I misread TXO and RXI as TX0 and RX1 and just didn't notice it on my pinout sheet.... so I had D0 and D1 swapped. All works well now. Learning more everyday! I appreciate your time...


text:
Capacitive Sensor and Thread
Looking for a great way to detect when someone touches thread, or if 4 people touch thread etc.
I'm not looking for a hand count, but I'm going to try to translate it into MIDI for use in a project.
Am I looking for a form of capacitive sensor?

what kind of thread?

something like this: https://www.ebay.co.uk/itm/50m-Orange-Builders-Line-PACK-OF-2-Rope-String-Building-Brick-Masonry-Home-DIY-/311438519959

No, unless you use wire.  Or, maybe, conductive thread.  Mentioning MIDI implies you want to make music.  Indicate if this is so - as I'm thinking there are much more reliable alternative that you could use.

The Arduino Lilypad boards might be the right place to start https://learn.sparkfun.com/tutorials/sewing-with-conductive-thread

I have conductive thread, but it might be a case of finding a nicer looking thread with conductivity, this thread is very thin, not appealing to touch at all


text:
Which kind of diodes I should use in buttons/keys matrix input? (Making gaming keyboard)
When making matrix input of NxM columns/rows with push buttons, there should be a diode next to each button to prevent "ghosting" and able read many keys pressed together correctly. There is a lot of pictures everywhere.
My problem is, which diodes to use and also why this type (or why it does not matter).

More details:
I would use 5 V Arduino (ATmega32U4), datasheet states for input low voltage max 0.3Vcc, which is 1.5 V and minimal high input voltage 0.7Vcc = 3.5 V and pullups at least 1.5 kΩ (Vcc-0.4 V / 3 mA)
I would like to use 74HC138 3-to-8 decoder for addressing, which makes one of 8 outputs Low (max 0.1 V), while other 7 High (min 4.5 V) and drive the Arduino inputs Low, if button is pressed.
To be on safe side, I would like also add resistors on each pin to make sure, that bad programming (make some input pin OUTPUT and HIGH and pressing key connect it to LOW output on other side) could not damage the circuits, so it looks like 5 V/20 mA = 250 Ω (and I will hope it would not hit more pins, so I would not consider total port/chip limitations).
In typical case it would be 5 V - 1.5 kΩ pullup - input - 250 Ω - wires and button - diode - 250 Ω - 0.1 V for selected line.
If the diode would be theoretical and ideal, then there is (in the worse case) promised to be max 1.2 V on Input, which is slightly less then "maximal low" voltage (1.5 V) and like 5V/2 kΩ = 2.5 mA current.
But the diode is not ideal and have some forward voltage, which make the case even worse.
So I probably cannot use simply INPUT_PULLUP (as it may work by luck, but is not guaranted by specs) but I need to use INPUT and set some higher pullup there to "burn" more volts on it to compensate for the diode.
The Input Current for each pin is 10 µA (in or out) and I heard some recommendation, that on resistor divider should be the total current 10x more, then the input current, so it would mean 100 µA = 0.1 mA
The pullup then could go as high as ((5 V - 0.1 V - Vf)/0.1 mA ) - 500 Ω If the forward voltage would be 1 V (wild guess) it would go to something like 38.5 kΩ pullup and 1.15 V on input. The maximal Vf forward voltage would be like 1.35 V (at 0.1 mA), pullup 35 kΩ and 1.5 V on input.

My problem is, that many online Arduino schemes works just because Arduino usually work good even in way out-of-spec situations, and suggested values cames from what the author just randomly had at hands and it worked by pure luck and maybe another hidden factors, as parasite capacity of breadboard or so. So I want to uderstand, why I should choose some parts and how to came to such conclusions by myself.
I want to make reliable projects, not just projects, which works most of the time and fail only occasionally.

It is the right path, how to compute it or did I some mistake?
I want use scanning frequency at least 800 Hz (8 lines and results
100x per second) or more (like 10 kHz to be done fast and to have more time to spend with other
tasks, like sending USB packets, computing macros, managing light
effects etc)
which common and cheap SMD diodes I should buy?

reverse voltage over 5 V, current over 100 mA, switch frequency over 10 kHz, forward voltage under 1.3 V at 0.1 mA (rather much less to have safe gap from limits)
really common cheap model, so everybody would know it and so I could use it everywhere in similar settings without thinking ( or even computing like in previous section)
preferably what you (and everyone else and his dog too) use for such cases
I would like to order from AliExpress, so rather higher margin for guaranteed values
preferably to fit on 0.1 inch spaced universal PCB (0805 SMD LEDs are really easy to solder there (so rather not smaller than that), but it may be twice the size too or something like that)
I would buy like some hundreds of such diodes to have them ready on hands and I will probably make more similar projects over time for me and my friends

Thanks for all comments and suggestions

Thanks for directing me to Electrical Engeneering, where the 1N4148 was so common in questions/answers, that I googled it and found, that it is ideal for nearly everything I could possibly do with  Arduino I/O pins. My problem is SOLVED

When I've used a keypad matrix I've wired it up like this:

I used 1N4148 SMD diodes which I bought cheaply. I cut the traces on my cheap board that I had purchased from Jaycar and soldered them in like this:

The dot is the cathode (there is a line etched on my diodes at the cathode end).
The 10k resistors effectively turn the columns into pull-ups, therefore there is no danger of bad code damaging the Arduino or anything else.
Example code to scan the matrix:
// Keypad_Decoder
//
// Author: Nick Gammon
// Date: 17th February 2018

// Outputs to Serial in the format: 0b1nnnnnnn for a key down and 0b0nnnnnnn for a key-up
//            nnnnnnn will be the current row/column combination
//            Also every HEARTBEAT_TIME outputs 0xFF if all keys are up (heartbeat)

#include <limits.h>     /* for CHAR_BIT */

const byte ROWS = 4;
const byte COLS = 4;
const bool ENABLE_PULLUPS = true;  // make false if you are using external pull-ups
const unsigned long DEBOUNCE_TIME = 10;     // milliseconds
const unsigned long HEARTBEAT_TIME = 2000;  // milliseconds
const bool DEBUGGING = false;               // make true for human-readable output

// define here where each row and column is connected to
const byte rowPins [ROWS] = {6, 7, 8, 9}; //connect to the row pinouts of the keypad
const byte colPins [COLS] = {2, 3, 4, 5}; //connect to the column pinouts of the keypad

// See: http://c-faq.com/misc/bitsets.html

#define BITMASK(b) (1 << ((b) % CHAR_BIT))
#define BITSLOT(b) ((b) / CHAR_BIT)
#define BITSET(a, b) ((a)[BITSLOT(b)] |= BITMASK(b))
#define BITCLEAR(a, b) ((a)[BITSLOT(b)] &= ~BITMASK(b))
#define BITTEST(a, b) ((a)[BITSLOT(b)] & BITMASK(b))

// number of items in an array
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))

// total number of keys
const byte TOTAL_KEYS = ROWS * COLS;

// remember previous setting of each key
char lastKeySetting [(TOTAL_KEYS + CHAR_BIT - 1) / CHAR_BIT];  // one bit each, 0 = up, 1 = down
unsigned long lastKeyTime [TOTAL_KEYS];       // when that key last changed
unsigned long lastHeartbeat;                  // when we last sent the heartbeat

void setup ()
{
  Serial.begin (115200);
  while (!Serial) { }  // wait for Serial to become ready (Leonardo etc.)

  // set each column to input-pullup (optional)
  if (ENABLE_PULLUPS)
    for (byte i = 0; i < COLS; i++)
      pinMode (colPins [i], INPUT_PULLUP);

}  // end of setup

void loop ()
  {
  byte keyNumber = 0;
  unsigned long now = millis ();  // for debouncing

  // check each row
  for (byte row = 0; row < ROWS; row++)
    {
    // set that row to OUTPUT and LOW
    pinMode (rowPins [row], OUTPUT);
    digitalWrite (rowPins [row], LOW);

    // check each column to see if the switch has driven that column LOW
    for (byte col = 0; col < COLS; col++)
      {
      // debounce - ignore if not enough time has elapsed since last change
      if (now - lastKeyTime [keyNumber] >= DEBOUNCE_TIME)
        {
        bool keyState = digitalRead (colPins [col]) == LOW; // true means pressed
        if (keyState != (BITTEST (lastKeySetting, keyNumber) != 0)) // changed?
          {
          lastKeyTime [keyNumber] = now;  // remember time it changed
          // remember new state
          if (keyState)
            BITSET (lastKeySetting, keyNumber);
          else
            BITCLEAR (lastKeySetting, keyNumber);
          if (DEBUGGING)
            {
            Serial.print (F("Key "));
            Serial.print (keyNumber);
            if (keyState)
              Serial.println (F(" down."));
            else
              Serial.println (F(" up."));
            }  // if debugging
          else
            Serial.write ((keyState ? 0x80 : 0x00) | keyNumber);
          }  // if key state has changed
        }  // debounce time up
      keyNumber++;
      } // end of for each column

    // put row back to high-impedance (input)
    pinMode (rowPins [row], INPUT);
    }  // end of for each row

  // Send a heartbeat code (0xFF) every few seconds in case
  // the receiver loses an occasional keyup.
  // Only send if all keys are not pressed (presumably the normal state).
  if (now - lastHeartbeat >= HEARTBEAT_TIME)
    {
    lastHeartbeat = now;
    bool allUp = true;
    for (byte i = 0; i < ARRAY_SIZE (lastKeySetting); i++)
      if (lastKeySetting [i])
        allUp = false;
    if (allUp)
      {
      if (DEBUGGING)
        Serial.println (F("No keys pressed."));
      else
        Serial.write (0xFF);
      } // end of all keys up
    } // end if time for heartbeat
  } // end of loop

Speedwise, I measured around 300 µs for doing a scan with no keys pressed. If that time seems a bit long, you could always do a time check, and scan every 5 ms or so.
I have a post about all this on my forum. In that post I also mention a library that handles N-key rollover, so you can detect multiple keys being pressed at the same time. For example, you could use A/B/C/D on the keypad as "shift" keys, so that A+1 meant something different than just 1.

Matrix from the front:

My problem is, which diodes to use and also why this type (or why it does not matter).

I don't think the exact diode is critical in this case. If this was a very high speed application, then a diode with fast switching might be required. If it was high voltage then a higher-spec diode might be required. In some cases the reverse voltage might apply. In this particular case, since we are dealing on/off at logic levels, I don't think much of this matters, although the switching speed might to a certain extent, however I am guessing from empirical observations that the speed of the 1N4148 is fast enough.
Also see: Wikipedia - 1N4148:

The 1N4148 is useful in switching applications up to about 100 MHz with a reverse-recovery time of no more than 4 ns.

Thank you, your answer would help many readers. But my question was more which type of diede to use (as you say IN4148) and mainly WHY, as I could found lot of schemes everywhere, little states what diode uses and none discuss, why this type exactly, or why it does not matter. There are many other kind of schemes on web, where correct values are critical (like some HiFi or so) and many schemes, where the values are just what author had handy and it does not work correctly in general, but he just had luck one time with out-of-spec just randomly worked for him. I wanted uderstand this point.

About bad programming - I often use sockets on my projects and reuse the microcontroller in other projects, when one came obsolete or I do not need it just now. Later I may go back to it again and put some MC to the socket and upload the original code again. So I was afraid of putting MC programmed for other project  (where it would set the pin for COL1 to High and pin for ROW1 to Low) to the socket and press the left top key before uploading corect code inside. So effectively shortcut those two pins and lead 5V to 0V over diode. ...

... So I put the restricting 250 Ohm resistors there to limit the current to 10mA even in this kind of mistake. (Similar thing happened to me before already, I soon realized, that the project does not work, but it was already late. So I came more paranoid about "impossible" programming bugs and I try to make HW such way, that it would nothing burn even if the MC actively tries to bur it/itself)

PS: I really like your site and read it often :)

Thanks! I've added another paragraph at the end explaining the choice of diode.

Solution: 1N4148 diode
generally if you want connect diode to Arduino pin, use this one as it would be OK under nearly any normal use

75 V reverse voltage (much more than 5V allowed there)
1 V forward voltage at 10 mA (less at lower current)
10 mA recommended current (destroys at 1 A 1 sec pulse) (and you do
not want more then 10 mA anyway)
usable up to 100 MHz (so using digitalRead/digitalWrite and
some logic you are way slower anyway)
super extra common for long time (even 10 years ago was considered
"classical") and still actual (so when you get old, it would still be
here)
dirty cheap (buy few hundreds just now and you do not need care
anymore)


text:
Handling arduino output current
I need to power an actuator that requires 12 volts and consumes between 5 and 10 amperes depending on the weight it is charging. Therefore I bought a power supply of 12 volts and 10 amperes.
My intention is to send in the arduino output the 12 volts and the current provided by the power supply.
The options that I have thought are the following:
a) Connect the power supply to the arduino input pins and send the voltage and current from the power supply to the actuator through the arduino output (I know I could do it directly to the actuator, but I am interested in doing it through of arduino since it will involve programming code to put conditionals)
My doubt with this option is if I do not damage the arduino by connecting that power source with that amperage. If there is no problem, my question is if I could handle the current of the power supply at the output or the current could only be handled by what arduino gives that would not be much.
b) The other option that I think is simply to send a flag to the output and then this flag activates the power supply in some way and then I could use the 12 volts and the 10 amperes to connect them to the actuator.
I would like you to guide me on the alternatives I have thought about and tell me what would be the right thing to do, or if you know some other way in which you should do it.
Thank you very much in advance
Cheers

sounds like the arduino will make a  great fuse .... you cannot send 10A of current through the arduino ... research how to control motors with the arduino

Think "Relay". Google that plus the magic "Arduino" keyword and you'll see lots of results that give you some nice circuits.

@Majenko I was just checking that on the internet, my question now is whether it would be better to do it with transistors because the relay is mechanical and could be damaged and have a short lifespan, besides if I could do it with transistors considering these voltages and currents? Thanks :)

As others have said, an Arduino pin can't handle 12V, and can't handle anywhere near 10A of current directly. A digital pin on an Arduino is limited to 20mA, or 1/500 as much current as you need, at 5V, which is less than half the voltage you need.
If you try to connect 12V to a pin on an Arduino pin you will almost certainly destroy that pin, and may destroy the entire Arduino. If you try to source or sink even 1/100 of the current you are talking about through an Arduino pin, even at 5V, you will also probably destroy that pin and possibly the entire Arduino.
This sounds like a good application for a power MOSFET transistor. With that much current you'll need to put a heatsink on the transistor.
Here's one that would work:
https://www.sparkfun.com/products/10213
You'd use a logic pin from the Arduino to control the gate on the transistor, and the transistor would switch 12V at high current with very little resistance.
If the actuator is inductive, you'll need to protect the transistor with a suitably large "flyback diode" to protect it from the reverse current (or "back EMF") you get from an inductor when you remove power from it:
https://en.wikipedia.org/wiki/Flyback_diode

It seems a good solution.Now Im going to research how to control the current and voltage levels with the mosfet. Thanks :)

I see I need to connect the 12V power supply to the mosfet and the lineal actuator, If  I am correct?. And then i Would need another independent source of 5V for the arduino, or I can use  the same power supply of 12 V by reducing  with a voltage reducer, if this is the case what happen with the current of the source that is 10A, There is no problem since arduino will  only consume the current it needs?

PD I am using a lineal actuator.

The Arduino has a built-in voltage regulator. You could feed 12V into the barrel connector on the Arduino and it would regulate that down to the 5V it needs. As long as your power supply is strong enough to drive your actuator and the Arduino without too much voltage droop it should work, although as the actuator turns on and off there will likely be significant variation in the voltage supplied to the Arduino. You should probably add filter capacitors to the feeds to both the actuator and the Arduino to even out the voltage.

Duncan's  answer is how I would do it as well. Indeed that is how I did do it as well.
Having said that the challenge I had to work out was how to mix the voltages. For me, this was the hardest part of the project as I had little idea about current and voltage.
I also wanted to use just one power supply.
So what's the problem? The LED strip requires 12V@1Amp. Which is, I think the upper limit for what can be supplied to arduinio's power jack. Also the arduino can only supply a small current at 5v to switch the relatively massive 12V 1A led circuit.
The MOSFET was the answer (after multiple failed attempts). MOSFETs are apparantly safe for connection to Arduino as there is apparantly no electrical connection between the base (where the arduino connnects) to the other two pins (where the power flows). The articles I read say that the base is insulated from the rest of the circuit by a piece of glass!
Anyway, Here is my  Motion activated stair lighting project. I am not an electronics expert, but FWIW, this has been running flawlessly 24x7 for almost 12 months now.

Hey thanks a lot for your answer, and  also for sharing your project :), Cheers.


text:
Will Funduino Joystick Shield work on a Mega?
I am trying to get a Funduino Joystick Shield working with an Arduino Mega and I need to use the WiFi capability. The specs I have found for the Funduino (see https://protosupplies.com/product/funduino-joystick-shield-v1-a/) use the standard UNO pins for the RF24: 9..13, The Mega uses pins in the high 40s for this interface. Is there a way to make this work?

The MEGA pins needed to support the SPI interface used by the nRF24L01 are 50, 51 and 52. I can easily assign these pins in my software, but to physically connect them, I need to understand where the other end of the wires goes. Do I disconnect the WiFi header create a separate header? This seems like a bit of a kludge to me. It' easy to say, "Just use these pins..." but not so easy to determine HOW to use them.

The shield will work on Mega, except of the SPI connection for the nRF24L01 connector. The shield expects SPI on pins 11, 12, 13 and Mega has them on 50, 51, 52. Other shields use the SPI pins on the ICSP header to have compatibility with different boards. This shield doesn't connect to the ICSP header.
You can wire the nRF24L01 to SPI pins on 50, 51, 52.

Thanks for the partial clarity. My question is now, HOW do I do this rewire given that the Funduino is sitting on top of the Mega, blocking all access to the pins.

Does the hardware automatically reroute the ports to pins 50-52 allowing me to just change how the nRF24 is addressed in  software?

@BobJones, as I see it, pins 50 to 53 for SPI and usual CS are not covered


text:
ATMEGA328P-U vs ATMEGA328-PU
On my Arduino UNO the chip part number is ATMEGA328P-U, i recently bought a ATMEGA328-PU to make a standalone Arduino. realized the part number differences after receiving the package...
I noticed that some arduino UNOs have the chip with part number of ATMEGA328P-PU! I'm totally confused!
Those chip are the same? can i use the one that i bought for an standalone Arduino?
If no what are the differences?

The datasheets say what...?

328 / 328p: https://forum.arduino.cc/index.php?topic=60001.0

Uno has ATMEGA328P-PU. ATMEGA328-PU will work in Uno. ATMEGA328P-U doesn't exist

The main difference is the bit before the -. That is, the 328 vs the 328P.  The "P" there denotes "Picopower" which allows the chip to run at very low power consumptions.
Basically the P version is a more modern version of the non-P chip.  There are probably other internal differences too but you will have to check the datasheets thoroughly for those.
Everything after the - is to do with the packaging and environmental grading of the chip.  For example PU is a -40C to +85C grade DIP chip. ANR is a -40C to +105C grade TQFP chip, etc.
If you see 328P-U then that's probably a fake chip. There's no such thing as single U suffix.

There are three die types:
328
328P
328PB
all have different signature bytes which may or may not impact loading code into them. Generally tho the programming software needs to know which part type is being used, at a minimum for installing bootloader code.  Serial downloading may end up ignoring the signature bytes of a bootloaded part.
They can be had in different packaging, this is what Digikey is showing as available options:
-PU - 28 pin DIP
-AU - 32 pin TQFP
-AN - 32 pin TQFP
-MM - 28 pin leadless package, smaller than 32 pin leadless
-MN - 32 pin leadless package
-MU - 32 pin leadless package
-15AZ - 32 pin TQFP, rated for a higher temperature range
-15MZ - 32 pin leadless package rated for a higher temperature range
Any letters to the right of those seen when ordering indicate the method they are supplied - loose parts, parts in a reel, parts in a tube, etc.
Anything else is either an older part that did not follow the convention, or is a counterfeit part.
Tables 38.7 and 38.8 lists these options for the 328 and 328P for example, with H indicating a type of lead finish, and R indicating Tape & Reel availability:
http://ww1.microchip.com/downloads/en/DeviceDoc/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061A.pdf
ATmega328-AU
ATmega328-AUR
ATmega328-MMH
ATmega328-MMHR
ATmega328-MU
ATmega328-MUR
ATmega328-PU
And 328P options:
ATmega328-AU
ATmega328-AUR
ATmega328-MMH
ATmega328-MMHR
ATmega328-MU
ATmega328-MUR
ATmega328-PU
With these rated to 105C
ATmega328P-AN
ATmega328P-ANR
ATmega328P-MN
ATmega328P-MNR
ATmega328P-PN
I think you need to pull up the Automotive data sheet to see the Z numbered parts.
And the PB is a different data sheet as well.

That help a lot, but in case other people are finding this looking for ATmegaXX-XXPI, then: PI are 40-pin, PDIP

'328s are never 40-pin. There are 40-pin DIPs in the Atmega family, and some, like the '644, '1284P, have been brought into the Arduino IDE. I like the '1284P myself; 32 IO arranged as 4 8-bit ports, dual hardware serial, 128K flash, 16K SRAM (twice what the '2560 has).

Good point and my comment was more general for ATmega's, as this is the first google hit and your answer are a good reference, so i just wanted to add the answer to my own question there was about ATmega16-16pi, just in case it could help somebody else finding this looking for that.

The 328PB also won't work with the stock Arduino IDE and has a number of differences from the earlier parts.  Some of these are physical; e.g. a pin that was VCC is now a GPIO.  For support in the Ardiuno IDE (or Eclipse/Sloeber) you'll need to install MiniCore.

User line_code from forum.arduino.cc recently received an ATMEGA328P-U (or actually ATMEGA328P U) from Mouser (a company which you would not suspect to send out fakes or source from the gray market). He asked Mouser (who contacted the manufacturer Microchip) and got the following response:

As part of Part marking change due to the migration from Atmel to
Microchip, the package identifier has been removed from the device
marking as this can be observed visually for different packages. This
will be updated in the upcoming revisions of the device datasheet.  As
per this new marking the ATMEGA328P U are valid devices without any
process change. [...]

(Source: https://forum.arduino.cc/index.php?topic=561928.msg3890391#msg3890391)
So the P stands for pico power (the low power modern version) and if the package is a 28-pin DIP like in the photo I took then this specific ATMEGA328P U is an ATMEGA328P-PU.

Note that the Microchip response does say that the packaging is omitted from the marking. Hence we can expect ATMEGA328P Us to pop up in other packages. What the U stands for is unclear.

The U signifies ROHS compliance.  For specialized applications other options are available.  The ATmega328-MMH, for example, has a NiPdAu lead finish.

@Julian
I went through all the Product Change Notification pdfs in this mouser link https://www.mouser.in/ProductDetail/Microchip-Technology-Atmel/ATMEGA328P-PU?qs=K8BHR703ZXguOQv3sKbWcg%3D%3D
There is no mention of ATMEGA328p U. Do you have some official docs that is saying ATMEGA328P U is a legit IC Code?


text:
Hardware/Software Serial communication abruptly stops (HC - 05 bluetooth module)
I'm trying to send the readings of 3 sensors simultaneously to my Android phone on an app I made using MIT App Inventor 2 via the HC-05 bluetooth module.
For this, I'm sending a string like "20.067, 58.234, 12 |" where the "," allows the splitting of the text and "|" acts as a delimiter to tell the app that the whole string has reached it.
The problem I'm facing is that after a while(which varies from 2 seconds to a few minutes), the readings just stop and the app stops responding (ie; touching any butons on the app does nothing). However, this is a non-issue when I'm not using Bluetooth at all and just printing to the Serial Monitor.
To find the cause, I tried the following things:

Sent text to the module via the normal Serial.print() function so that I can see it on my PC and my app at the same time. Strangely, after the readings stopped (on the serial monitor as well), as soon as I closed the Serial Monitor and opened it again, the readings were back and again stopped after a while.
I used the SoftwareSerial.h library to define a different pair of RX/TX pins to send the text to the module and the serial monitor separately. This time, when the readings stopped, restarting the serial monitor had no effect.

I'm not exactly sure how to interpret these outcomes but it leads me to believe the problem lies in the serial communication.
Additional information:

The baud rate is set to 115200
I'm sending a string every 500ms and the app clock fires every 100ms

This is a screenshot of the codeblock on MIA 2:

This is the relevant portion of the Arduino sketch. The rest of it just calculates the variables being printed
  if(millis()-looper>500){
  // Sensor 1 data
  Serial.print(" X = ");
  Serial.print(x1);
  Serial.print(" Y = ");
  Serial.print(y1);
  Serial.print(" Z = ");
  Serial.print(z1);
  Serial.print(",");

  // Sensor 2 data
  Serial.print(" X = ");
  Serial.print(x2);
  Serial.print(" Y = ");
  Serial.print(y2);
  Serial.print(" Z = ");
  Serial.print(z2);
  Serial.print(",");

  // Sensor 3 data
  Serial.print(angle);
  Serial.println("|");
  looper = millis();
  }

opening Serial Monitor resets the Arduino. do you use String class? show the Arduino sketch

Thanks, I didn't know that. That explains why it starts working again, but I still need to know why it stops in the first place. I've included the sketch as you said.

the problem is not in this part of the sketch

The rest of it is just maths, I don't know where else the problem could be

you need to determine the location of the failure .... reduce your arduino loop()  code to a single  line that sends  a fixed string like "20.067, 58.234, 12 |" and pauses 500ms ..... do not do any sensor reading, no interrupt handling, nothing more than minimal code that communicates with the android device


text:
Arduino with external Wi-Fi antenna?
I need to create a project where I need to send data via Wi-Fi using an Arduino.
I need the Arduino to have a U.FL connector to place an external Wi-Fi antenna (I can't use the MKR1000 with integrated Wi-Fi antenna because the Arduino will be placed inside a metal box).
Is there any solution-like Arduino for this without the need to use an external board like: SparkFun WiFi Shield - ESP8266 ?
I could also use the BeagleBoard Green Wireless that contains this U.FL connector for an Wi-Fi antenna, but I wanted something smaller such as an Arduino.
PS: Wi-Fi is the only option.

some Wemos board clones have U.FL connector as alternative to on-board antenna https://robotdyn.com/wifi-d1-mini-esp8266-dev-board-usb-cp2104.html

It is commonly stated that many WIFI components have 50ohm impedance.  If true then swapping out internal and external antennas may be possible.  Even on boards which do not have an external antenna connector.  Notice that the SparkFun product you pointed to might be switchable to the external antenna by un-soldering, moving and re-soldering a jumper on the PCB (moving R10 to position R11 which is a do-not-place part).

I had "Grove UART Wifi" V1.0 with ceramic antenna in a metal box without external antenna. the AP was upstairs and the esp8266 worked without problems


text:
ESP8266 Websockets problem
I am trying to set up a network of 4 esp8266 programmed via the Arduino IDE. The Network will have 1 server (esp8266 running in AP mode) and 3 clients (esp8266 running in STA mode). I would like to do two things on the network.

Each client signals the server when a certain event happens (event is different for each client) and
Server broadcasts a byte of data to ALL clients on a regular basis (e.g. 1 second)

I have adapted various code to come up with the following (most examples I have seen do not use a standalone server).

#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WebSocketsServer.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <Hash.h>

#define USE_SERIAL Serial

const char *ssid = "MyNetwork";
const char *password = "MyPassword";

unsigned long last_10sec = 0;
unsigned int counter = 0;

ESP8266WebServer server(80);

WebSocketsServer webSocket = WebSocketsServer(81);

void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {

    switch(type) {
        case WStype_DISCONNECTED:
            USE_SERIAL.printf("[%u] Disconnected!\n", num);
            break;
        case WStype_CONNECTED: {
            IPAddress ip = webSocket.remoteIP(num);
            USE_SERIAL.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);
            // send message to client
            webSocket.sendTXT(num, "Connected");
            }
            break;
        case WStype_TEXT:
            USE_SERIAL.printf("[%u] get Text: %s\n", num, payload);
            break;
    }

}

void setup() {
    WiFi.disconnect();
    USE_SERIAL.begin(115200);
    USE_SERIAL.println();

    for(uint8_t t = 4; t > 0; t--) {
        USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
        USE_SERIAL.flush();
        delay(1000);
    }

    WiFi.softAP(ssid, password,10,false,8); // setup AP on channel 10 and set 8 possible connections

    IPAddress myIP = WiFi.softAPIP();
    USE_SERIAL.print("AP IP address: ");
    USE_SERIAL.println(myIP);

    // start webSocket server
    USE_SERIAL.println("start websockets");
    webSocket.begin();
    webSocket.onEvent(webSocketEvent);
    USE_SERIAL.println("websockets started");

    server.on("/", []() {
      // send index.html
        server.send(200, "text/html", "LED Control:

R: <input id=\"r\" type=\"range\" min=\"0\" max=\"255\" step=\"1\" oninput=\"sendRGB();\" />
G: <input id=\"g\" type=\"range\" min=\"0\" max=\"255\" step=\"1\" oninput=\"sendRGB();\" />
B: <input id=\"b\" type=\"range\" min=\"0\" max=\"255\" step=\"1\" oninput=\"sendRGB();\" />
");
    });
    USE_SERIAL.println("start server");
    server.begin();

    USE_SERIAL.println("end setup and goto main loop");
}

void loop() {
    unsigned long t = millis();
   //;
    server.handleClient();

    if((t - last_10sec) > 30000) {
        counter++;
        bool ping = (counter % 2);
        int i = webSocket.connectedClients(ping);
        USE_SERIAL.printf("%d Connected websocket clients ping: %d\n", i, ping);
        last_10sec = millis();
    }
}

client code is
#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

#include <WebSocketsClient.h>

#include <Hash.h>

const char *ssid = "MyNetwork";
const char *password = "MyPassword";
bool isConnected = false;

ESP8266WiFiMulti WiFiMulti;
WebSocketsClient webSocket;

#define USE_SERIAL Serial
#define MESSAGE_INTERVAL 10000
#define HEARTBEAT_INTERVAL 15000
uint64_t messageTimestamp = 0;
uint64_t heartbeatTimestamp = 0;

void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {

  switch(type) {
    case WStype_DISCONNECTED:
      USE_SERIAL.printf("[WSc] Disconnected!\n");
      isConnected=false;
      break;
    case WStype_CONNECTED: {
      USE_SERIAL.printf("[WSc] Connected to url: %s\n", payload);
      isConnected = true;
      // send message to server when Connected
      webSocket.sendTXT("Connected");
    }
      break;
    case WStype_TEXT:
      USE_SERIAL.printf("[WSc] get text: %s\n", payload);

      // send message to server
      // webSocket.sendTXT("message here");
      break;
    case WStype_BIN:
      USE_SERIAL.printf("[WSc] get binary length: %u\n", length);
      hexdump(payload, length);

      // send data to server
      // webSocket.sendBIN(payload, length);
      break;
/*        case WStype_PING:
            // pong will be send automatically
            USE_SERIAL.printf("[WSc] get ping\n");
            break;
        case WStype_PONG:
            // answer to a ping we send
            USE_SERIAL.printf("[WSc] get pong\n");
            break;
    }*/
  }
}

void setup() {

  USE_SERIAL.begin(115200);

  //Serial.setDebugOutput(true);
  USE_SERIAL.setDebugOutput(true);

  USE_SERIAL.println();
  USE_SERIAL.println();
  USE_SERIAL.println();

  for(uint8_t t = 4; t > 0; t--) {
    USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
    USE_SERIAL.flush();
    delay(1000);
  }
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
 // was WiFiMulti.addAP("SSID", "passpasspass");

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    USE_SERIAL.printf(".");
  }

  USE_SERIAL.println("start websocket");
  // server address, port and URL
  webSocket.begin("192.168.4.1", 81, "/");

  // event handler
  webSocket.onEvent(webSocketEvent);
  delay(10000);
  // try ever 5000 again if connection has failed
  webSocket.setReconnectInterval(5000);
  USE_SERIAL.println("end of setup. Goto Main loop");
}

void loop() {
  webSocket.loop();
    if(isConnected) {
        USE_SERIAL.printf("Connected\n");
        uint64_t now = millis();

        if(now - messageTimestamp > MESSAGE_INTERVAL) {
            messageTimestamp = now;
            USE_SERIAL.printf("send message\n");
            // example socket.io message with type "messageType" and JSON payload
            webSocket.sendTXT("42[\"messageType\",{\"greeting\":\"hello\"}]");
        }
        if((now - heartbeatTimestamp) > HEARTBEAT_INTERVAL) {
            heartbeatTimestamp = now;
             USE_SERIAL.printf("heartbeat\n");
            // socket.io heartbeat message
            webSocket.sendTXT("2");
        }
    }
    else
    {
      USE_SERIAL.printf("not connected\n");
      delay(10000);
    }
}

The debug output for server is
19:38:30.671 -> SDK:2.2.1(cfd48f3)/Core:2.5.2=20502000/lwIP:STABLE-2_1_2_RELEASE/glue:1.1-7-g82abda3/BearSSL:a143020
19:38:30.671 ->
19:38:30.671 -> [SETUP] BOOT WAIT 4...
19:38:31.657 -> [SETUP] BOOT WAIT 3...
19:38:32.689 -> [SETUP] BOOT WAIT 2...
19:38:33.673 -> [SETUP] BOOT WAIT 1...
19:38:34.657 -> [AP] softap config unchanged
19:38:34.704 -> AP IP address: 192.168.4.1
19:38:34.704 -> start websockets
19:38:34.704 -> [WS-Server] Server Started.
19:38:34.704 -> websockets started
19:38:34.704 -> start server
19:38:34.704 -> end setup and goto main loop
19:38:58.354 -> wifi evt: 7
19:38:58.495 -> wifi evt: 7
19:38:58.635 -> wifi evt: 7
19:39:00.606 -> 0 Connected websocket clients ping: 1
19:39:00.935 -> add 1
19:39:00.935 -> aid 1
19:39:00.935 -> station: xx:xx:xx:xx:xx:xx join, AID = 1
19:39:00.935 -> wifi evt: 5
19:39:01.075 -> wifi evt: 9
19:39:03.102 -> wifi evt: 7
19:39:03.257 -> wifi evt: 7
19:39:03.377 -> wifi evt: 7
19:39:03.527 -> wifi evt: 7
19:39:03.837 -> wifi evt: 7
19:39:30.567 -> 0 Connected websocket clients ping: 0
19:40:00.595 -> 0 Connected websocket clients ping: 1
19:40:30.573 -> 0 Connected websocket clients ping: 0
19:41:00.577 -> 0 Connected websocket clients ping: 1

and debug output for client is
19:13:45.235 -> SDK:2.2.1(cfd48f3)/Core:2.5.2=20502000/lwIP:STABLE-2_1_2_RELEASE/glue:1.1-7-g82abda3/BearSSL:a143020
19:13:45.235 ->
19:13:45.235 ->
19:13:45.235 ->
19:13:45.235 -> [SETUP] BOOT WAIT 4...
19:13:46.267 -> [SETUP] BOOT WAIT 3...
19:13:46.642 -> wifi evt: 2
19:13:47.251 -> [SETUP] BOOT WAIT 2...
19:13:48.095 -> scandone
19:13:49.032 -> state: 0 -> 2 (b0)
19:13:49.032 -> [SETUP] BOOT WAIT 1...
19:13:49.032 -> state: 2 -> 3 (0)
19:13:49.079 -> state: 3 -> 5 (10)
19:13:49.079 -> add 0
19:13:49.079 -> aid 1
19:13:49.079 -> cnt
19:13:49.079 ->
19:13:49.079 -> connected with MyNetwork, channel 10
19:13:49.079 -> dhcp client start...
19:13:49.079 -> wifi evt: 0
19:13:49.219 -> ip:192.168.4.2,mask:255.255.255.0,gw:192.168.4.1
19:13:49.219 -> wifi evt: 3
19:13:50.626 -> ....scandone
19:13:52.641 -> .start websocket
19:13:59.062 -> pm open,type:2 0
19:14:02.624 -> end of setup. Goto Main loop
19:14:02.624 -> [WS-Client] connect ws...
19:14:02.624 -> [hostByName] Host: 192.168.4.1 is a IP!
19:14:02.671 -> [WS-Client] connected to 192.168.4.1:81.
19:14:02.671 -> [WS-Client][sendHeader] sending header...
19:14:02.671 -> [WS-Client][sendHeader] handshake GET / HTTP/1.1
19:14:02.671 -> Host: 192.168.4.1:81
19:14:02.671 -> Connection: Upgrade
19:14:02.671 -> Upgrade: websocket
19:14:02.671 -> Sec-WebSocket-Version: 13
19:14:02.671 -> Sec-WebSocket-Key: 8L/m+WcjssjBS/Sa8a0Qvg==
19:14:02.671 -> Sec-WebSocket-Protocol: arduino
19:14:02.671 -> Origin: file://
19:14:02.671 -> User-Agent: arduino-WebSocket-Client
19:14:02.671 ->
19:14:02.671 -> [write] n: 241 t: 17509
19:14:02.671 -> [WS-Client][sendHeader] sending header... Done (23209us).
19:14:02.671 -> not connected
19:14:12.661 -> not connected
19:14:22.659 -> not connected
19:14:32.664 -> not connected
19:14:42.687 -> not connected
19:14:52.671 -> not connected
19:15:02.657 -> not connected
19:15:12.692 -> not connected
19:15:22.677 -> not connected
19:15:32.674 -> not connected

I am reading this as the client connecting to the AP but not connecting via websockets. Can anyone assist?

The server you set as server(80) and the client you set as webSocket.begin(ip, 81,...) .why you do that? Try to use same port.


text:
Why map Arduino pins 2 and 3 to Rx and Tx instead of using the build in Rx and Tx pins?
In many examples I see the following:
#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

// set up a new serial object
SoftwareSerial mySerial (rxPin, txPin);

what is the benefit of mapping pins 2 and 3 like this? Why not just use the built in RX (pin 0) and TX (pin 1) pins? I'm using a standard Arduino Uno.

it allows to have two serial ports ... one can then be used for debugging

@jsotola  Please do not answer questions in comments - use the answer box for that. Comments here are for seeking more details about the question.

SoftwareSerial lets you add an additional serial port using "bit banging" to read/write to the port. This lets you connect up another serial device (eg. GPS, RFID reader, MIDI device, LCD) to this extra port, and still use the hardware serial interface (pins 0 and 1) via the USB port to send messages and/or debugging to the connected PC.

Is there any special wiring needed to send messages to the connected PC? Or is it enough that they just not be in use?

Pins 0 and 1 are connected to the Atmega16U2 USB interface chip. If it gets what looks like serial data it will forward it to the PC.

Is there any special wiring needed to send messages to the connected PC? Or is it enough that they just not be in use?
I'm currently using the hardware ports to communicate with an ESP8266 WiFi module, and I'm still able to see the output of Serial.print() in my serial monitor.

@AdrianM, but the esp8266 gets your debug prints too. if you have AT firmware in esp8266, the firmware attempts to process them. it disturbs the previous and/or the following AT command

See my amended answer. I agree with Juraj though, stuff you send through ports 0 and 1 will also go to whatever you have connected to those pins and the USB interface.

Nick Gammon indicated Pins 0 (RX) and 1 (TX) are already connected to the USB-Serial 16U2 chip.  Correct.  Although the transmit pin, pin 1, can drive multiple devices / serial ports, the receive pin, pin 0, is being driven by the 16U2 chip.
See: https://www.arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf
Trying to use this would result in tying two outputs together (never good unless the outputs are configured for open collector/open drain).  I've seen many shields that try to use pins 2 and 3 for a serial port.  (Not a good idea for a serial peripheral...)

Re “would result in tying two outputs together”: there is a 1 kΩ resistor between the 16U2’s TX and the 328P’s RX that makes this safe.


text:
What are the better options to the basic Arduino Serial Plotter?
Arduino Serial Plotter does not allow analysis or saving of data. What are the best serial data graphing software (preferably free, but i don't mind if it's paid as long as it's better than the bare-bones Arduino Serial Plotter)?

It should work well with Arduino
It should allow plotting several variables on the same graph
Allow exporting data to CSV so i can show it in Excel.

you can print CSV to Serial Monitor or to SD card file and then process it

I tend to just save the serial data into a file: stty -F /dev/ttyACM0 raw 9600 && cat /dev/ttyACM0 > data.tsv, then graph it with gnuplot. But it's not real-time serial plotting, so I don't know if it could count as an answer...

you could write an app that does what you want using Processing .... http://processing.org ... there may be example programs that do what you want

If you are willing to install the 'Processing' JAVA environment take a look at: https://github.com/digamesystems/DigameSerialPlotter

Custom devices require custom solutions.
I suggest using Python (don't be scared).
This tutorial shows us how to read data from serial and save it to .csv file. You don't have to use a file. For example you can modify it to use an in memory list, and save just values from last 30 seconds. You can also read several values, and not just one.
import serial
import time
import csv

ser = serial.Serial('/dev/ttyACM0')
ser.flushInput()

while True:
    try:
        ser_bytes = ser.readline()
        decoded_bytes = float(ser_bytes[0:len(ser_bytes)-2].decode("utf-8"))
        print(decoded_bytes)
        with open("test_data.csv","a") as f:
            writer = csv.writer(f,delimiter=",")
            writer.writerow([time.time(),decoded_bytes])
    except:
        print("Keyboard Interrupt")
        break

This tutorial (and this one) shows you how very quickly to show a sophisticated plot of the data you collected. You can even make a plot that shows several graphs and updates in real time.
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()

Don't be scared it's not black magic. It just takes few days to understand how things work.


text:
Variable declaration inside main loop
In the past I declared variables inside the main loop which worked just fine.
In a new project I did the same:
void loop(void)
{
    uint8_t counter;
    ....
    if (buttonPress)
        counter = 0;
    ...
    if (someCondition == true)
    {
        Serial.println(counter);
        counter++
    }
}

But then the output of the variable counter shows that for some reason the counter variable is reset to 0 instead of counting up. This happens even after the button is released.
The scope of the variable counter is the main loop and I just assumed that it will keep its value and count up.
What might be the reason for this variable to reset to 0?
Is it that other functions are called within the main loop?
Is it that an interrupt handler is called every now and then?
The solution I've found is to declare the variable as static:
static uint8_t counter;

Then it increments as expected.
Even though I've found a solution I'd really like to understand what the problem with my first approach was.

This question fits better in stack overflow, since it is not related to Arduino.

So the main loop in the Arduino just behaves as any regular function that is called?
For some reason I thought that variables declared in main() are automatically static and keep their value.

No they are not, afaik the loop() is just a function that has a while(true) or while(1) inside.

Thank you very much for the explanation and possible solutions.

Just to get this straight:
With the arduino the main loop() just is a regular C-function with all the implications regarding variable scope.
But in a C-program a variable declared in main() keeps its value.
So if I used plain C for my program instead of the Arduino framework the counter variable would work without being declared static.
Of course then the if-statements would be located in a while(1) loop.

Yes you are right (if I follow your sentences correctly). I'm not fully sure, but I guess the main() which is mandatory for c is created by the IDE and invisible for the user, it initializes something, than calls setup (once), than maybe some other checks are done, than a `while (true) { loop(); } is called,

(btw if an answer is helpful, upvote it (by clicking the 'up' arrow), if an answer (or the best answer is given that solves your problem), accept the answer.

@MichelKeijzers: Here is main().

@EdgarBonet Thanks for that code.

@Sören "But in a C-program a variable declared in main() keeps its value." - A variable in main() keeps it value until execution leaves main(). Just as for Arduino's loop(), and indeed any other function. (One difference of course is, that once you leave main(), your program exits and it doesn't matter what happens to the variables.)

Michael's answer was good, as usual. Let me give you some more background though:
In C/C++ (And in most modern languages) variables have a "scope", or an area where they are defined.
Global scope:
Variables declared at the top level of your program have global scope, and exist for the life of your program. These variables are usually created on the .data or .bss sections.
Local scope
Variables declared inside a function have local scope. Unless they are static, they get created when the function is entered, and get discarded when the function exits. These variables are created on the stack as part of the function's stack frame.
Object scope
In C++ and other object-oriented languages, instances of objects have their own scope, "instance variables". Every instance of an object has its own set of instance variables. (Think of cars, and a car radio. You and I might own the exact same model of car, but if I set my car's radio station and you set your car's radio to a different station, each instance of the car has a different setting for the radio station.)
Static variables:
Static variables are variables that are declared "statically." That means that they are only created once and persist, even if they are declared inside a scope like a function or a class instance. These have the lifespan of a global variable but can be declared inside a function or in an object.

Loop is a function, so variables declared inside of loop() are local variables. They get created anew every time the function is called, and discarded every time the function exits.

+1 for the great explanation and background

Your code has a couple of bugs.  First you don't initialize counter before using it.  Second the variable 'counter' has limited scope, it has no definition when loop() exits.  If you want this variable to stay around declare it as static.
Both bugs corrected
e.g.:
void loop(void)
{
    static uint8_t counter = 0;
    ....
    if (buttonPress)
        counter = 0;
    ...
    if (someCondition == true)
    {
        Serial.println(counter);
        counter++
    }
}

Note:  Initializing counter to 0 only happens once, on subsequent calls to loop() counter will retain it's previous value.

The problem is that you declare a new variable. So even though the name is the same, the local variable is destroyed at the end of the loop and recreated at the beginning.
Actually, there is no good solution:

Global variables are best to be avoided. They can be seen as 'singleton's', e.g. variables that are needed at many places in the code and have only one occurrence.
As you found out, static solves the problem. I would use this option, although personally I'm not a fan of static variables.
Another way is to put the loop in a while, so you get:
void loop(void)
{
    uint8_t counter = 0; // Always initialize variables
    while (true)
    {
        // Your code
    }
}
This will work too, as your counter is only initialized once, however the loop is already (internally) a while loop, so you have two.
A much better way but more extra work, is to create a C++ class, where counter can be a class variable, which is local for that class (which could still be a singleton). Of course this is only true when the counter variable is belonging logically to that class, if it is not, just keep it a global variable (updated after Edgar Bonet's remark).

Making the counter a property of an object which is itself a global variable would be no better than making the counter itself global. It would actually be worse: any complexity that serves no useful purpose is always a bad thing in a program.

@EdgarBonet You are right when that variable (the counter) is unrelated to the class that would be created (I was assuming so, but I will update my answer). If the counter is unrelated, than you are absolutely right.

Could you explain why simply using a global variable should be avoided? I see no disadvantage in terms of memory usage or performance. I'd say, using a global variable is just fine in many situations. In my opinion making it more complicate is also not very elegant.

@SimSon There is no disadvantage in terms of memory usage or performance, bit if you make all variables global and you have thousands of them, you can imagine what mess it will be. This will not happen easily in an Arduino Uno with 2 KB memory, but it's best to keep functionality isolated. Actually, one of the worst things about the Arduino IDE is that it works best with just an Ino file, and most people do not get further creating classes or separate files.

@SimSon: See Are global variables evil in Arduino?.

@MichelKeijzers okay, so how to manage this kind of problem is more a personal decision. I'm quite used to having several globals and I think it's very readable (a huge program with "thousands" of global variables will be complex anyway). Thanks for clarification

@EdgarBonet thanks, I allready know this question.

@SimSon In your case, you can use the static, because you will use the variable only in that one function. Or keep it global (than you can use it in different functions too when you decide to split the loop function when it gets to big, or when you need it in an interrupt). In the program I'm making I have classes with variables inside classes (called properties) but my program is over 1,000 lines.

@MichelKeijzers I'll keep that in mind, thank you!

Btw, there is a disadvantage of using not global variables, as Duncan C mentioned, global variables to to the heap, and local variables to a stack. That means they will not be counted in the summary you get when you build your sketch (so you have to manually keep track of the local variable size (and parameters) to know if you can run into memory problems.

Globals are statically allocated into the .data or .bss sections, just like static locals. They are all counted in the build-time memory usage summary. The heap is where you get with malloc() and new.

@EdgarBonet You are fully right (again) ... in the case of the OP both global and static will be counted towards .data/.bss, and local (non static) go to stack.

I don't like the "loop in a while" idea.  The void loop(void) function is already called from a loop, which can be presumed to have some other code in it until we know otherwise.  The "loop in a while" idea prevents that other code from running because it never returns.

@AaronD True ... actually it does  not even work  as Edgar Bonnet shows there is some code called in the framework after each call to loop.


text:
Arduino Timer0 Piggyback
As described here
https://learn.adafruit.com/multi-tasking-the-arduino-part-2/timers
I use timer 0 to get my own timer with a milliseconds resolution.
It is setup like this:
void setup (void)
{
    ...
    cli();
    OCR0A  = 0xAB;
    TIMSK0 |= (1 << OCIE0A);
    sei();
    ...
}

The value 0xAB is chosen randomly and should not affect the behaviour.
The interrupt handler looks like this:
ISR(TIMER0_COMPA_vect)
{
    if (myTimer != 0)
        myTimer--;
    return;
}

This works just OK but having a closer look at the actual timing values using millis() I've found that the timer values given by this ISR are about 2-3% too long.
According to adafruit.com this method should exactly follow the built-in millis() timer of the Arduino.
In my program there are no other interrupts active. There are some Serial.print() outputs, maybe they affect the timing?
The solution I've found looks like this:
ISR(TIMER0_COMPA_vect)
{
    static unsigned long timeLast;

    unsigned long timeNow = millis();
    uint8_t timeDiff = (uint8_t)(timeNow - timeLast);
    timeLast = timeNow;

    if (myTimer != 0)
        myTimer -= timeDiff;

    return;
}

Instead of simply decrementing the timer, the timer value is decreased by the actual amount of time since the last call of the ISR.
With this my timer follows exactly the millis().
But why doesn't the first approach give an exact timing? Apparently there are some cases where the time between calls of the ISR is not 1ms but 2ms.

Does that mean that millis() already returns the corrected value i.e. millis() gives the actual number of milliseconds and not the 1.024ms?

The Arduino core configures Timer 0 for a period of 1,024 µs. Your
ISR will then be called at very regular intervals, and is a good place
to have timing-related code. You just have to keep in mind that the unit
of time is not one millisecond, but 1.024 ms.
If this “weird” unit bothers you, then you could do what the Arduino
timing ISR does: keep track of how late, relative to a 1 ms
period, you are getting. When you notice you are 1 ms late, count
one extra millisecond.


text:
Make a set LED dimming schedule?
I'm trying to made the LED's go from minimum brightness to maximum brightness and back to minimum in 2.55 seconds.
I really don't know where to begin. I have the following basic code for making it blink simultaneously, but how do I make it cycle through during the time I want:
int led = 10;           //the PWM (tilde) pin the LED is attached to

int led2 = 9;

int led3 = 11;

int brightness = 0;    //how bright the LED is

int delaytime = 25;

int fadeAmount = 5;    //how many points to fade the LED by

//the setup routine runs once you press the reset:

void setup() {

  // declare pins to be an output:

  pinMode (led, OUTPUT);

  pinMode (led2, OUTPUT);

  pinMode (led3, OUTPUT);

}

//the loop routine runs over and over again forever:

void loop() {

  // set the brightness of pin 10:

  analogWrite (led, brightness);

  analogWrite (led2, brightness);

  analogWrite (led3, brightness);

  //change the brightness for next time through the loop:

  brightness = brightness + fadeAmount;

  //reverse the direction of the fading at the ends of the fade:

  if (brightness <= 0 || brightness >= 255) {

    fadeAmount = -fadeAmount;

  }

//wait for set milliseconds to see the dimming effect

delay (delaytime);

}

**bonus: the next part includes making each LED go on its own schedule so the more thoroughly you can explain this first the better I can attempt the next part.
THANK YOU!

You can set the delay and fadeAmount for getting through in 2.55s.  And what do you mean by "on its own schedule"?

So I sort of get the initial delaytime and fadeAmount values based on this reasoning: You set the fade amount and delay to specific values or at least keep the same ratio
FadeAmount/510 = delayTime/TotalTime
5/510=25/2550
510 being the total brightness change from low to high to low again.

But I need my first LED to go from min to max to min brightness in 2.55 seconds, my second to go in 5. 1 sec, and my third in 10.2. How would I be able to set each of them on their own schedule, Like make LED each have its own fadeAmount if I kept the delaytime constant at 25? Does that make sense?

is this a school assignment?  ... the word "bonus" says that it is one

It is a school assignment, though I don't get bonus points for the second part...I just have to do it. Thankfully ya'll explained it well enough for me to do it on my own. thanks!

The way to go is the non-blocking coding style, that can be found in the BlinkWithoutDelay example, that comes with the Arduino IDE. There you use millis() to measure time. You save a timestamp for every LED and in every execution of the void loop() you check, if enough time has passed since the last timestamp. You have to do this for every LED.
Since this coding style has been explained numerous times through the internet and on this site, I will not go more into detail. You can google the rest, understand, how that style works and then transfer that to your case.

Have a look at these instructables...
One does the gradual fading of an led (on and off) via PWM: LED lighting in a staircase.
The second deals with the "there own schedule" bit - which I assume means cycle on and off independently of one another.:  cooperative multitasking.
Disclaimer.. they are my instructables posts, but they do address the question. There are also several libraries available for running "timed tasks" if you prefer an alternative solution.
Here is an practical example that should deal with both aspects of your question (hopefully it will stem the tide of negative feedback)...
It should work on an UNO or any other Arduino with PWM on pins 3, 5 and 6. Of course you are free to adjust the pins to suit your needs (including adding more or taking some out).

int pwmPin[] = {3, 5, 6 };        // Pins that are being used for PWM.
int pwmValue [] = { 0, 0, 0};     // Initial value of PWM duty cycle in the range 0 to 255.
int pwmIncrement[] = {1, 1, 1};   // The value by which the PWM will be incremented at each step.
                                  // NB, this can not be zero but you can start with negative numbers if you wish.
unsigned int pwmDelay[] = { 20, 30, 70 }; // The delay between steps for each PWM.

// To get a good effect select good initial values for the delay, value and increment.
// larger delays mean less frequent changes to the PWM duty cycle.
// larger increments means each adjustment to the PWM duty cycle is larger.
// Set the value at the starting point e.g. 0, for off, 127 for 50% brightness or 255 for 100%.

#define PINS sizeof(pwmValue)
unsigned long pwmNextStepTime[PINS]; // The point in time when the PWM will next be adjusted.

void setup() {
  for (int i = 0; i < PINS; i++) {   // Initialise each pin as:
    pinMode(pwmPin[i], OUTPUT);      // an output.
    pwmNextStepTime[i] = millis() + pwmDelay[i];   // The time when next the duty cycle shoud be adusted.
    analogWrite(pwmPin[i], pwmValue[i]);           // Set the duty cycle of the PWM.
  }
}

void loop() {
  // put your main code here, to run repeatedly:
  for (int i = 0; i < PINS; i++) {    // On each loop, check the PWM pin to see if we need to do anything.
    unsigned long now = millis();     // What is the current "time"?
    if (now > pwmNextStepTime[i]) {   // Has the time passed the adjustment time for PWM pin i?
      pwmNextStepTime[i] = now + pwmDelay[i];  // Yes, calculate the next adjustment time.
      pwmValue [i] += pwmIncrement[i];         // Adjust the duty cycle as per the pin's increment.
      if (pwmValue [i] >= 255) {               // Have we gone too far up?
        pwmValue[i] = 255;                     // Yes, set the maximum value.
        pwmIncrement[i] = -pwmIncrement[i];    // Reverse the increment (so now we count down)
      } else if (pwmValue[i] <= 0) {           // Have we gone too far down?
        pwmValue[i] = 0;                       // Yes, set the minimum value.
        pwmIncrement[i] = -pwmIncrement[i];    // Reverse the increment (so now we count up)
      }
      analogWrite(pwmPin[i], pwmValue[i]);     // Finally, set the duty cycle for the LED.
    }
  }
}


text:
Why won't this code play a converted wav2c header file through an Arduino to my speaker?
I used this converter wav2c to convert a .wav file to a C that I can put in a header file. I was able to put converted audio into the h file but the program where I reference it does not seem to be working correctly. The code compiles and uploads to the Arduino but no sound plays. I used the code here to implement the converted audio. I'm using an 8-ohm 0.25w speaker. I'm no programmer nor an expert at electronics so it's likely something dumb that I did wrong. Any help is much appreciated!
Note: The speaker does work with a simple tone sketch.
The code in the header file (minus the hundreds of lines of values for the audio)

#ifndef _HEADERFILE_H    // Put these two lines at the top of your file.
#define _HEADERFILE_H    // (Use a suitable name, usually based on the file name.)

const int sounddata_length=10000;
//const int sounddata_sampleRate=8000;

const unsigned char sounddata_data[] PROGMEM = {
  15,1,49,0,150,0,138,0,219,255,133,0,176,0,15,1,210,254,16,1,197,255,65,0,9,0,227,0,127,254,87,0,175,1,61,254,132,1,135,255,21,1,72,0,104,1,172,0,122,0,213,1,65,255,188,1,100,1,215,0,210,255,59,2,17,0,193,0,200,2,207,255,203,0,65,1,17,1,169,255,121,2,112,0,193,255,65,255,252,255,232,0,101,255,88,2,4,0,26,255,

//Several hundred lines more of these numbers for the audio

105,108,101,45,49,46,48,46,50,52,41,0,105,100,51,32,42,0,0,0,73,68,51,3,
  0,0,0,0,0,31,84,88,88,88,0,0,0,21,0,0,0,83,111,102,116,119,97,114,101,0,76,97,118,102,53,50,46,57,51,46,48,0,};

#endif // _HEADERFILE_H    // Put this line at the end of your file.

Here is the code that I used from the Arduino Playground page to play the audio from the header file.
#include <stdint.h>
#include <avr/interrupt.h>
#include <avr/io.h>
#include <avr/pgmspace.h>

#define SAMPLE_RATE 8000
#include "Test.h"

int ledPin = 3;
int speakerPin = 11; // Can be either 3 or 11, two PWM outputs connected to Timer 2
volatile uint16_t sample;
byte lastSample;

void stopPlayback()
{
    // Disable playback per-sample interrupt.
    TIMSK1 &= ~_BV(OCIE1A);

    // Disable the per-sample timer completely.
    TCCR1B &= ~_BV(CS10);

    // Disable the PWM timer.
    TCCR2B &= ~_BV(CS10);

    digitalWrite(speakerPin, LOW);
}

// This is called at 8000 Hz to load the next sample.
ISR(TIMER1_COMPA_vect) {
    if (sample >= sounddata_length) {
        if (sample == sounddata_length + lastSample) {
            stopPlayback();
        }
        else {
            if(speakerPin==11){
                // Ramp down to zero to reduce the click at the end of playback.
                OCR2A = sounddata_length + lastSample - sample;
            } else {
                OCR2B = sounddata_length + lastSample - sample;
            }
        }
    }
    else {
        if(speakerPin==11){
            OCR2A = pgm_read_byte(&sounddata_data[sample]);
        } else {
            OCR2B = pgm_read_byte(&sounddata_data[sample]);
        }
    }

    ++sample;
}

void startPlayback()
{
    pinMode(speakerPin, OUTPUT);

    // Set up Timer 2 to do pulse width modulation on the speaker
    // pin.

    // Use internal clock (datasheet p.160)
    ASSR &= ~(_BV(EXCLK) | _BV(AS2));

    // Set fast PWM mode  (p.157)
    TCCR2A |= _BV(WGM21) | _BV(WGM20);
    TCCR2B &= ~_BV(WGM22);

    if(speakerPin==11){
        // Do non-inverting PWM on pin OC2A (p.155)
        // On the Arduino this is pin 11.
        TCCR2A = (TCCR2A | _BV(COM2A1)) & ~_BV(COM2A0);
        TCCR2A &= ~(_BV(COM2B1) | _BV(COM2B0));
        // No prescaler (p.158)
        TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

        // Set initial pulse width to the first sample.
        OCR2A = pgm_read_byte(&sounddata_data[0]);
    } else {
        // Do non-inverting PWM on pin OC2B (p.155)
        // On the Arduino this is pin 3.
        TCCR2A = (TCCR2A | _BV(COM2B1)) & ~_BV(COM2B0);
        TCCR2A &= ~(_BV(COM2A1) | _BV(COM2A0));
        // No prescaler (p.158)
        TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

        // Set initial pulse width to the first sample.
        OCR2B = pgm_read_byte(&sounddata_data[0]);
    }

    // Set up Timer 1 to send a sample every interrupt.

    cli();

    // Set CTC mode (Clear Timer on Compare Match) (p.133)
    // Have to set OCR1A *after*, otherwise it gets reset to 0!
    TCCR1B = (TCCR1B & ~_BV(WGM13)) | _BV(WGM12);
    TCCR1A = TCCR1A & ~(_BV(WGM11) | _BV(WGM10));

    // No prescaler (p.134)
    TCCR1B = (TCCR1B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

    // Set the compare register (OCR1A).
    // OCR1A is a 16-bit register, so we have to do this with
    // interrupts disabled to be safe.
    OCR1A = F_CPU / SAMPLE_RATE;    // 16e6 / 8000 = 2000

    // Enable interrupt when TCNT1 == OCR1A (p.136)
    TIMSK1 |= _BV(OCIE1A);

    lastSample = pgm_read_byte(&sounddata_data[sounddata_length-1]);
    sample = 0;
    sei();
}

void setup()
{
    pinMode(ledPin, OUTPUT);
    digitalWrite(ledPin, HIGH);
    startPlayback();
}

void loop()
{
    while (true);
}

are you using the correct pin for output?

Put a minumum 125 ohm resistor in series with the pin and the speaker to limit the current out of the pin to 40mA max.  10,000 samples read back at 8,000 Hz = 1.25 second burst of sound. Is that what you are expecting?

This program uses the Timer 2 PWM facility to generate audio output on
pins OC2A or OC2B. On the Arduino Uno, these pins are labeled “11” and
“3” respectively, and the program carries this mapping as an implicit
assumption. You are trying to run the program on an Arduino Mega, which
has a different pinout. For instance, on the Mega:

OC2A = digital 10
OC2B = digital 9

You can easily port the program to the Mega by replacing every reference
to pins 11 and 3 by 10 and 9 respectively. E.g., every occurrence of
if(speakerPin==11){

becomes
if(speakerPin==10){

Make sure to fix the comments so that they remain consistent with the
code.
And you should, of course, choose an appropriate pin for your speaker.
Side note: you are stressing the output pin if you connect it directly
to an 8 Ω speaker. It's fine for a test as long as you don't care
too much about the life span of your Arduino.


text:
Arduino IDE doesn't pick up serial ports
I am fairly new to Arduinos and I recently bought a nodeMCU Amica esp2866 for this tutorial. I have my board connected to my MacBook Air (10.14.5 with Mojave) and only the "/dev/cu.Bluetooth-Incoming-Port" is the only one that shows up.

I am using a basic USB cord to connect the board to my MacBook and I know the cable isn't broken because I have used it in the recent past. If anyone knows how to fix this problem or has run into this problem in the past, please let me know. Let me know if you'd like anymore information. Thank you!

A Mac is (sort of) a Unix box.  So, try opening a console and typing in "lsusb".  I think that should list all the USB devices the computer sees.

What version of the nodeMCU are you using?

The MAC / Arduino install instructions appear to be here.
If your Arduino (possibly a NodeMCU 1.0 version board) is using the CP210x chip set there appears to be a download page here.
If your Arduino (possibly a NodeMCU 0.9 version board) is using the ch340g, ch34g or ch34x chip set there appears to be an effort to create a Mac OS X driver here.
The install instructions from that github page are as follows:

Installation
Unplug any CH34* devices.
Unload the old drivers if running:
    sudo kextunload /Library/Extensions/usbserial.kext
    sudo kextunload /System/Library/Extensions/usb.kext
Remove the old driver by issuing one of the following commands (depending on your installation):
    sudo rm -rf /System/Library/Extensions/usb.kext
    sudo rm -rf /Library/Extensions/usbserial.kext
Double-click on the CH34x_Install_V1.5.pkg file and install (no need to reboot)
Instead of rebooting, you can force quit Installer after it completes.
Load the new driver:
    sudo kextload /Library/Extensions/usbserial.kext
Plug in your device. It should now be listed under the /dev directory. Examples:
    /dev/cu.wchusbserial1410
    /dev/tty.wchusbserial14210 (driver version 1.5)


text:
Fingerprint sensor Arduino IDE code errors (Arduino Uno)
This code is for a fingerprint sensor. I keep getting the "function definition is not allowed before '{' token" error on the Arduino IDE. Any further corrections would also be immensely appreciated.
#include <Adafruit_Fingerprint.h>
#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3);

Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

void setup()
{
  Serial.begin(9600);
  while (!Serial);  // For Yun/Leo/Micro/Zero/...
  delay(100);
  Serial.println("fingertest");
  pinMode(12, OUTPUT);

  // set the data rate for the sensor serial port
  finger.begin(57600);

  if (finger.verifyPassword()) {
    Serial.println("Found fingerprint sensor!");
  } else {
    Serial.println("Did not find fingerprint sensor :(");
    while (1) { delay(1); }

  finger.getTemplateCount();
  Serial.print("Sensor contains "); Serial.print(finger.templateCount); Serial.println(" templates");
  Serial.println("Waiting for valid finger...");
}

void loop()                     // run over and over again

{
  getFingerprintIDez();
  delay(50);            //don't ned to run this at full speed.
  digitalWrite(12, LOW);
}

uint8_t getFingerprintID() {
  uint8_t p = finger.getImage();
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.println("No finger detected");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("Imaging error");
      return p;
    default:
      Serial.println("Unknown error");
      return p;

  // OK success!

  p = finger.image2Tz();
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("Could not find fingerprint features");
      return p;
    default:
      Serial.println("Unknown error");
      return p;

  // OK converted!
  p = finger.fingerFastSearch();
  if (p == FINGERPRINT_OK) {
    Serial.println("Found a print match!");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_NOTFOUND) {
    Serial.println("Did not find a match");
    return p;
  } else {
    Serial.println("Unknown error");
    return p;
  }

  // found a match!
  Serial.print("Found ID #"); Serial.print(finger.fingerID);
  Serial.print(" with confidence of "); Serial.println(finger.confidence);

  return finger.fingerID;
}

// returns -1 if failed, otherwise returns ID #
int getFingerprintIDez() {
  uint8_t p = finger.getImage();
  if (p != FINGERPRINT_OK)  return -1;

  p = finger.image2Tz();
  if (p != FINGERPRINT_OK)  return -1;

  p = finger.fingerFastSearch();
  if (p != FINGERPRINT_OK)  return -1;

  // found a match!

  digitalWrite(12, HIGH);
  delay(3000);
  digitalWrite(12, LOW);

  Serial.print("Found ID #"); Serial.print(finger.fingerID);
  Serial.print(" with confidence of "); Serial.println(finger.confidence);
  return finger.fingerID;
}

Here is the circuit diagram-

This program works for products like- https://www.flyrobo.in/finger_print_sensor
.The wire connection is as follows- fingerprint sensor white wire - pin 3, yellow wire - pin 2, red wire - “+5v” , black wire - “GND” servo wire - pin 4
Any and all help is appreciated.

check the braces {} ....  make sure that they all match .... it helps to copy and paste your code into a text editor such as notepad++ and use it to count the braces .... https://notepad-plus-plus.org/

Hint: Look at else block in setup and at your loop function


text:
Error: exit status 1 stray '#' in program
I got this error:
exit status 1 stray '#' in program

How can I remove this error..?
int keys = {1,2,3,A,4,5,6,B,7,8,9,C,*,0,#,D};

you should use char literals instead of numbers, operators, identifiers and macros.
just place every single list entry in single quotes like this {'1', ...'#', 'D'}

only some of the elements in keys are integers ... you need to rethink what you are doing

If s/he quotes every one that will be OK. A single quoted character can be stored in an int.

"How can I remove this error?" Well, just delete your code from the beginning to the end and this will certainly "remove the error". Done. Now, please, make an effort to ask questions that at least makes some basic sense. Yours currently doesn't make any. Until you tell us what you were trying to do and what is that # doing there, there's no way to answer your question.

There are several -more or less severe- issues in your one line of code
const char keys[] = {'1','2','3','A'
                    ,'4','5','6','B'
                    ,'7','8','9','C'
                    ,'*','0','#','D' };

( Find the differences :) )
Depending on your usage, you eventually even need a 2-dimensional array
const char keys[4][4] =  ...


text:
What is the difference between Nano 328p-au and 328p-mu?
What is the difference between Nano 328p-au and 328p-mu? Does it have to do with the updated bootloader or is it just a different board design? I want to make sure I order the correct one and I could not find a proper answer so far. Thanks.

The only difference is the MCU package. If you're ordering the pre-assembled Nano boards, it makes no practical difference.

The AU and MU on the chip just refer to the shape of the chip. AU is TQFP and MU is VQFN.
You can see the full list of suffixes here (select the red "Buy Now" tab for a table).


text:
What is the right way to query an I2C device from an interrupt service routine?
The ADXL345, for example, requires that interrupts are responded to by querying the INT_SOURCE (interrupt source) register. In example code for the SparkFun ADXL345 Arduino Library, there is code that looks like:
void ADXL_ISR() {
  // getInterruptSource clears all triggered actions after returning value
  // Do not call again until you need to recheck for triggered actions
  byte interrupts = adxl.getInterruptSource();

  // Free Fall Detection
  if(adxl.triggered(interrupts, ADXL345_FREE_FALL)){

However, under the covers adxl.getInterruptSource() is sending an I2C message and receiving a response. This seems to be a bad idea in an interrupt service routine (ISR).
A possible option seems to be to turn on interrupts prior to calling adxl.getInterruptSource(), however there is much advice about not doing this (such as, Nick Gammon's informative post). I've managed to get it to work with something of the form:
void setup() {
  attachInterrupt(digitalPinToInterrupt(INT_PIN), isr, LOW);
  ...
}
void isr() {
  detachInterrupt(digitalPinToInterrupt(INT_PIN));
  interrupts();
  byte interrupts = adxl.getInterruptSource();
  ...
  attachInterrupt(digitalPinToInterrupt(INT_PIN), isr, LOW);
}

This seems to work but I'm worried I'm missing something. Any suggestions?
EDIT: Thanks for the answers that suggest polling, however I am using a MKR1400 and wish to minimise power consumption by putting the processor into a sleep state - only waking up to process the relatively rare "activity" or "free fall" events. As pointed out by @Majenko, a combination of sleeping and polling might be used. So this really just leaves the question of why is the above a bad idea.

I think your solution is allowed, but it is still totally nuts. Other interrupts might be missed because this one takes so long. To use the adxl.getInterruptSource function in a ISR is probably with a SPI interface in mind. Can you use the sensor with SPI mode ?

@Jot thanks for the response. I don't quite get why another interrupt gets missed (but very happy to be educated). It's not possible for us to change to SPI and presumably it should be able to interface with this sort of device using I2C.

For example Timer0 runs at 1ms interrupt for millis, or when there is serial input with 115200 baud. I think something will go wrong with everything together.

@Jot this would be true if I didn't re-enable interrupts in the second line of the ISR. As it is, interrupts are only disabled during the call to detachInterrupt.

Just because a pin is called "interrupt" doesn't mean that you have to read it using an interrupt input.  The INTx pins of the ADXL345 are simple "level" outputs.  All the time there is an "interrupt" pending (a signal from the ADXL345 that something has happened) the corresponding INT pin is held LOW.  It remains LOW until the interrupt has been handled by your code.
It's not something that is very brief - it's something that persists as long as you need it to.
You can just read the INTx pins with normal digitalRead() from within your loop() function (polling). Unless you really need to respond right now to an event on the ADXL345 there is no need to use an interrupt input.

Although this is true - this doesn't help when you have a low power application. Polling would mean that the main processor is constantly on whereas if I drive from an interrupt, the main processor can be in a low power "sleep" state.

You can still poll and sleep. The two aren't mutually exclusive. Poll an interrupt pin.

OK - it's a bit cumbersome as it means that you need to make sure that you wake up often enough to service the interrupts. Can you help me understand, though, the reason why there is a problem with detaching the interrupt handler, turning on interrupts and then proceeding from there?

What is cumbersome? Wake on the interrupt pin, then sample in your loop. Or set a flag in the interrupt routine and use that to decide whether or not to sample.

ISRs should be short. Nothing else happens while the ISR is running. Things that use interrupts cannot be used inside an ISR. It's best to do as little as possible in an ISR.

The cumbersome part is that the polling time needs to be the shortest time that would ordinarily occur between interrupts to make sure that you don't miss any. This might not be easily discernible. In my case, it's possibly around 10ms, which means that I will still have quite a significant duty cycle. Although, I agree with your general principles - they are just that.

The time taken to poll is negligible compared to the time taken to perform the I2C operations. If you are sleeping and you are woken by the interrupt pin going low, you can just immediately go into a while loop processing any pending events until the interrupt pin goes high. Where's the cumbersome component there? The fact that you have woken up is your "interrupt" to start processing whatever events are available.  Note: I use "events" to indicate things the ADXL wants to tell you about, and "interrupt" for the ISR being triggered to differentiate the two.

If I understand you correctly, you are saying: have an ISR that just detaches the interrupt; in the main loop, sleep_until_interrupt(); when woken check if pin is low and if so, respond to I2C and reattach interrupt. Thank you! Do you want to update your answer?

Majenko's answer is useful — you can simply forego the use of interrupts for this and poll the pin directly in your main loop. Especially on AVR where the external pins are exposed as registers which can be read as fast as main memory this is a reasonable approach. But what if you really want the code to be "interrupt-fast" without writing code that might deadlock an ISR handler? Given the case of a fall or impact sensor, latency might be a genuine issue. Well, there are some things you can do.
First, structure your code so that you never go too long without polling the pin. That means that every bit of code needs to either return to the main loop within an acceptably short period of time, or else needs to take on the job of periodically polling the pin itself. Large compute tasks should have polls sprinkled into them, or be broken into subtasks that can be run by a state machine in the main loop. Long delays should be rewritten in the form
start = micros();
while (micros() - start < howLong) {
  // poll the ADXL interrupt
}

or, again, avoided entirely by queuing up work for the main loop to run later, instead of calling delay.
Second, consider using direct port access for the polling. A check like if (PORTB & (1<<3)) compiles down to a bare couple of instructions, and costs 2 cycles if the interrupt isn't actually asserted (which will be the usual case). Doing if (digitalRead(port)) does a call to a function which takes around 25 times as long. It's still only a few microseconds, but if you've taken the advice of the previous step to poll as frequently as possible to minimize latency, then you don't want all of those microseconds to add up and impact the performance of other code.
Lastly, a technique that doesn't make a lot of sense for this scenario, but could be applicable if you were running on a system other than an AVR-based Arduino, or if you wanted to react to some interrupt other than a level-triggered pin interrupt: you have an ISR that doesn't do any real work, but instead sets a global volatile variable to true and then immediately returns. Then in your main code, instead of polling the port directly, you check the value of that variable. If it's true, you set it to false and then run your "interrupt handler" code. The handler runs shortly after the interrupt triggers, but it's run in an interrupts-on context where it's safe to do slower operations or operations that require timer interrupts to work. This is equivalent to the old Linux concept of "bottom halves".

Nice thorough answer. (Voted) I would suggest adding an imperative "Whatever you do, don't try to read a serial port from an ISR" however.

Thanks for the detailed answer. It might also help if you can describe the failure mode of the code in the question (i.e., why will it fail?). Your second part helped me most.

"What is the right way to query an I2C device from an interrupt service routine?"
The right way is to NOT query an I2C device from in ISR. Interrupt service routines should be very fast to execute. (people advise going as far as avoiding digitalWrite() and digitalRead() function calls and using port registers directly, since those functions are a little slow. Anything done on a serial line is, by definition, not fast. It takes multiple milliseconds to read or write a few characters from a serial port, which is an eternity.)
When the Arduino services an interrupt it stops doing everything else, including handling other interrupts. Your timers will stall, other sensor data will be missed, any other serial communications that are in progress when the interrupt triggers will get errors, etc.
JUST DON'T DO IT.

I am not sure you understood my code - I enable interrupts just after calling detachInterrupt. The period of time when interrupts are disabled won't be very long.