What is the name of a peripheral which reads servo output data physically?

What you need is an absolute rotary encoder.

It will provide feedback about the absolute rotational position of the servo shaft.

An encoder that uses gray code is preferred because only one binary bit changes between adjacent positions.


The board has a voltage regulator which converts 9-12V to the 5V that the chip uses.

Why does it need 9V if the board works at 5V? Well, it doesn't need 9 exactly, but it needs something greater than 5. The reason for this is that the regulator has whats called a dropout voltage.

Looking at the schematic of the Uno we see it uses a NCP1117, which has a dropout of 1.2V. So the minimum voltage you can give it to get 5V is 6.2.

The 9V pin is the Vin pin which is at the same level as the input voltage (before converting).


how do I power my motor shield without an arduino uno?

Welcome!

I'm not sure I understand what you are asking because what you are trying to do doesn't make much sense.

The motors connected to the motor shield are controlled by the output pins of the Arduino that the motor shield is plugged in to.

You could run jumper leads from an separate Arduino into your unplugged motor shield, but that's just extending what you already have.  You really do need some form of controller, not necessary a microprocessor, otherwise how can you go forwards and backwards?

Is the problem you have put the Arduino into a plastic case and you can't plug the motor shield in any more?  If so get a set of long male to female connectors (they look like the Arduino connectors) and use them as extensions.

Is the problem you have a different format of board and can't plug it in? If so use the wires method to form the correct connections.

I hope that answers your question, if not please try and explain what I'm misunderstanding.


Most of the time this isn't a problem, because code normally runs pretty fast. The problem, most of the time, is the use of delays. What I did was use my own delay function that checks if the expression has changed, and if so, immediately returns.

Below is my code. I had to modify it a bit, so it might not work out of the box, but will give you the idea as to how.

volatile byte expression;
volatile boolean expressionChanged = false;

switch(expression) {

   case constant-expression_1  :
      statement(s);
      myDelay(1000);
      statement(s);
      break; /* optional */

   case constant-expression_2  :
      statement(s);
      myDelay(500);
      statement(s);
      break; /* optional */

   /* you can have any number of case statements */
   default : /* Optional */
      statement(s);
}

void myDelay(int ms)
{
    uint32_t start = micros();
    while (ms > 0 && !expressionChanged)
    {
        //yield();not implemented in arduino
        if ( (micros() - start) >= 1000)
        {
            ms--;
            start += 1000;
        }
    }
}

void ISR(void){
   expression = constant-expression_2;
   expressionChanged = true;
}


What you are asking really makes no sense at all.

You are starting from the mid-point of your project and wondering how to communicate using bare GPIOs without really knowing what it is you want to communicate and what you want to do with that data - or at least you haven't made any of that clear to us.

It is unclear what you want to do with the shield from the Pi. Do you want to control the relays on it by sending instructions from the Pi? Do you want the Pi to send and receive data through the XBee? Either way the Arduino is pretty redundant in the system and in fact gets in the way more than is useful.

If it's just relays you want then it would be far simpler to wire cheap relay modules direct to the GPIOs of the Pi - then you don't have to worry about "how to communicate" - you just turn the relays on and off.

If you want to communicate with the XBee there are far simpler shields available that will plug directly into a Pi. Indeed, there are some good shields around for the Pi ("Hats" I think they call them) which give you an Arduino footprint and an XBee socket together.

The Arduino is completely pointless in this system. And anyway, if you wanted to make the two systems communicate there are far easier ways than with bare GPIO pins. Serial, for a start. The simplest ever method is to just plug the Arduino into the Pi's USB. That way it gets power and data all in one go. Just like using it with a computer.


How to start a dendrometry dimension build (Dimensions of Trees) for research?

The measuring principle, that is describe in that link, is quite cool and simple.

The string is wrapped around the tree. One end is connected to a fixed point (here the casing of the sensor). The other end is connected to a spring, which in turn is again connected to a fixed point. As the tree get's bigger, it will pull at the string. At the first side of the string nothing happens (because it is a fixed point). But the end with the spring will move according to the force of the tree. Force and displacement have a linear relationship for a spring (as long as you don't overload it): F = k*x with the force F, the spring constant k and the displacement x.

The displacement of the springs end can be measured with a linear potentiometer. That is just a simple strip of resistive material with a glider, which can be set to any position at the strip. It will create a voltage divider, giving you an analog voltage depending on the position (most potentiometers are linear, but there are also others). Connect both ends of the potentiometer to Vcc (supply voltage) and ground respectively and the glider to an analog pin of the Arduino. Then you can measure the voltage with analogRead().

As jsotola mentioned in his comment: Be sure to use a string, that will not stretch too much, as this will make your measurement less precise.


Save a fingerprint to the database of the fingerprint sensor

The sizeof() operator doesn't do what you think it does. It's not a function that is executed at runtime, it's an operator that is interpreted at compile time.

It takes a variable and returns the size (in bytes) of that variable. Since you are passing it a pointer it gives you the size of that pointer. That's 2 bytes on an 8-bit system like the Uno.

In C an array is not a single entity with a size. It's a pointer to a block of memory that has been reserved at the time the array is declared. All you get is that pointer, and it's up to your program to remember the size.

You will have to pass the size of the arrays your packet_1 and packet_2 pointers are pointing to, or always assume that those arrays are the same size at all times.


Problem assign float to an embed class within the Linked-list libary

One possible error is a memory leak as you did not allocate the memory to the class
Try

CsC *c=new CsC();


Prevent Arduino Mega from setting all Outputs to HIGH on Reset

The ATmega2560 itself comes out of reset with all pins in high-Z (DDRx=0, PORTx=0). Your observations are likely due to the bootloader. Check the bootloader source to verify that it is responsible for this.


I do not use Gentoo, but I can tell you how things work on Ubuntu 14.04,
which also installs Arduino 1.0.5. I assume Gentoo should not be that
different... The dependency tree is like this:

The package named "arduino", version 1.0.5, contains the IDE. It
depends on Java and on arduino-core.
arduino-core, version 1.0.5 also, has the Arduino core libraries. It
depends on gcc-avr, avrdude and avr-libc.
gcc-avr comes as version 4.8, avr-libc is version 1.8.0.

When you compile a program for an Uno, on the link stage avr-g++ gets
called, and it is asked to link your object files with libcore.a (the
Arduino core) and -lm (the math library). avr-g++ in turn calls the
linker (collect2) and asks it to link together
/usr/lib/avr/lib/avr5/crtm328p.o (the C runtime), your object files,
libcore.a, -lgcc (the GCC support libraries), -lm and -lc (avr-libc).
Notice that there is no crtatmega328p.o, it's called crtm328p.o instead.
And there is no -latmega328p.

For diagnosing your problem, you can set an IDE preference so that it
shows you the exact command lines it runs for compiling your program.
You can then copy and paste the last command (link stage) on a terminal.
If you add the -v option (meaning “verbose”), you will see what gcc is
asking the linker to put together.

You may be able to fix your problem with a simple symlink from
crtm328p.o to crtm328p.o. If you are using vanilla Gentoo packages, you
should then file a bug to the packager. On Ubuntu, you type
sudo apt-get install arduino and it just works.


Convert a Serial string to a sketch command on Yun?

There is a third option: install an interpreter on the Arduino, then
just send it the program you want it to run. There are a few such
interpreters available. A quick search showed:

Bitlash, a C-like language
iArduino, another
C-like language
FlashForth, a
Forth
implementation
FINF Is Not Forth, a Forth-like
language

There are probably many others.

The difference between this option and Majenko's option 2 is that this
would allow you to send a complete program, with functions,
conditionals, loops, etc., whereas with a Firmata or similar approach
you would keep the program logic (functions, loops, conditionals) on the
host computer, and only send simple commands to the Arduino.


What are the implications of running an ATmega328P at 8 MHz and 3.3 V with the Arduino system?

The formula seems to be volt*5.9-6.6=mhz (valid between 1.8v and 4.5v), so at 3.3v, this would give 12.8mhz. Be aware that, if you are running at 12.8mhz, ANY drop below 3.3v MAY cause problems (and very hard to diagnose, too!) or you MAY get away with it.

However, Arduino Atmega328p chips have a "brown-out" detection set at 4.3v - any drop below that, the chip shuts down. You can get an ISP (AKA ICSP) to change the fuses - go to http://www.engbedded.com/fusecalc/ to work out what to set fuses to. You can also use the ISP to read the current fuses, or indeed reprogram the chip without an Arduino board - all my projects have a 6-pin header. If you do this, before reprogramming using the Arduino board, you will have to "Burn Bootloader" (in the tools menu). Note that programming can still be done via Arduino IDE.

Alternatively, if you want to go "light" (and have an ISP), you can change the fuses to use the internal 8mhz clock - this frees up 2 extra pins, too! Be aware, however, that the internal clock may drift 1.2 hours per day (=5%), compared to 1.7 seconds per day (=20 parts per million) on a typical quartz crystal. If you don't use it for timekeeping, this probably doesn't matter.

You will need to make changes to the timing, for your code - you need to add a boards.txt with correct settings for your chip/clockspeed etc - you can copy the settings from the entry for the board, change the name, and change the setting "build.f_cpu"; restart (or start) your Arduino IDE, go to "Tools->Board" and select the board you added.

You can move the chip on/off the board, and reprogram it there (note that the board selected in Tools->Board is the FINAL board, not the programming board). Be careful plugging/unplugging it - eventually, you WILL bend the pins! Alternatively, you can use ISP (ICSP), as mentioned above - much recommended. ISP programming will also work if the chip is factory default, so long as it has a working clock.

How much power is used by the chip depends hugely on what you do with it - not just clock speeds, clock source, etc but also sleep modes. If you are sleeping a lot, it may draw less when running faster than running slower - if almost all your time is asleep, then the power consumption should be counted per clock cycle, not per second - if your clock is half the speed, and half current, then you draw the same current per instruction. Since the rest of your time is spent asleep, you get no benefit. See http://www.gammon.com.au/power for a very good breakdown of power usage, tips on how to save power, etc.

