text:
Can I use and external power supply and USB at the same time on my Arduino?
Can I use the Arduino with an External wall-wart and the USB at the same time?  I need to power more LEDs, and the USB on my computer can only supply so much.  But, I didn't want to destroy my computer because I had the USB and the external plugged in.
I saw this,
External power supply?
But I am still unsure.  The reason I want to at all is because when I connected this circuit, the Arduino would cease to be recognized on the USB.  I don't know if it is because there wasn't enough power to the LED, if I short-circuited something, or something else.  I do not wish to break my laptop though.
What happens if I power the Arduino with both the USB and external power voltage simultaneously?
These all seem to indicate you don't just "plug in" with both, and you need some other kind of regulator or something.  But in that same answer, one person says,
https://arduino.stackexchange.com/a/896/69706
And that indicates when the power is plugged in the USB is cut off.  Again, my fear is breaking my laptop, and that is the main question.  Especially in light of this,
Is supplying 5V from both external 5V and USB harmful?
The external power is this,
9 VDC 1000mA regulated switching power adapter

don't use the arduino as a power supply for the LEDs

Don't I power the Arduino and run the wires through the GPIO?

you do if you want to use the arduino as an expensive fuse .... GPIO pins have a limited current source/sink capacity .... the internet has many examples of controlling high current devices with a microcontroller

Besides the limits of the signal pins, the 5V pin on the arduino cannot supply as much current as your 9V 1A wall wart. Question is, how you power more LEDs ?

Yes, you can simultaneously connect external power supply and USB. As explained in one of the answers, that you linked, the Arduino chooses it's power input through the supplied voltage on Vin/barrel jack. Vin has no direct connection to the VUSB, so the USB port will not get any voltage from the external supply, thus it does not get damaged.
BUT: Your thinking is wrong. Clearly your LEDs need more than 500mA. This current should never flow through the Arduino. You can easily fry the protection diode or the voltage regulator (which is an inefficient linear regulator), if you connect all the LEDs to the 5V pin. One GPIO pin can only provide about 20mA (40mA at absolute max, you should stay below 20mA) and only 100mA through all GPIOs together. They are not made to provide power, but for switching.
Instead you should connect the LEDs outside of the Arduino to the power supply. If you want to use the specified 9V power supply, you need to buy a buck switching voltage regulator, which gets the voltage down to 5V for you. Make sure, that this regulator is rated for a current significantly higher, than what you need.
How to control the LED then? That depends on your LEDs. If you just have some bare LEDs, you could use a transistor to switch the higher voltage from the Arduino. If you have a plain LED strip you can also use a transistor. Best use a MOSFET for this. If you have an addressable LED strip, just connect the power lines to the 5V output of your new switching regulator and the data line to the Arduino.


text:
TQFP Atmega328pu-th cant upload sketch sync error (breadboard)
So I have a USB to ftdi connected to my qtfp 32 socket trying to upload a sketch but I get a sync error , as far as I am aware I have uploaded the sketch correctly

sync error usually means upload was impossible. In your case, wiring is the first problem candidate, sorry.

Does your chip have a bootloader on it? How have you wired up your setup?

@majenko exactly like this picture Burn https://imgur.com/gallery/8xpHGqo

Which one? The first or second?

@Majenko sorry if I am using this wrong really new here. the second one with the red board (ftdi) I have everything wired like that but I get sync error. Also my chip has a weird suffix, -UTH

And did you first wire up like the first way and install the bootloader?

yep and it said boot loader burned successfully or something like that, I've checked everything so many times no idea what I am doing wrong

Check the crystal. Make sure it's as close to the chip as possible. If you are using a breadboard, try lower value capacitors, or no capacitors.

@gerben thank you will do

Hey guys I managed to figure it out I had to remove the dtr pin from pin 29 , I made a video to help anyone else looking to do it, I don't know if it breeches any self promotion? But hope it helps because i found it difficult to find any resources. https://youtu.be/5CPYz6Kde7M

source: Stack Exchange

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

sort: votes


text:
need to make my partners pill box turnover sensitive
ive done some arduino stuff back in uni like 7 years ago; and reserached premade items-ive looked online at many pill organisers and the best and cheapest one is $149 and isn't shipping to the UK rite now. but basically my partner needs to take 1 pill a day without fail. second set of pills is less urgent and not an issue if he misses, but basically is there like a thing I could whip together to sense when he has turned the pill case over that day or not? maybe sync to phone(would be super useful)  so he knows when he has actually taken it.

yes, there is probably something that you could build .... it is unclear how you would detect that the pill was actually swallowed

Is this a pill case that holds pills for 7 days? Surely the absence of a pill on a certain day indicates that at least it has been removed from the case (and hopefully swallowed). The "has the box turned over" gadget wouldn't prove the pill had been swallowed anyway.

I wouldn't go with a "turn-over" sensor, but would just use a (big) button. I'd go with something like an ESP8266/ESP32. Those can connect to WiFi. Then have it send a push notification when being pressed (that is; the pill has been taken). Maybe light up an LED to also indicate the pill has been taken. Turn off the led at midnight. Also send a different notification when the button hasn't been pressed before, say noon.
For push notifications, you can use PushSafer, PushBullet, or Prowl (which I had most success with).
Have a look at Kevin Darrah article, and youtube channel. He uses it's own boards, but most of the code will work on any ESP board.
But try to imaging how the system would work, in your head first. Just throwing technology at a problem isn't always the best solution. My grandma has 7 pill boxes, one for each week. Which helped to keep track of whether a pill was taken that day.
Best of luck.

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


text:
Connecting Arduino Arduino to MOSFET
I want to use my Arduino Nano to control a 12V peristaltic pump via a BDX33c N-Channel MOSFET. The pump has a maximum current draw of 1,4 A. The Arduino (via VIN) and the pump are powered by a 12V supply. I connected the parts like shown in the schematic diagram.

When I plugged the supply in, the Arduino voltage regulator and the Mosfet got really hot (I could not touch it longer than 1-2 seconds) and the RX-LED was on continously, even after turning it off and on again. The Arduino isn't recognized by my Computer anymore, so I assume it is dead.
What did I do wrong with my wiring?

I think this is not a MOSFET, but a NPN bipolar Darlington transistor

The 'schematic' shows both sides of the motor connected to ground. The 5V output from the Arduino's regulator goes nowhere. Have you connected it up like this in real life? There's a chance you have pumped 12V to one of the Arduino inputs.

The maximum base current is specified as 250mA, which is really much for an Arduino

That little blue wire on your breadboard is shorting out the motor. You have most likely now blown the transistor and maybe your power supply. The 12V may also now have made its way into the Arduino through the dead transistor and nuked the rest of it.
Alternatively, the massive base currents imposed by the shorted ground connection may have burned out parts of the Arduino.

That little blue wire on your breadboard is shorting out the motor.

That is not the problem. That blue wire is actually correct. It connects the source to ground. (-ve)
Your drawing shows the Drain of the Mosfet connected to +12 volts and the Source connected to ground. (the -ve of the supply) If you didn't have the short (blue wire from Source to ground) it still would not have worked.
You can't put an N channel mosfet in the positive side of the supply and control it from a voltage lower than the positive supply. (something the previous answer didn't even mention)
You must have the source connected to ground (as you have) but the drain has to then connect directly to the motor, and the other side of the motor goes to the +12 connection. This would be the correct way, but there still is an important omission. You need to have a diode connected across the motor to control the flyback pulse when the mosfet turns off. Otherwise the voltage spike generated by the motor's inductance will destroy the mosfet switch.
Your blue wire on the breadboard is correct. What is wrong is the red wire to the center terminal of the mosfet. The red wire should be going to the motor. The Blue/yellow connection. The green wire should be going to the mosfet's center pin.And as I said before, there needs to be a diode across the motor, with the cathode (line on the body of the diode) connected to the +ve side of the motor connection.
This is a correct drawing as far as the mosfet and motor connections are concerned. This drawing shows 5 volts being brought to the breadboard to power the motor. In your case this should be the 12 volts from the power supply.

While the beadboard may be adequate for verifying the circuit, it may cause connection problems due to the significant current that the motor will draw. Even if you wired it up properly you may still have issues due to the poor connections.
EDIT:
I looked up the specs for the BDX33B and it is a darlington transistor and not a mosfet. But in the end, all that I said also applies whether it was a bipolar transistor or a mosfet. But you need to include a series resistor as shown in the drawing I provided. You can't drive it direct from a port pin as if it were a mosfet.
Another schematic.

This shows a darlington transistor like the one you listed, and a 12 volt power source.


text:
F() messes with program
I'm working on command-handler library and I have a big problem with F() function.
Example sketch for library uses quite a lot of RAM, because it has to print a lot of text over UART. As before, I've used F() to lower RAM usage. It worked on first!
Lib works with help of strtok function. Command fomar is:

cmd1,..,paramN;..;cmdN,..,paramN

Commands are separated with ; while command parameters(params) are separated with ,
Library works without any problems, it returns memory address(char*) of any command and every param.
When I try to compare parameter/command with strcmp it works only if all commands are in uppercase.
Let's take LED command for example:
It works only with Led, LED or any case where is letter d in uppercase. led won't work, and it will say that command le doesn't exist. Yes, le, it won't print led. But, after DURATION command, it somehow start working.
Memory for serial buffer is dynamicly allocaed in object constructor, in global scope.
Why? All those problems are because F(). Can someone explain why? Here's the code and screenshot of serial monitor.
void execCmd(const char *set)
{
char *cmdParam = CMDHandler.find(set, CMD_PARAM);

if (!strcmp(cmdParam, "LED"))
{
    // ONE WAY TO CHECK IF COMMAND HAS PARAM(S) - BEFORE GETTING PARAM(S) == BETTER WAY
    if (!CMDHandler.count(CMDHandler.getNext(CMD_PARAM), CMD_PARAM))
    {
        Serial.print(F("->> Command LED: Current LED status is "));
        Serial.println(digitalRead(LED_PIN));
        return;
    }

    cmdParam = CMDHandler.find(nullptr, CMD_PARAM);
    LEDStatus = 0;
    uint8_t status = atoi(cmdParam);

    digitalWrite(LED_PIN, status);
    Serial.print(F("->> Command led: LED Status is "));
    Serial.println(status, DEC);
}
else if (!strcmp(cmdParam, "LOOP"))
{
    cmdParam = CMDHandler.find(nullptr, CMD_PARAM);

    // SECOND WAY TO CHECK IF COMMAND HAS PARAM(S) - AFTER GETTING EVERY PARAM
    if (cmdParam == nullptr)
    {
        Serial.println(F("->> Command LOOP: Expected one parameter!"));
        return;
    }

    uint8_t status = atoi(cmdParam);
    if (status)
    {
        LEDStatus = 2;
        digitalWrite(LED_PIN, HIGH);
        Serial.println(F("->> Command LOOP: LED Blink Loop is on!"));
        delay(blinkDuration);
    }
    else
    {
        LEDStatus = 0;
        digitalWrite(LED_PIN, LOW);
        Serial.println(F("->> Command LOOP: LED Blink Loop is off!"));
    }
}
else if (!strcmp(cmdParam, "DURATION"))
{
    if (!CMDHandler.count(CMDHandler.getNext(CMD_PARAM), CMD_PARAM))
    {
        Serial.print(F("->> Command DURATION: Current blink duration is "));
        Serial.print(blinkDuration, DEC);
        Serial.println("ms");
        return;
    }

    cmdParam = CMDHandler.find(nullptr, CMD_PARAM);
    blinkDuration = atoi(cmdParam);

    Serial.print(F("->> Command DURATION: New blink duration is "));
    Serial.print(blinkDuration, DEC);
    Serial.println("ms!");
}
else if (!strcmp(cmdParam, "HELP"))
{
    Serial.println(F("------ HELP ------\n-> LED [0/1] - Turns off/on LED on pin 13\n-> LOOP [0/1] - Stops/starts blink loop with LED on pin 13\n-> DURATION [X] - Changes duration of LED loop blink. Recommended values is 50-500ms\n"));
}
else
{
    Serial.print(F("->> Command "));
    Serial.print(cmdParam);
    Serial.println(F(" does not exist!"));
}

}
char *CMDHand::find(const char *input, uint8_t const type)
{
    char *found = nullptr;
    char separator = delimiter[type];

    if (input != nullptr) // FIRST CALL
    {
        constrain[type] = input + strlen(input) - 1;
        next[type] = input;
    }
    else if (next[type] > constrain[type]) return (nullptr);

    found = strtok(next[type], &separator); // FOR SOME REASON IT DOES NOT WORK IF I PUT &delimiter[type] INSTEAD OF &separator
    last[type] = next[type];
    next[type] += strlen(found) + 1;

    return (found);
}

