text:
Can a MEMS accelerometer sensor be used as a shock sensor?
I am trying to make an IOT project- SMART DOOR where I have used a serve motor and NodeMcu and for adding further functionality I have been thinking of adding a theft detection feature where whenever a large force is applied on the lock an alarm starts beeping and for that I don't have a shock sensor but I do have MEMS accelerometer sensor(MPU6050 Accelerometer and Gyroscope).
So can I use it to add this functionality?
If yes, can I get a little guide on what configuration and sensitivity I should use?
THANK YOU!

Please don't scream at us. I removed the capslock from the title for you

haha! Thank you :D

Sure you can. A "shock" is merely a large amount of acceleration over a short period of time.
You would probably want to set the MPU6050 to its least sensitive setting (±16g), and you might even be able to make use of the "tap" function whereby the MPU6050 itself looks for a sudden short sharp shock to trigger an interrupt (though that may be a little too sensitive for your needs, I don't know).

Thank you so much!


text:
Can I emulate Arduino in a headless CI/CD setup?
6 years ago, there has been a question "How to emulate Arduino on PC".
Since then, probably many more Arduino emulators have been introduces.
With this question, I would like to narrow the search scope down to the following criteria:

Linux compatible
headless operation mode without UI/IDE possible to run in a CI/CD (continuous integration/delivery) system in collaborative environment where many code versions need to be merged and tested.

Do such setups exist already?

The Arduino itself is usually only a tiny portion of a project. The rest is other devices and sensors which interact in a "real world" way. Such things can not always be reliably simulated. Sure, you could run an AVR emulator, but what do you do about that ultrasound detector? How do you know that the motor is spinning right? What do you do when the device you want to use isn't even simulated at all?

Please close this question as accepted as you have already the next one -this is not a forum but one question at a topic knowledge base

I am not sure it's mandatory to accept a question with just 1 answer; the comment by Majenko does contain valuable information, too. My following question addresses another aspect of the knowledge base.

The problems with this kind of software is:

always behind the recent releases of cores/ hw variations.
reliable only for simple programs/tasks
Imho all the products I tested (mainly on Win) are actually a (somewhat crippled ) teaching and visualization help.
if you look into the emulators you mostly see only support for different chips and not the whole micro computer, which is far more complex to create

Due to the low cost of the hardware it is easier to run real HW setups with HW diagnostics (and get also feedback for thermal/electric issues) So this kind of SW is for the low cost avr/esp HW and its hundreds of variants (even between production batches from one manufacturer) hard to develop and mantain. So you'll only find nice "play around" emulators which won't fulfill any professional requirement (even if some claim it)

source: Stack Exchange

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

sort: votes


text:
Uno - error during uploading with library
I'm writing the code in VS Code on IO Platform. Yesterday i finished my code and uploaded it to the Arduino Uno. It works fine. Next day i launched the VS Code and i changed the code a bit, then i uploaded it and i got the error.
Error:
Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
(.text+0x0): multiple definition of `__vector_7'
NewPing.cpp.o (symbol from plugin):(.text+0x0): first defined here
collect2.exe: error: ld returned 1 exit status
*** [.pio\build\uno\firmware.elf] Error 1

I am using the libary NewPing.h. The code should does this: If is distance more than 20cm, the the buzz makes the sound and turns on the red led. If distance is less than 20cm, the blue led turns on
The code:
#include <Arduino.h>  //It has to be there, because the arduino ide in VS Code will not work.

#include <NewPing.h>

#define echo_pin 3
#define trig_pin 4
#define max_range 450

#define red_led_pin 7
#define blue_led_pin 9
#define buzz_pin 10

int distance = 0;

NewPing sonar(trig_pin, echo_pin, max_range);

void setup(){
  Serial.begin(9600);
  pinMode(red_led_pin, OUTPUT);
  pinMode(blue_led_pin, OUTPUT);

  pinMode(buzz_pin, OUTPUT);
}

void loop() {

  distance = sonar.ping_cm();
  delay(50);

  if (distance > 0) {
          distance = 0;

    for (int i=0; i<5; i++) {
      distance += sonar.ping_cm();
      delay(50);
    }
    distance /= 4;

    Serial.print("Distance: ");
    Serial.print(distance);
    Serial.println("cm");

    if (distance > 20) {

      digitalWrite(blue_led_pin, LOW);
      digitalWrite(red_led_pin, HIGH);
      tone(buzz_pin, 1500);
      tone(buzz_pin, 800);
    }

    else {

      digitalWrite(red_led_pin, LOW);
      digitalWrite(blue_led_pin, HIGH);
    }
  }
}

I don't undersand, what has changed. I tried to import again the libary https://www.arduino.cc/en/guide/libraries by importing the *.zip file, also installing in IDE.

Please look into "NewPing.h". Is the line #define ENABLE_TIMER_BASED_PING 1 commented out or active?

Did you change the pin numbers from before? If yes, which exactly?

@chrisl How can i look into? How to open that file?

I'm not sure, why you are asking be that. It is a simple text file. You can open it with any text editor. All the source files are pure text files, that can be edited easily with any text editor

I was able to compile your code without errors (using the Arduino IDE). I used this NewPing library from github. Please give us information about, which NewPing library you have used exactly.

@chrisl I am using this library https://github.com/as000fm/NewPing-1.9.1/blob/master/NewPing.h Version 1.9.1. I tried to upload it with Arudino IDE to my arduino and it works. But the VS Code still doesn't work and i am getting the same error.

I'm not a VSCode expert, but that sounds like VSCode is using the wrong library files for compilation. Cannot say, how to fix that

@chrisl sure. But THANKS you for fix my problem with Arduino! And if i may ask, which code editor do you use for arduino or for any other language? I don't really like how the IDE looks, that's why i am asking.

You have a conflict of interrupts. Both the internal tone() command and the NewPing.h use Timer 2 by default, which makes them mutually exclusive.
However you can change NewPing to not use a timer by editing the src/NewPing.h file and setting TIMER_ENABLED to be false:
    #define TIMER_ENABLED true      // Set to "false" to disable the timer ISR (if getting "__vector_7" compile errors set this to false). Default=true

I wrote it to the my code under line with including th libary, but nothing has changed. What exactly and where should i type it? Finally, I installed the library based on instructions in this video: https://www.youtube.com/watch?v=_pSVzV4PdiA

@AuthorCliment Majenko asked you to change the corresponding line in the NewPing.h file, not in your sketch. Open the NewPing.h file (which you can find somewhere in your libraries folder) with a text editor, find that line and change it according to Majenkos answer

@chrisl I dound that line. I changed it to false. And I'm still getting the same error.

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


text:
Can I integrate Arduino in a CI/CD setup?
While it seems less valuable to emulate Arduino in a CI/CD setup, are there any experiences/best practices for collaborative teams to automate their acceptance tests where a real Arduino is integrated into a CI/CD toolchain (or, what are comparable practices)?
Minimal example of acceptance testing:

compilation is successful for a given compiler version.

Step one: Define what acceptance means in your project workflow.

added a minimal example.

For that: run arduino-builder in a script run by a cron job.

There are different approaches around. I can only point you to some of them:

GitLab CI approach A
GitLab CI approach B
Your specific solution: To build pipelines for Arduino (although its Azure) but you can use this technique on Linux with Jenkins

As a valuable commenter mentioned on your previous question - this does not cover the attached hardware testing (sensors/ motors) - this has to be "integrated" via a test lab station, which you have to control manually (or semi-automated via lab equipment) on defined release/version changes

thank you so much @Codebreaker007! Trying out approach A to compile the controller code for an open source ventilator project :-)


text:
Can stack size be determined by free heap?
i have NodeMCU with es8266 onboard on it. I read heap and stack memory are facing each other and if heap or stack gets full and reachs another strange things happen. So i am wondering if can we use ESP.getFreeHeap() to get free heap and conclude usage of stack.
one tiny question here: can Serial.println("asd asd") cause memory fragmentation?

I read heap and stack memory are facing each other and if heap or stack gets full and reachs another strange things happen.

Indeed they do. And such things can be a pain to track down.

So i am wondering if can we use ESP.getFreeHeap() to get free heap and conclude usage of stack.

No, you can't.  The "free" amount of heap does not equate to the top address of heap. Heap can (and generally does) have holes in it. The "free" space is the sum of all those holes plus any extra "heap reserved" space above the highest heap entry.
To get the current stack usage you need to know two things:

The staring address of the stack, and
The current extent of the stack

Item 1 will be a fixed value, though what that value is I have no clue, but some reading will surely give you that value.
Item 2 can be obtained by allocating a local variable in a function and getting the address of that variable.
If all you care about is the change in stack imposed by your code you can record the "starting" stack point and use that in point 1.  For example:
char *stack_start;

void setup() {
    char stack;
    stack_start = &stack;
}

Then you can use that to get the current stack size compared to the start of your program:
uint32_t stack_size() {
    char stack;
    return (uint32_t)stack_start - (uint32_t)&stack;
}

one tiny question here: can Serial.println("asd asd") cause memory fragmentation?

No.  Use of String and other dynamic allocation is what causes memory fragmentation.

but isnt "asd asd" a string? and that stack code seems really useful thanks.

It's a "string literal", not a String. A String is specifically an instance of the (Arduino specific) String class.


text:
How to install a dependency library to an Arduino compilation environment?
Following approach A from this Arduino SE answer, I managed to kick off an Arduino CLI compilation in a Docker environment.
However, the project I am trying to compile has a dependency on a LCD control library.
Error output:
...../OpenSourceVentilator/OpenSourceVentilator.ino:494:116:
fatal error: LiquidCrystal_PCF8574.h:
No such file or directory
compilation terminated.

What is the proper way to link dependencies to the compilation environment of an Arduino project?
While the source suggests a direct compiler call, maybe I need a Makefile instead of the following?
arduino-cli compile --fqbn esp32:esp32:esp32 -o ignored.bin OpenSourceVentilator.ino

The tutorial, that you linked to as approach A from the other question, also has a part, which explains how to install extra libraries

@chrisl is that also an "Arduino-like" way or is there a more standard approach/package manager?

Why do you expect a non-Arduino like or more standard approach, when using the Arduino CLI?

I just wonder there is no management for external libraries Golang-style, but maybe it's even good.

If the library is installed the Arduino IDE (or CLI I assume too) just finds it and compiles/links it for you.

so what activities does installation of a library include if the library is on GitHub?

https://www.arduino.cc/en/guide/libraries


text:
How to control one Mosfet with another mosfet
I've got 4x 12V 6a peltiers and some 3d printer mosfet controllers to drive them using PWM with my arduino. But I've found the mosfets need ~7V to switch on, so I'm now wanting to control them with some logic level ones I had around. I could just use the logic ones directly to the peltiers, but am finding it difficult to make my stripboard capable of handling 24A (this page seems to say I need tracks/wire of 2.3+mm diameter which I don't have). Hence I'm trying to make a circuit for the arduino to use the logic mosfets to control the 3d printer mosfets but can't quite get my head around how to do it. I think I'm missing a power source for the first mosfet - do I need to have a whole separate DC power supply for this to the peltiers? Very grateful for a bit of help please!

There's one thing you missed with your arrangement, and that is getting the 12V to turn the MOSFET on.  In your current arrangement it's possible to turn it off, but never on.  Adding a pullup resistor can help:

simulate this circuit – Schematic created using CircuitLab
R1 pulls the gate of M1 up above the switching threshold to turn it on. M2, when on, pulls the gate down below the switching threshold, turning it off.
However: you may have noticed that the switching is now backwards: send a HIGH from the Arduino to turn it off. Which of course has the effect that the output is normally on and you have to actively turn it off.
Again a pullup resistor can help:

simulate this circuit
Now R2 keeps the gate of M2 pulled up (switched on) which keeps M1 turned of. That is, until you actively pull the gate down to ground by sending a LOW from the Arduino.
To ensure that the peltier never turns on when you don't want it to you should also take steps to ensure that the 12V power is never provided without the 5V also being provided - so you could maybe power the Arduino through the barrel jack from the 12V supply.  It doesn't matter if the 5V is provided but not the 12V, but the other way around could mean the peltier comes on with no active control over it.

Brilliant, thanks for your help Majenko!


text:
Regarding Strings and assignments
I have this code which works :
String ErrorMsg;
.......
if(!UploadPacketError)
{
    ErrorMsg="OK";
}
else
{
   ErrorMsg="NOK";
}

String creates a dynamically allocated array which I want to avoid. I would prefer something like :
unsigned char ErrorMsg[5];
......
if(!UploadPacketError)
    {
        strcpy(ErroMsg,"OK",3); // +1 for the Null Termination ?
    }
    else
    {
       strcpy(ErroMsg,"NOK",4); // +1 for the Null Termination ?
    }

i.e. is there a way to dynamically assign a value to a fixed size character array ?
Cheers
Thomas

Almost.
First it's char not unsigned char:
char ErrorMsg[5];`

Second you don't specify a size with strcpy:
strcpy(ErrorMsg, "OK");

There is a variant of strcpy called strncpy which copies at most n characters:
strncpy(ErrorMsg, "OK", 5);

That is used to prevent buffer overruns. But when working with string literals like that it's pretty pointless.

Thanks Majenko. Is there a way to do do something like : String flashhtml = "Programming" + ErrorMsg + " Programming Over " ;   Something similar to concatenating multiple fixed strings and variable strings ? I know there are other ways to do this , but i was looking for the simplest possibility.

Into a suitably sized char buffer? Yes.  strcpy replaces the string content from the start. strcat concatenates more content on to the end.  strcpy(buffer, "
Programming

"); strcat(buffer, ErrorMsg); strcat(buffer, " Programming Over "); ...

Terrific , Majenko,exactly what I was looking for !

@EmbSysDev I have a small blog post about replacing String with C strings. https://majenko.co.uk/blog/evils-arduino-strings

Very nice blog indeed. Arduino is a wonderful tool;but it does seem to help you mess up bigtime. I guess like everyhing else, one learns by first messing up

@majenko Sorry to be questioning but wouldn't strncpy(ErrorMsg, "OK", 5); write the terminator out of bounds, shouldn't it be strncpy(ErrorMsg, "OK", 4); for a char[5] ? As I normally do it like strncpy(ErrorMsg, "OK", strlen (ErrorMsg)-1) to be on the safe side

No. The 5 includes the terminator if there is one within the first 5 bytes. But even then, it will only do 3 bytes anyway since it stops on the NULL before it reaches the limit of 5.

Yes clear with the example of "ok" but if I do "first" wouldn't that write out of bounds -since that could be a problem for general usage of strncpy Thanks for your time

No, you just won't get a null terminator.

http://www.cplusplus.com/reference/cstring/strncpy/

Also recomending the fixed char approach but for completeness there is a possibility to "get away with String class" IF you ONLY use fixed AND predefined Strings to build dynamicly variable messages:
bool first = true;

String A = F("My first ");
String B = F("My second ");
String C = F("answer");
if (first) serial.println(A+C);
else serial.println(B+C);

Read more on the F-macro here. Conclusion:

Large blocks of text to a file system (like SPIFFS, LittleFS, SD)
dynamic texts to large enough fixed char arrays and
short messages (consisting of fixed parts) can be created with the F-Macro

Assigning strings A, B and C will allocate heap and copy the data into it wasting RAM. Adding the strings will concatenate them in memory and return the result wasting more RAM. There is never a good reason (or even a good way) to use String.

@Majenko: for people with a casual amateur interest in programming, efficiency and performance aren't likely to be driving factors compared to code simplicity and readability. For large projects every bit counts, but using direct port access or cstrings won't improve the perceived performance of a simple 4x20 LCD digital thermometer project, and could very well be harder for the "programmer" to customize than one using digitalWrite(), literals, operators, and String methods. Sometimes "getting away with ___" means "yes, i can mod this" vs "idk what this even means"; have mercy on the noobs.

@dandavis I said "good" reason. That is not a good reason. It is a reason, but not good. It's not about efficiency, or performance. It's about someone writing some seemingly simple code and then turning up here some time later saying "My Arduino crashes randomly after a few hours and I can't work out why". And of course they used String. And the heap fragmented, and overflowed.


text:
Error compiling for board Arduino Nano
I have multiple Arduino Nano boards.
I am able to compile or upload code only once. If I try to compile/upload again I get an error: "Error compiling for board Arduino Nano". However there is a workaround: to be able to upload again I change something in tools menu for example board or processor.
I tried all of the nanos and all of the ports.
The error message is below (verbose is enabled).
The problem appeared from nowhere.
Thank you in advance!
C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\Nauris\Documents\Arduino\libraries -fqbn=arduino:avr:nano:cpu=atmega328old -vid-pid=1A86_7523 -ide-version=10812 -build-path C:\Users\Nauris\AppData\Local\Temp\arduino_build_956544 -warnings=none -build-cache C:\Users\Nauris\AppData\Local\Temp\arduino_cache_309115 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino5.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Users\Nauris\Documents\Arduino\RC\wifi_arduino\wifi_arduino.ino
C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\Nauris\Documents\Arduino\libraries -fqbn=arduino:avr:nano:cpu=atmega328old -vid-pid=1A86_7523 -ide-version=10812 -build-path C:\Users\Nauris\AppData\Local\Temp\arduino_build_956544 -warnings=none -build-cache C:\Users\Nauris\AppData\Local\Temp\arduino_cache_309115 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino5.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Users\Nauris\Documents\Arduino\RC\wifi_arduino\wifi_arduino.ino
Using board 'nano' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
Using core 'arduino' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
Detecting libraries used...
Error compiling for board Arduino Nano.

Please enable verbose output for compilation and upload in the preferences. There might be a better error description about the problem in the verbose output

If that is really the verbose output, there is something wrong with the IDE. Have you tried reinstalling it (with the latest version)? As you are on Windows, don't install the Arduino IDE from the Windows app store, since that version is buggy as hell. Use the latest version from the official website

Sorry, didn't mention that I tried to reinstall the ide. Deleted "Arduino15" folder, deleted "libraries" folder and uninstalled arduino ide.

I resolved this issue by installing older arduino ide version.

ive been having this same issue for the last 9 or so month it is driving me insane i have uninstalled and reinstalled arduino in every way i possibly can... using revouninstaller and cccleaner and even tried starting a new user account on my computer and installing it and i still have this issue.. i can only click verify or upload one time and the very next time as soon as i click it i get the exact same error message.. and not just for the nano for every board i have on the list,, it is so irritating!!!! the only work around i have found. well the simplest is to change back and forth from nano old bootloader to atmega328.. or switch back and forth from nano and uno in the boards menu..
so when im trying to put multiple codes together and get it to compile every time i click verify i have to change the board info.. or it instantly says
Using core 'arduino' from platform in folder: C:\Program Files\Arduino\hardware\arduino\avr
Detecting libraries used...
Error compiling for board Arduino Nano.
about to just throw it all in the trash


text:
Possibly fried a new atmega328p?
I have a new atmega328p IC that I wanted to program. To do so I placed it into the socket of an arduino uno. I accidentally placed it the wrong way around (180° rotated), and powered it via USB and tried to upload the blink sketch, which obviously did not succeed. After I noticed it I turned it around and placed it into the socket the right way. I tried again uploading the blink sketch again without success.

Have I fried the atmega328p by placing it in the socket the wrong way?
Is there something else you need to do to new atmeag328p before you can program them the usual way?

Update: It seems that just rotating the IC did not damage it in the state where there was no bootloader programmed. And and the bootloader needed to be programmed first before the IC could be used.

does the new atmega328p have a bootloader programmed?

@jsotola I don't know, I have no experience with that. Is that something you usually have to do with new ones?

if the atmega328p is blank, then you could use the Uno as a programmer .... use google to find a tutorial

@jsotola So is that something that you usually have to do with new atmega328p?

Chips come blank. It's up to you to put the bootloader on them.

Whether your chip is fried or not, we can't say, but they're reasonably tough and will stand a bit of abuse before they fail. Did anything smoke or get hot?
You can buy atmega328p chips pre-programmed with a bootloader from a few vendors, but they don't come from the factory that way so most are not. Preprogrammed chips typically cost a couple of $ US more than blank chips for the time spent by the vendor to buy blank ones, program, and repackage them for sale in small quantities, and are almost always advertised as such. If you don't know whether yours is programmed with a bootloader, it probably isn't. It's worth trying to do it yourself, on a breadboard, using a known-working Uno as a bootloader- programmer. There are lots of how-to articles on the internet.

Thanks for the explanation! It seems that mine did not have a bootloader, and I managed to program it. The basic blink program works so these are two very good signs so far! But I have yet to test all the other pins.

After a reset it should blink pin13 led as all Arduinos do. If not, I'd first try uploading  a bootloader cause I have gotten ones that don't have bootloaders. The 328p if a pretty resistant chip. One time i put 12v into a digital pin and it got so hot the smd desoldered itself but worked fine apart from that pin being blown.

Thanks, that is very good to know. It seems so far that it did survive my mistake as I managed to program the bootloader!


text:
No Websockets Server for Arduino mkr1010?
I've seen some interesting explanations on using websocket comms on mkr 1010 but it's always handling the mkr 1010 as the client and the server being always a computer or some other "non-arduino" server . I'm working on a system with several mkr 1010's in a master/slave setup and bidi comms i.e. i want to use one of the mkr's as a server (does the calculations etc.) and the other as clients (get result from calculations ans send back sensor info). I did not found any library or example of websocket server for mkr1010. I found it for ESP systems. Please help as i tried my bidi comms with webclient and webserver using http but not good enough for my applicaton (not realy bidi).
thanks a lot !

Most websocket libraries work over a Client. Client is base class for all EthernetClient and WiFiClient classes.
But why do you want to use a Websocket for communication of two MCU in the same LAN? Websockets are intended for communication over HTTP infrastructure (firewalls, proxies) to a web server in Internet or from browser to a web server.
Use a basic TCP socket over Arduino Client.
WiFiClient object wraps a TCP socket. A normal TCP socket is connected to IP address and port. WiFiServer starts a listening socket on a port. If server on listening socket is contacted by a remote client socket, it creates a local socket connected with the remote client socket on a free port and returns a WiFiClient object wrapping the socket. Everything you write or print to a WiFiClient is send to that one remote socket.
If one of your client boards creates a WiFiClient and connects it to IP address and port of the WiFiServer on your 'server' board, then you get there a WiFiClient from server.available() and this two WiFiClient objects are connected. What you write/print on one side you read only from the WiFiClient object on the other side.
client socket
if (client.connect(serverIP, PORT)) {
  client.print("request\n");
  String response = client.readStringUntil('\n');
  Serial.println(response);
  client.stop();
}

server side
WiFiClient client = server.available();
if (client && client.connected()) {
  String request = client.readStringUntil('\n');
  Serial.println(request);
  client.print("response\n");
  client.stop();
}

thanks a lot ! I have also used the chatserver example to work it out !


text:
Runtime compilation
I want to compile a sketch on Arduino Uno, while Arduino is running and not connected to anything else, and then run the compiled sketch automatically.
Is this feasible?
How?

maybe yes, google arduino forth .... here is one of the search hits https://arduino-forth.com/

While the answer is no, jsotola's suggestion might be a work-around. Forth is an interpreted language. Python would be another option.

No, not feasable, not possible.
The Arduino runs machine code and it does not have enough space or computation power for a compiler (also there is simply no version of the avr C++ compiler for the AVR platform, for obvious reasons). Also it is internally hardwired to run code from the flash memory. You cannot execute code from RAM. The Arduino is a microcontroller, not a computer. (Here I mean computer as something like: Has a microprocessor to execute code from RAM; has an OS; has huge amount of resources in relation to the average microcontroller)
Also: "not connected to anything else" --> Then how would you interact with the Arduino, writing the code, triggering compilation?
If this is about the cable connection, you can implement programming over bluetooth through the HC-05 module (google for it, there should be plenty of tutorials out there). Or go away from the Arduino and change to an ESP, so that you can do Over The Air (OTA) updates over wifi.
Or you could change to a minicomputer like the Raspberry Pi Zero, which is just a little bigger than the Arduino Nano and smaller than the Uno. (Though that hardly depends on the goal, what you are trying to achieve. Microcontrollers are sometimes better used for specific tasks in contrast to minicomputers)

No. It's not feasible.
The Uno cannot compile.  The Uno cannot run code from RAM.  The Uno is not a computer.
You might be able to find some small scripting language that could run on an Uno, but TBH the Uno is so underpowered you'd be able to do little more than blink an LED...

Of course it's a computer. It's just a computer with limited function. As a single function microcontroller it's ideal for a vast number of purposes not just blinking LEDs.

It may be a computing device, but it's not a "computer" - as in that big box on your desk with a screen and keyboard.

@Dougie and the "little more than blinking a LED" is in the context of trying to use a scripting language. You know, you really should learn to read the whole of an answer, not just pick out individual short phrases and pick at them like a complete pedantic ****.


text:
Adrduino IDE doesn't show port for connected ESP32 module
When I go to select port there's no port for the connected ESP32 module. I am using Mac OS Mojave, mac mini.
The port I find is

maybe the reason is that the ESP32 module is not connected

Or maybe it uses a USB to UART chip that needs drivers installing, and you haven't installed them.

@jsotola it's connected for sure, it lights up and works with my windows.

@Majenko this is also my suspect. how do i know which driver and where to find and install them ?

Read the number on the chip. CH350G?

I see ESP32-WROOM-32D...

this one infact [https://www.amazon.fr/SeeKool-ESP-32S-d%C3%A9veloppement-Bluetooth-Ultra-Low/dp/B07DPP3BGZ/ref=sr_1_4?__mk_fr_FR=%C3%85M%C3%85%C5%BD%C3%95%C3%91&dchild=1&keywords=esp32&qid=1586468528&sr=8-4]

It's the number on the little black square chip you need. CP2102 or something is it?

It is written AMS1117, 3.3 XJS88

No, I said square, not rectangular.

oh hha unfortunately there's nothing written on it, totally black!

but we are in luck, from amazon listing i see it's CP2102!

@Majenko so what should i install? thanks

No idea, I'm not a mac user, and the way OS X is going I can see a lot of people jumping ship from OS X to something that they can work in.

@Majenko what you mean, what's wrong with OS X ?

Well, already in Catalina lots of things are failing to work (no 32-bit, increased obnoxious security, etc). And in the near future loads of drivers (kexts) will fail to work at all. My guess is that, at least for a while, the CH340G drivers will cease to work, and then be an even bigger pain to get going. Bybye cheap arduino clones on the Mac...

yes I have tried with some drivers like CH340G from other post solution but didn't work


text:
read state from button to check if clicked
I"m kinda new here and new to the arduino framework.
I want to build a "menu" using LCD 20*4, so I want to detect "button clicked" event.
I've connected button to pin 8 and to ground, like this(please ignore the other wiring):

int leftButton = 8;

void setup() {
  pinMode(leftButton, INPUT);
  digitalWrite(leftButton, HIGH);
  Serial.begin(9600);

}
bool leftButtonClicked(){
  return digitalRead(leftButton);
}
void loop(){
  delay(20);
  Serial.println(digitalRead(leftButton));
}

I am receiveing on the serial 1 while the button is not clicked, and when its clicked I receive 0.
What is the problem? Thank you guys.

That's normal to wire a button so that it connects to ground when pressed.  That way you can use INPUT_PULLUP in your pinMode and you don't need any pull-up resistor.  So in normal cases your code will read a pressed button as 0 if you wired it the normal way.

Why do you think that this is a problem?

@Delta_G
so according to your saying, 1 mean unclicked, and 0 mean clicked.
is this the acceptable way for doing this?
there is an preffer method to isolate the clicked event?

According to my saying it depends on how you wire the button, but most people prefer to wire it so that 0 is pressed and 1 is unpressed.  You can wire it so that 1 is pressed, but that requires an extra resistor.

Also you need to change your pinMode to INPUT_PULLUP instead of just INPUT or you will start seeing random phantom button presses as the floating input picks up noise from the environment.

@Delta_G, yes I've updated the code.
there is an preffer method to isolate the clicked event?

What do you mean by "isolate the click event".  You test like you did with an if statement.  If the digitalRead returns false then the button was pressed and you do whatever it is that you want to do for that.  Arduino isn't really an event driven system.  You're writing code at a little more base level than that.

@Delta_G yes, I'm usally program on JS and etc, so its really weird for me the way of thinking in that programing way.

As you are a beginner, you seem to have some misconceptions:

Reading button state with digitalRead(): You thought something is wrong, because you thought that digitalRead() returns, if the button was pressed (thus 1 would mean pressed). But that is not directly the case. digitalRead() returns the electrical state of the corresponding pin (if the pin voltage is at ground level (0) or Vcc (supply voltage) level) (1)). This corresponds with the button depending on your wiring. I guess you copied the wiring somewhere in the internet. It shows the most common way of connecting a button. The button consists only of two contacts, which get pressed together, when you press the button. So the button can connect the pin to either ground or Vcc, but not to both. When the button is not pressed, the pin is connected to nothing, thus it is floating and the value changes erratically. This is solved with a pullup or pulldown resistor (a rather big resistor from the pin to either Vcc or ground), which sets the value of the pin, when the button is not pressed. That means, that you need 1 resistor for each button, that you want to use. The good news is: The Arduino already has internal pullup resistors, that you can activate via pinMode(pin, INPUT_PULLUP). That way you can save 1 extra component. Since it is a pullup resistor, which connects the pin with Vcc, you need to connect the button with ground.
That also gives you the inverted logic. In the end it is determined by you, what the digitalRead() value means. Think electrically about it.
Events: In Arduino programming there are not events. You are programming very much directly the hardware. There is no OS or GUI system, that would handle events for you. The program, that you write, runs command after command with a specific speed (determined by the Arduinos clock frequency; 16MHz for the Uno), pretty much linearly. Though there is one exception for that: interrupts. Microcontrollers have some peripherals build into them (ADC, communication interfaces, Timers, ...) and many of them work parallel to the main program (since their function does not need code, but is implemented in hardware). These peripherals can generate interrupts (for example to service the peripheral), which pauses the normal run of the program, runs an ISR (Interrupt Service Routine) and then returns to the main program. That is somewhat like an event, but very hardware specific and not nearly as generically usable as events on a PC.
Reading a button click: In your code you don't read the "button click", but only the state of the button. Thus you get multiple times 0 for one long enough button press. For the real click action you need to look for the transition from 1 to 0, which ideally only happens one time per button press. I write "ideally", because real life buttons bounce. In the moment of contact the value changes rapidly multiple times, until the button contacts have settled. So you need to debounce the button. You have already done basic debouncing by using delay(20) (because the button may need about that time to stabilize). You can see more sophisticated debouncing in the Bounce2 library, which is also easy to use for reading button clicks and presses.


text:
The Arduino Oscilloscope - Error message: 'ADCSRA' was not declared in this scope
Project: The Arduino Oscilloscope - published in The MagPi No. 71 July 2018
This is my first Arduino project!
I'm porting over the sketch "Gather_A0.ino" but I'm encountering compile errors:
Error message: 'ADCSRA' was not declared in this scope.
What am I missing?
Error message:

Arduino: 1.8.12 (Windows 10), Board: "Generic ESP8266 Module, 80 MHz, Flash, Legacy (new can return nullptr), All SSL ciphers (most compatible), dtr (aka nodemcu), 26 MHz, 40MHz, DOUT (compatible), 1MB (FS:64KB OTA:~470KB), 2, nonos-sdk 2.2.1+100 (190703), v2 Lower Memory, Disabled, None, Only Sketch, 115200"
D:\Arduino & Raspberry Pi\Oscilloscope\Arduino_Scope\Software\Gather_A0\sketch_apr09a\sketch_apr09a.ino: In function 'void setup()':
sketch_apr09a:15:3: error: 'ADCSRA' was not declared in this scope
   ADCSRA = (ADCSRA & 0xf8) | 0x04; // set 16 times division
   ^
D:\Arduino & Raspberry Pi\Oscilloscope\Arduino_Scope\Software\Gather_A0\sketch_apr09a\sketch_apr09a.ino: In function 'void trigger()':
sketch_apr09a:58:4: error: expected 'while' before '{' token
   }{
    ^
sketch_apr09a:58:4: error: expected '(' before '{' token
sketch_apr09a:58:4: error: expected primary-expression before '{' token
sketch_apr09a:58:4: error: expected ')' before '{' token
sketch_apr09a:58:4: error: expected ';' before '{' token
sketch_apr09a:60:1: error: expected '}' at end of input
 }
 ^
exit status 1
'ADCSRA' was not declared in this scope

ADSCRA is a register involved in analog inputs on an AVR board.  The analog input on an ESP8266 works completely differently.  You'll have to figure out what the AVR code does and then figure out how to do the same thing on the ESP.  It's not going to be a simple "change this to that" sort of solution.

I see, my best solution is to order a real Arduino board. I will do that. Thank you -Delta.

The article is using an Arduino Nano. You can get the source code without the bugs you've introduced at https://github.com/Grumpy-Mike/Mikes-Pi-Bakery/tree/master/Arduino_Scope

the esp8266 like to hang if you read its ADC more than ~1000 times per sec.


text:
How do I set up a multi-file project in the Arduino IDE?
Suppose I have a project with several modules and a main program.  This works well by adding the modules to main_program.
module1.cpp
module1.h
module2.cpp
module2.h
...
main_program.ino

I'm having problems when I have test programs for each of the modules.  These allow the various devices to be tested in isolation.
module1.cpp
module1.h
module1.ino # test program
module2.cpp
module2.h
module2.ino # test program
...
main_program.ino

I'm required to have each ino file in a directory of the same name.  I can add the files to main_program by adding (e.g.) ../module1/module1.{cpp,h}.  But, I discover that it has actually copied module1.{cpp,h} to main_program/.
How do I set this up?  Is there any option other than making each module a library?  If possible I would like to keep these files more local than the library directory, since they're specific to this project and not general-purpose libraries.

Make each module a library.

You have two options with ArduinoIDE.
First Each module in a module directory
So the structure looks like
  main_routine
     main_routine.ino
  --module1
      module1.ino  #test routine
      module1.cpp
      module1.h
 --module2
  .....

included in main_routine.ino
   #include "module1/module1.h"
   #include "module2/module2.h"

So you have everything in your master dir and in module specific subdirs below - Nothing is or will be copied by the ArduinoIDE (v1.8.12)
The second (more hacky way) is to have everything in one dir and for development testing working with include guards in the main_routine.ino
 // for production comment all MODULEX_TEST and uncomment PRODUCTION
 //#define PRODUCTION
 #define MODULE1_TEST
 //#define MODULE2_TEST
.....
#if defined (PRODUCTION) || defined (MODULE1_TEST )
   #include "module1/module1.h"
#endif

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

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

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

Pros and cons

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

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


text:
Arduino Uno and 7 segment display - wrong value displayed
I am working at this project and I found that if I have set the temperature by rotating the pot to 312 C, the iron started heating up, but when it was at about 60 C then on the display (7 segment, 3 digit) appeared 312 (the temperature that I have set) and then appeared about 70 C. I did not rotate the pot, the 312 appeared from "nowhere".
I powered on again the soldering station and it showed 35 C - then 312 C - and then 52 C and then the temperature rise normally.
I set the pot randomly at 244 C and the problem did not appeared.
The problem also appeared at 344 C set temperature.
I tried with different soldering irons and 2 different potentiometers and the problem still persist.
I have also tried with different Arduino boards, but the problem still persist.
Is there a solution for this problem ?
The project page: https://www.allaboutcircuits.com/projects/do-it-yourself-soldering-station-with-an-atmega8/?utm_source=eetech&utm_medium=eetech-social&utm_campaign=reposts-projects/
Explanation of the schematic: J2 from "schematic.jpg" is connected to J1 of "7 segment.jpg", pin to pin. The last 4 pins of J2 from "schematic.jpg" are connected to J3 from "7 segment.jpg" and the last pin from J2 ("schematic.jpg") is connected to J6 from the "7 segment.jpg".
https://ibb.co/Zdrt1Hq
https://ibb.co/DC0LzV2
My code:
//Thank you Alex from https://geektimes.ru/ for help with led array function
//AllAboutCircuits.com
//epilepsynerd.wordpress.com

#include <PID_v1.h>

//This array contains what segments need to be turned on to display numbers 0-9
byte const digits[] = {
  B00111111, B00000110, B01011011, B01001111, B01100110, B01101101, B01111101, B00000111, B01111111, B01101111
};

int digit_common_pins[] = {8, 9, 10}; //Common pins for the triple 7-Segment LED display
int max_digits = 3;
int current_digit = max_digits - 1;

unsigned long updaterate = 1200; //Change how fast the display updates. No lower than 500
unsigned long lastupdate;

int temperature = 0;

//Define Variables we'll be connecting to
double Setpoint, Input, Output;

//Define the aggressive and conservative Tuning Parameters
double aggKp = 4, aggKi = 0.2, aggKd = 1;
double consKp = 1, consKi = 0.05, consKd = 0.25;

//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint, consKp, consKi, consKd, DIRECT);

void setup()
{
  DDRD = B11111111;  // sets Arduino pins 0 to 7 as outputs
  for (int y = 0; y < max_digits; y++)
  {
    pinMode(digit_common_pins[y], OUTPUT);
  }
  //We do not want to drive the soldering iron at 100% because it may burn, so we set it to about 85% (220/255)
  myPID.SetOutputLimits(0, 220);
  myPID.SetMode(AUTOMATIC);
  lastupdate = millis();
  Setpoint = 0;
}

void loop() {
  //Read temperature
  Input = 0;
  for(int i=0;i<50;i++)
  Input += analogRead(A0);
  Input /= 50;
  //Transform the 10bit reading into degrees celsius
  Input = map(Input, 0, 550, 25, 400);
  //Display temperature
  if (millis() - lastupdate > updaterate) {
    lastupdate = millis();
    temperature = Input;
  }
  //Read setpoint and transform it into degrees celsius(minimum 150, maximum 350)
  double newSetpoint = analogRead(A1);
  newSetpoint = map(newSetpoint, 0, 1023, 150, 400);
  //Display setpoint
  if (abs(newSetpoint - Setpoint) > 3) {
    Setpoint = newSetpoint;
    temperature = newSetpoint;
    lastupdate = millis();
  }

  double gap = abs(Setpoint - Input); //distance away from setpoint

  if (gap < 10)
  { //we're close to setpoint, use conservative tuning parameters
    myPID.SetTunings(consKp, consKi, consKd);
  }
  else
  {
    //we're far from setpoint, use aggressive tuning parameters
    myPID.SetTunings(aggKp, aggKi, aggKd);
  }

  myPID.Compute();
  //Drive the output
  analogWrite(11, Output);
  //Display the temperature
  show(temperature);
}

void show(int value) {
  int digits_array[] = {};
  boolean empty_most_significant = true;
  for (int z = max_digits - 1; z >= 0; z--) //Cycle through each digit
  {
    digits_array[z] = value / pow(10, z); //We now take each digit from the number
    if (digits_array[z] != 0 ) empty_most_significant = false; //Do not display leading zeros
    value = value - digits_array[z] * pow(10, z);
    if (z == current_digit)
    {
      if (!empty_most_significant || z == 0) { //Check to see that we do not have leading zeros and display the current digit
        PORTD = ~digits[digits_array[z]]; //Remove ~ for common cathode
      }
      else
      {
        PORTD = B11111111;
      }
      digitalWrite(digit_common_pins[z], LOW);//Change to LOW for common cathode
    } else {
      digitalWrite(digit_common_pins[z], HIGH);//Change to HIGH for common cathode
    }

  }
  current_digit--;
  if (current_digit < 0)
  {
    current_digit = max_digits; //Start over
  }
}```

change your code to display the value of newSetpoint continuously ... that will determine if the value is "bouncing"

The value of newSetpoint seems to be good, it's not bouncing.

if (abs(newSetpoint - Setpoint) > 3) { is sometimes true without you changing the pot position


text:
Trouble Uploading Sketch - Issues with SPISettings
Full disclosure - I'm very new to Arduino. I am probably missing something simple. However, I've scoured the internet and can't seem to figure it out. I am trying to use an Arduino Duo Wifi rev2 to install a bootloader onto my Ender 3 (3D printer) - see: https://howchoo.com/g/mge1mdfkzjv/ender-3-bootloader-firmware-update-marlin
When I try to upload the ArduinoISP sketch, I get the following error:
Arduino: 1.8.12 (Mac OS X), Board: "Arduino Uno WiFi Rev2, ATMEGA328"

/Applications/Arduino.app/Contents/Java/arduino-builder -dump-prefs -logger=machine -hardware /Applications/Arduino.app/Contents/Java/hardware -hardware /Users/brandonbarks/Library/Arduino15/packages -tools /Applications/Arduino.app/Contents/Java/tools-builder -tools /Applications/Arduino.app/Contents/Java/hardware/tools/avr -tools /Users/brandonbarks/Library/Arduino15/packages -built-in-libraries /Applications/Arduino.app/Contents/Java/libraries -libraries /Users/brandonbarks/Documents/Arduino/libraries -fqbn=arduino:megaavr:uno2018:mode=on -vid-pid=0000_0000 -ide-version=10812 -build-path /var/folders/sc/1v4cm6053k7bmhv2bd02k44w0000gn/T/arduino_build_226513 -warnings=none -build-cache /var/folders/sc/1v4cm6053k7bmhv2bd02k44w0000gn/T/arduino_cache_822969 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avrdude.path=/Users/brandonbarks/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=/Users/brandonbarks/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -prefs=runtime.tools.arduinoOTA.path=/Users/brandonbarks/Library/Arduino15/packages/arduino/tools/arduinoOTA/1.3.0 -prefs=runtime.tools.arduinoOTA-1.3.0.path=/Users/brandonbarks/Library/Arduino15/packages/arduino/tools/arduinoOTA/1.3.0 -prefs=runtime.tools.avr-gcc.path=/Users/brandonbarks/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino5.path=/Users/brandonbarks/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5 -verbose /Applications/Arduino.app/Contents/Java/examples/11.ArduinoISP/ArduinoISP/ArduinoISP.ino
/Applications/Arduino.app/Contents/Java/arduino-builder -compile -logger=machine -hardware /Applications/Arduino.app/Contents/Java/hardware -hardware /Users/brandonbarks/Library/Arduino15/packages -tools /Applications/Arduino.app/Contents/Java/tools-builder -tools /Applications/Arduino.app/Contents/Java/hardware/tools/avr -tools /Users/brandonbarks/Library/Arduino15/packages -built-in-libraries /Applications/Arduino.app/Contents/Java/libraries -libraries /Users/brandonbarks/Documents/Arduino/libraries -fqbn=arduino:megaavr:uno2018:mode=on -vid-pid=0000_0000 -ide-version=10812 -build-path /var/folders/sc/1v4cm6053k7bmhv2bd02k44w0000gn/T/arduino_build_226513 -warnings=none -build-cache /var/folders/sc/1v4cm6053k7bmhv2bd02k44w0000gn/T/arduino_cache_822969 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avrdude.path=/Users/brandonbarks/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=/Users/brandonbarks/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -prefs=runtime.tools.arduinoOTA.path=/Users/brandonbarks/Library/Arduino15/packages/arduino/tools/arduinoOTA/1.3.0 -prefs=runtime.tools.arduinoOTA-1.3.0.path=/Users/brandonbarks/Library/Arduino15/packages/arduino/tools/arduinoOTA/1.3.0 -prefs=runtime.tools.avr-gcc.path=/Users/brandonbarks/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino5.path=/Users/brandonbarks/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5 -verbose /Applications/Arduino.app/Contents/Java/examples/11.ArduinoISP/ArduinoISP/ArduinoISP.ino
Using board 'uno2018' from platform in folder: /Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6
Using core 'arduino' from platform in folder: /Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6
Detecting libraries used...
/Users/brandonbarks/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega4809 -DF_CPU=16000000L -DARDUINO=10812 -DARDUINO_AVR_UNO_WIFI_REV2 -DARDUINO_ARCH_MEGAAVR -DUNO_WIFI_REV2_328MODE -DMILLIS_USE_TIMERB3 -I/Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/cores/arduino/api/deprecated -I/Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/cores/arduino -I/Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/variants/uno2018 /var/folders/sc/1v4cm6053k7bmhv2bd02k44w0000gn/T/arduino_build_226513/sketch/ArduinoISP.ino.cpp -o /dev/null
Generating function prototypes...
/Users/brandonbarks/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega4809 -DF_CPU=16000000L -DARDUINO=10812 -DARDUINO_AVR_UNO_WIFI_REV2 -DARDUINO_ARCH_MEGAAVR -DUNO_WIFI_REV2_328MODE -DMILLIS_USE_TIMERB3 -I/Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/cores/arduino/api/deprecated -I/Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/cores/arduino -I/Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/variants/uno2018 /var/folders/sc/1v4cm6053k7bmhv2bd02k44w0000gn/T/arduino_build_226513/sketch/ArduinoISP.ino.cpp -o /var/folders/sc/1v4cm6053k7bmhv2bd02k44w0000gn/T/arduino_build_226513/preproc/ctags_target_for_gcc_minus_e.cpp
/Applications/Arduino.app/Contents/Java/tools-builder/ctags/5.8-arduino11/ctags -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives /var/folders/sc/1v4cm6053k7bmhv2bd02k44w0000gn/T/arduino_build_226513/preproc/ctags_target_for_gcc_minus_e.cpp
Compiling sketch...
/Users/brandonbarks/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino5/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega4809 -DF_CPU=16000000L -DARDUINO=10812 -DARDUINO_AVR_UNO_WIFI_REV2 -DARDUINO_ARCH_MEGAAVR -DUNO_WIFI_REV2_328MODE -DMILLIS_USE_TIMERB3 -I/Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/cores/arduino/api/deprecated -I/Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/cores/arduino -I/Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/variants/uno2018 /var/folders/sc/1v4cm6053k7bmhv2bd02k44w0000gn/T/arduino_build_226513/sketch/ArduinoISP.ino.cpp -o /var/folders/sc/1v4cm6053k7bmhv2bd02k44w0000gn/T/arduino_build_226513/sketch/ArduinoISP.ino.cpp.o

ArduinoISP:191:27: error: reference to 'SPISettings' is ambiguous
     void beginTransaction(SPISettings settings) {
                           ^~~~~~~~~~~
/Applications/Arduino.app/Contents/Java/examples/11.ArduinoISP/ArduinoISP/ArduinoISP.ino:167:7: note: candidates are: class SPISettings
 class SPISettings {
       ^~~~~~~~~~~
In file included from /Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/cores/arduino/api/ArduinoAPI.h:31:0,
                 from /Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/cores/arduino/Arduino.h:23,
                 from /Applications/Arduino.app/Contents/Java/examples/11.ArduinoISP/ArduinoISP/ArduinoISP.ino:39:
/Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/cores/arduino/api/HardwareSPI.h:37:7: note:                 class arduino::SPISettings
 class SPISettings {
       ^~~~~~~~~~~
ArduinoISP:191:27: error: 'SPISettings' has not been declared
     void beginTransaction(SPISettings settings) {
                           ^~~~~~~~~~~
/Applications/Arduino.app/Contents/Java/examples/11.ArduinoISP/ArduinoISP/ArduinoISP.ino: In member function 'void BitBangedSPI::beginTransaction(int)':
ArduinoISP:192:39: error: request for member 'clock' in 'settings', which is of non-class type 'int'
       pulseWidth = (500000 + settings.clock - 1) / settings.clock;
                                       ^~~~~
ArduinoISP:192:61: error: request for member 'clock' in 'settings', which is of non-class type 'int'
       pulseWidth = (500000 + settings.clock - 1) / settings.clock;
                                                             ^~~~~
/Applications/Arduino.app/Contents/Java/examples/11.ArduinoISP/ArduinoISP/ArduinoISP.ino: In function 'void start_pmode()':
ArduinoISP:410:24: error: reference to 'SPISettings' is ambiguous
   SPI.beginTransaction(SPISettings(SPI_CLOCK, MSBFIRST, SPI_MODE0));
                        ^~~~~~~~~~~
/Applications/Arduino.app/Contents/Java/examples/11.ArduinoISP/ArduinoISP/ArduinoISP.ino:167:7: note: candidates are: class SPISettings
 class SPISettings {
       ^~~~~~~~~~~
In file included from /Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/cores/arduino/api/ArduinoAPI.h:31:0,
                 from /Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/cores/arduino/Arduino.h:23,
                 from /Applications/Arduino.app/Contents/Java/examples/11.ArduinoISP/ArduinoISP/ArduinoISP.ino:39:
/Users/brandonbarks/Library/Arduino15/packages/arduino/hardware/megaavr/1.8.6/cores/arduino/api/HardwareSPI.h:37:7: note:                 class arduino::SPISettings
 class SPISettings {
       ^~~~~~~~~~~
exit status 1
reference to 'SPISettings' is ambiguous

If anyone has any advice, I'd really appreciate it. Thanks!

What type of Arduino are you actually using? There is no Arduino Duo. Possibly you meant Arduino Uno or Arduino Due, though you tagged the question with Arduino Mega. Which one is it?

update the megaavr core


text:
acelermetor count goes down after 1 peak
I am using a Wemos D1 Mini and an mpu 6050 accelerametor. I managed to get the acceleratmetor to work and have 1 value come out of movements. So when a peak it hit (aka, the threshold of 1.00 is hit) n gets incremetented with 1. So it work a bit like a pedometer. This value is pushed to my firebase DB.
However mY problem is that after pushing it once, so the value of n is 1. The program blocks for a second and either slows down bad or the accelerametor value drops to 0. this only happens when i my piece of firebase code in. Im not sure if this causes any delays..
here is my part of my code:
#include <Wire.h>

#include "ESP8266WiFi.h"
#include "FirebaseArduino.h"

#define FIREBASE_HOST "xxxxxxxxxx.firebaseio.com" //Without http:// or https:// schemes
#define FIREBASE_AUTH "XXXXXXXXXXXXXXXXXXXXX"
#define WIFI_SSID "Bankai"
#define WIFI_PASSWORD "xxxxxxxxxxxx"

const float HI_THRESHOLD = 1.00;
const float LO_THRESHOLD = 0.70;
bool count_flag = false;

int n= 0; //will be used to store the count
int oldValue = n;
String myString;

const uint8_t MPU_addr = 0x68; // I2C address of the MPU-6050

const float MPU_GYRO_250_SCALE = 131.0;
const float MPU_GYRO_500_SCALE = 65.5;
const float MPU_GYRO_1000_SCALE = 32.8;
const float MPU_GYRO_2000_SCALE = 16.4;
const float MPU_ACCL_2_SCALE = 16384.0;
const float MPU_ACCL_4_SCALE = 8192.0;
const float MPU_ACCL_8_SCALE = 4096.0;
const float MPU_ACCL_16_SCALE = 2048.0;

struct rawdata {
  int16_t AcX; //Acceleration
  int16_t AcY; //Acceleration
  int16_t AcZ; //Acceleration
  int16_t Tmp;
  int16_t GyX; //Gyroscope
  int16_t GyY; //Gyroscope
  int16_t GyZ; //Gyroscope
};

// Using int variables to convert later on to degrees and decimals
struct scaleddata {
  float AcX; //Acceleration
  float AcY; //Acceleration
  float AcZ; //Acceleration
  float Tmp;
  float GyX; //Gyroscope
  float GyY; //Gyroscope
  float GyZ; //Gyroscope
};

bool checkI2c(byte addr);
void mpu6050Begin(byte addr);
rawdata mpu6050Read(byte addr, bool Debug);
void setMPU6050scales(byte addr, uint8_t Gyro, uint8_t Accl);
void getMPU6050scales(byte addr, uint8_t &Gyro, uint8_t &Accl);
scaleddata convertRawToScaled(byte addr, rawdata data_in, bool Debug);

//start connection, serial, and connection to db
void setup() {
  Wire.begin();
  Serial.begin(115200);

  mpu6050Begin(MPU_addr);

    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(100);
  }
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();
    Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);

}

//if the value now is different from the current value it gets pushed to the DB, otherwise a flood of numbers apperars.
void loop() {
  rawdata next_sample;
  setMPU6050scales(MPU_addr, 0b00000000, 0b00010000);
  next_sample = mpu6050Read(MPU_addr, false);
  convertRawToScaled(MPU_addr, next_sample, false);

I feel likeit is thei part which creates the bottleneck.
  //myString = String(n);
  if(oldValue != n){
   Firebase.setInt("Reps/Value", n);
  }
  delay(100); // Wait 5 seconds and scan again

}

 float filterConstant = 0.05;
  values.AcX = (float) data_in.AcX / scale_value;
  values.AcY = (float) data_in.AcY / scale_value;
  values.AcZ = (float) data_in.AcZ / scale_value;
  filteredAx = filteredAx * (1.0 - filterConstant) + values.AcX * filterConstant;
  filteredAy = filteredAy * (1.0 - filterConstant) + values.AcY * filterConstant;
  filteredAz = filteredAz * (1.0 - filterConstant) + values.AcZ * filterConstant;
  float result = sqrt((filteredAx * filteredAx) + (filteredAy * filteredAy ) + (filteredAz * filteredAx ));

//  Serial.print(values.AcX); Serial.print("\t");
//  Serial.print(filteredAx); Serial.print("\t");

  Serial.println(result);

  //    Serial.print(values.AcY); Serial.print("\t");
  //    Serial.print(values.AcZ);
//  Serial.println();

 if( result > HI_THRESHOLD && !count_flag) //if analog_in > Hi_THRESHOLD and count_flag == false
     {
           n++;
           count_flag = true;
     }

     if(result <= HI_THRESHOLD) //set count_flag to false only when below the threshold
           count_flag = false;

  Serial.println(n);

  return values;
}

Can you help me find the problem? Thank you!

Logging the data is indeed what slows your program down.  You can't avoid that.  There are several ways to deal with it depending on what you need.
Instead of logging data all the time, you could try to accumulate a bunch of data and then write it.  This approach of buffering data will still fail to read while you log, but you will be able to get bursts of good data in between.


text:
Motor driver shield l239D should be giving enough power but it doesn't
I am doing a line follower robot using motor driver shield l239D stacked with an Arduino uno to run 2 DC motors and two infrared sensors. I am supplying 12V to the motor driver shield trough three 18650 batteries.
The point is the car was working fine and it followed the line but  two days ago it stopped working after one week of working fine...
When the two DC motors and two sensors are connected the motors don't move they just buzz(the sound it makes when it's not getting enough power), it works sometimes a little bit...
Basically the car only works with no sensor connected. So I made measurements with the multimeter and I got this:
The three batteries:12.62V
The shield receives: 12.39V only with the two sensors connected and the motors disconnected.
The shield with the motors and two sensors connected:12.28V.
And when I measured how much the motors where receiving I got 0V! In both of them...
With just one motor and the sensors connected the motor started buzzing and I got 0.07V till the sound stopped and I got zero again.
Sometimes the motors work a little bit sometimes they just buzz and some times they don't buzz at all...
I see that the batteries are fine and they can deliver enough current for everything to work but the motors don't receive almost anything!!!
Can you help me and tell me suggestions of what I need to do please? I searched and asked a lot but haven't found anything that helps...
Here is my car and my circuit.

If you are working  with dupont plugs check each of them sounds like a problem with connection - check for loose/not fully connecting plugs and pins. Because if it worked the only other solution is you fried something by overheating/overpowering

If it is "only works with no sensor connected", then it is something to do with your code. Edit your post and add your code.

The cause is really the lack of power because with one sensor it works. But could it be because my wires for the batteries are thin? Wich doesn't make sense because they can passe the 12V to the shield... But could it be from it?

Does the motors work with the sensors disconnected? Do the sensors work with the motors disconnected? Did you measure the voltage at the output terminals of the shield as well as the input? If you can isolate the fault to one component it would be a lot easier to fix.


text:
store multiple of float type on EEPROM
I have 7 float variables.
float temperature, differential, calibration,hta,lta,hha,lha;
I want to store them all on the EEPROM memory, how do I calculate the addresses given that there type is float.
Thanks!

create a struct and store the struct
#include <EEPROM.h>

const int DATA_ADDR = 0;

struct MyData {
  float temperature, differential, calibration,hta,lta,hha,lha;
};

MyData data;

void setup() {
  data.temperature = 1.2;

  EEPROM.put(DATA_ADDR, data);

  EEPROM.get(DATA_ADDR, data);
}

void loop() {

}

With the sizeof function:
int nrOfBytesOfTemperature = sizeof(temperature);

You can also use directly a type:
int nrOfBytesOfFloat = sizeof(float);


text:
Making a Bluetooth Mouse with Arduino
I'm trying to make a bluetooth mouse using Arduino. I will be using an analog 2 axis thumbstick as the sensor. I understand that it's possible to do this with the Arduino connected directly to the computer (https://www.arduino.cc/reference/en/language/functions/usb/mouse/). Would it be possible for the arduino to instead communicate wirelessly using bluetooth? The controller I'm interested in is here: https://www.dfrobot.com/product-1259.html
Thank you!

With that specific board, yes you can.  According to this review:

Bluno also supports the HID (Human Interface Device) mode. When running in this mode, Bluno simulates an input peripheral (keyboard, mouse…) connected via BLE.


text:
sending numbers from server to client (arduino mkr1010)
I want to send basic information from a server to a client. 4 numbers representing a random sequence
for example 0100. I have put this in byte array and use the "server.write" to send it to the client. At the client side I always get 4 times "255" when i print it on the monitor (when i print in on serial monitor on the server side it shows the right sequence numbers).
This is (only relevant part of ) my code on the server:
int sequence;
byte myseq[4]={0,0,0,0};
int i;
byte a;

void loop() {
  // wait for a new client:
  WiFiClient client = server.available();

  sequence=random(0,3);

for (i = 0; i < 4; i = i + 1) {
  if (i == sequence){
  a=1;
  }
  else{
  a=0;
  }
   myseq[i] = a;
     }

  // when the client sends the first byte, say hello:
  if (client) {
    if (!alreadyConnected) {
      // clead out the input buffer:
      client.flush();
      Serial.println("We have a new client");
      client.println("Hello, client!");
      alreadyConnected = true;
    }

    if (client.available() > 0) {
      // read the bytes incoming from the client:
      char request = client.read();
      Serial.print(request);
      for (i = 0; i < 4; i = i + 1) {
      Serial.print(myseq[i]);
      server.write(myseq[i]);

      }

    }
  }
}

the code on the client side
byte response[4]={0,0,0,0};

void loop() {

if (client.connect(ServerIP, 23)) {
  client.print("741G");
  //String response = client.readStringUntil('\n');
  for (i = 0; i < 4; i = i + 1) {
  response[i] = client.read();
  Serial.println(response[i]);

  }

  //client.stop();
}

Can somebody help me in explaining what i'm doing wrong ? what happens with the numbers once they get sent ? Apparently they arrive in a different format ?
thanks in advance !
ps : i see now that my sequence numbers are always 4 booleans (half a byte) maybe there is an easier way?

you don't test with client.available() if the bytes arrived so read returns -1


text:
Client.available remains empty (0)
i use the "client.availbale" to check incoming data on the (mkr1010) client coming from (mkr1010) server but it always contains "0". Serial printing (monitor) it on server works. It looks as if the data never arrives? Thanks for helping out !
client code :
if (client.connect(ServerIP, 23)) {
client.print("741G");
byte i = 0;
Serial.println(client.available());

    while (client.available() > 0 && i < bufferSize) {

      incomingMessage[i] = client.read();
      Serial.println(incomingMessage[i]);
      Serial.println(i);
      // check if end of incoming message
      if (incomingMessage[i] == '\r') {
        // replace carriage return with null terminator
        incomingMessage[i] = '\0';
        // set array index counter to end
        i = bufferSize;
        // flush out any remaining control characters which would
        // stay in client buffer until next loop
        client.flush();
      }
      // increase array index counter
      i++;

my server code :
// when the client sends the first byte, say hello:
  if (client) {
    if (!alreadyConnected) {
      // clead out the input buffer:
      client.flush();
      Serial.println("We have a new client");
      client.println("Hello, client!");
      alreadyConnected = true;
    }

    if (client.available() > 0) {
      // read the bytes incoming from the client:
      char request = client.read();
      Serial.print(request);

      for (i = 0; i < 4; i = i + 1) {
      Serial.print(myseq[i]);
      server.write(myseq[i]);

      }

use client.write(). does the server print "We have a new client"?

thanks for your reply. Apparently client.write gives same result. this is logic since if I'm right client.write writes to the specific client and server.write writes to all clients connected.

I don't know that specific board, but most often you need to accept the client's connection on the server with client = server.available().

that is done in another part of my server code. data from client to server works fine it is the other direction that doesn't work

@Majid that's what Majenko says. Do you use client.connected() anywhere?


text:
Stepper Motor is not working with A4988 board
So, I have been following this tutorial on how to run a stepper motor with Arduino using an A4988 Stepper Driver. This is the tutorial: How To Control a Stepper Motor with A4988 Driver and Arduino. I have connected the wires according to this schematic:

I have connected the wires exactly like this and triple-checked it! The problem is the stepper motor is not turning. This is the code(it's simple):
// defines pins numbers
const int stepPin = 3;
const int dirPin = 4;

void setup() {
  // Sets the two pins as Outputs
  pinMode(stepPin,OUTPUT);
  pinMode(dirPin,OUTPUT);
}

void loop() {
  digitalWrithe(dirPin,HIGH); // Enables the motor to move in a particular direction
  // Makes 200 pulses for making one full cycle rotation
  for(int x = 0; x < 200; x++) {
    digitalWrite(stepPin,HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin,LOW);
    delayMicroseconds(500);
  }
  delay(500); // One second delay
}

One weird thing:

When I connect the sleep and reset pin on the A4988 board the stepper motor starts turning. Like why?

NOTE: I replaced the MEGA with a UNO because at the moment I'm just testing.

Have you tried pulling Sleep and Reset to HIGH, like shown on page 1 and 7 of the A4988 datasheet?

I have NOT. Because I didn't see it. Wait I'll try it out. Thanks!

I have the same problem. My motor is vibrating but not realy moveing. Can you help me?

@PurpleOwl See the answer below, that's what I tried and it worked for me. You essentially need to connect the sleep and reset pin together. If they still don't work, see the debugging options below.

You have to connect the sleep and reset pin together. I assume that you took this schema on how to mechatronics. In his video you see that the sleep and reset pins are connected. I don't know why but it has to be like that.
Then, if the motor vibrates or click, it may be one of these problems:

You didn't connect the motor properly
The current is set too low on the board (screw on the motor driver)
The battery (Vmot) isn't powerful enough

If it's not one of those problems, the A4988 chip might have an issue. I have a similar problem where it turn in one direction and only when the pwm signal goes throught the direction pin  instead of the step pin.

Thanks! The question is from about two years ago. So, I figured it out myself then. But appreciate your effort and am accepting it as an answer. Thanks again :)


text:
random soft wdt reset while request
i am making post requests with esp8266 on nodeMCU. i have a messy code so i dont want to annoy you with showing it here. the problem is i get soft wdt reset time to time while making request. for example i change piece of code(removing or adding some serial.println lines) and i see i get soft wdt reset right there in http.post.
i tried my best to avoid Strings. I only used a few times, without in the loop. I am only using WiFiClientSecureBearSSL with FirebaseESP8266.
do you have any idea what cause this problem?

How are you powering the board?

with usb. i am not using without cable yet i am still dealing with these resets.

Connected direct you your computer? Not through an unpowered hub?

It is connected directly to the usb port. Why is there something wrong with it?

No. Quite the opposite. I have seen WDT timeouts when the board has been under-powered, but that's not the case here.

yeah. my problem is more like random here. i get wdt resets at diffrent requests. i thought maybe stack or heap reach each other but that is not related to soft wdt reset, is it?

It was the randomness that made me think power. But that's unlikely. A watchdog timeout could be caused by anything than makes execution go wrong.

Can usage of strings a few times cause memory fragmentation? Those Strings size are less than 100 characters.

Show examples of the error - and install ESPexeption decoder to analyse the stack trace this will at least show why the wdt was caused
So the only thing as of now I can recommend
There is an issue with bearssl:
It's a WDT error caused by an extended SSL negotiation.

Change the core frequency to 160MHz (if not already done) and try again.
Use instead of LWIP1.4 (memory hog) low-mem LWIP2.0 with your program.
Since SSL negotiation can take 5 seconds even at 160MHz for some websites be sure by adding a yield() not to trigger a wdt reset

So without code/ trace and error messages its hard to guess


text:
Arduino "Phantom Powering"
I am using an Arduino Uno in my project. I recently found that if I disconnect the power from my Arduino (I am powering it by USB port, from a 5V regulator - 7805), then it remains under power from the input pins. I also found that if I disconnect the 3 digit 7 segment common anode display (which is also powered from same 7805) and if I remove the LM358 (which is again powered from the same 7805) from the socket, then my Arduino is not powered anymore.
My questions are:

Is my setup correct - if I am powering it from the 5V regulator (7805) through the USB port ?
My Arduino and the other components from the schematic - the display, the LM358, the mosfet - will be powered on at the same time, when the 230V switch that is placed on the mains input of the 24V SMPS is closed. Could this be a problem in terms of "phantom powering" ? Is there any better way to power the Arduino when I have 5V regulated supply on the schematic ? I will always keep connected the Arduino to the 5V output of the 7805 to the USB port.

Please find attached 2 schematics, one is the main PCB (the one with Arduino) and the other schematic is the one with the display, which is placed on the front panel. The J2 connector from first schematic is connected pin to pin to the J2 from second schematic.
https://ibb.co/QnLHsM0
https://ibb.co/KxLFKsQ

Is my setup correct - if I am powering it from the 5V regulator (7805) through the USB port ?

Yes.

My Arduino and the other components from the schematic - the display, the LM358, the mosfet - will be powered on at the same time, when the 230V switch that is placed on the mains input of the 24V SMPS is closed. Could this be a problem in terms of "phantom powering" ? Is there any better way to power the Arduino when I have 5V regulated supply on the schematic ? I will always keep connected the Arduino to the 5V output of the 7805 to the USB port.

Not really.
Your problem only occurs when you "break" the system by separating the 5V from the Arduino - at which point current flows from the output of the op-amp and through the LED displays, through the IO pins, up through the clamping diodes inside the IO pins, and to the Arduino's 5V.
Since it only happens if you disconnect the 5V and you don't intend to disconnect the 5V then it's not a problem. However if you wanted to improve it then you could take the output of the 5V reguator and feed that direct into the Arduino's USB port. You could then power all the other devices that run at 5V from the Arduino's 5V pin.  That way if you remove the 5V from the Arduino then you also remove it from all the other 5V devices that potentially feed power back in.

When you disconnect the arduino from 5V you must also remove either

disconnect any other device that is connected to the arduino and has its own power supply
or disconnect every device that is connected to the arduino from its power supply

When you disconnect 5V from the arduino while devices connected to a gpio are still powered, this gpio might see a voltage larger than zero. But the voltage at any pin must not exceed the arduino's actual supply voltage by more than 0.3V. Otherwise the atmega's supply rail will be pulled high through esd protection diodes and the atmega will try to operate. It will then probably draw more current than what the esd diodes are rated for and they will eventually fail (destroying that gpio).


text:
Why is delay(1000) breaking my serial communication?
I have the following sketch...
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
}

void loop() {
  if(Serial.available() > 0){
    Serial.println("Hello world from Ardunio!");
  }
}

This works great with my client code...
import SerialPort from 'serialport';
const port = new SerialPort('/dev/ttyACM0', {
  baudRate: 115200,
  autoOpen: false
})

port.open(function (err) {
  if (err) {
    return console.log('Error opening port: ', err.message)
  }

  // Because there's no callback to write, write errors will be emitted on the port:
  console.log("port opened");
  port.on('readable', function () {
    console.log('Data:', port.read())
  })
})

Now I want to slow it down so I change the sketch to...
void loop() {
  if(Serial.available() > 0){
    Serial.println("Hello world from Ardunio!");
  }
  delay(10000);
}

I would expect this to delay each message by 10 seconds, however, it seems to never rerun so I do not get any messages. What am I missing? Why would delay break the loop?

What if you double the line Serial.println("Hello world from Ardunio!");?

what happens if you remove the delay?

I thought it was working fine but now I am questioning that as I am having trouble again after going back from a couple of other things I was trying. I am not sure if when it was working I was still accidentally using while. I will try adding a few writes with delays and see if that helps at all. The ultimate goal is to write to the serial port every n seconds.

It just doesn't seem that loop is looping, If I remove the if and add multiple prints and delays it does seem to work. Why doesn't it work if I use the if statement?

Do you write anything to the arduino on the serial line?

because the if statement test does not evaluate to true

NEVER use delay() in a loop - its a bad habit you get used to and then you return later on with complex code asking why nothing is happening or your webserver is dead for 10 seconds every time you receive a request.
So instead of
void loop() {
  if(Serial.available() > 0){
    Serial.println("Hello world from Ardunio!");
  }
  delay(10000);
 }

you would do
unsigned long timerStart = 0;
unsigned long myTimer = 10000;

setup(){....}

 void loop() {
  if(Serial.available() > 0 ){
     if(millis() - timerStart > myTimer){      // non blocking
       Serial.println("Hello world from Ardunio!");
       timerStart = millis(); // reset timer
     }
   }
 }

What your code does at the moment is enter the IF clause if exactly in this millis the buffer is filled, then wait for ten seconds ignoring whatever you do. Next chance tohit and so on. Delay() is blocking processing => not a good thing todo in communication scenarios,

Sure makes sense thanks

Get rid of if(Serial.available() > 0). You only need that if statement if you're expecting information from Serial, but it doesn't seem to be the case for your project.
Also, only use delay() if you have a really good reason to.

So that is the next step. So that is triggered when you write?

Also that was probably why it worked the first time, I tried to simplify the code for SO and assumed removing the write would not be an issue. I was wrong

if(Serial.available() > 0) is triggered when something is received from the PC. If you have a problem with your code - post the entire code. You don't know where the bug is - it could be in the code that was left out


text:
Car PA system enhancement
Hello i have one of these
My goal for this project is to have a higher quality mic and be able to play music through it
My question is how would i link a 3.5mm aux cable to the arduino as input and output to the rj9 line. I have prior knowlege on liking a aux as i have setup my Christmas lights as a vu meter using relays and a aux but the confusing part is the rj9 line
Are the speaker pins only to trigger a relay and allow power to flow from the car battery or am i completely wrong if im right i assume i could just solder the audio jacks positive negative to the rj9 mic positive negative and then find a method to triger the speaker relay

your question about modifying the PA device is not related to an Arduino

Well assuming that my bottom portion was true the arduino was going to trigger the speaker if audio was comming off the jack there could be a better way though that would not require a arduino

"how would i link a 3.5mm aux cable to the arduino as input and output to the rj9 line" - the arduino uno doesn't have a digital to analog converter, so without external hardware it's not possible to make him generate the audio signal. Also its ADCs are not fast enough to sample an audio signal coming from a microphone at a sufficient sample rate (I think the maximum are 1-2kHz). As you explicitly want to improve sound quality this is an issue.
When using an arduino uno you might be better off using an external audio circuit which only gets switched on and off by the arduino.
Controlling the siren's buttons will not be a big difficulty. You have to do some reverse engineering to find out the siren's logic level and how the buttons are used in the device. You can probably simply replace them with mosfets, but that is an electronic issue.

So even with a adc the standard sample rate being 44.1 khz i would need almost 30 times the current capabilities of a adc. I didnt realise that perspective thank you


text:
Restart sequence of NeoPixel stick with a push button at any time
I am really happy with my new Arduino stuff and playing around with all those pixels :).
I am new to programming and it's difficult to understand it, but with every success, I grow in knowledge.
My latest problem now is to restart my loop of incrementing the strip at any time with the push of a button.
I know that delay(); will stop the code completely and wait till the time passes, but I wrote some code without the use of delay(); and used millis(); instead.
So far my LEDs are incrementing through my strip, but I am not able to restart it until it passes though completely. I read that the while(); part in my code works kinda like a delay(); and that would prevent it from restarting until a full cycle. I used some millis(); code from a different sample so it's not like the ones from Blink Without Delay.
I searched so many sites and cannot write another code to increment without a delay, so hopefully you can help me with it.
#include <FastLED.h>

#define NUM_LEDS_PER_STRIP 16
CRGB ledStrip[NUM_LEDS_PER_STRIP];

const int signalButtonPin = 4;
const int ledStripPin = 8;

int buttonState = 0;
int lastButtonState = 0;

int delaySignalAnimation = 100;

unsigned long currentMillis = 0;
unsigned long previousMillis = 0;

void setup() {
  pinMode(signalButtonPin, INPUT_PULLUP);
  pinMode(ledStripPin, OUTPUT);
  FastLED.addLeds<NEOPIXEL, 8>(ledStrip, NUM_LEDS_PER_STRIP);
}

void loop() {
  buttonState = digitalRead(signalButtonPin);
  if (buttonState != lastButtonState) {
    if (buttonState == LOW) {
      fill_solid(ledStrip, NUM_LEDS_PER_STRIP, CRGB::Black);
      for (int i = 0; i < 16; i++) {
        ledStrip[i] = CRGB::Blue;
        FastLED.setBrightness(100);
        FastLED.show();
        currentMillis = previousMillis = millis();
        while (previousMillis + delaySignalAnimation >= currentMillis) {
          currentMillis = millis();
        }
      }
    } else {
      lastButtonState = buttonState;
    }
    fill_solid(ledStrip, NUM_LEDS_PER_STRIP, CRGB::Black);
    FastLED.setBrightness(0);
  }
  FastLED.show();
}

Thanks in advance for you help.

Firstly, good for you trying to avoid delay().
However your while loop pretty much does exactly what delay() does anyway.
Instead you need to change your way of thinking. Instead of "I want to light LEDs 0 to 15 in sequence" you need to instead think "I have 6 LEDs lit. Now I need to light the 7th".
Each time through the loop, if enough time has passed (check the BlinkWithoutDelay example) then light just one more LED.  Once you have lit all 16 you can then restart your sequence.
And when you know how to restart your sequence at the end you should also know how to restart the sequence when you press a button.
For example loop() might look something like this (untested):
void loop() {
    static uint8_t lednum = 0;
    static uint32_t animTicker = millis();

    if (millis() - animTicker >= 1000) { // Once per second
        animTicker = millis();

        lednum++;
        if (lednum > NUM_LEDS_PER_STRIP) lednum = 0; // This resets the sequence

        // Turn on up to lednum LEDs and turn off the others
        for (uint8_t i = 0; i < NUM_LEDS_PER_STRIP; i++) {
            if (i < lednum) {
                ledStrip[i] = CRGB::Blue;
            } else {
                ledStrip[i] = CRGB::Black;
            }
        }

        FastLED.show();
    }

    buttonState = digitalRead(signalButtonPin);

    if (buttonState != lastButtonState) {
        lastButtonState = buttonState;
        if (buttonState == LOW) {
            lednum = 0;
        }
    }
}

The key there is that the variable lednum contains the number of LEDs that you want to display. Once per second, controlled by millis(), the LEDs are updated to display that number of LEDs.

Thanks for answering to my question. I will look up your sketch and will respond how its going. Yes, I read that it would be the same as a delay. I saw some code using unit8_t or unit32_t but it scared me for using it because it looks scary :D.

Those are just specific sized variables.  "u" is "unsigned". "int" is "integer", and "x_t" is the number of bits.  uint8_t is the same as byte but is portable (byte is Arduino-specific). uint32_t is the same as unsigned long but again is portable over different architectures.

Alright, that sounds not so scary anymore, its like a short version of those words. Thanks.

I loaded your sketch in and I can now reset during the counts. Now I need to look how I can start the sequenz with the same button and that it would stop after 1 cycle, cause it runs over and over again, but thats what a loop is for :)

This is not an answer, but an expansion on Majenko's code.
It adds another layer between the button press and the led display functions to make the program more flexible
void loop() {

    static bool     tick          = false;                 // periodic trigger signal
    static bool     zap           = false;                 // enable signal to run sequence
    static bool     buttonClicked = false;                 // button moved from "released" to "pressed"

    static uint8_t  mode          = 0;                     // chooses the light sequence to run
    static uint8_t  lednum        = 0;

    static uint32_t animTicker    = millis();

    if (millis() - animTicker >= 1000) {                   // Once per second
        animTicker = millis();
        tick = true;                                       // set the tick flag
    }

    if (buttonClicked) {                                   // you could check for a double-click here
        buttonClicked = false;
        zap = !zap;                                        // start/stop with button  ... zap is used for the separation of the button click function and the display function
        if (zap) {
            lednum = 0;                                    // start animation sequence at beginning
            mode += 1; if (mode > 2) mode = 0;             // select the next mode .... this could be done with a double-click
        }
    }

    if (tick && zap) {
        tick = false;                                                   // clear the tick flag .... zap stays set for the duration of the animation sequence
        lednum++;

        if (lednum > NUM_LEDS_PER_STRIP) {
            zap = false;                                                // This stops the sequence (runs only once) ... use a counter if multiples are needed
        }

        else {
            switch (mode) {                                             // pick one of the sequences ....  only colors change in this example

                case 0:
                    for (uint8_t i = 0; i < NUM_LEDS_PER_STRIP; i++) {  // Turn on up to lednum LEDs and turn off the others
                        if (i < lednum) {
                            ledStrip[i] = CRGB::Blue;
                        } else {
                            ledStrip[i] = CRGB::Black;
                        }
                    }
                    break;

                case 1:
                    for (uint8_t i = 0; i < NUM_LEDS_PER_STRIP; i++) {
                        if (i < lednum) {
                            ledStrip[i] = CRGB::Red;
                        } else {
                            ledStrip[i] = CRGB::Black;
                        }
                    }
                    break;

                case 2:
                    for (uint8_t i = 0; i < NUM_LEDS_PER_STRIP; i++) {
                        if (i < lednum) {
                            ledStrip[i] = CRGB::Green;
                        } else {
                            ledStrip[i] = CRGB::Yellow;
                        }
                    }
                    break;
            }

            FastLED.show();
        }
    }

    buttonState = digitalRead(signalButtonPin);

    if (buttonState != lastButtonState) {        // button state transition
        lastButtonState = buttonState;           // new "last state"
        if (buttonState == LOW) {                // transition from "released" to "pressed"
            buttonClicked = true;
        }
    }
}

Hi jsotola, I see you have posted a state machine. I have moving forward to a state machine as well, but am not yet familiar with it. I will try to inplement your code and will share my progress. Does the double click takes aktion if I press the button twice directly after it, or does it count forever to the second press? Thanks for your code and your time to make it. :)

you have to implement double click function ... that example code does not have it ... the code is mostly meant to demonstrate that button presses should not directly cause an action to occur, unless the code is very simple ... as far as double clicks go, all you have to do is to "remember" when the last click happened ... if the time interval, between the previous click and the current click, is shorter than some chosen value, then a double-click is detected

a real life state machine example is yourself when you are driving a motor vehicle on city street and you approach an intersection that is controlled by a traffic light .... think of yourself as a microcontroller ... you continuously monitor the traffic light state in a loop and you take action as a result of your observation


text:
Error messages while verifying code with Visual Studio Code
I move recently to use Visual Studio Code to develop for arduino. But I'm receiving some error messages while I'm trying to verify my code that confuse me. The messages are:
2020-04-12T13:53:40.409Z INFO c.a.u.n.HttpConnectionManager:148 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Connect to https://builder.arduino.cc/builder/v1/boards/0x8087/0x0ACA, method=GET, request id=20892E5EE7E84976
2020-04-12T13:53:40.926Z INFO c.a.u.n.HttpConnectionManager:152 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Request complete URL="https://builder.arduino.cc/builder/v1/boards/0x8087/0x0ACA", method=GET, response code=404, request id=20892E5EE7E84976, headers={null=[HTTP/1.1 404 Not Found], Cache-Control=[no-cache, no-store, must-revalidate], Server=[nginx], Connection=[keep-alive], Vary=[Origin], Pragma=[no-cache], Expires=[0], Content-Length=[0], Date=[Sun, 12 Apr 2020 13:53:41 GMT]}
2020-04-12T13:53:40.926Z WARN p.a.h.BoardCloudResolver:64 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Fail to get the Vid Pid information from the builder response code=404
2020-04-12T13:53:40.937Z INFO c.a.u.n.HttpConnectionManager:148 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Connect to https://builder.arduino.cc/builder/v1/boards/0x8087/0x0ACA, method=GET, request id=D8C082A90BB14CDF
2020-04-12T13:53:41.044Z INFO c.a.u.n.HttpConnectionManager:152 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Request complete URL="https://builder.arduino.cc/builder/v1/boards/0x8087/0x0ACA", method=GET, response code=404, request id=D8C082A90BB14CDF, headers={null=[HTTP/1.1 404 Not Found], Cache-Control=[no-cache, no-store, must-revalidate], Server=[nginx], Connection=[keep-alive], Vary=[Origin], Pragma=[no-cache], Expires=[0], Content-Length=[0], Date=[Sun, 12 Apr 2020 13:53:41 GMT]}
2020-04-12T13:53:41.044Z WARN p.a.h.BoardCloudResolver:64 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Fail to get the Vid Pid information from the builder response code=404

Based on this output it seems something is happening with these URLs but when I try to do the same in the same computer with Arduino IDE there is no such error messages.
Does anybody know how to get rid of these messages?
Thank you very much.

Downgrade your Arduino IDE to a version below 1.8.10.

It works with Arduino IDE either 1.8.9 OR 1.8.12 BUT the VS code extension is broken. So

You have to downgrade to January release 1.42 AND
Then turn off automatic updates for the moment.

How to get the release: Click here
Before installing /downgrade
The excessive debug logging is caused by running Java with -DDEBUG=true. Adding -DDEBUG=false to the C:\Program Files (x86)\Arduino\arduino_debug.l4j.ini fixes it for now.

Thank you corebreaker007. I was aware of the debug logging problem as that was the first issue I ran into and after some research, I was able to work it out. I'm using Arduino ide 1.8.12, Visual studio code 1.44 and Arduino extension 0.3.0. I will try to downgrade following your advice. After trying to find a replacement for Arduino IDE as the editor is far from being perfect, I thought that Visual Code could be a fit as it's simple but complete. It's a pity because it seems there are many minor mistakes that are time-consuming to have a platform you can rely on. Thank you for your help.

Also check out the PlatformIO extension for VSCode!