If you slow your clock down too much, serial and i2c may become unreliable (unless you slow down the speed), but I would expect to be able to go down to  1mhz before this to be a problem - a 1mhz chip trying to do 9600bps has 104 instructions per bit of data transferred. i2c runs at 100khz, so you get 10 instructions per bit (at 1mhz) - possibly pushing it. 8mhz should be fine. Test, test, test.

UPDATE:
There are 3 possible settings for the brown-out detection - there are 3 possible values for the AtMega328p: disabled, 1.8v, 2.7v, and 4.3v. I was under the impression (above) that Arduinos were normally set to 4.3v; apparently that is not the case (see comment below). I recall seeing somewhere that there was brownout detection. This is something to keep in mind, if your arduino resets, especially when putting larger loads on the battery (running motors, multiple leds etc).


How to connect an Output to a Pullup Input of another arduino

Connecting any signal that is within the voltage range of the receiving Arduino is safe. So if you use Arduino UNOs or similar with a 5V operating level, you can connect any signal between 0 and 5V to an input. It does not matter whether the input is in pull-up-mode or not. So connecting an output to an input of another Arduino (or even of the same Arduino) is safe. In addition to the signal values, you do need to connect the ground of both Arduinos.
The only thing you must not do is connect two outputs together (because if one of them is high and the other is low, you have a shortcut that will potentially fry one or both of the boards). And you would need to be careful if you used different types of Arduinos, like a Uno and a Due, because they run at different voltage levels.


Powering Motor doesnt work from Digital Pin, but works on 5V power

Power is made up of two values, not one. Besides the voltage there is the current (P=VI), and it's the current you are lacking.

A motor needs a large amount of current to start turning (called the stall current) and a digital I/O pin can only supply a relatively small amount (absolute maximum 40mA, recommended maximum 25mA). The power pins though can supply many hundreds of mA.

You should never try and power a motor directly from an I/O pin since you risk damaging the I/O pin.  Instead you should use the I/O pin to control an NPN transistor or N-channel FET, which is then used to switch the power (actually the ground connection) to the motor from one of the power pins.

Here is a good tutorial: http://www.circuitstoday.com/pwm-generation-and-control-using-arduino


How can I get Serial.print to print a variable thats a char?

To make your code work, you must use character array pointers. A "char" holds only one character, while "char*" can point to a string.

char foo = 'a';
char *bar = "string with lots of stuff.";

So the full code to implement your example is:

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

void dataprint(char *parameterName, float dataNum, char *unitName)
{
  Serial.print(parameterName);
  Serial.print(",");
  Serial.print(dataNum);
  Serial.print(",");
  Serial.println(unitName);
}

void loop() {
  char *temp = "temperature";
  float t = 123.4;
  char *unit = "C";
  dataprint(temp,t,unit);

  while(1)
  {
    //do nothing
  }
}

Which prints the following to the serial port:

temperature,123.40,C


It sounds like you are trying to make a digital to analog converter driving some type of load.  Look at this link: http://emesystems.com/BS2PWM.htm
It will give you a start. Please note they use an opamp as a buffer.

This 'buffer' has a very high input impedance and a low output impedance.  It can drive from a few mills to over an amp depending on the opamp chosen.  Additional circuitry can get you into thousands of amps if desired.  The schematic is a 2 pole filter originally designed for the Stamp microcontroller.

The filter soothes it out but adds a delay on the final output value (settling time).  The greater the filter capactance the lower the ripple and the slower the response.  You can add another pole to filter if you want.

As a bit of information from an old semiconductor guy absolute ratings are just that.  If you exceed them even for a few nanoseconds you can be sure you damaged the device, you just do not know when it will fail.

I have seen a lot of microcontrollers damaged because of capacitors connected to the pins, power excluded, doesn't matter if the pin is input or output.  When the power supply collapses it will inject current into the microprocessor substrate possibly damaging it.

Good Luck


Controlling LED and Button with single pin

I think this is what you want...

simulate this circuit – Schematic created using CircuitLab

To check for button, set pin to INPUT and enable pullup. If pin is LOW, then the button is pushed.

To light LED, set pin to OUTPUT and LOW.


Your 1st pixel should go indigo & stay there, & the other 2 very briefly show Aqua before going back to Indigo. Try a longer delay than 0 at the end, and then clear them down for the next loop.


Particle Electron to RS232 Serial gibberish

If the OP has correctly stated that only three connections to the MAX3232 have been made, power to the device is missing.
Code tested with an RS232 transmitting device (Maxbotix 7092) with Sparkfun MAX3232 breakout and Particle Photon. Serial monitor correctly displays continuous range reading.


How to transmit Float sensor values via NRF24L01 module?

Simple float transmission:
For TX use
float payload = 0.12345;
radio.write(&payload, sizeof(payload));

For RX use
float payload = 0;
radio.read(&payload, sizeof(payload));


Photo by John Boxall

Which pins do they use?

To determine if two shields are compatible, you have to read the specifications of both shields.

The best source for this information is the data sheets supplied with the shields. However there is also this Shield List

Can you reassign pins?

Some shields provide a means to alter which pins are used for communications. This can take the form of a switch or a jumper - either pull-off or solder-bridge type. (the GPS shield in the question has jumpers).

Where the shields do not support pin-reassignment or provides insufficient flexibility, to work-around incompatibilities you can use an in-between shield designed for the purpose.

here is one example:

  You hear it all the time in the Arduino community, “will this shield work with my other shield?.” I think we’ve all been disappointed to find that two of our favorite shields compete for control of a digital pin here or a serial pin there. While there are sometimes some clever workarounds from elegant code modifications to aggressive ‘greenwiring,’ Mayhew Labs may have come up with the simplest solution thus far: The Go-Between Shield.

Are any alternatives for the foo shield

I notice that Arduino.cc now point people to the list referenced above. They used to have their own list.

Product recommendations are off-topic here but, obviously, you can search


Ultrasonic sensor underwater calibration

If I understand your question correctly, your problem is probably that the working range of the AJ-SR04M sensor is 20cm - 500cm.

The sensor uses the same transducer to create the sound pulse and to listen for the echo.  It needs time to switch from one mode to the other, which explains why your sensor can't measure distances of less than 20cm.

The speed-of-sound in water is about 5x the speed of sound in air.  More specifically, at 20 degrees Celsius the speed-of-sound in air is approximately 343 meters per second, while the speed-of-sound in water is approximately 1482 meters per second.

This will cause the sensor to 'under-report' the distance in water.  The minimum distance will also be approximately 5x the minimum distance in air.

As an aside, you will also need to make allowance for the differences in the characteristic impedance and absorption between sound and water.

It's worth reading the paper Underwater Sound by P. Vigoureux (Proceedings of the Royal Society of London. Series B, Biological Sciences, Vol. 152, No. 946) for a discussion of all the factors involved.


Difference between FreeRTOS libary (AVR_ATmega328PB_Xplained_mini_GCC) Versus FreeRTOS compatible for Arduino boards from Richard barrey

ATmega328PB is not the same MCU as used by Arduino boards. Those use ATmega328P (no B). ATmega328PB is a mostly compatible successor and offers more timers, built-in touch functionality and more but does not come in large DIP packages. Arduino uses the older ATmega328P.


Arduino Uno + Adafruit Ultimate GPS Shield Serial issue

It looks like you are using the wrong baud rate somewhere.

You mentioned that you had checked your baud rates but check again because the second terminal window looked as if the baud rate was wrong.

In your terminal window. Go to bottom right hand corner where it says 9600 and change it to match the serial speed set in your arduino code.

Or it could be that you are receiving too much data as per the bottom of this article:  https://learn.adafruit.com/adafruit-ultimate-gps-logger-shield/soft-serial-connect


How to wire a hall effect sensor to arduino?

The UGN3503 that you use gives out a analog voltage that changes when there's a magnetic field present. So this sensor needs to be connected to an analog pin.

If there is no field present the voltage is around 2.5Volt. If the south pole of a magnetic field is present the voltage will be higher that 2.5V. With a north pole the voltage will be lower that this 2.5Volt. The amount of higher/lower voltage is based on the strength of the field.

A capacitor near the sensor could help reduce, so called, noise. Though 100µF is too high. I think you mean 100nF (0.1µF).

The pull-up is for other types of hall-effect sensors. Some of these sensors just give a HIGH of LOW output, based on whether a magnetic field is present. Those you connect to a normal input pin.


Use Arduino's PWM to control motor direction?

You seem to have misunderstood PWM here. It's actually a digital signal which is constantly pulsing on and off very quickly (several hundred times per second). You don't actually change the output voltage at all -- it's only ever HIGH or LOW (+5v or +0v). The thing you change is how long the signal is HIGH for on each pulse.

This page gives a deeper explanation: http://arduino.cc/en/Tutorial/PWM

When you're controlling a DC motor, this approach is actually better than varying the voltage. The constant pulses still make the motor turn at an adjustable speed, but without losing torque. PWM is also useful for controlling the brightness of LEDs, which don't respond so well to changes in current/voltage.