To compare with F() macro encased strings you have to use special forms of the string functions that are suffixed with _P.  You also need to cast the string literals to the right type (PGM_P).
To do a case-insensitive comparison you should use strcasecmp instead of strcmp.
To put those together you end up with:
if (strcasecmp_P(cmdParam, (PGM_P)F("help")) == 0) {
    ...
}

There is a problem here:
found = strtok(next[type], &separator)

strtok takes a C string as a list of separators (must be NULL terminated). You're passing it the address of a single character. There may or may not (probably not) be a NULL in the next byte in memory, but everything else up to the first NULL found in memory will be taken as delimiter characters.

Are all these specific '_P' functions documented somewhere? I know a few but not all of them like strcasecmp_P.

@MichelKeijzers https://nongnu.org/avr-libc/user-manual/group__avr__pgmspace.html

No, I've used F() for Serial.print() and Serial.println(), not for ˙strcmp(). Why I should used it in strcmp()` then?.

For the same reasons as in Serial.print. To save RAM.

Thank you very much (I already upvoted your answer).

@Majenko sorry, but no. It doesn't work as it should. led doesn't work because somehow led becomes le(I know because it says command le doesn't exist). LED works. I don't know why letter d(lowercase d) causes all those problems. No matter what command I type, if it has d, it will cause problem. Without F() in Serial.print/ln all works fine. Why?

@SilvioCro Then there is something strange happening in the mysterious CMDHandler class's find method. If your string is not parsing correctly you should look at the parser, not the comparison structure.

@Majenko added find method. Code works fine when I don't use F(), even I tried as C++ program. Seems like F() overrides part of the buffer for the Serial, since if I print text using next from find method, I can see part of the text that I didn't write.

You have a critical mistake in your find method. See my edit above.

Thanks a lot, now it works.


text:
Can someone check my schematic and code? My Led is not turning on
Led1 is on the left Led2 is on the right The code is making LED1 blink every second but it should also turn on Led2 so that whenever I press the push button it should turn off Led2. But Led2 isn't turning on when I run the code but Led1 is blinking

#include <avr/io.h>
#define F_CPU 16000000
#include <util/delay.h>
#include <avr/interrupt.h>
void setup();
void initInterrupt0();
// ---------Main Program -------------------------------------------
int main()
{
setup();
initInterrupt0();
// ------ Event loop: Just flashing LED-----------------------------
while (1)
{
PORTB ^= 0b00000010; // flash PB1 at 1 sec interval
_delay_ms(1000);
}
}
// -------- Initialization ------------------------------------------
void setup( )
{
DDRB = 0b00000011; // LED PB0, PB1 active
DDRD = 0b00000000; // all inputs
PORTD = 0b00000100; // enable pullup on PD2
}
// ---------- Initializing Interrupt 0 ------------------------------
void initInterrupt0( )
{
SREG |= 0b10000000; // set global interrupt enable bit
EIMSK |= 0b00000001;// enable INT0
EICRA |= 0b00000000; // trigger when button is low
}
// Interrupt Service Routine: Runs every time there is a change on button
ISR (INT0_vect) // INT0 interrupt function
{
int PButton = PIND; // read portd
if (PButton & 0b00000100) // is button PD2 pressed
{
PORTB |= 0b00000001; // turn PB0 on
}
else
{
PORTB &= 0b11111110; // turn PB0 off
}
}

I reposted it because the other code was only screenshots and not formatted

There both my accounts I made two accounts by accident.

edit the first post ... delete this one

I guess you want your interrupt to fire on any change, not only when going low, or it'll never turn on.
Change your EICRA line to 0b00000001.
I also found it very useful to include some macros for setting and clearing bits, so you don't have to write out all the bytes and |= / &=s manually

I second @towe 's comment. Secondly; since the button has a pull-up resistor, the PD2 bit of the PIND register will be 0 when the button is pressed, and 1 when not pressed. Your code assumes the reverse. Thirdly; you may have to look into debouncing the button. Lastly; indenting your code makes it more readable, for us and yourself.


text:
device signature 0x000000 when burning bootloader
I receive this message: "device signature 0x000000" when a try to burn the bootloader on a atmega328p-au (SMD) inserted on PCB
i am using arduino uno as isp i already uploaded the ArduinoISP sketch and i check "Arduino as ISP" as programmer  with "arduino nano" as board
i do not know what is the problem i tried to check the ISP wiring with the arduino uno and everything is alright
what i noticed is that when i remove the GND wire attached to ISP the pin13 of the arduino lights up when i connect it it lights off i do not know what to do
here is the full schematic
Thank you for helping me

Not necessary related, but what the D4 for? it make your 7805 ground 0.6v higher than the ground.

If all the lights go out on the Arduino when you plug it in, it sounds like a short circuit...

On an unrelated note: where are all your decoupling capacitors?

@Majenko Can you explain me please why the short circuit happens and how to fix it ?

Your schematic looks ok, so it may be your PCB where the problem lies.

@Majenko you are absolutely right i fixed my bootloader problem and i was able to burn the sketch when i power 3 to 4 LEDS every thing seems to be fine but when i power on all the leds  they start blinking so quick so you are right there is a short circuit happening can you help me please ?

Take some high resolution photographs of your PCB with good lighting.

@Majenko Here are the pictures

@Majenko
https://ibb.co/b1qh2rx
https://ibb.co/n3hthH7
https://ibb.co/42SdNYY
Thank you for helping me

Looks ok on first inspection, but you do have some quite tight clearances there. Check for shorts with a DMM

@Majenko should the tight clearances  makes a problem ?

@Majenko i will check using DMM as you told me to and i will keep you on update in the mean while please let me know if you noticed anything wrong thank you very much again

Tight clearances can cause problems with the etching.

if so can you suggest me a solution ?

@Majenko i did a test and it worked what i did is i supplied the circuit with independent 5v coming out from arduino (vcc5v & gnd) and the 12v was wired to all the LEDS only so i eliminated the role of 7805 and every thing seems to work perfect i think the D4(B5819W) seems to make the problem i do not know why this is happening  any suggestions ?

@Majenko can you please help

@Majenko you said : <<If all the lights go out on the Arduino when you plug it in, it sounds like a short circuit>> can you please explain to me why and how to fix this because it is happening :(

Did you ever find the solution? I'm stuck as well.


text:
Getting Accurate Velocity Readings From IMU
Hi I am currently using a BNO055 for a design project. This sensor outputs a linear acceleration vector corresponding to three (xyz) directions. I am trying to "integrate" the acceleration to get a speed the object it is mounted to is traveling.
I noticed early on that in my speed graph there is large amounts of drift.
I was looking for any guidance someone might have for tuning out the drift some way or filtering options I could use for acceleration data to reduce the drift

The process of integrating acceleration to derive velocity and integrating velocity to derive position are commonly known as dead reckoning.  In this link it is stated:

Dead reckoning is subject to cumulative errors. Advances in
navigational aids that give accurate information on position, in
particular satellite navigation using the Global Positioning System,
have made simple dead reckoning by humans obsolete for most purposes.

It may help to calibrate each of the 3 accelerometers using Earth's gravity as a constant.  Test if each accelerometer is symmetrical providing the same absolute values when pointed toward the Earth as when pointed away from the Earth. If any are not symmetric calculate an appropriate offset.  Next compare the range of each of the 3 accelerometers.  If they are not the same calculate an appropriate magnitude correction factor for maximum and minimum accelerometer ranges.
To find the offset and range correction values look at page 26 of the BNO055 specification sheet.  There you will find a picture of the BNO055 chip which relates to the direction of the X, Y and Z accelerometers.  Position the chip such that the X accelerometer is pointed downwards toward the earth.  Record the raw value.  Now repeat the measurement with the X accelerometer pointing away from the earth.  The absolute value of these two measurements should be the same.  If not, determine the offset needed to correct X accelerometer measurements and incorporate that value into your program.  Repeat this for the Y and Z vectors.
Now compare the maximum - minimum values for the X, Y and Z accelerometers.  These 3 values should be the same.  If not, find a value to multiply the smallest of the three such that it matches the middle value and incorporate that value into your program. Repeat this for the largest of the three values.
It is desired all 3 accelerometers work the same.  If they do not, using the values derived above should adjust the raw values such as the result appears as 3 nearly identical accelerometers.
That said, most accelerometers are very usable with no correction factors.  And it is expected any correction factors to be small.  However, as experienced, when integrating, small errors can accumulate quickly.
Next consider the application in which dead reckoning is to be used.  There may be clues as to the velocity at a given moment which, if used, can reset the assumed velocity to a known value.  For example, if the accelerometer were attached to a runner's foot, it can be assumed the velocity is zero for each foot to ground impact detected.

How would I find the ranges for the accelerometers?

I added a procedure to the answer.


text:
Arduino clone woks only with USB - NOT with external power
I have an Arduino UNO ch430 clone. It works with USB power supply, I can upload a Sketch and it works just fine. With external power supply, doesn't work. What do I mean? No LED lights up, high pins output  ~ 0V. I'm using that barrel jack plug with 9V (6 x 1,5V batteries). Input voltage is measured OK. The AMS1117 regulator has Vin pin = Vout pin; i mean it gets no input Voltage. On the other hand, the M7F rectifier diode that comes between the jack and the regulator takes all voltage. I don't understan why, given that the anode is at higher voltage than the cathode (+9V). It shouldn't block current flow.
I tried jumping the rectifier and getting the jack +pin directly to the Vin at the regulator: current starts to flow, but apparently so much that the ams1117 heats a lot and really fast. Well i don't know why it suddendly gets so much current, I have absolutely nothing pluged to the board and I couldn't find any stain or damaged spot on it.
I can't figure out what is happening. I hope you can help me, and thanks in advance.

This is an exact (i'm pretty sure) schematic of my board.
Link

What kind of batteries? Good quality rechargeable batteries can supply enough current to blow a diode or even to melt wires.

It sounds like there's some form of short, or the AM1117 regulator is dead. Too much current being drawn by the regulator (as it gets so hot) has caused the diode to blow.
You will need to replace both the regulator and the diode and hope it works - or use a separate external regulator into the 5V pin instead.
Personally, I'd use a switch-mode regulator (UBEC regulators are cheap and easy to get hold of) since it is far more efficient than the LM1117.


text:
How to give an analog output of 0-5V
I'm trying to program an Arduino to control a motor at different intensities by giving a 0-5V reference value from the board. I have some programming experience, but have very little knowledge of manipulating an Arduino or about electricity. As I understand from reading this, I need to call the AnalogWrite function to output the signal, but how do I do this? How can I control when the voltage (and by extension, the motor intensity) is increased or decreased. Is it possible to do this without additional hardware?
Any help is much appreciated, it doesn't have to be code. I mostly want to understand how to use the Arduino, but code would also help a lot with that. I'm using an Arduino Due, which as I understand, has true analog out.

What is the motor you are trying to control?

I'll do my best to describe it, but essentially it is a robot that has a series of pressure regulators that supply air to pneumatic tubes in a mesh that act like muscles when pressurized. The regulators control which group gets pressure. The arduino will not be powering the motor, simply controlling the level of pressure the "muscles" are getting from intensities 0-5 based on what the board is outputting. I realize that's a bit different from what I wrote in the OP, but I explained it that way for simplicity.

The actual hardware used matters in this case. If the pressure regulator is only getting a "signal" and not drawing it's operating current from the Arduino, then you may not need to fool with MOSFETs. But it depends a great deal on the actual item the Arduino is connected to. Would you be able to provide a link to a datasheet for the pressure regulator or whatever device the Arduino would be connected to? It might also be that the device really requires a true Analog signal and not a PWM average voltage.

https://create.arduino.cc/projecthub/ArduPic/how-to-modify-analog-output-range-of-arduino-due-6edfb5

Why do you want true DAC? PWM can be amplified with MOSFET. For analog you need a voltage convertor.

You would indeed need to use analogWrite to send a PWM signal to the motor. PWM will turn on and off the power to the pin really fast. In effect powering the motor with pulses. The length of these pulses will determine how much power the motor receives.
The DUE also has a true analog output, but you don't want to use that for motors. The use of the word analogWrite is a bit misleading when it's used for generating a PWM signal.
analogWrite will ask for a value between 0 and 255 to indicate the pulse length. 0 is OFF, 255 is full ON, 127 is ON for 50% of the time.
Also note that most motors require more current that the Arduino pins can provide, so you need to use a transistor/mosfet to "amplify" the signal to a higher current.

So is there a way I can control the voltage output rather than pulse length?

@Gerben correct,  I missed the Due tag.

not only to amplify the current, but to go to 5 V

@Nyra why would you want to? Like I said; for a motor you’d want to use PWM instead.

You can't do it without additional hardware because Due output is max 3.3 V. You need to amplify PWM or the analog output. PWM can be amplified using a MOSFET. If you are new to electronics I would recommend Grove MOSFET module. I use it to amplify PWM of M0 to 5 V.
It is normal to use PWM for regulation. True analog output is used for sound and similar waves. If you really need true analog value to 5 V with Due, you must use a voltage converter like in the tutorial linked by Majenko in comments.
The Arduino core handles the DAC of the SAMD boards with analogWrite() too.
Quote from the analogWrite reference:

The Arduino DUE supports analogWrite() on pins 2 through 13, plus pins
  DAC0 and DAC1. Unlike the PWM pins, DAC0 and DAC1 are Digital to
  Analog converters, and act as true analog outputs.

And you can set the resolution with analogWriteResolution():

By setting the write resolution to 12, you can use analogWrite() with
  values between 0 and 4095 to exploit the full DAC resolution.


text:
Neo 6M GPS Module does not work properly inside own sketch
I am doing a project right now that involves a Neo 6M GPS module, a micro sd card module and 6 BH1750 light sensors. All the modules work fine when testing them standalone, especially the GPS module works as it should with TinyGPS++ example sketches.
When i run the "DeviceExample" sketch, it takes around 6 seconds to revieve time and around 10 seconds to recieve the location. However in my own sketch it only updates time every 3 or more seconds as well as i think it also updates location very slow.
Sometimes it even works for a short time, sometimes it never works, no matter how long the sketch runs.
Here is an example log:
As you can see, the sketch did not retrieve full date 20 secs after starting, but time is updating every second. Yet you can see that the time isn't updated anymore 5 seconds before the module is retrieving location and then the update interval gets slowed down, even though the module itself still indicates the update interval of around .5-1 second.
The Neo 6M GPS module is connected directly to RX,TX,GND,VCC and works fine with the example sketches. Has anybody a solution to this?
ms(), longitude, latitude,month,day,year,hour,min,sec,centisecs,alt,6 lux values
17642, 0.000000, 0.000000,0,0,2000,22,26,13,95,0.00,106,106,6,0,3,106,
17980, 0.000000, 0.000000,0,0,2000,22,26,13,95,0.00,106,106,6,0,3,106,
18333, 0.000000, 0.000000,0,0,2000,22,26,13,95,0.00,106,106,6,0,3,106,
18803, 0.000000, 0.000000,0,0,2000,22,26,14,95,0.00,106,106,6,0,3,93,
19131, 0.000000, 0.000000,0,0,2000,22,26,14,95,0.00,33,33,6,0,3,0,
19530, 0.000000, 0.000000,0,0,2000,22,26,14,95,0.00,0,0,6,0,3,40,
19956, 0.000000, 0.000000,0,0,2000,22,26,15,95,0.00,106,106,6,0,3,106,
20311, 0.000000, 0.000000,0,0,2000,22,26,15,95,0.00,106,106,6,0,3,106,
20787, 0.000000, 0.000000,0,0,2000,22,26,16,95,0.00,106,106,6,0,3,106,
21114, 0.000000, 0.000000,0,0,2000,22,26,16,95,0.00,106,106,6,0,3,106,
21504, 0.000000, 0.000000,0,0,2000,22,26,16,95,0.00,106,106,6,0,3,106,
21942, 0.000000, 0.000000,0,0,2000,22,26,17,95,0.00,106,106,6,0,3,106,
22292, 0.000000, 0.000000,0,0,2000,22,26,17,95,0.00,106,106,6,0,3,106,

...
240540, 0.000000, 0.000000,10,14,2018,22,29,56,95,0.00,106,106,6,0,3,106,
240869, 0.000000, 0.000000,10,14,2018,22,29,56,95,0.00,106,106,6,0,3,106,
241249, 0.000000, 0.000000,10,14,2018,22,29,56,95,0.00,106,106,6,0,3,106,
241697, 0.000000, 0.000000,10,14,2018,22,29,57,95,0.00,106,106,6,0,3,106,
242035, 0.000000, 0.000000,10,14,2018,22,29,57,95,0.00,106,106,6,0,3,106,
242531, 0.000000, 0.000000,10,14,2018,22,29,58,95,0.00,109,109,6,0,3,106,
242859, 0.000000, 0.000000,10,14,2018,22,29,58,95,0.00,106,106,6,0,3,106,
243238, 0.000000, 0.000000,10,14,2018,22,29,58,95,0.00,106,106,6,0,3,106,
243687, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
244016, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
244425, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
244892, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
245260, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
245754, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
246083, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
246494, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,109,6,0,3,106,
246947, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,109,109,6,0,3,106,
247320, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
247820, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,109,106,6,0,3,106,
248160, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
248676, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
249027, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
249425, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,106,6,0,3,106,
249889, 0.000000, 0.000000,10,14,2018,22,29,59,95,0.00,106,109,6,0,3,106,
250253,xxxxx,xxxxx,10,14,2018,22,30,6,0,0.00,106,106,6,0,3,106,
250768,xxxxx,xxxxx,10,14,2018,22,30,6,0,0.00,106,106,6,0,3,106,
251097,xxxxx,xxxxx,10,14,2018,22,30,6,0,0.00,106,106,6,0,3,106,
251608,xxxxx,xxxxx,10,14,2018,22,30,8,0,646.30,109,106,6,0,3,106,
252021,xxxxx,xxxxx,10,14,2018,22,30,8,0,646.30,106,106,6,0,3,106,
252412,xxxxx,xxxxx,10,14,2018,22,30,8,0,646.30,106,106,6,0,3,106,
252883,xxxxx,xxxxx,10,14,2018,22,30,8,0,646.30,109,106,6,0,3,106,
253248,xxxxx,xxxxx,10,14,2018,22,30,8,0,646.30,106,106,6,0,3,106,
253765,xxxxx,xxxxx,10,14,2018,22,30,8,0,646.30,106,106,6,0,3,106,
254094,xxxxx,xxxxx,10,14,2018,22,30,8,0,646.30,106,106,6,0,3,106,
254608,xxxxx,xxxxx,10,14,2018,22,30,11,0,646.30,106,109,6,0,3,106,
255020,xxxxx,xxxxx,10,14,2018,22,30,11,0,646.30,106,106,6,0,3,106,
255412,xxxxx,xxxxx,10,14,2018,22,30,11,0,646.30,106,106,6,0,3,106,
255882,xxxxx,xxxxx,10,14,2018,22,30,11,0,646.30,106,106,6,0,3,106,

Here is the sketch:
////
//initialising constants
static const  int out_min = 5;
static const  int out_max = 10;
static
const uint8_t RXPin = 0,
              TXPin = 1;
static
const uint16_t GPSBaud = 9600;
static
const uint16_t chipSelect = 4;
//initialising Objects
SoftwareSerial ss(RXPin, TXPin);
TinyGPSPlus gps;

BH1750 active_sensor(0x23); // We will use this adress for stating the active sensor
BH1750 inactive_sensor(0x5C);
SdFat sd;
SdFile file;

//initialising variables for collecting data
float lng_;
float lat_;

String month_ = "";
String day_ = "";
String year_ = "";

uint16_t lux_ = 0;
uint8_t hour_ = 0;
uint8_t min_ = 0;
uint8_t second_ = 0;
uint8_t centisecond_ = 0;
float altitude_ = 0;

unsigned long runtime_ = 0;

uint16_t values[6];
char buf[6];
char data_buffer[12];
char fileName[13] = FILE_BASE_NAME "00.csv";
uint8_t lines = 0;

void setup() {
  digitalWrite(2, HIGH);
  pinMode(2, INPUT);
  Serial.begin(115200);
  Wire.begin();

  pinMode(3, OUTPUT);
  digitalWrite(3, LOW);

  for (int i = out_min; i <= out_max; i++)
  {
    pinMode(i, OUTPUT);
    digitalWrite(i, LOW);
  }

  ss.begin(GPSBaud);

  if (active_sensor.begin(BH1750::CONTINUOUS_HIGH_RES_MODE)) {
   Serial.println(F("BH1750 Advanced begin"));
  } else {
    Serial.println(F("Error initialising BH1750"));
  }
}

void(* resetFunc) (void) = 0;
void loop() {

  while (ss.available() > 0)
    if (gps.encode(ss.read())) {
      digitalWrite(3, HIGH);
    }
  if (millis() > 5000 && gps.charsProcessed() < 10) {
    while (true);
  }
  if (gps.location.isValid()) {
    lat_ = gps.location.lat();
    lng_ = gps.location.lng();
  }

  if (gps.date.isValid()) {
    day_ = gps.date.day();
    month_ = gps.date.month();
    year_ = gps.date.year();
  }

  if (gps.time.isValid()) {
    hour_ = gps.time.hour();
    min_ = gps.time.minute();
    second_ = gps.time.second();
    centisecond_ = gps.time.centisecond();
    altitude_ = gps.altitude.meters();
  }

  int i;
  for (i = 5; i <= 10; i++) {
    digitalWrite(i, LOW);
    switch (i) {
      case 7:
        active_sensor.begin(BH1750::CONTINUOUS_HIGH_RES_MODE);
      case 8:
        active_sensor.begin(BH1750::CONTINUOUS_HIGH_RES_MODE);
      case 9:
        active_sensor.begin(BH1750::CONTINUOUS_HIGH_RES_MODE_2);
      case 10:
        active_sensor.begin(BH1750::CONTINUOUS_HIGH_RES_MODE_2);
      case 5:
        active_sensor.begin(BH1750::CONTINUOUS_LOW_RES_MODE);
      case 6:
        active_sensor.begin(BH1750::CONTINUOUS_LOW_RES_MODE);
    }
    delay(15);
    lux_ = active_sensor.readLightLevel();
    values[i - 5] = lux_;
    digitalWrite(i, HIGH);
  }
  delay(10);
  digitalWrite(3, LOW);
  delay(5);
  file.print(millis());
  file.write(',');
  dtostrf(lng_, 9, 6, data_buffer);
  file.print(data_buffer);
  file.write(',');
  dtostrf(lat_, 9, 6, data_buffer);
  file.print(data_buffer);
  file.write(',');

  file.print(month_);
  file.write(',');
  file.print(day_);
  file.write(',');
  file.print(year_);
  file.write(',');

  file.print(hour_);
  file.write(',');
  file.print(min_);
  file.write(',');
  file.print(second_);
  file.write(',');
  file.print(centisecond_);
  file.write(',');
  file.print(altitude_);
  file.write(',');

  for (int i = 0; i <= 5; i++) {
    file.print(values[i]);
    file.write(',');
  }
  file.println();
  lines++;

  int state = digitalRead(2);

}

Example Output:

You can't (and certainly shouldn't ever even try to) use SoftwareSerial on pins 0 and 1. Not when you're using Serial, since they are the same pins.
Pick a different pair of pins for your GPS connection.

But Pin 0 and 1 are the only Serial Pins on the arduino nano i use. Could i instead just remove all Serial functions? (Yet i think, i already tried that and it did not help)

The whole point of SoftwareSerial is that it doesn't use the serial pins.

I just had to look that up, since i never heard about that before. So i tried and even without using Serial it does not work. Why would all the internet still use the standard RX and TX pins, if they also use the SoftwareSerial library...

Just use different pins for SoftwareSerial. The point behind it is, that you can use it, if you need more serial interfaces, than the board already has. Serial is the Hardware serial interface and it's definitely better than SoftwareSerial, which has some serious limitations. You are using it because you don't have a second hardware serial on an Arduino UNO.

@Th3Fi3nD Because once upon a time some idiot without a clue did it, and then another idiot without a clue copied him. And then more idiots without a clue copied those, and since the internet is peopled by idiots without clues it rapidly became the norm. Now whenever anyone looks for example code they get a derivative of that original clueless idiot's code.  I wish it were like a vampire - then I could hunt down the original and kill it and all the descendants would revert to good code - but alas it isn't....

I see^^ This is commonly when trying to get help for arduino stuff. Anyways, i will try this out and let you know if it works.

So this does not help at all. It still takes several seconds to update...


text:
ESP32 playing wav sounds distorted or too fast (but not all wav's)
I am building a sound project on an ESP 32 via I2S  using an example from:
https://github.com/nhatuan84/esp32-i2s-sdcard-wav-player
It works fine with the example wav file t.wav posted in the repository.
But when I try to use a custom wav which I exported from audacity it sounds distorted  and/or too slow/fast (it sounds fine when I play it within audacity).
This is an example that is totaly distorted when playing from the esp with I2S:
badly sounding wav
While it sounds fine when playing from audacity.
I tried different settings in audacity exporting 16 bit, 32 bit. 44100 Hz, 11025.
Any hints or tips what I could try or am doing wrong?
Thx!
Jeroen

The provided file from the repo is 16 bit mono with 11025 Hz. Have you tried these settings?

@crisl yes I did (at least I think I did but I am no expert on audacity...), it is this file: link 11025 file. This file is not distorted but plays too fast ( I think twice the speed)

@jstola. Not sure I understand what you propose. I created the wav file from https://text-to-speech-demo.ng.bluemix.net/. Then I opened it in audacity, converted it to several different sample frequencies exported the file to 16 bit pcm wav and put it on the sd. I just tried to copy the file back from the pc and play them and that works fine

sounds like maybe the data rate is too high, or low, depending on your perspective. i see the github file as a mono 32bit float at 11k. chances are, you just need to keep trying permutations of settings until you nail it.

I know this is an old question, but I ran into the same issue and spent days trying to figure it out, so I hope this answer can save another poor soul from that:
The Problem
For reference, I have an ESP32 (HUZZAH32 from Adafruit) hooked up to a breakout board that uses a PCM5102a chip as an external DAC. I would set the sample rate to 44.1khz but it seemed my song, which I confirmed had accurate data, would play at double speed. Lowering the sample rate to 22.05khz made it play at the correct speed, but quality seemed reduced.
The Root Cause
The issue was that my .channel_format value was set to I2S_CHANNEL_FMT_RIGHT_LEFT, however my data was mixed to mono in Audacity. This problem may exhibit itself differently depending on how you push bytes via I2S, but for me, this meant double speed. This is because the protocol was reading every 2 samples (which should be separate) as the left/right channels. Effectively, this meant that it was skipping every other sample, which doubled the playback speed.
Code Snippets
My i2s_config_t code:
#define DMA_BUFFER_COUNT 8
#define DMA_BUFFER_LENGTH 1024

i2s_config_t i2s_config = {
    .mode = I2S_MODE_MASTER | I2S_MODE_TX,
    .sample_rate = 44100,
    .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT,
    .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT, // this was causing double speed due to being I2S_CHANNEL_FMT_RIGHT_LEFT
    .communication_format = (i2s_comm_format_t) (I2S_COMM_FORMAT_I2S | I2S_COMM_FORMAT_I2S_MSB),
    .tx_desc_auto_clear = true,
    .dma_buf_count = DMA_BUFFER_COUNT,
    .dma_buf_len = DMA_BUFFER_LENGTH,
    .use_apll = false,
    .intr_alloc_flags = 0
};

My code for sending bytes to the external DAC (which is its own task):
(rx_buffer and readPointer here are part of a ring buffer that I streamed in over wifi on a separate task, please only use as reference and substitute for your own sound data)
int FRAMES_TO_SEND = 1024;
int32_t frames[FRAMES_TO_SEND];

for (int i = 0; i < FRAMES_TO_SEND; i++) {
    // copy into i2s buffer
    int32_t sample = (int32_t)rx_buffer[readPointer];

    // write bytes to the i2s peripheral
    esp_err_t err = i2s_write(i2s_num, (char *) &sample,
        sizeof(int32_t), &bytesWritten, 100);

    if(err != ESP_OK) {
        printf("ESP32 i2s Errorcode %i", err);
    }

    readPointer++;
    if (readPointer == TOTAL_BUFFER_SIZE) {
        readPointer = 0;
    }
}

Hopefully this helps out some of you, or at least get you on track to the solution. Unfortunately, the I2S protocol on the ESP32 is not very well documented so there's a lot of trial and error to be had. Keep at it!


text:
How to measure nitrogen flow through a tube?
I am looking for a simple way to detect nitrogen gas flow through a tube. I don't even need any sort of precision, just really need to know if flow exists or not.
What are some options I could pursue to easily measure this with the arduino?

Something like this might work. Though it is made for liquids, so might not work great for gasses. Especially if there isn't a lot of gas flow.

@Gerben I've seen a lot of that on Google as well, but I'm afraid that they won't work at all for gases. But for my purposes, as long as I get any indication of flow, its good. Maybe if I find a water flowmeter with enough flow rate?

What you are looking for is a mass flow sensor (MAF), or something along those lines as you mention wanting to know if there is flow, this gives you the 'speed' of the flow. There are various types available according to size, flow rate, type of element, and accuracy. Just search for mass flow sensor, you can even hack them off cars.
If you just want to detect only the presence of the N2 as you say then you can split your pipe somewhere,and then add a T-piece to that. You then put a gas sensor in the T part, and seal it off so there is no leaks. You would then hook that up to the Arduino board and interpret the signal.
Can't recommend any specific sensors though.
Here is an image for the idea:

You can use a pressure sensor for gas and measure the pressure differential between two points and if there is a large pressure differential then you know a flow exists.

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


text:
Serial monitor listing unreadable characters

My Serial Monitor is displaying unreadable characters.  If anybody can give me some insight on why this would be happening please let me know.
Thank You.

It greatly helps to post the code as text (copy from IDE, paste here) - that way people can copy/paste it into their own IDE for testing. What you have done forces people to read from your image, and retype. Please format the code using the code formatting markdown (four leading spaces). For help see Markdown help. You should be able to do this by selecting the code and pressing Ctrl+K to have your browser do this for you.

I changed from 9600 to Serial.begin(115200) and matched the serial monitor to 115200 and it worked. Went back to 9600 and back to same error. Interesting to know wht

Change Serial.write to Serial.print (or Serial.println).
write writes in binary, which gives you unprintable characters.

I am facing same issue https://arduino.stackexchange.com/questions/38289/at-commands-is-sending-response-in-square-box-on-serial-monitor can you help me what I am doing wrong

I changed Serial.print as well but no success

Make sure the selected baud (like 115200, 57600) in Serial Monitor matched the one specified in code like Serial.begin(115200)

This is sound general advice, however the image in the question clearly shows that the baud rates match.

I had the same problem, baud rate was the same in the code as it was in the serial monitor. I tried changing the baud rate in the code to 19200 and the same in the serial terminal and that fixed the problem. Hope this helps, not sure why it wasn't working with the 9600 baud value. Also found that clicking on the wrong baud rate in the terminal and back on the right one fixed the issue with it displaying gibberish.

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


text:
Arduino to breadboard with LM35 temp sensor
I have moved the MCU of the Arduino to a breadboard using these steps https://www.arduino.cc/en/Main/Standalone then interfaced it with an LM35 temperature sensor to the ADC0. But I can't get proper values from the LM35. I think it's because of the Aref or AVcc. Both are just connected to +5?
Here is my code:
float tempC;
float reading;

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

void loop()
{
    reading = analogRead(0);
    tempC = (reading * 0.4882815) + 5;
    Serial.print(tempC);
    delay(1000);
}

I get hex values and sometime high values. What to do with Aref and AVcc?
EDIT: I get values like these
€
Œ

Hex values? Can you copy and paste some of them into your question please?

I get values like €
Œ

Well, that isn't hex, that's mumbo-jumbo. I suspect you are not operating at the correct clock rate. Do you have a crystal on your breadboard? If so what frequency is it? If not, how do you have the fuses configured?

Yes I have a crystal. It says 22.000C16 at the top. I thought I bought a 16MHz oscillator. Now I'm doubting. So you think it's the crystal oscillator's fault?

Well, if it worked on the Arduino board, but not on your breadboard. Make a simple test, like flashing an LED every ten seconds. Time how quickly it flashes on your breadboard.

Okay so I tried a simple flashing LED every second. And clearly it's not flashing every second. So the problem is the oscillator hmm? I'll buy a new one later and test it again to see if the problem persists. Thank you Nick

For what it is worth, with the clock rate wrong, you baud rate may also be wrong.

Also why the +5 in your calculation? Make tempC and reading ints as well

I haven't bought any 16 MHz crystal. What will I do? :(

You can configure the fuses to work from the 8 MHz internal oscillator, and then if you compile for 8 MHz Lilypad, that should give you the right baud rate.

clearly it's not flashing every second.

Is it flashing about every .73 seconds? That would be the period you'd expect if you have a 22.000MHz crystal: period = (16/22 * 1.00 sec). (If so, that is a rather high over-clock rate for the chip but suggests just how hardy they really are.)

I haven't bought any 16 MHz crystal. What will I do?

Buy a 16MHz crystal. That's the right fix. But you might (if I guessed correctly that you have a 22MHz crystal) - might - get away with trying a baud rate of (16/22) times your present baud rate, de-rating it to compensate for the clock rate. Be as precise as you can. You'll need to reprogram the chip with your Arduino board because the chip's bootloader expects a 16MHz clock.
Or, if it's not 22MHz, you could time a number of blinks (50 or 100), calculate the clock rate error, and re-calculate a baud rate the way I did above. Use a lower baud rate to start with; it is likely to be less affected by small timing errors.

Check the baud rate of your serial monitor matches what you have set in your setup() function.  In the above code that is 9600.  If the baud rate is incorrect you typically get rubbish output in the serial monitor.

You may also want to change the Serial.print(tempC) to
Serial.println(tempC,2);

To get some decimal places.
As for the circuit ~

You don't need ARef connected.
The LM35 VCC should be connected to Arduino 5V
The LM35 GND to Arduino Gnd (any of them)
Finally LM35 signal (Vout) to Arduino A0.

Thanks for answering but my baud rate is correct and adding ",2" did not help :(

Hanging ARef didn't change anything. The next three steps I did already. Nothing changed

@user5434720 - Your circuit looks like the diagram right?

No sir since I moved the MCU to a breadboard. I'm not using the Arduino board anymore


text:
Esp8266 WebServer crashes when I use PracticalCrypto library! why?
So here is my code, Its the simple_server example from ESPAsyncWebServer.h and encryption example from PracticalCrypto.h combined.
the webserver works fine and I can see the / page, but the moment I open the /get page, where the code for encryption exmple is, esp8266 crashes. I tried removing  while (1) yield(); but the problrm is persistent. Is PracticalCrypto  too much for esp8266? So why is this happening?
#include <Arduino.h>
#ifdef ESP32
#include <WiFi.h>
#include <AsyncTCP.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#endif
#include <ESPAsyncWebServer.h>
#include <Arduino.h>
#include <PracticalCrypto.h>

PracticalCrypto crypto;
AsyncWebServer server(80);

const char* ssid = "123456789";
const char* password = "123456789";

const char* PARAM_MESSAGE = "message";

void notFound(AsyncWebServerRequest *request) {
    request->send(404, "text/plain", "Not found");
}

void setup() {

    Serial.begin(115200);
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);
    if (WiFi.waitForConnectResult() != WL_CONNECTED) {
        Serial.printf("WiFi Failed!\n");
        return;
    }

    Serial.print("IP Address: ");
    Serial.println(WiFi.localIP());

    server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
        request->send(200, "text/plain", "Hello, world");
    });

    // Send a GET request to <IP>/get?message=<message>
    server.on("/get", HTTP_GET, [] (AsyncWebServerRequest *request) {
        String message;
        if (request->hasParam(PARAM_MESSAGE)) {
            message = request->getParam(PARAM_MESSAGE)->value();
        } else {
            message = "No message sent";
        }
String key = crypto.generateKey();
           crypto.setKey(key);

    // let's make sure the key was set.
    // if the key is empty, it's likely your key doesn't have the right length
    key = crypto.getKey();
    Serial.printf("\nEncryption key: %s\n", key.c_str());

    String plaintext = "hello world!";
    Serial.printf("Plaintext: '%s'\n", plaintext.c_str());

    String ciphertext = crypto.encrypt(plaintext);

    if (ciphertext.length() == 0) {
        Serial.printf("Encryption failed (status %d)\n", crypto.lastStatus());
        while (1) yield();
    }

    Serial.printf("Ciphertext: '%s'\n", ciphertext.c_str());
        request->send(200, "text/plain", "Hello, GET: " + message);
    });

    // Send a POST request to <IP>/post with a form field message set to <message>
    server.on("/post", HTTP_POST, [](AsyncWebServerRequest *request){
        String message;
        if (request->hasParam(PARAM_MESSAGE, true)) {
            message = request->getParam(PARAM_MESSAGE, true)->value();
        } else {
            message = "No message sent";
        }
        request->send(200, "text/plain", "Hello, POST: " + message);
    });

    server.onNotFound(notFound);

    server.begin();
}

void loop() {
}

Here last prints before crash
23:02:10.050 -> Encryption key: E*o24<7c%J3Ss1Qk=7*_.c/Y3wIi']Er sjaSE8KyxX)*XqROj)X#$7+\tvhv Q/
23:02:10.050 -> Plaintext: 'hello world!'
23:02:10.050 ->
23:02:10.050 -> User exception (panic/abort/assert)
23:02:10.050 -> --------------- CUT HERE FOR EXCEPTION DECODER ---------------
23:02:10.050 ->
23:02:10.050 -> Panic core_esp8266_main.cpp:191 __yield


text:
How to refresh an iframe in a page made with Espasyncwebserver
So, I have this page on esp8266:
  controlserver.on("/UDEL", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(200, "text/html", htmltd);
  });