To address your original motor control question, there's no sensible way to change the motor's direction using the PWM value. You will need some additional circuitry which is able to reverse the polarity of the connections to the motor (meaning your PWM value just controls speed, and doesn't care about direction).

An H-bridge is the usual approach for this. Here's a fairly good tutorial which covers the basic principles: http://www.instructables.com/id/H-Bridge-on-a-Breadboard

Obviously you'd need to modify it for use with your Arduino project. The push switches could easily be replaced by digital signals from a couple of Arduino pins. The motor's power supply would be controlled by the PWM signal. You'll need an extra transistor for that, because you can't safely power the motor directly from an Arduino pin.


Arduino Fried? Power is being delivered to Arduino but COM not found

If you were powering from 12V and shorted the 5V to GND then yes, it is all dead. The regulator will have stopped regulating. 12V will have then been sent to every component on the board. The USB chip, the main MCU, the 5V regulator - all will be toast.

You could repair it by replacing almost every component on the board, but when they're so cheap, why would you bother?


How to write http response from HttpClient to Serial monitor with a ESP32 (Wemos Lolin32)?

it is http://arduino.cc/asciilogo.txt. without www. www is redirected to https. you can verify it from a browser


Try this code: first delay produces 1ms pulse on pin D5. Without this delay the pulse could be too short for the nano to catch it (you can use delayUs and try finding the shortest interval that produces reliable result). We know that after this pulse, nano sends some data. So wait 100ms to collect it. If you call readSerial right after the pulse was sent, you won't get anything, because you need to wait at least for single byte transmission

void loop() {
    digitalWrite(D5, HIGH);
    delay(1);
    digitalWrite(D5, LOW);

    delay(100);
    readSerial();

    delay(1000);
}


Why does Arduino IDE recommend storing 0-255 numbers in "byte" instead of "char"?

Is byte datatype a solely Arduino construct?

Yes. Much of the Arduino "language" is "bent" to look like Java, since it originated from Processing, which is Java. So we have data types the "look like" Java ones, including "byte" for "unsigned char" and "boolean" for "bool".

  If so, why is it recommended over char?

Personally I don't ever recommend using it, since it's non-standard. Instead you should use uint8_t which is essentially the same thing, but portable.

It is recommended to use "hard signedness" data types for portability.  The problem with char is that whether it is signed or not is entirely down to the compiler implementation. Some systems have it as signed, some as unsigned. By using byte (or better, uint8_t) you are always going to get an unsigned 8-bit value.

For just storing of binary data it doesn't really make any difference, but when it comes to doing mathematics with the stored data you may find you suddenly have negative values when you don't want negative values (a char might be storing your number as -128 to +127, not 0 to 255).


The sample rate will be somewhat inconsistent since the first few samples' print output will go into the print buffer with little delay. Once the buffer fills, subsequent samples' time spent in Serial.print() will vary somewhat depending on how long printing the currently printing character takes to finish, when Serial.print() is called. But the average sample rate will settle to about to about 64 Hz (1 sec / (15/960 lines/sec).

The printing time for one line is about 15.6 msec, much longer (140 times) than analogRead() takes, about 0.111 msec, according to this author's measurements.

Update:

  So I could just use 50ms + 15.6 for the sampling rate, ignoring
  analogRead?

That would get you pretty close to the average sampling interval. If consistency is important to you, you'd need to measure that.

How many samples do you need at a time? Another way is to store the data in an array and print it later. Then the jitter in the sampling interval will be much smaller. You'd be limited to the number of samples you could fit in memory, though. Each 10-bit sample would need 2 bytes of storage.

If the range of your data is less than 256, you could subtract from each sample, the lowest value you expect to see; the difference will fit in 1 byte, doubling your storage capability. Don't forget to add back that lowest value to each one when you print them, though.

It would also be a good idea to test each sample against that lowest number and the lowest + 255, and if any sample is outside those limits, store the low or high limit value instead. Then when you plot your data,
you'll see it "clipping" and know that it exceeded your bounds. Otherwise you'll get overflows in the arithmetic and the out-of-bounds numbers will appear to suddenly take on high values when they really are low, and vice versa.


If you can find another way of calculating the BMP during displaying an effect on the strip depends highly on your BMP sensor. If you can do the measurement with interrupts, it should work. In this case you should make sure, that the interrupt cannot be fired during the execution of the Adafruit_NeoPixel.show() function, since it is quite timing sensitive.

But since I recently worked on a project with a NeoPixel LED strip, I have already edited functions from the strandtest example for use with the millis() function. So you will not have to reinvent the wheel again :D I will try to strip away my custom code, so that you can easily use it.

float brightness = 1.0;
uint32_t strip_state=0;

uint32_t Wheel(Adafruit_NeoPixel *strip, byte WheelPos) {
  WheelPos = 255 - WheelPos;
  if(WheelPos < 85) {
    return strip->Color((255 - WheelPos * 3)*brightness, 0, WheelPos * 3*brightness);
  }
  if(WheelPos < 170) {
    WheelPos -= 85;
    return strip->Color(0, WheelPos * 3 * brightness, (255 - WheelPos * 3)*brightness);
  }
  WheelPos -= 170;
  return strip->Color(WheelPos * 3 * brightness, (255 - WheelPos * 3)*brightness, 0);
}

void fill_color(uint32_t color){
  byte r= ((color & 0xFF0000) >> 16) * brightness;
  byte g= ((color & 0xFF00) >> 8) *brightness;
  byte b= (color & 0xFF) * brightness;
  color = strip.Color(r,g,b);
  for(unsigned int i=0; i < strip.numPixels(); i++) {
    strip.setPixelColor(i, color);
  }
  strip.show();
}

void fade_color(){
  for(unsigned int i=0;i<strip.numPixels();i++){
    strip.setPixelColor(i,Wheel(&strip,strip_state));
  }
  strip.show();
  strip_state++;
  if(strip_state>255) strip_state = 0;
}

void moving_rainbow(){
  for(unsigned int i=0; i<strip.numPixels(); i++) {
    strip.setPixelColor(i, Wheel(&strip,((i * 256 / strip.numPixels()) + strip_state) & 255));
  }
  strip.show();
  strip_state++;
}

void colorWipe(uint32_t color) {
  byte r= ((color & 0xFF0000) >> 16) * brightness;
  byte g= ((color & 0xFF00) >> 8) *brightness;
  byte b= (color & 0xFF) * brightness;
  color = strip.Color(r,g,b);

  strip.setPixelColor(strip_state, color);
  strip.show();
  strip_state++;
}

//Theatre-style crawling lights.
void theaterChase(uint32_t c) {
  byte r= ((c & 0xFF0000) >> 16) * brightness;
  byte g= ((c & 0xFF00) >> 8) *brightness;
  byte b= (c & 0xFF) * brightness;
  c = strip.Color(r,g,b);
  for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
    strip.setPixelColor(i + strip_state % 3, c);    //turn every third pixel on
    strip.setPixelColor(i + (strip_state +1) % 3, 0); // turn others off
    strip.setPixelColor(i + (strip_state +2) % 3, 0);
  }
  strip.show();
  strip_state++;
}

//Theatre-style crawling lights with rainbow effect
void theaterChaseRainbow() {
  for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
    strip.setPixelColor(i + strip_state % 3, Wheel(&strip, (i+strip_state) % 255));    //turn every third pixel on
    strip.setPixelColor(i + (strip_state +1) % 3, 0); // turn others off
    strip.setPixelColor(i + (strip_state +2) % 3, 0);
  }
  strip.show();
  strip_state++;
}

The functions use the float variable brigthness to modulate the overall brightness of all LEDs. You can set it to every value between 0.0 and 1.0.

The variable strip_state holds the current state of the effect on the strip. It is incremented everytime one of the functions is executed. Reset it to 0 if you want to restart an effect.

You yourself have to declare the variable strip as from the type Adafruit_NeoPixel.

So now you only have to call these function from the typical millis() code (like from the BlinkWithoutDelay example) in an interval, that you chose.


Using AysncUDPMessage for ESP32 to send string data

Use udp.print(row.postString().c_str())

AsyncUDPMessage in AsyncUDP library is only a buffer. It is used only in AsyncUDP send function:

size_t AsyncUDPPacket::send(AsyncUDPMessage &message)
{
    return write(message.data(), message.length());
}


Several solutions:

Are your SPI components 5V or 3.3V parts? The ESP8266 is 3.3V only, and is NOT 5V-tolerant; you may have already fried it.
In most cases that I've had problems with SPI with the ESP8266 (in particular, the Adafruit 8266-12E HUZZAH board), they went away when I drastically lowered the SPI speed to 8000000.
Once you've programmed the 8266, and assuming you don't use Serial for debugging output, it's free to use to communicate with the world. Again, be careful about signal levels -- the 8266 is NOT 5V-tolerant, and most arduinos have 5V signals. So either use a 3.3V arduino-like part (my favorite is the Teensy 3.2 for larger projects, and the Adafruit Trinket for smaller ones), or use a level converter. If you need debugging output, you can still use Serial1 for output only (and don't forget to change its bit rate -- by default it's something crazy like 74380bps).
Run the 8266 as another SPI slave and have the Arduino write to it. Or come up with your own serial protocol! Again, careful about signal levels.
You can use a different version of the 8266 (or another wifi chip), one that's already meant to be used with the Arduino. Sparkfun and Adafruit have several, as do a lot of other vendors.

I'd still suggest that you try to work out the SPI problems and stick to the 8266.

Also, don't forget that neither serial nor SPI guarantees data integrity. Always use a CRC to make sure your data were transferred correctly, and have some provision for retransmissions if you can't afford to just ignore corrupted data.

/ji


USB and UART simultaneous power to Arduino?

That's perfectly fine.  As it's the same 5V source the voltage should be the same and it'll just combine them together as if you had 2 wires in parallel.  However, if there are things like diodes in the path of one connection that causes the voltage to be slightly lower then the increased voltage imposed on the lower voltage side would reverse bias those diodes and end up cutting off that one source, so only one would be used.

So no, it's nothing to concern yourself over.


SPI Digital Potentiometer not working on ESP32

I managed to get it to work in a strange way. I opened the example included in the ESP32 SPI Library and copied some points from there.

I first initialise a pointer to the SPI class, then I call begin() at that pointer and inside the digitalPotWrite function I call beginTransaction(10000,MSBFIRST,SPI_MODE0) and end the transaction before digitalPotWrite finishes. Full code here:

#include <SPI.h>

static const int spiClk = 1000000;
byte address = 0x00;
SPIClass * hspi = NULL;

void setup()
{
  pinMode(15, OUTPUT);
  hspi = new SPIClass(HSPI);
  hspi->begin();
}

void loop()
{
  for (int i = 0; i <= 128; i++)
  {
    digitalPotWrite(i);
    delay(10);
  }
  delay(500);
  for (int i = 128; i >= 0; i--)
  {
    digitalPotWrite(i);
    delay(10);
  }
}

int digitalPotWrite(int value)
{
  hspi->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
  digitalWrite(15, LOW);
  hspi->transfer(address);
  hspi->transfer(value);
  digitalWrite(15, HIGH);
  hspi->endTransaction();
}


This is widely happen problem - serial communication with SIM800L stopped working.
You can do reset, but in my case it didn't help: on powered SIM800L module shortcut "RST" pin with the ground for half of second - unit should reset and restart. I think it's defective architecture/firmware, but unfortunately SIMCOM dropped support for this model, so best advise is to avoid SIMCOM until they study how to make quality products.


Which library to use for 23LC1024 SRAM 1 Mbit

SPI RAM has two modes of operation: single byte and "page mode".

In single-byte mode you first send the read or write command followed by the (typically 3-byte) address and then read a byte. That's 5 bytes per transaction, or 40 SPI clock cycles. At the maximum of 8MHz (SPI_CLOCK_DIV2 on a 16MHz MCU) that would be at absolute best (1/8000000*40) 5µS per byte read or written. That's not including the time taken to toggle the CS pin and perform the other software-level parts of controlling the SPI peripheral.

In page mode it is possible to send one start address and then read or write sequential data from that address upwards. Ideal if you need to read a larger number of bytes that are sequentially in memory. For instance, to read 100 bytes sequentially it would take 104 SPI bytes - one for the read/write command, three for the start address, and 100 for the data. That is 832 SPI clocks, or at 8MHz, 104µS.

As you can see, reading 100 bytes within 10µS is not possible on an Arduino with SPI SRAM. There just isn't enough speed. Even 100 sequential bytes. 100 "small groups of bytes" just ain't gonna happen.

There are other technologies that are faster which may be more suited to your use, but they require different peripherals in the chip (namely SQI), and the chips with that in tend to be more powerful and have more RAM anyway, so your 1Mb of external SRAM would be redundant.


Append Text to Variable Names: Please Help Me Shorten This Code

variableNames[i] = readEE(variableNames[i] + 'Pos');

  Is this possible using C++ / Arduino?

No! Very few programming languages allow that as it requires a lot of run-time information.

Let us instead revisit you issue; Load a large set of variables from EEPROM. What mechanisms do we have in C/C++ and AVR library that could help with this?

Here is a really simple solution that results in a "one-liner"; eeprom_read_block().

struct var_t {
  byte fanSpeed, nl1Toggle, ledsToggle;
};
var_t var;
const void* pos = ...;
eeprom_read_block(&var, pos, sizeof(var));

Obviously var_t and var are not very good names (and you will have to come up with something better) and this is for the internal EEPROM but the same technique can be used for the I2C EEPROM.

Cheers!

BW: What AT24CXXX library are you using? Because this looks strange.

 uint8_t readEE(uint8_t entry) {
   readEEPROM(AT24C32_ADDRESS, 1, entry);
 }

No return statement, etc.


How to measure the supply voltage of Arduino without using an analog pin

Yes, you can do it.

You can measure the voltage of the internal (approximately) 1.1V reference voltage using the ADC and use the results of that to calculate what the reference voltage you used (VCC) must have been to get the results you did.

This is a function I commonly use:

long readVcc() {
  long result;
  // Read 1.1V reference against AVcc
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  delay(2); // Wait for Vref to settle
  ADCSRA |= _BV(ADSC); // Convert
  while (bit_is_set(ADCSRA,ADSC));
  result = ADCL;
  result |= ADCH<<8;
  result = 1125300L / result; // Back-calculate AVcc in mV
  return result;
}

Depending on how close to 1.1V your internal reference voltage is, you may need to adjust the value 1125300L in the code above.  Measure the actual VCC voltage and adjust that value until it results in the same voltage being returned (multiplied by 1000 since that function returns millivolts).

However, as Edgar Bonet mentions, you don't need to care about the supply voltage in your situation, since your thermistor readings are just a ratio that input voltage, whatever it is. Change the input voltage and you will get the same results, since the ADC returns a value between 0 and Vcc in 1024 steps. With different supply voltages you still get 1024 steps.


The IDE package usually ships with the driver(at-least the latest one).
Go to Program Files in C: and find the Arduino folder and you should find a folder named Drivers. Inside you will find an application named dpinst-x86. Run it and you should be good to go!


Setting a number inside a struct causes timer to misbehave

This:

led* redLed;

defines a global variable implicitly initialized to zero (i.e. a NULL
pointer). This is an invalid pointer you are not allowed to use until
you properly initialize it.

Here:

redLed->pin = 3;

you are writing to the memory pointed to by this invalid pointer. This
invokes what the C and C++ standards call undefined behavior. What
that means is that, according to the definition of the C++ language, the
behavior of your program is not defined. In other words, anything can
happen. Typically you get a program crash, but even that behavior is not
guaranteed.

Do not ever access memory through an invalid pointer.


xyz_dv_eprom.ino uses low-level access rather than Arduino calls to manipulate PD7, most likely for speed reasons. Lines 96 through 104 (specifically 96, 97, 100, and 104) need to be modified in order to change both the port and the bit used.

ATmegaXX8 pin mapping
ATmegaXXX0 pin mapping
ATmegaXXU4 pin mapping


avr/sleep.h is part of the compiler. You don't need to download it.

There are other libraries that act as a wrapper to it to make life easier:

https://github.com/lowpowerlab/lowpower
https://github.com/rocketscream/Low-Power


First time arduino attempt. 4 switch inputs controlling 8 LED outputs

Micheal well easy solution is to use arduino nano as its bread board friendly and easy as it comes with the arduino IDE installed, well if size is what you are looking for then digispark attiny 85 can also do the task and its size is almost equal to a coin but for that youll need to install it in the arduino IDE which is a bit difficult.
if you need any help with attiny 85 you can come here


The pin 3 and 11 only refers to boards based on the ATMega328. On these boards timer2 is used by tone, disabling PWM on pins 3 and 11. See Majenko answer about timers.

The Micro (ATMega32u4) tone uses timer 3, which is connected to pin 5 only.

So on the Micro, just don't use pin 5 for PWM when using tone.

Secondly don't trust everything on the arduino.cc website. There quite a bit of misinformation on there.


It is likely that the alarm clock does not provide any voltage level (I mean GND) to the  buzzer when it does not have to ring, the circuit is just left "open" then; it will provide a voltage level (depending on your clock power supply) only when the alarm has to ring.

On the other side, your Arduino pin 8 must have a voltage level that can be mapped to a 0 (anything between GND and 5V/3) or a 1 (anything between 2x5V/3 and 5V).

However, in the absence of alarm, the input is left "dangling" (no voltage level at all). In CMOS technology, leaving an input pin dangling will make it randomly take 0 and 1 levels as you described.

Fortunately, the solution to this problem should be easy: you just have to force a 0 level to pin 8, by connecting it to GND through a resistor. I generally use 10K or 15K for that resistor. This is called a "pulldown" resistor:

when the alarm does not provide any voltage, the input pin level will be "pulled down" to GND, ie 0.
when the alarm provides a 5V (see important remark below) to the input pin, then it will be seen as 1.

IMPORTANT: you have to make sure that your alarm clock, when ringing, provides a voltage that is not higher than 5V (it would grill your UNO, or more precisely the ATmega328 of your UNO) and is at least ~3V to be "recognized" as 1.

NOTE: it is likely that solving this first issue will not be enough to make your complete program work, because your alarm clock probably does not send a continuous voltage to your buzzer but and alternate one to make it ring, hence you will get successive 1 and 0 at high speed (between 100Hz and 100Hz I would say) in your program. If that is the case please open another question as the solution for that specific issue is disconnected from the current one (random 1 and 0).


I would suggest a few things:

1) comment on your code -> lay out the basic logic so that you and others can help you debug it;

2) use brackets liberally -> don't rely on memory (=faulty) on the order of operations. instead, define it explicitly;

3) check your logic -> make sure that your code does what you want it to do;

4) pay attention to data type: 8-bit vs. 16-bit, etc.

5) modularize your code -> this allows more efficient debugging and code reusing.

for example, your code can be simply described as

  button_state = read_button(); //read button state, with debouncing
  if (button_state = BUTTON_UP) pwminc_dc(pwm_dc); //increase duty cycle, with boundary checking
  if (button_state = BUTTON_DOWN) pwmdec_dc(pwm_dc); //decrement duty cycle, with boundary checking

with the code modularized, you just need to worry about getting individual pieces right.


Different color LEDs are not the same.  The are made with different impurities.  And some colors (blue) were really hard to figure out.  So much so that the blue LED inventor was awarded the Nobel Prize!

Consequently, it should not be assume all LEDs operate at the same voltage and current.  As such, when driving an LED with a constant voltage source, derive the proper series resistance for each case.

Example 1:

Given a red LED which may have 1.8 volt drop and may need 20mAmps to operate driven by a 5 volt source, we find the proper series resistor to be...

  V = I * R

  5 - 1.8 = 20mA * R

  R = (5 - 1.8) / 0.020

  R = 160 ohms

Example 2:

Given a blue LED which may have a 3.3 volt drop and may need 20mAmps to operate driven by a 5 volt source, we find the proper series resistor to be...

  V = I * R

  5 - 3.3 = 20mA * R

  R = (5 - 3.3) / 0.020

  R = 85 ohms

Your specific LEDs may have different specifications.  The above are only examples.

Go here for more about calculating the proper LED series resistance.

In general, LEDs that are over driven will grow dimmer and not recover.


DHT 11 sensors and i2c LCD to Wemos Wifi not Working

Constant D14 is for Wemos D1 and other esp8266 dev boards mapped in arduino core to esp8266 io pin 4. Pin 4 is used as I2C SDA pin. The LCD uses I2C so pin 4 (D14) can't be used for the sensor.

from pins_arduino.h for Wemos D1 R1:

#define PIN_WIRE_SDA (4)
#define PIN_WIRE_SCL (5)

static const uint8_t D14  = 4;
static const uint8_t D15  = 5;

The origin of this confusing esp8266 io pin to Dx constants mapping is the big Wemos D1. There are esp8266 pins mapped to standard Uno pinout.


Arduino Mega PWM pins stop working for LEDs once servo is attached?

Looks like the mega has some clever servo handling features. Servo control always uses a timer of some sort and can conflict with the pwm timer. The first 12 servos knock out pins 44,45,46 ...

  For Arduino Mega it is a bit more difficult. The timer needed depends on the number of servos. Each timer can handle 12 servos. For the first 12 servos timer 5 will be used (losing PWM on Pin 44,45,46). For 24 Servos timer 5 and 1 will be used (losing PWM on Pin 11,12,44,45,46).. For 36 servos timer 5, 1 and 3 will be used (losing PWM on Pin 2,3,5,11,12,44,45,46).. For 48 servos all 16bit timers 5,1,3 and 4 will be used (losing all PWM pins).