htmltd  is a string, generated by a function and it contains some forms, and they run in iframe tag,
<FORM action="/process" method="post" id="config" target="iframe">

</form>

and processed by:
controlserver.on("/process", HTTP_POST, [](AsyncWebServerRequest *request) {
.
.
.
request->send(200, "text/html", HTML_CSS_STYLING + "");
.
.
.
});

They work perfectly fine, and after clicking on submit button the page shows an alert, and it must be reloaded, because the submitted form must be removed from the page. it happens when I reload the page manually. but I want it to happen automatically after each form submission. it tried many ways like :
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>Reload iFrame</title>

  <input onclick="reloadIframe()"  type="button" value="Click me">

but it doesn't work in esp8266.

it doesn't work ... that is an extremely vague description of an observed behavior .... what exactly happens? ... please update your question ... do not add information in comments

form must be removed from the page ... why don't you simply hide it? ... page reload would not be necessary

here is an example of updating a web page without a reload
https://projecthub.arduino.cc/donskytech/nodemcu-esp8266-ajax-enabled-web-server-928fa0

@jsotola yeah you are right, I was working on this all day, I was a little tired. nothing happens when I tried the described method. My project is kind of big and there are many forms in this page, so I wanted to save some space. thank you, I'll look, into it.

your main page could be just skeleton html that uses XHR to load each form as needed ...

From my understanding, your intention is to automatically reload the main page (which contains the form and the iframe) after submitting the form. but the challenge is that the form submits inside the iframe so when you send a response to the iframe, it won't directly impact the main page.
I believe you could use a small trick to work this problem around.
1- After successfully processing the form data inside the iframe, send back a script that communicates with the parent window (the main page) and instructs it to reload
2- In the main page, listen to the received message and then reload.
Here is how to implement the proposed solution:
On your ESP8266 route handler, send a script in the response to post a message to the parent window after processing the form:
controlserver.on("/process", HTTP_POST, [](AsyncWebServerRequest *request) {
    //add your processing code
    String response = HTML_CSS_STYLING +
                      "";
    request->send(200, "text/html", response);
});

window.parent.postMessage will send "reloadPage" string from iframe to parent window. And on your main page (the page that contains the iframe), listen for this message and reload the entire page when the message is received:
<FORM action="/process" method="post" id="config" target="iframe">

</form>

Btw instead of using an iframe, you could use AJAX to submit the form so that you get a response directly from the server and refresh the page using location.reload(). This way you can submit form data (or retrieve data) without refreshing the entire page. Only the necessary parts of the page updates.
I hope that this helps, if not, please inform me.

Thank you soooooo much it worked like a charm! I know nothing about the AJAX :) Basically I started html like 2 weeks ago ;)