Specified folder/zip file does not contain a valid library

That's because it contains two libraries, and the IDE doesn't know how to handle that.

Because of this repository structure, you will need to do a manual installation.

Extract the zip file manually and copy the libraries folder into your Arduino sketchbook folder. You can find the location of your sketchbook folder in the Arduino IDE at File > Preferences > Sketchbook location.


Can this work as a waterproofing method?

Nail polish would work in general as a fair conformal coating. However, conformal coatings are not generally intended as waterproofing, but moisture or humidity resistance.

If you product is going to be regularly submerged or deluged with water, you are better off using a waterproof enclosure with a good watertight gland around the cable entrance.


How can an Arduino determine the status of a washer or dryer using only vibration data?

I think the simplest option is to experiment first: record the vibration
level as a function of time during one wash cycle, and do that with a
few different washer models. Then look at your data and devise an
algorithm with your eyes on the measured curves. This is really the
only reasonable way to do any kind of signal processing: look at the
signal first. If you still have problems finding an algorithm, you can
come back here and show your data.

Unless you live in a region with huge geologic activity, chances are
that the vibration level of any washing machine will be well above the
background, which should allow you to choose a single vibration
threshold suitable for every model.


that no matter what the inputs are Motor1 always moves

The code isn't wrong, it's far too simple to be at fault.

The error is from within Proteus. Those 'pushbutton' switches (and the other switch simulations) are not quite as straightforward as one would like. They have an OFF resistance, usually 100 Megaohms, but that's enough to trick the simulation into not behaving like it should do. You MUST pull the inputs to ground with a resistor - any sensible value will do as it's only required for the simulation. As they are, they're in some odd floating/magic/unknown state; common sense does not apply here!

An alternative is to swap the pushbutton for a SPDT switch; connect the common to the Arduino and the other contacts to the 7805 output and ground. You won't need the resistor in this case.


Can you charge and use a LiPo battery at the same time?

can I charge the battery while the arduino is still on, but on power savig mode?

You can draw power from a Li-Ion battery whilst charging it, but it isn't recommended. This is because the load on the battery affects the ability to detect the different phases of charging, and determine the end-of-charge condition.

Instead you should provide a bypass facility so that if external power is applied the external power is routed to the Arduino to power it, but when the power is removed the battery provides the power to the Arduino.

The circuit I usually use is:

simulate this circuit – Schematic created using CircuitLab

When 5V is applied the battery charges up. Q1 is held off. The 3.3V regulator is then powered through D1. When the 5V is removed Q1 is turned on by R1 pulling the gate low and the battery powers the 3.3V regulator.


How to logically tell than an UNO is being, or about to be programmed

Your proposed solution is the normal method. A GPIO pin which is an "Activate Device" signal. It's pulled in one direction, the "inactive" direction, and you actively drive it in the other "active" direction in your program.


ICSP stands for In Circuit Serial Programming, which represents one of the several methods available for programming Arduino boards.  Ordinarily, an Arduino bootloader program is used to program an Arduino board, but if the bootloader is missing or damaged, ICSP can be used instead.  ICSP can be used to restore a missing or damaged bootloader.

A typical Arduino ICSP header has six pins, arranged 2x3.  The article Connecting the Programmer:
In-Circuit Serial Programming (ICSP) at Sparkfun describes some of the functions of ICSP pins, which include MISO, MOSI, SCK, V+, Ground, and Reset.

Each ICSP pin usually is cross-connected to another Arduino pin with the same name or function.  For example, MISO on an Uno or Nano's ICSP header is connected to MISO / digital pin 12; MOSI on the ISCP header is connected to MOSI / digital pin 11; and so forth.  Note, MISO, MOSI, and SCK pins taken together make up most of an SPI interface.

Several Arduinos, including the Uno, have two ICSP headers.  One of them is for use with the ATmega328 (or similar), and the other for use with the ATmega16U2 (or similar) chip that implements USB. When present, this  allows reprogramming the USB chip.

AVR refers to the instruction set architecture used in a family of Atmel microcontrollers.  Several Arduinos  – Mega, Uno, Nano, Micro – use AVR chips.  Others, like the Zero and Due, instead use ATSAM3 chips, with an ARM instruction set architecture.


Coin Slot Sensor Using AttachedInterrupt

Again, it makes sense to just use an attachInterrupt capable pin; but if can't for some reason:
Library install
Applying what I suggested in the answer on your other question to the code you've provided here, means installing the mentioned library:

And searching for and installing the library from the manager:

Code changes
Including the header
Patterned after documentation and an example for the library, your code would need to include the header for the library:
#include "PinChangeInterrupt.h"

Replacing attachInterrupt
Your attachInterrupt call would need to change to attachPinChangeInterrupt; likewise with the function that maps the pin to the interrupt number:
attachPinChangeInterrupt(digitalPinToPinChangeInterrupt(9), coinInterrupt, FALLING);

That is about all there is to it.  On the UNO/Nano or broadly ATMega328P-based Arduinos, only pins 2 and 3 work with attachInterrupt.  attachPinChangeInterrupt will work with most pins of most AVR-based Arduinos; any pins that have an PCINTn signal routed to them.  These are not as desirable to use, for performance reasons that you don't need to worry about for push buttons or your coin detector, and for easy-of-use reasons that are taken care of for you by this library.


Reading Serial String Gives Null Lines with JSSC

This is a common misconception about how serial communication works.
You're "sending" the "string" test. Except you're not.
What you're actually doing is you're placing the string test into the send buffer. Another routine then takes each byte from that send buffer in turn and sends it out through serial.
The Arduino then receives that byte and places it into its internal receive buffer.
You then get around to reading from the serial and you just get whatever is in the receive buffer at that moment in time - however many bytes that happens to be.
Then you "send" those bytes back - except again, you don't. You place those bytes into the internal transmit buffer in the Arduino and another routine takes each byte in turn from that transmit buffer and sends it out through the serial.
Again the Java program gets around to reading from the serial, and all it gets is what happens to be in its receive buffer at the time, however many bytes that may be at the time.
There is no such thing as "a string" or "a line" in serial. All there is is bytes - one after another.
It is up to you to receive those bytes and reconstitute them back into the form you want as each byte happens to arrive.
As it stands you have no way of knowing what that form should be, since you just send four bytes with no meaning attached to them.
It's common to add a "terminator" to a string when sending so that the receiver knows when all the bytes have arrived.  For us humans the simplest to use is a "line feed" or \n character.
Your receiving routine would then receive each character in turn appending it to the target String up until it receives the terminating character, at which point it knows that it has finished receiving this chunk of data and can act on it.
I have a popular blog post all about reading serial on the Arduino here, and the same principle can be applied to any other language.


How to connect a LiFePO4 battery directly to an esp32?

No. Absolutely not.
A LiFePO4 battery is 4.2V when fully charged. The absolute maximum voltage of an ESP32 is 3.6V.
You will kill the ESP32.
Instead you need to have a voltage regulator with a very low dropout. Ideally a switching ("buck") regulator with a zero-dropout "pass" mode to give the maximum life from your battery.
Even better is a "buck/boost" battery regulator that will boost the voltage up to a stable 3.3V once the battery voltage drops too low.
If all this is beyond you then you're better off using a powerbank to do the regulation to 5V for you then convert that back down to 3.3V with a simple buck regulator.


Arduino I2C Wire.onReceive hangs after a few loops

After a bit of tinkering, I noticed that removing the delay() call in the slave fixed it and there were no more hangs. Also, when using the Servo library to move a servo instead of blinking the led, Servo.write() hangs while Servo.writeMicroseconds() doesn't. I'd mark the answer that has an explanation for this strange behavior.


Shouldn't be a problem. The minimal voltage required to run at 16MHz is 3.8 Volt. No extra steps required.


The code as shown has a bunch of problems; the probably-most-important are as follows.

• score is not initialized.  Add score = 0; after
 time_since_reset = millis();

• As noted in a comment, the delay(1000) statement in light() prevents checking for whacks during the first second of a light being on.  This probably is undesirable – most people expect to whack a mole much sooner than a second after it appears.  If you want a delay there, make it at most 20 milliseconds. [See edit 2]

• The sequence randomSeed(analogRead(0)); currentNum = randomGenerator(); has a good chance of generating the same value of currentNum several times in a row, which may result in multiple counts for a given whack.

• Instead of saying randomSeed(analogRead(0)); within the inner loop, say it just after time_since_reset = millis(); or (probably better) in setup().  If analogRead(0) changes slowly, the same random seed may get used over and over, resulting in the same sequence of numbers from the random(3,8) expression.

• Your randomGenerator() routine has undefined behavior:  It doesn't return a valid result if the current random  number is the same as the previous one.  You could add a loop that calls random() again if the value is the same as before; but not returning a value results in  undefined behavior.

Edit 2:  When you turn a light on, record the current millis() time reading, say in onTime[i] for light i, and set flag isOn[i] true.  Later, when isOn[i] && (millis()-onTime[i] > targetDelay[i]), turn the light off and clear the flag (via isOn[i] = false).  Within checker(), a condition like port == 6 translates to isOn[6], an expression which is true when light 6 is on, else false.

The approach of using arrays like onTime[] and isOn[] and targetDelay[], variable subscripts, and recorded on-times has several benefits:  It lets you loop through lights, getting rid of that needlessly repetitious code in checker(); it enables other processing in the main game loop (such as whack-testing) to proceed independently of light control; it allows multiple moles to pop up at the same time; and it allows different moles to have different or varying up times.


First, I have to say I am not familiar with the Zero hardware, so I am
answering in quite general terms. Hopefully you will also get some
answers with hardware-specific information. That being said, here are my
first thoughts:

Your approach seems reasonable to me, but you are too optimistic
regarding the achievable sampling rate.
DACs are usually fast. It's unlikely that the DAC will limit the
frequency you can achieve.
You cannot achieve a sampling frequency of 45 MHz in software
with a CPU running at 48 MHz: your code to output a sample would
have to run in less than 1.07 CPU cycles.
You may achieve a higher sampling rate with an array of
16 samples rather than 15, as wrapping the array index modulo 16
can be optimized by the compiler into a bitwise AND, which is likely to
be faster than computing index%15.
Fastest would probably be to use a busy loop with constant execution
time and interrupts turned off (I know how to do that on AVR, but not on
ARM). Problem is: the program cannot do anything else than outputting
samples.