I am glad to hear that it worked for u, AJAX is used for asynchronous web applications but don't rush it. You will eventually learn about it. Have a nice day, coding!


text:
Problem installing RPLidar library
I'm trying to add the RPLidar library. I've already checked this solution, but it's not working for me, I get this error :
Error: 13 INTERNAL: Library install failed: extracting archive: Not a supported archive
Do you have a solution ?

Are you trying to install this library through the Arduino IDE? Then maybe it doesn't work, because this library doesn't conform to the normal library structure for Arduino.
You can install it manually.

Download the library from Github

either by downloading the ZIP-file and extracting it
or by using git clone on your machine, if you have git installed.

Move the folder RPLidarDriver into the libraries folder. You can normally find this in Arduino/libraries in your home directory. If you cannot find it, look in the Arduino IDE in the preferences dialog. There the sketchbook location should be mentioned. libraries is a folder inside the sketchbook location.

Then you should be able to compile your code. I've tested this with the examples provided by the library.


text:
How to make a stepper motor's speed follow a sine wave
I'm trying to have the rotational speed of a stepper follow that of a sine wave with a period of x seconds. So it starts at a speed of 0 at 0°, picks up and peaks at 90°, slows back down to 0 at 180°, back up to peak speed at 270°, and back to 0 at 360°, if that makes sense. I'm trying to have the period of the rotation adjustable as well.
Right now I'm having trouble even getting it to spin with what I have now. if I start at 0 speed it doesn't step and therefore doesn't continue with the sketch, or at least I think that's what's happening. Any advice on how to do this would be appreciated.
I'm using the equation (topSpeed) * sin((pi * time) / period) for the wave.
#include <Stepper.h>