Arduino bluetooth HC-05 data reading problem

You are mixing ASCII characters and integer values.

The serial data is a pure binary stream, a series of bytes. It is up to the programs on both sides to interpret, how these bytes are meant. When you type 1 into your bluetooth serial app, it already does this. It complies to the ASCII standard, which gives a meaning to every binary value between 0 and 127. Google "ASCII" to get a table of the mapping. Each character (alpha numeric and some special characters and control characters) has a binary value associated with it. That way we can interpret a binary data stream as text.

The ASCII character 1 corresponds to the decimal value 49. You are saving the read byte from the bluetooth serials as long, which is a big integer. So, when you are printing it, you will see the decimal value, which is 49.

What to do now? The easiest way is to subtract the ASCII value of '1' from the received byte:

players = BT.read() - '0';

'0' is the C/C++ representation of a single ASCII encoded character. It's the same as subtracting the decimal value 48, but it's a bit clearer to see, what happens here. We are shifting the numbers row (0 to 9) from position 48 to position 0. That way the ASCII '0' is transformed to a decimal 0, the ASCII '1' to a decimal 1, and so on up to 9.

Note: You might want to make sure, that only numbers are used for these variables, as the principle will result in garbled data, when the user inputs some other characters. You would need to read the binary data into a temporary variable (here called c) and then check, if they are numeric. Either by hand:

if(c >= '0' && c <= '9')

or by a convinient function

if(isDigit(c))


I have found the Gas Sensor Library for Proteus, so I thought to share it here so that others can also get benefit out of it. They have also posted the complete method of How to use this Gas Sensor Library and have also given an example to download.

Thanks.


I can't turn on the motor by Arduino IoT Cloud

The following code is an example. As I don't know the Arduino Cloud Thing configuration, and I don't have access to the cloud and the Hardware, the
programm is just a guess making some commented assumptions.
There are many assuptions I made, and I can not rely on the schematics you showed me. Eventually you have to redesign the circuit/hardware setup. A L298N is a so called H-Bridge. That needs at least two control pins in1 and in2 connected to arduino outputs to define the direction of the motor. You only connected one of them to an output of the arduino. And one of them to the button and an input of the arduino. (If that part of the schematics is correct.)
If you press the button in1 gets HIGH but the in2 may also get HIGH because your program switches the motor pin to HIGH. That turns the motor off. If one pin is HIGH the other must be LOW to drive the motor. Some L298N modules also need a PWM signal at the enA pin. That sets the speed of the motor with the duty cycle of the PWA signal. Most modules have a pullup at enA and enB so per default the motors are configured for full speed.
#include "thingProperties.h"
#include <FTDebouncer.h>

#define MOTOR_PIN 2
#define BUTTON_PIN 5

FTDebouncer buttons;

void setup()
{
  pinMode(MOTOR_PIN, OUTPUT);

  // !!! PPK: Handler methods added
  buttons.addPin(BUTTON_PIN, LOW, onPinActivated, onPinDeactivated);

  buttons.init();

  setDebugMessageLevel(2);
  Serial.begin(9600);
  delay(1500);
  // Defined in thingProperties.h
  initProperties();
  // Connect to Arduino IoT Cloud
  ArduinoCloud.begin(ArduinoIoTPreferredConnection);
}

void loop()
{
  buttons.update();
  ArduinoCloud.update();
}

void onPinActivated(int pinNr)
{
  if ( pinNr == BUTTON_PIN )
  {
     toggle = !toggle;
     // this assumes that the toggle triggers a change for
     // the motor variable in arduino cloud. If not,
     // the motor variable will not be changed and my code does not work.
     // uncommenting the following line may help, in that case
     // motor = toggle;
  }
}

void onPinDeactivated(int pinNr)
{
  // Intentionally left empty, we only react to the rising edge.
}

void onMotorChange()
{
  digitalWrite( MOTOR_PIN, motor );
  Serial.print("The motor is ");
  if ( motor )
  {
    Serial.println("ON");
  }
  else
  {
    Serial.println("OFF");
  }
}


How can I turn this into an (Ableton) controller?

The hard part here is that you essentially have 216 inputs you need to read.

You could multiplex the analog pins using two 74HC4051. Analogread takes around 0.1ms, so around 2ms for all 18 knobs. Debouncing would however be pretty hard.

I'd probably go with input shift registers, and remove all the resistors. You would however need 27 8-bit shift register (3 registers per 2 knobs).

To reduce this you could encode the rotary position into 4-bit using a diode network. That way you can use only 1 shift register per 2 knobs. So 9 in total.


I'm trying to display the numbers 0-99 by multiplexing to two 7 segment displays. One number does not display

Missing pinmode(4,OUTPUT) in your setup routine.

As a general comment, using variable names instead of 'magic numbers' makes your code easier to read - and thus usually easier to debug. for example:

const int leftDisplay = 4;
const int rightDisplay = 5;
const int seg1 = 12;
const int seg2 = 11;
[...]

You can also use HIGH and LOW instead of 1 and 0 for the digitalwrite elements


Arduino water pump not working and beeping

Regarding your motor just making high pitched noise (beeping) I would say that you are not supplying enough power to your motor for it to pull in the load and get rotating, you might try to first get it started by a higher power setting (PWM) and then when it's running see how far down you can set it before it stalls (stops).

I don't belive a 12V pump would work any different.

As to the motor and L298 chip getting hot, this is sort of normal and in some cases would require som way of dissipating this heat. A heatsink might be an option.

If you were to overheat the L298 it will shut down before being destroyed (it should).


How do I use I2C from an Arduino Uno when I have a GSM shield mounted?

There seems to be a number of different Sim900 shields from different suppliers? I suggest you check/post the datasheet of the one you're using. If I2C works without the shield, and does not work with the shield connected , then it seems logical that there is a pin clash.
There is a good Random Nerd Tutorial on getting started with the shield on a Uno. Maybe test it out completely before connecting to the Raspberry Pi?
The Raspberry Pi is 3.3v and the Uno is 5v. You didn't mention level shifting in your question, but it may be worthwhile.


Your question has multiple layers:

The custom PCB: Breadboards are good for experimenting, but not for a finalized circuit. Depending on some factors you can decide between multiple options. One, that I myself often use, is soldering the parts onto a perfboard. That are cheap PCBs, where - depending on the type - you have a grid of single through-hole solder pads or connected groups of through-hole solder pads. I like to use these:

The pads are connected nearly like a breadboard, so it is easy to use with Arduinos and such. You can build your circuit on there by soldering the parts to it, and make the PCB the right size by cutting it into the needed size.

A more professional option is to buy real custom PCBs. You need to create the PCB layout on your PC (common programs are Eagle or Kicad, though there are many others). Then you can choose the PCB manufacturer of your trust and give them your layout files. They will manufacture the PCBs and send them to you. This options costs a bit money (though not a lot) and you will have to wait for the PCBs to arrive.
The casing: There are many options to choose from:

You can buy a generic case somewhere (hardware store, or the internet shop of your trust). Then you can work on it to fit your purpose (drilling holes for the LEDs, using screws or glue to fix your PCB, ...)
There are some standard cases to buy, though most of them most likely don't fit you good, since they are made for special industrial purposes.
You can create a custom 3D printed case. For this you first need to design the case on your PC (a common program is Fusion360, though I'm using FreeCAD). For the actual printing you can either use your own 3D printer, or you can again find a good 3D printing service, that you can give your design file (commonly in the stl format). They will print it for you for a bit of money. You will have to choose between different manufacturing methods, mainly FDM (putting lines of molten plastic onto each other layer after layer) or Resin printing (curing layers of fluid resin one after another). FDM is still cheaper. And you need to decide on the material (PLA is common, others are ABS or even metal (though the last is expensive). Also you need to design your case in a way, that it is good printable with the chosen method. You need to read more about 3D printing elsewhere (there are tons of material about it on the web).

One rule of this site is to not give product recommendations. That's not, what the site is for, and they are pretty fast outdated. Instead you need to do the research yourself.


Where can I find a central repository of all available Arduino libraries?

Since this question was first asked, there is now the Arduino Library Manager, built into the Arduino IDE. There you can search for and install libraries.

There is information about how the library manager works here:
https://github.com/arduino/Arduino/wiki/Library-Manager-FAQ

There isn't however an official website listing the libraries, so I recently created this unofficial site, based on the same data in the Arduino Library Manager:

http://www.arduinolibraries.info/


IMHO it is possible to connect more than one server PWM control inputs to a Arduino output pin.

The Servo input is something like a comparator with an very high resistance. So the servos should not influence each other in any way, nor will the output pin be overloaded.

Because of the input capacities of the servos, there might be a limit of the count of the servos.

And if you supply the servos with power from the arduino then, there is of cause a limit.

EDIT:

It is always a good idea to use buffers in a servo control circuit, to keep a sharp square wave signal. Parasitic capacities can reshape the signal even to a sinus signal.

That might confuse the servo control unit which works well only with a square wave (i.e a PWM-Signal).

simulate this circuit – Schematic created using CircuitLab


Why is that any sensor signal need to be hooked up to the interrupt pins on Andruino boards?

The interrupt pins are used to notify the MCU that a device needs attention. The INTx pins are chosen first because they are easy to program for; each gets a dedicated interrupt vector and hence ISR.

There is another type of external interrupt though, the Pin Change interrupt. This can be invoked via any of the PCINTxx pins on the device; on the '328 any pin can act as an interrupt.

The main difference between INT and PCINT is that PCINTs are grouped into banks of 8, which means that once the ISR has been invoked the appropriate pins need to be checked for their level, which furthermore means that it is possible to misread an interrupt if a bank is shared by multiple devices and the interrupt pulse itself is very short.

Further details can be read in the "External Interrupts" and "Interrupts" sections of the MCU datasheet.


Let's deconstruct this down to a simple example which we can test without the MPU6050:

#include <PID_v1.h>

double Setpoint, Input, Output;
//Specify the links and initial tuning parameters
double Kp = 2, Ki = 5, Kd = 1;
PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);