const int stepsPerRevolution = 200.000;
const float pi = 3.14159265358979;
const int period = 5; // Seconds
const int topSpeed = 100; // RPM

Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

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

void loop() {
  for (int tStart = millis(); (millis()-tStart) < period;) {
    float speed = topSpeed * (sin((pi * (millis() / 1000.000)) / period));

    if (speed = 0) {
      myStepper.setSpeed(1);
      myStepper.step(1);
    } else {
      myStepper.setSpeed(speed);
      myStepper.step(1);
    }
  }
}

Checking for equality in an if statement needs ==, not =, which is a  assignment

Disclaimer: This is not intended to be a complete answer, it is only
meant to help you with the math.
I find a contradiction in the problem statement:

it starts at a speed of 0 at 0°, picks up and peaks at 90°, slows back
down to 0 at 180° [...]

If the speed is a sinusoidal function, then at this point you have
completed the positive part of the period. The speed will now become
negative (i.e. the stepper will move backwards), and remain negative for
the second half of the period.

back up to peak speed at 270°, and back to 0 at 360°

No. It will reach peak (negative) speed at 90°, and back to zero speed
at 0°.
If you really want the stepper to turn always in the same direction, the
speed cannot be sinusoidal. What you can do instead is use a sinusoidal
function with an offset, such that the speed fluctuates between zero
and some maximum, instead of fluctuating between ±maximum.
The graph below represents speed as a function of time. The first curve
(“sine”) is a movement that rocks back and forth like: 0° → 90° → 180° →
90° → 0°. The “shifted sine” curve is a continuous rotation doing a full
revolution with a speed that is always non-negative.

If you want to properly describe the movement, you should integrate the
speed in order to find the (angular) position as a function of time. You
will find a continuous ramp (because of the shift in the speed)
superimposed with a sinusoidal movement, as in this graph:

If that may help, I did the integration for you and found this formula:
angle = 360° × (t/T − sin(4πt/T)/(4π))
where t is the current time and T the rotational period. This can then
be differentiated to get the speed:
speed = 360°/T × (1 − cos(4πt/T))


text:
Fail to discard the character T from my transmitter Arduino
I wrote code for my transmitter Arduino. I want to send the data to the receiver Arduino through Tx and Rx serial.
The issue is that I could not discard the char "T" and it appears as output value on pin 9 or 10 or 3.
This is the transmitter and receiver code. I only need my receiver code to be modified.
Transmitter code :
char HEADER_BYTE = 'T';  // Character header

#define potPin1 A1  // Potentiometer 1 pin
#define potPin2 A2  // Potentiometer 2 pin
#define potPin3 A4  // Potentiometer 3 pin

void setup() {
  Serial.begin(9600); // Set baud rate for serial communication
  Serial1.begin(9600);
}

void loop() {
  int servo1Angle = map(analogRead(potPin1), 0, 1023, 0, 180); // Map potentiometer reading to servo angle range
  int servo2Angle = map(analogRead(potPin2), 0, 1023, 0, 180); // Map potentiometer reading to servo angle range
  int motorSpeed = map(analogRead(potPin3), 0, 1023, 0, 250); // Map potentiometer reading to motor speed range (adjust based on driver)

  // delay(1);
  Serial1.write(HEADER_BYTE);  // Send header character
  Serial.println(HEADER_BYTE);
  Serial1.write(servo1Angle); // Send servo 1 angle
  Serial.println(servo1Angle);
  Serial1.write(servo2Angle); // Send servo 2 angle
  Serial.println(servo2Angle);
  Serial1.write(motorSpeed);  // Send motor speed
  Serial.println(motorSpeed);

  delay(10);
}

Receiver code:
#include <Servo.h>

Servo myservo1;
Servo myservo2;
int pot_pin = 3;

void setup() {
  Serial.begin(9600);  // Start serial communication
  Serial1.begin(9600);

  pinMode(pot_pin,OUTPUT);
  myservo1.attach(9);
  myservo2.attach(10);
  // myservo.write(90);  // set servo to mid-point
}

void loop() {
  if (Serial1.available() >= 4) {
    if (Serial1.peek() == 'T') {
      Serial1.read();  // Discard the 'T' character
    }
    int incomingByte = Serial1.read();

    // switch (incomingByte) {
    //  case 84:
    int pot1 = Serial1.read();
    int pot2 = Serial1.read();
    int pot3 = Serial1.read();

    myservo1.write(pot1);
    Serial.print(pot1);
    Serial.print("   ");
    myservo2.write(pot2);
    Serial.print(pot2);
    Serial.print("   ");
    analogWrite(pot3,3);
    Serial.print(pot3);
    Serial.println("  ");
    //  break;
    //}
  }
}

you don't wait for a T, you just assume that it will be the first character

I see two issues here.
First, T is not a very good choice for a header. You are using a
binary protocol (because of Serial.write()), sending bytes with
numeric values between 0 and 250. The constant 'T' actually means 84
(the ASCII code for the uppercase letter T), and this value can appear
within the actual data. If you want to frame your messages with a header
byte, I suggest you choose a byte that cannot be part of the body of the
message. E.g. 255.
Second, your logic for reading the message is wrong:
if (Serial1.peek() == 'T') {
    Serial1.read();  // Discard the 'T' character
}

You should ask yourself: what would this code do if the byte at the top
of the buffer is not 'T'? What should it do instead? I think the
right thing to do would be to discard all incoming bytes until it finds
the expected header.
int incomingByte = Serial1.read();

Why discard this byte? The header byte has already been discarded (if
present). Why discard the following byte? Doing so will reliably mess
your communication.
I suggest something along these lines:
void loop() {
  if (Serial1.available() >= 4) {
    if (Serial.read() == HEADER_BYTE) {
      int pot1 = Serial1.read();
      int pot2 = Serial1.read();
      int pot3 = Serial1.read();

      // ...
    }
  }
}

Here, if we expect the header byte and we get anything else, we just
discard the byte we got and move to the next loop() iteration. Next
time we have four byte in the serial input buffer, we try again.


text:
8relay module asks more than specs
I have a 8 relay module that should use not more than 20 mA per relay.
Altough when measuring it asks around 70.
If I use 6 relays, that would be more than an Arduino Mega can give.
(I already lost 1 arduino here.)
How this is possible..?

What are you measuring? The input pins will be the low current pins, however the power supply pins will take more (and you can power those without going through the arduino)

Someone told me to give 5v en GND to the relais module not from arduino but from another source. Will try that.

I don't see why and Arduino mega can't supply 420mA from the 5V pin. It's also below the USB limit of 500mA.

please add a link to where you bought the relay module .... also add the schematic of the connections between the arduino and the relay module

Hello Gerben, it should be indeed possible for the mega but in practice it seems that the relays are asking more than the specs are telling..
Jsotola: will look up the fritzing

@jsotola I've uploaded a fritzing. This is the version which doesn't work. It means, powering the 6 relays from the arduino.
There are signals coming from buttons that can put - if in the correct order - will cut of the power of the magnets which have external power.
The 8module relays says it doesn't need that much mA but in practice it is no solution. It keeps asking quite some mA.
Why it's not as the specs are telling?
It's this one: https://www.sainsmart.com/products/8-channel-5v-relay-module.
Should the module has external power too?

it is solved by giving the relay module power with external transfo. Not by arduino.

it is solved by giving the relay module power with external transfo. Not by arduino

Most of Arduino relay modules have a relay and a supporting circuit. The circuit connects the VCC line to relay coil if signal line is HIGH. Some relays have it conversely, they disconnect if signal is HIGH and hold the coil if signal is LOW.
Your relays need VCC which you can supply for 8 relays from 5 V pin of Arduino. This pin is connected over regulator to power supply of the board so it is limited only by power supply and regulator parameters. The power doesn't go over MCU.
The signal pins of individual relays should be connected to digital pins of Arduino. The signal pins don't draw much current since they only signal a state to the circuit of the relay module.


text:
Change operational mode of CAN transceiver
I have two MCP2515 stand-alone CAN controllers with SPI interface, two TJA1042 CAN transceivers and two Arduino Uno boards. As you may know TJA1042 have two operational modes:

Sleep mode
Normal mode.

If I want to change the mode of operation of one transceiver from sleep mode to normal mode(wake it up), I should send a wake up pattern waves from the other transceiver which is in normal mode. for example one of the wake up patterns is: 5.5 µS low, 5.5 µS high and again 5.5 µS low. Now I don't know how to send these patterns with Arduino because MCP2515 is SPI interface.
I use this library: MCP_CAN

Transmitting this "wake signal" does not "wake" the transceiver.  What it's actually doing is the transceiver, when in "standby" mode, only allows through signals that have a dominant or recessive state that is longer than the filter time (5.5µs). Any transitions in the bus after a stable period of 5.5µs or more will get passed through.
The transceiver does not enter "normal" mode at that point. It is down to the CAN device to activate the transceiver through setting the STB pin LOW.

When pin RXD goes LOW to signal a wake-up request, a transition to Normal mode will not be triggered until STB is forced LOW.

Exactly what you send is of no consequence to the transceiver - only whether it has D and R states that are longer than 5.5µS.  It's up to the CAN device to interpret them and know if it should wake up the transceiver and place it in NORMAL mode.
And the MCP2515 also doesn't care what it receives.  When the WAKEIE bit is set it will cause the MCP2515 itself to wake from its sleep mode when anything is received - at which point it signals to the Arduino through its INT pin that it's woken up.
However your chosen library has no ability included in it to control the WAKEIE bit of MCP_CANINTF - only the TXxIF bits are supported.  So you will have to expand the library to provide that facility.
The general idea of operation is:

The transceiver lets through a "slow" signal (like transmitting 0b00110011)
The MCP2515 receives "something"
INT pin goes LOW and the Arduino reacts to it
The Arduino drives STB LOW and reception can proceed normally.

Note that it is the Arduino that will be controlling STB, not the MCP2515.

Thanks for answering me. Actually I have some testcases that I should test each of them. In each of them the R or D duration is different, So it's easy for me to use digital write and delay functions of Arduino.Maybe it's a stupid question but, Can I use GPIO of MCP2515 for it?

There are two pins that can be controlled as outputs - and they are primarily designed to be IRQ pins to indicate the receive interrupts to the MCU. If you are using a shield with the transceiver already wired, then no you can't, since you can't control the TX and RX pins as GPIO. If it's not already wired and you're wiring it yourself, then why would you? Just wire it to the Arduino and don't use the MCP2515.

Thank you for helping me.Sorry for asking a lot of questions! Yes it becomes easy if I didn't use MCP2515, But I also have problem with baud rate of transceiver. When I don't use MCP2515 to set baud rate of CAN transceiver, bus signals aren't sharp enough. I don't use a shield and my mean of using GPIO was to send pulses using RXnBF pin of MCP2515. Is it possible?@Majenko


text:
Send data string from Arduino UNO to ESP8266-01
Is there anyway to send a string from an Arduino UNO to a ESP8266-01 (one with only 8 pins RX, TX, CH-PD, vcc, ground, reset, GPIO0, GPIO2) without using without using AT commands.  I've looked everywhere and from what I can see UART doesn't work and SoftwareSerial uses only AT commands.  I am at my wits end.  Can anyone help here? please.
I have tried Serial.write but only writes String and Esp8266 only receives ints.
I found some code I thought might work but so far I can see that the arduino is sending <100.00:200:00>, but on the esp8266 all I get is four backwards question marks
this is the code on the Arduino UNO
#include <SoftwareSerial.h>

SoftwareSerial ESPserial(2, 3); // TX | RX
 float water = 100.00;
 float battery = 200.00;
void setup()
{
    Serial.begin(9600);     // communication with the host computer
    //while (!Serial)   { ; }

    // Start the software serial for communication with the ESP8266
    ESPserial.begin(57600);

}

void loop()
{
   ESPserial.print("<");
          ESPserial.print(water,2);
          ESPserial.print(":");
          ESPserial.print(battery,2);
      ESPserial.print(">");
      Serial.print("<");
          Serial.print(water,2);
         Serial.print(":");
          Serial.print(battery,2);
      Serial.print(">");
     delay(10000);
}

and here is the code on the ESP8266
#include <SoftwareSerial.h>
#include <string.h>

SoftwareSerial ESPSerial(2,0);

const byte numChars = 32;
char receivedChars[numChars];
boolean newData = false;

String water;
String battery;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  ESPSerial.begin(57600);
  delay(10);

}

void loop() {
  // put your main code here, to run repeatedly:
  recvWithStartEndMarkers();
  showNewData();

 water= getValue(receivedChars, ':', 0);
  battery = getValue(receivedChars, ':', 1);
Serial.println(water);
}

void recvWithStartEndMarkers() {
    static boolean recvInProgress = false;
    static byte ndx = 0;
    char startMarker = '<';
    char endMarker = '>';
    char rc;

    while (ESPSerial.available() > 0 && newData == false) {
        rc = ESPSerial.read();

        if (recvInProgress == true) {
            if (rc != endMarker) {
                receivedChars[ndx] = rc;
                ndx++;
                if (ndx >= numChars) {
                    ndx = numChars - 1;
                }
            }
            else {
                receivedChars[ndx] = '\0'; // terminate the string
                recvInProgress = false;
                ndx = 0;
                newData = true;
            }
        }

        else if (rc == startMarker) {
            recvInProgress = true;
        }
    }

The Arduino sends writes every 10 seconds and the esp prints the ???? every 10 seconds but with a lag.
I am not sure what the pin out to pin in should be.  Right now I have the Arduino 2(TX) attached to the GPIO0 and the Arduino 3(RX) attached to the GPIO2.
Can someone look at my code and see what I am doing wrong.  I thought I would send over two values because eventually I want to show water level and battery level.

Why do you think UART doesn't work? UART is what I would suggest...

How do I do it.  I want to use Arduino IDE to upload but language I found didn't work.  Do I need a separate board.  Sorry

You just have to connect rx->tx/tx->rx and look for an example. There are many tutorials about serial communication between arduino and esp8266.

@user1114881 are you using End of Line and Carraige Return characters at the end of string you are sending?

Arduino 2(TX) attached to the GPIO0 and the Arduino 3(RX) attached to the GPIO2 nope, you have to connect Arduino-TX to Esp-RX and Arduino-RX to Esp-TX. At least the esp8266 has very limited possibilities on gpio0 and gpio2

how do I handle   SoftwareSerial ESPSerial(2,0); on ESP and SoftwareSerial ESPserial(2, 3); // TX | RX on the Arduino.  Do I just leave that part out or how do I assign them

I changed it to SoftwareSerial ESPSerial(1,3); on ESP and Software Serial ESPserial(0,1); on the Arduino and still all I get is ???? on the Serial Monitor 57600 baud

I may have found one glitch.  The code I found has #include <string.h> but there is no library string.h and I cannot find it on line.  Can you point me to a good example of what I want to accomplish.  Thanks for you help and patience.  by the way now under 57600 I get four 0s

I figured this out.
send code is
Arduino Uno side
 f = String('<')+String("Hi")+String(',')+String(waterSensorOutValue)+String(',')+String(sensorBatValue)+String('>');

    Serial.print(f);

ESP side
const byte numChars = 32; char receivedChars[numChars]; char tempChars[numChars];        // temporary array for use when parsing // variables to hold the parsed data char messageFromPC[numChars] = {0}; float floatFromPC = 0; float floatFromPC2 = 0; boolean newData = false; //end stuff ti bring in string String f;  long itt = 500;
    long itt2 = 500;

void loop() {

  //new stuff string recvWithStartEndMarkers();
    if (newData == true) {
        strcpy(tempChars, receivedChars);
            // this temporary copy is necessary to protect the original data
            //   because strtok() used in parseData() replaces the commas with \0
        parseData();
        showParsedData();
        newData = false;
    } }

void recvWithStartEndMarkers() {
    static boolean recvInProgress = false;
    static byte ndx = 0;
    char startMarker = '<';
    char endMarker = '>';
    char rc;

    while (Serial.available() > 0 && newData == false) {
        rc = Serial.read();

        if (recvInProgress == true) {
            if (rc != endMarker) {
                receivedChars[ndx] = rc;
                ndx++;
                if (ndx >= numChars) {
                    ndx = numChars - 1;
                }
            }
            else {
                receivedChars[ndx] = '\0'; // terminate the string
                recvInProgress = false;
                ndx = 0;
                newData = true;
            }
        }

        else if (rc == startMarker) {
            recvInProgress = true;
        }
    } }

//============

void parseData() {      // split the data into its parts

    char * strtokIndx; // this is used by strtok() as an index

    strtokIndx = strtok(tempChars,",");      // get the first part - the string
    strcpy(messageFromPC, strtokIndx); // copy it to messageFromPC

    strtokIndx = strtok(NULL, ","); // this continues where the previous call left off
    floatFromPC = atoi(strtokIndx);     // convert this part to an integer

    strtokIndx = strtok(NULL, ",");
    floatFromPC2 = atoi(strtokIndx);     // convert this part to a float

}

//============

void showParsedData() {
    Serial.print("Message ");
    Serial.println(messageFromPC);
    Serial.print("Float ");
    Serial.println(floatFromPC);
    Serial.print("Float ");
    Serial.println(floatFromPC2); } //end new stuff string

Then connect to wifi and upload to ThingSpeak.
I had to get rid of Softwareserial and connect the RX on the Arduino Uno to the TX on the ESP8266-01 and the TX on the Arduino Uno to the RX on the ESP8266-01.
Everything worked great till I changed from an Arduino UNO R3 to an Arduino Pro Mini for size and energy conservation.
With the wiring the same (I think) and the code the same the string (f) doesn't get sent over to the ESP.  I don't see the TX led flashing on the Pro Mini when it should be transferring string(f) and nothing gets uploaded to ThingSpeak.  Not sure why but I will post another question for that one.  Thanks for everyone's help.

It is OK to accept your own answer as the solution.

Sending data between Arduino and NodeMcu (Serial Communication)
youtube link  (in French):
https://youtu.be/0TXmi9EgaCs

When you make a video that is entirely in french, please don't write the title entirely in english.  Use some french, or write "[french]" in the title or something.

hi ..  i make that video to help people to solve the problem.. i forget to ad the language in title .. but the important thing it's the methode (arduino code) using to send the data .. i'm gonna change the title and maybe i will make a video in english  ..  thank you

I appreciate that there are non-english videos out there  =).  It's just good that people know what they're going to get, particularly if they're already frustrated by a problem they're having. Voted you up.


text:
How to properly declare a random URL in ESPAsyncWebServer?
I'm trying to make a onetime URL with a random string to for example give a user onetime access to a house with a smart lock. I have a function to make a fixed 8-character string and the following code with the address that is randomly made.
  controlserver.on(userurl, HTTP_GET, [](AsyncWebServerRequest *request){
   if(urlactive==true){
   if(request->authenticate("admin","admin")){
      running=true;
      request->send(200);

      Serial.println("entered");
      urlactive=false;
      }else {
       return request->requestAuthentication();
      }
   }else{
       generateRandomString();
       request->send(200, "text/html", HTML_CSS_STYLING+ ""
    "

LInk is not valid!
" );

   }
  });

the following function generates the userurl which is a const char* because the requirement of ESPAsyncWebServer library.
void generateRandomString() {
  const char specialChars[] = "0123456789";
  const char letters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  String randomStringurl = "";
  String keppmyuserpass = "";
  randomStringurl += letters[random(26, 51)];
  for (int i = 0; i < 6; i++) {
    randomStringurl += letters[random(0, 51)];
  }
  randomStringurl += specialChars[random(0, 9)];
  Serial.println(randomStringurl);
  userurl = randomStringurl.c_str();

}

everything works fine when I enter the generated string that I convert into const char* using c_str() but I noticed an error when I copied the string partially by accident and too much to my surprise, I saw that the popup for the username and password showed up and I didn't expecte it, because I have a notFound function that will show an error when the entered URL doesn't exist. entered different strings but the problem is persistent. I think there is a problem with my string conversion to const char* using c_str(). but is it?
Here is compliable code, the wifi mode is STA WiFi.mode(WIFI_STA); :
#include <Arduino.h>
#ifdef ESP32
#include <WiFi.h>
#include <AsyncTCP.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#endif
#include <ESPAsyncWebServer.h>

const char* userurl;
String  randomStringurl = "";
String  keppmyuserpass = "";

AsyncWebServer server(80);

const char* ssid = "your_ssid";
const char* password = "your_password";

const char* PARAM_MESSAGE = "message";

void notFound(AsyncWebServerRequest *request) {
    request->send(404, "text/plain", "Not found");
}
void generateRandomString() {
  const char specialChars[] = "0123456789";
  const char letters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  randomStringurl = "";
  keppmyuserpass = "";
  randomStringurl += letters[random(26, 51)];
  for (int i = 0; i < 6; i++) {
    randomStringurl += letters[random(0, 51)];
  }
  randomStringurl += specialChars[random(0, 9)];
  Serial.println(randomStringurl);
  userurl = randomStringurl.c_str();
  keppmyuserpass = randomStringurl;
  keppmyuserpass += letters[random(26, 51)];
  keppmyuserpass += specialChars[random(0, 9)];
  Serial.println(keppmyuserpass);

}
void setup() {

    Serial.begin(115200);
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);
    if (WiFi.waitForConnectResult() != WL_CONNECTED) {
        Serial.printf("WiFi Failed!\n");
        return;
    }

    Serial.print("IP Address: ");
    Serial.println(WiFi.localIP());

    server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
        request->send(200, "text/plain", "Hello, world");
    });

    // Send a GET request to <IP>/get?message=<message>
    server.on(userurl, HTTP_GET, [] (AsyncWebServerRequest *request) {
        String message;
        if (request->hasParam(PARAM_MESSAGE)) {
            message = request->getParam(PARAM_MESSAGE)->value();
        } else {
            message = "No message sent";
        }
        request->send(200, "text/plain", "Hello, GET: " + message);
    });

    // Send a POST request to <IP>/post with a form field message set to <message>
    server.on("/post", HTTP_POST, [](AsyncWebServerRequest *request){
        String message;
        if (request->hasParam(PARAM_MESSAGE, true)) {
            message = request->getParam(PARAM_MESSAGE, true)->value();
        } else {
            message = "No message sent";
        }
        request->send(200, "text/plain", "Hello, POST: " + message);
    });

    server.onNotFound(notFound);

    server.begin();
    generateRandomString();
}