void setup() {
  Setpoint = 100;
  //turn the PID on
  myPID.SetMode(AUTOMATIC);
  Serial.begin (115200);
  Serial.println (F("\n\nStarting\n\n"));
}

void loop() {
  int a = 0;
  int val = map(a, -1300, 1300, 0, 1023);
  Input = val;
  myPID.Compute();
  Serial.print (F("Input = "));
  Serial.println(Input);
  Serial.print (F("Setpoint = "));
  Serial.println(Setpoint);
  Serial.print (F("Output = "));
  Serial.println(Output);
  Serial.println();
  delay (300);
}

Output:

Starting

Input = 511.00
Setpoint = 100.00
Output = 0.00

Input = 511.00
Setpoint = 100.00
Output = 0.00

Input = 511.00
Setpoint = 100.00
Output = 0.00

Input = 511.00
Setpoint = 100.00
Output = 0.00

Indeed it isn't changing. Let's analyze why:

The input is 511
The setpoint is 100
Therefore the error is 100 - 511 = -411
Disregarding (for the moment) the integral and differential terms, you have a proportional term of 2 (Kp) so the algorithm tries to output 2 * Error
Output would be 2 * -411 = -822
However the maximum and minimum limits default to 0 to 255, and thus the output is clamped to 0.
The algorithm outputs 0.
And the next time it does the same thing.

There is a function SetOutputLimits which can be used to change the default minimum and maximum output values.

The Ki and Kd values might eventually have an impact, but you won't notice anything with the output clamped to zero.

For example, adding this line in setup gives different results:

  myPID.SetOutputLimits (-5000, 5000);

Result:

Starting

Input = 511.00
Setpoint = 100.00
Output = -5000.00

Input = 511.00
Setpoint = 100.00
Output = -1233.00

Input = 511.00
Setpoint = 100.00
Output = -1438.50

Input = 511.00
Setpoint = 100.00
Output = -1644.00

Input = 511.00
Setpoint = 100.00
Output = -1849.50

Input = 511.00
Setpoint = 100.00
Output = -2055.00

Input = 511.00
Setpoint = 100.00
Output = -2260.50

Input = 511.00
Setpoint = 100.00
Output = -2466.00

Whether they are valid limits depend on what you are attempting to do exactly.


Raspberry Pi Outputting Signal to arduino

The Arduino and the Raspberry pi should have a common ground. Connect the ground pin of the Arduino to the Raspberry pi. Both boards should be powered by the same power source and connect a pull-down resistor from the digital pin of the Arduino to ground. about 10Kohms might be enough.


How to write & read from SPIFFS file as object data on ESP8266

I directly see 3 problems with your code:

Serial.write() will not return the written data, but the number of send bytes. This means that in your for loop you are only assigning the written number of bytes to the variable, not the data. But I guess you want to display the actual data, which was read from the file. You should assign the return value of fr.read() to a variable. Then you can send it via Serial.write() and still use that variable for other things later (like displaying).

You need to look into variable scope. You have a global variable number. But in the for loop you are defining a local variable with the same name via
 byte number = ...

This variable is only valid in that specific for loop iteration. When the iteration ends, the variable is thrown away and redeclared in the next iteration. It will not be there anymore, when you leave the for loop. So currently you are saving your data in a variable local to the for loop. It does NOT touch the global variable. Thus the other functions only see the value zero, with which the global variable number was initialized. You can remove the type byte before the variable in the for loop. That makes it an assignment instead of a definition. Thus then you really write the data into the global variable.

Data encoding: Clearly you have your number in the file as ASCII encoded text. But you seem to handle it as binary data. That cannot work. For example: When you read the first character of 1234 (which is written in the file), then you get '1' (the character, not the number). When looking at an ASCII table you can see, that this character corresponds to a decimal number of 49 (or 0x31 in hex). You can convert an ASCII encoded digit to a real number by subtracting the value of the character '0':
 int number = fr.read() - '0';

or
 int number = fr.read() - 48;

(both are equivalent).
Also you are currently just saving the read character into a single variable. That means, that after the for loop only the last character is left. Since this is a composite number, you should do something to compose it. Like this:
 number = 0;
 int factor = 1000;
 for(int i = 0; i<4; i++){
     number += (fr.read() - '0') * factor;
     factor /= 10;
 }

Note: This is untested, it is not the best way, but the easiest at this point, and it only works for numbers between 1000 and 9999 (4 digit numbers). You can implement this more versatile.
First we are resetting the number variable, so that old values are not getting in our way. We are using a variable holding the current factor (starting with 1000, since that is the figure in which the first digit lies). Then we go through the 4 characters, reading them. We subtract the character '0' (as described above) and then multiply by the factor. That resulting number is added to the variable number. Then we divide the factor by 10 (getting from 1000 to 100, then to 10 and finally to 1). At the end we can use number like any other integer variable.

Alternative implementation of reading the number, which is suitable for different numbers of digits:
number = 0;
// Prepare character buffer to read the number in
char buffer[10] = ""; // space for maximum 9 digits
int pos = 0; // position variable in the buffer
while(fr.available() && pos < 9){ // loop while there is data left to read in the file or we have no pace left in buffer (leaving one character for the terminating null character
    char c = fr.read(); // read character into variable
    if(isDigit(c)){
        buffer[pos] = c; // save digit in buffer
        pos++; // increment position for the next character
    } else {
       break; // break out of loop, if read character is not a digit (we don't want to read further when a non-digit character comes up)
    }
}
buffer[pos] = 0; // terminate buffer with null character
number = atoi(buffer); // use standard function to convert to integer number

Note:

This code is not tested, though it compiles without errors
You see, that it is not smaller, than the other one, but can handle different number of digits.
You can still use the first version with smaller numbers, if you always pad them with zeros. So instead 991 you would write 0991 to the file. That will make the first version work.


After a couple of hours I figured out what was happening so I will write all my analysis here for anyone having some of my problems.

First, a list of my components:

-USB TTL ship, used to upload programs to Arduino Pro. The one on the picture on instructables dot com /id/Usb-to-SerialTTL-adapter/, and used that driver.

-Arduino Pro. Chinese copy, red board just like Sparkfun's. 328p chip @ 5V = 16mhz.

-A board very similar to this one. It has a chip with FT232 written on it, also FTDI in bold letters.

The big USB TTL pcb I was using has 5 output pins: 3v3, 5v, TX, RX, GND. Turns out this is not enough to program Arduino Pro as you need one more pin. If you don't connect this pin, avrdude just gets stuck after opening the COM port and waits indefinitely/until you kill the process. To even be able to see this USB TTL chip in Windows, you need to download a driver from the website(first link) and my guess is that the driver is buggy since it won't exit the process when it encounters this type of error, further leading to suspicious/dangerous behaviour which results in Windows completely shutting down all COM ports until next restart.

To get this pin(it's called DTR/GRN), I borrowed the other chip(3rd) and I connected it regarding to this scheme:

I also had to download a different driver for it, I don't remember where I downloaded it from but it's called CDM21226 driver, when you install it it says FTDI driver installed.

Now my uploading was getting stuck no more, however after the first successful upload to my Arduino Pro the upload process would get stuck in the part where it is burning the program, if you turn verbose option in Arduino IDE on, you can see something like Writing: [#######              ].

It turns out this driver was faulty too, as I uninstalled it and when I installed it with the very same setup as before it worked seamlessly ever since. It also took me some time how to uninstall a Windows driver without using Device Manager because it wouldn't show up there - no device attached to it.

To do that open Command Prompt as admin and type pnputil.exe -e to get a list of all drivers. Among them will be one called FTDI and that's the guy, in my case he was called oem51.inf. To delete him, type pnputil.exe -d oem51.inf, or add -f before -d to force deletion - in my case it kept saying device is busy so it required this drastic measure. Change 51 to the number you have above your ftdi driver. After this just install the driver again and everything should be fine, even without reboot.

Phew...
So much work to get a simple program burned to Arduino Pro. Hope you have less trouble with it than I did.


What's the difference between analogWrite and digitalWrite?

digitalWrite will set the specified pin to one of two states - HIGH/LOW, which equate to 5v (3.3v on some boards) and ground respectively.

analogWrite can vary by the type of output used.

If applied to a PWM pin - it will set the pin to a periodic high/low signal, where the percentage of the signal spent high is proportional to the value written.
for example  -

    analogWrite(PWMpin,255)

Will be HIGH 100% of the time, while

    analogWrite(PWMpin,127)

Will be HIGH 50% of the time, and LOW 50% of the time

When applying analogWrite to a DAC pin (available on some boards, like the DUE or MEGA)
analogWrite will actually cause the specified pin to output a voltage level proportinal to the specified analog value

For example, on the Due, with maximal voltage of 3.3v and a default analog resolution of 8 bits -[0:255]

    analogWrite(DACpin,255)

Will cause the specified pin to output 3.3v, and-

    analogWrite(DACpin,127)

Will cause the specified pin to output 1.35v


USB connector between Arduino and a lever (switch)

I'd suggest using a multimeter to figure out what's connected to what after hooking up the complete wiring scheme; there aren't that many options and you should be able to figure out what's connected to what soon enough. On a more philosophical note, it's only a bad idea if the alternatives weren't worse.


I have cooked 3 regulators applying 12 V to RAW pin. Am I doing something wrong or did I get a bad batch?

The Pro Mini's 5V regulator (MIC5205) can supply a maximum of 150 mA, from which the Pro Mini uses about 20 mA, leaving around 130 mA for other applications.

Check the data sheet of the relay, to get the maximum current draw. For example, the RWH-SH-105D relay requires around 70 mA in the "on" position. While this is under the 130mA limit, you may be using other IOs or powering other modules.

To reduce the current draw, use a transistor to drive the relay like this:


It depends actually on your requirements what is 'best'.

If (transmission) speed is an issue, there are mainly some things you can do to improve this:

Increase the transmission speed (this depends on the distance of the wires and the noise).
Decrease the start/stop bits (this reduces the certainty the values will arrive ok)
Pack your data (takes more processing time possibly, and more programming work, but can be faster).

About the third option: since you are mostly sending values, you can make some improvements. So you can send them as float (by sending the float data, with the length of sizeof(float)). However, note there could be inaccuracies in the last digit.


KEY_LEFT_GUI is the left Windows key. I think the problem may be that your code is only holding those keys down for microseconds. You need to give the computer a little bit of time to recognize the keypresses because it's expecting a human using a keyboard, not a microcontroller running at 16MHz. Try adding a delay before Keyboard.releaseAll();.


Its working as long as the connection doesn't break or the server doesn't stall. We must wait till the response .

while (client.connected())
{
 while(client.available())
 {
 char ch = client.read();
 Serial.print(ch);
 }
}
 client.stop();


You solved your problem.

You said

  I checked the LED with a multimeter and indeed it is a visible bicolor
  LED, so there is no IR blaster in this board.

So, be kind, accept this answer so we can close your question.

I'm posting, not comment, only to get this out of the "unanswered".


formatting strings in Arduino for output

If you need the result in a single string then your 3rd option is the preferred way.

If you don't, then the first option of printing each part separately is the most efficient in terms of memory.

The second version, String concatenation, is the worst option in all respects and should be avoided at all costs.

I often use sprintf to a buffer if I need a specific format (for instance leading zeroes on a number).

If you want to avoid the extra code bloat of sprintf you can use various combinations of strcpy, strcat and itoa etc to build up a string into a memory buffer (if you really need to put it in a buffer).

Note that on an 8-bit Arduino sprintf has no float support - so you would still need to use dtostrf to format a float into a char buffer first, or print it directly.


If the setup() or loop() functions call delay() then of course that will delay getting to the next function and will slow down the whole process.

The only way to deal with that is to rewrite the code, combining what you're calling and fixing it so that it takes into account the other work it needs to do.

Same thing if you call any blocking functions, like reading from Serial until you get a newline.

If that's not the case... well, the ESP8266 is a small, not particularly fast processor. If there are no delays or blocking functions then your code is running as fast as your code might run and you'll just have to live with it.


Bluetooth Modules not communicating correctly

SoftwareSerial.read() returns a single character as an integer. When you print an integer the print() functions convert it to a human readable format.

You want to covert (cast) the output of read() to the char type. Either:

void loop() {
  char c;
  c = mySerial.read(); // store the result in a temporary variable c
  Serial.println(c);
  delay(2000);
}

or

void loop() {
  Serial.println((char)mySerial.read()); // cast the type to char befor printing.
  delay(2000);
}

However since only one character at a time is being read your output will be one character per line (assuming no data loss due to the delay):

1
0
0


This is an excellent question to illustrate the amount of string copying and heap operations (malloc/free) going on when using the Arduino String class.

void loop()
{
  Serial.println(foo("def"));
  while(1);
}

The compiler will generate loop() something like this:

void loop()
{
  // String literal is stored in program memory. Needs to be copied
  // to temporary variable. This is done before main() is called.
  static const char temp0[4] PROGMEM = "def";
  static const char temp1[4];
  copy_from_program_memory(temp1, temp0);

  // The parameter to the call to foo() is actually a temporary String
  // variable constructed from the string literal. Storage is allocated
  // on the heap and the assigned from the value of the string literal.
  String temp2;
  temp2.constructor(temp1);

  // The return value of the call to foo() is a String that is passed
  // to Serial.println(). This is also a temporary String variable.
  String temp3;
  temp3.constructor(foo(temp2));
  Serial.println(temp3);

  // The String class destructor has to be called for the temporary
  // String variable so that the string values on heap are deallocated.
  temp2.destructor();
  temp3.destructor();
}

Note that each call to the constructor involves allocating and copying data to the heap.

String foo(String arg1)
{
 String test = "abc";
 test = test + arg1;
 return test;
}

The function foo() needs to copy strings several times to perform the string concatenation. The operator+ will require an intermediate String copy.

Cheers!

PS: For more details please see the assembly listing below with the calls to String member functions. The compiler reduces inline member functions and reuses temporary local variables. Also the call to foo() is inlined. The member function reserve() is part of the constructor.

00000198 <main>:
 1de:   60 df           rcall   .-320       ; 0xa0 <String::reserve(unsigned int)>
 1fc:   50 d2           rcall   .+1184      ; 0x69e <strcpy>
 212:   46 df           rcall   .-372       ; 0xa0 <String::reserve(unsigned int)>
 230:   36 d2           rcall   .+1132      ; 0x69e <strcpy>
 248:   62 df           rcall   .-316       ; 0x10e <String::operator=(String const&)>
 26a:   1a df           rcall   .-460       ; 0xa0 <String::reserve(unsigned int)>
 27e:   0f d2           rcall   .+1054      ; 0x69e <strcpy>
 28e:   3f df           rcall   .-386       ; 0x10e <String::operator=(String const&)>
 294:   60 df           rcall   .-320       ; 0x156 <String::~String()>
 29a:   5d df           rcall   .-326       ; 0x156 <String::~String()>
 2a0:   5a df           rcall   .-332       ; 0x156 <String::~String()>

Bottom-line is that the String class uses a lot of instruction cycles and memory, and there is a potential risk of heap fragmentation and allocation failure.


Rasberry Pi Controlling Arduino - Reads "Ghost" Input - Doesn't Complete Logic Loop

What motor are you using? If it works straight from the 5v but not from a GPIO, it could be an issue of insufficient power.
As @StarCat4 mentioned, you also need to add a digitalRead inside your while loop if you want the motor to ever turn off.


How to use correctly a microstepping driver with a lower voltage stepper motor

That doesn't matter at all.
The voltage stepper motors are rated for is the voltage that, if applied to the motor coils, would create its rated current.
Stepper motor drivers monitor the current, and always use the full voltage available to them (9 - 40V in your case) to drive the stepper motor - using PWM.
The stepper motors coils inductance slows down the change in current, allowing the driver to reach its set current.
Higher drive voltages simply mean that it's easier to overcome that inductance, allowing for faster stepper motor movements.
You'll want to set your driver at 1.0 or 1.5 A, and supply it with as much voltage (up to the rated 40 V) as you can.


The bootloader is there for convenience.

Yes, you understand what the bootloader does and how it operates.  However, you have missed out one benefit, and that is evident when you're not using the bootloader.  That is, when you're not using the bootloader the same connection can be used for a serial connection to the PC.  If the 32U4 were directly programming the main MCU then it would be talking to the SPI pins not the UART pins, so you would need a second connection, or both a connection to the UART and the SPI pins, and much more complex firmware on the 32U4, in order to get a serial connection to the PC.

So the simplest option is just to have a dumb pass-through interface from the USB to the UART pins and have the main MCU self program with a bootloader.

It also means that you don't need any special programming hardware when making your own board - just something (another arduino maybe) to get the bootloader on there in the first place (or buy the MCU pre-programmed) and then use any TTL serial interface to program it with your main program.


As I mention in my answer about serial communication:

  Before reading, always make sure data is available. For example, this is wrong:

if (Serial.available ())
  {
      char a = Serial.read ();
      char b = Serial.read ();  // may not be available
  }

  The Serial.available test only ensures you have one byte available, however the code tries to read two. It may work, if there are two bytes in the buffer, if not you will get -1 returned which will look like 'ÿ' if printed.

In your code:

if(Serial.available() > 0)
    {
    server.send(200,"text/plain","Data");
     for(int n=0; n<64; n++)
     {
       data[n] = (Serial.read());

So you know that one byte is available, but you are reading 64. No, that won't work.


No, it's not possible.

PWM is not actually analog - it's digital, but switching on and off at a high speed.

If the pin were capable of reading an analog value at the same time as outputting a PWM waveform (which I highly doubt...) all you would get is alternating 0 and 1023 values (or whatever range the Teensy reads in).


Receiving garbled `char` array returned by a function

It's because you're returning a pointer to a local variable.

You are only returning the address in memory where your char array is allocated. That allocation is on the stack and only exists for the lifetime of the function.  But you still have the address where that memory was allocated, and you're using it as if it's still allocated.

When you append it to a String room is allocated on the heap and the data is copied in. That heap allocation remains until the String object is destroyed, either by going out of scope or by you manually destroying it.

It's pure chance that the data is still available and intact at the point of copying.

In short:

You must never return a pointer to a locally allocated (non-static) array.

Things you can do that are correct:

Pass an array pointer to the function to be populated by the function
Return a pointer to a statically allocated local array
Return a String object (though I wouldn't recommend using String for anything)

My preferred method is the first, whereby you define an array in the outer scope, then pass that (and possibly the array length) to the function. The function then populates the array it has been passed.  This also has the advantage that the function can use the return value to indicate a status or other quantity.

For example:

void myFunc(char *buf, int len) {
    for (int i = 0; i < len - 1; i++) {
        buf[i] = 'A';
    }
    buf[len - 1] = 0;
}

char myBuf[20];
myFunc(myBuf, 20);
Serial.println(myBuf);

--> AAAAAAAAAAAAAAAAAAAA


Why does the reading on the ESP32 read max, when the reading on UNO read accurately?

The ESP is a 3.3v device. If your Uno is a 5v device, its A/D converter can measure and report voltages from 0 to 4.9878v (5v minus 1 LSB). If the same signal is presented to the ESP, any value above 3.29919 volts (3.3v - 1 LSB) will read as 4095, i.e., out of range.

(If this isn't your issue, adding wiring diagrams of each system to your question will help us understand it better.)

Update:

  Perhaps a different ESP unit would be the ideal solution?

As far as I know, all of the ESP's are 3.3v devices. So the solutions I see are:

Power your sensor with 3.3v (is this an option?) so its output will be within the input range of the ESP's built-in A/D.
Scale the sensor output from it's 0-5v range to the 0-3.3v range the ESP can accept. Whether you can use a simple divider network or would need an op-amp may depend on the sensor, but if, as I suspect, it is a simple resistance device, a voltage divider should work.
Use an external 5v A/D converter. This will require a 5v power supply (which I presume you are using already, to power the sensor) and voltage level conversion between the A/D and input pin(s) of the ESP. The conversion could be a purchased level-converter board or a simple resistor-divider network.