void loop() {
}

And here is the code from ESPAsyncWebServer.h library, that required the url to be a  const char* uri what am I doing wrong?
AsyncCallbackWebHandler& on(const char* uri, WebRequestMethodComposite method, ArRequestHandlerFunction onRequest, ArUploadHandlerFunction onUpload, ArBodyHandlerFunction onBody);

New Update: So, I forgot to add a "/" before the URL, by doing so it solved the problem and here is the new function:
void generateRandomString() {
  const char specialChars[] = "0123456789";
  const char letters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  randomStringurl = "";
  keppmyuserpass = "";
  randomStringurl +="/";
  randomStringurl += letters[random(26, 51)];
  for (int i = 0; i < 6; i++) {
    randomStringurl += letters[random(0, 51)];
  }
  randomStringurl += specialChars[random(0, 9)];
  Serial.println(randomStringurl);
  userurl = randomStringurl.c_str();
  keppmyuserpass = randomStringurl;
  keppmyuserpass += letters[random(26, 51)];
  keppmyuserpass += specialChars[random(0, 9)];
  OTUPC = keppmyuserpass.c_str();
  Serial.println(keppmyuserpass);

}

But when I renew the link, the new link is not recognized and the first generated link was working. I think that @6v6gt might be right about this: "Could it also be that the value of userurl must be known when setup() runs and the callback is registered?"

useurl will point to a char array, that is no longer there, as the local String randomStringurl object is created on the stack and destroyed when the function exits. The dynamically created array inside of it will also be deleted. So this will only work as long as that memory portion won't be overwritten (which you cannot know).

Though your problem doesn't really fit that. Please show us a minimal compilable example code that shows the problem, not just some snippets.

@chrisl I made the randomStringurl global String but the problem is still persistanat. I added a compliable code. Isn't the null terminated character at the end of char the problem maker? because normally I define the URL's like "/someurl" not just by passing a const chr* someurl.

const char* userurl; . . . ; userurl = randomStringurl.c_str(); This is not preserving a copy of the String variable's contents. It is simply keeping a copy of a pointer to an area which may vanish (as has been pointed out). You have to create a global (or static) buffer something like char userurl[80] and then use strcpy() to populate it. Could it also be that the value of userurl must be known when setup() runs and the callback is registered?.

@6v6gt how can I know that the value of userurl must be known?

is random() useful here? you should use the CSPRNG of the ESPs, if not for the generation then at least for randomSeed()...

6v6gt is right, that the URI for the handler must be known, when you use the on() function to set the handler. Inside the library, the on() function calls setUri(const String& uri), which which saves the uri in the classes interal String member variable. Thus the handle will not notice, if the originally used variable changes.
I think the most elegant solution here would to be to use a regular expression for your handler URI (A regular expression is a string expression, that describes a template that can match other strings). That will let the handler match any URI, that fits that regex. Inside the handler you can then get the relevant part of the URI and check, if it is currently valid. If yes, you serve your content, otherwise you serve an error (for example a 404 Not Found).
The third answer to this question has a code snippet for this:
#include <uri/UriRegex.h>

web_server.on(UriRegex("/home/([0-9]+)/first"), HTTP_GET, [&]() {
    web_server.send(200, "text/plain", "Hello from first! URL arg: " + web_server.pathArg(0));
});

The part of the URI, that's between the brackets, is the regex group, that is then made available via web_server.pathArg(0). Your current code creates a string with one capital letter, 6 lower case letters and one digit, thus a regex group ([A-Z][a-z]{6}[0-9]). You can read about how regex work online.
When you look at this repo of ESPAsyncWebServer (I'm not sure, which version you have), in the Readme right at the end under "path variable" you find this snippet:
server.on("^\\/sensor\\/([0-9]+)$", HTTP_GET, [] (AsyncWebServerRequest *request) {
  String sensorId = request->pathArg(0);
});

And a note, that regex support must be enabled.
As I didn't test this, I suggest you try both methods and see, what works for you.


text:
Switch case options get broken after a function call
I'm sorry for the basic question, but I have a switch case where any code placed after a certain function call simply never gets called, and I've spent half a day looking at it, so thank you so much for your help.
Running on an Arduino UNO.
Here is the loop, and every option in the switch case after the call to moist_sensor.read() simply never gets in:

void loop() {

  while (Serial.available() > 0) {
    char val = (char)Serial.read(); // read data byte by byte and store it
    Serial.println(val);
    switch(val) {

      case 'O':
            digitalWrite(13, LOW);

            break;

      case 'I':
            digitalWrite(13, HIGH);

            break;

      case 'W':
            water(2000);
            break;

      case 'E':

            int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
            //Serial.println(reading); // send the received data back to raspberry pi
            break;

//it never enters any of these cases below

      case 'M':

        //String reading2 = moist_sensor.packaged_reading();
        //Serial.println(reading2); // send the received data back to raspberry pi
        break;

      case 'W':

        water(5000);
        break;

      default:

        delay(5000);

    }
  }

I've tried changing the name of the function with fears of special keywords, swapping it with other cases (such as putting case 'W' above, where it works, and vice versa), and I always get the same behaviour. If i comment the line, everything works as expected.
I know the method isn't actually called all the time, but for sanity's sake, moist_sensor.readd() right now is just:
int readd() {
return 0;
}

It also works fine if its the last case, but this buggs me, and I want to create other cases with function calls.
Thank you so much!

You seemed to have solved it. For the reason, take a look at the compiler errors:
sketch_nov22a:31: error: jump to case label [-fpermissive]
       case 'M':
            ^
sketch_nov22a:25: error: crosses initialization of 'int reading'
             int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
                 ^
sketch_nov22a:38: error: jump to case label [-fpermissive]
       case 'W':
            ^
sketch_nov22a:25: error: crosses initialization of 'int reading'
             int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
                 ^
sketch_nov22a:43: error: jump to case label [-fpermissive]
       default:
       ^
sketch_nov22a:25: error: crosses initialization of 'int reading'
             int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
                 ^
exit status 1

If you got it to compile your compiler must be configured a bit differently to mine. However you can see that by putting int reading = ... in the case block, the compiler tries to execute that first (to initialize reading) which causes it to jump case labels.
By moving int reading outside the case statement, the compiler no longer has to initialize the variable, and that line merely becomes a function call and assignment (not a variable initialization).

You can avoid that by putting the code into its own block, that is, instead of:
  case 'E':

        int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
        //Serial.println(reading); // send the received data back to raspberry pi
        break;

Use:
  case 'E':
        {
        int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
        //Serial.println(reading); // send the received data back to raspberry pi
        }
        break;

Yeah, I'm using the arduino-cli to compile/upload to the board from the RPI, and while I do get error messages, turns out I might be missing a ton of warnings.
Interesting to actually look into the "error: jump to case label" and how it messes the compilers logic by still considering the variable declaration valid in the next cases of the switch, but not the initialization.
Thank you for the block fix! I always thought repeated declarations in cases like this would be optimized by the compiler, does it apply to this case? I'd prefer to avoid a needlessly global variable.

The scope and lifetime of a (non-static) variable inside a block is the block itself. The compiler may well put that variable into a register and not use memory at all. So I would say, yes the compiler will optimize as much as it can.

As soon as I posted this, I looked at the variable declaration inside the case and thought I'd fix this ugly code, and turns out that is what breaks the entire thing, I had no idea...
case 'E':

            int reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
            //Serial.println(reading); // send the received data back to raspberry pi
            break;

should just be
case 'E':

            reading = moist_sensor.readd(); //THE PROBLEMATIC LINE
            //Serial.println(reading); // send the received data back to raspberry pi
            break;

with the "int reading;" declaration somewhere else above.


text:
Errors occured when switching from Uno to Nano Every
I wrote a code that worked perfectly on an Uno. I switched everything out to a Nano Every, and now I'm getting the following errors:
In file included from C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\libraries\LiquidCrystal\src\LiquidCrystal.cpp:1:0:

C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\libraries\LiquidCrystal\src\LiquidCrystal.h:45:36: error: expected class-name before '{' token
 class LiquidCrystal : public Print {
                                    ^
C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\libraries\LiquidCrystal\src\LiquidCrystal.h:86:9: error: 'Print' has not been declared
   using Print::write;
         ^~~~~

exit status 1

Error compiling for board Arduino Nano Every.

I'm new to programming (this is the first thing I've done that wasn't from a tutorial), so I don't understand what any of the above means.
In the Tools dropdown, I have
Board: Arduino Nano Every
Registers Emulation: None (ATMEGA4809)
Programmer: Onboard Atmel mEDBG (Uno Wifi Rev2)
Here's the code:
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  lcd.begin(16, 2);
  lcd.print("Charging");
  delay(750);
  lcd.print(".");
  delay(750);
  lcd.print(".");
  delay(750);
  lcd.print(".");
  delay(750);
  lcd.clear();
  lcd.print("Charged");
}

void loop() {
  const int buzzerPin = 6;
  const int switchPin = 13;
  const int buttonPin = 7;
  const int ledPin = 9;
  pinMode(switchPin, INPUT);
  pinMode(buzzerPin, OUTPUT);
  int switchState = digitalRead(switchPin);
  int buttonState = digitalRead(buttonPin);
  lcd.setCursor(0, 1);
  lcd.print("Mode: ");
  if (switchState == LOW) {
    lcd.print("Stun");
  } else {
    lcd.print("Kill");
  }
  if (buttonState == HIGH) {
    const int buzzerMax = 2000;
    const int time = 3;
    int buzzerTone;
    int totalReps = 50;
    int reps = 10;
    while (reps < totalReps) {
      buzzerTone = ((totalReps - reps) * 2 * (buzzerMax / totalReps));
      tone(buzzerPin, buzzerTone);
      analogWrite(ledPin, (255 / reps));
      delay(time);
      reps++;
      delay(time);
      if (reps == totalReps) {
        noTone(buzzerPin);
        analogWrite(ledPin, 0);
      }
    }
    lcd.clear();
    lcd.print("Charging");
    delay(333);
    lcd.print(".");
    delay(333);
    lcd.print(".");
    delay(333);
    lcd.print(".");
    delay(333);
    lcd.clear();
    lcd.print("Charged");
  }
}

Looks like you're using the Windows Store version of the IDE. That's known to be faulty in so many ways. Download the newest version from the Arduino website and update all the cores to the latest version.

it is a know issue with a workaround https://github.com/arduino/Arduino/issues/10025