text:
Arduino Infinity Loop
I'm new to this Arduino programming. So I want to ask about my current project. My lecturer told me to make a temperature sensor using an LM35, where a green LED will light up when below some certain temperature that I set. The same goes for yellow and red LEDs for medium, and high temperatures. The tricky part here is that I need to make sure my buzzer (piezo) is on forever if it reaches the high temperature, until I press a button to reset it.
This is my coding so far:
const int greenLed = 3;
const int redLed = 4;
const int yellowLed = 5;
float tempC;
int reading;
int tempPin = 0;
int speakerOut = 11;
const int buttonPin = 2;
int buttonState = 0;
long duration = 10000;
int tempo = 0;

void setup() {
// initialize digital pin 13 as an output.
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(2, INPUT);
pinMode(11, OUTPUT);
analogReference(INTERNAL);
Serial.begin(9600);
}

// the loop function runs over and over again forever
void loop() {
buttonState = digitalRead(buttonPin);
reading = analogRead(tempPin);
tempC = reading / 9.31;
Serial.println(tempC);
delay(500);

if (tempC < 30.00) {
//Serial.println("Temp LOW");
digitalWrite(3, HIGH);
delay(10);
}else {
digitalWrite(3,LOW);
delay(10);

}

if (31.00 < tempC < 33){
//Serial.println("Temp MED");
digitalWrite(4,HIGH);
digitalWrite(5,LOW);
delay(50);
digitalWrite(4,LOW);
digitalWrite(5,HIGH);
delay(50);

}else {
digitalWrite(4,LOW);
digitalWrite(5,LOW);

}

if(tempC >= 34){
**WHAT SHOULD I FILL UP HERE TO MAKE SURE MY PIEZO BUZZER ON FOREVER**
}
if(buttonState = 1);{
digitalWrite(11, LOW);
}

}
Any help would be great. Or if you have a better idea on how to do this, I'm gonna love it.

Please post the wiring of this and format the code. Also use the constants you have defined. Why define "greenLed = 3" and still use "digitalWrite(3, ...)"?

uhmm i dont get what you mean.its my 1st month learning this.well if i do "greenLed =3 , it is not good to use digitalWrite(3,...)"? .Whats the better way?

A better way is "digitalWrite(greenLed, ...)". The whole idea behind giving a pin a "name" is to allow change but also make the code easier to read. But your lecturer should have told you that :)

You can use the toneAC library, which allows even better handling of piezo speakers then the standard "tone"-functions.

Features: Nearly twice the volume (because it uses two out of phase pins in push/pull fashion)
      Higher quality (less clicking)
      Capability of producing higher frequencies (even if running at a lower clock speed)
      Nearly 1.5k smaller compiled code
      Bug fixes (standard tone library can generate some odd and unpredictable results)
      Can set not only the frequency but also the sound volume
      Less stress on the speaker so it will last longer and sound better

With the library you can do something like:
int freq = 1000
int vol = 10
int length = 0
boolean background = true

toneAC(freq, vol, length, background);

The tone now will play forever in the background, until you stop it with:
toneAC(0);

Ohh cool.Gonna try this one later. Thanks for ur help!

The answer is simple add
digitalWrite(speakerOut,HIGH);

Common mistake made by beginners is to use assign operator instead of compare operator
if(buttonState=1)

should actually be
if(buttonState==1)

Never pull that pin LOW
if(buttonState = 1);{
digitalWrite(11, LOW);
}

is wrong use the below code
if(buttonState == 1){
    digitalWrite(11, LOW);
}

Don't forget to connect the button to buttonPin or you will get random HIGH or LOW from that pin since its floating
Hope this helps.

That's not how a Piezo-Speaker works...

Comments are not for extended discussion; this conversation has been moved to chat.


text:
Water heater coding problem
I need help with my coding. I'm still learning on how to use interval millis().
Currently I'm working on a water heater with a safety feature. This means that you can only pour water out when you activate the child-lock feature. The child-lock feature will turn on for 5 seconds and within that 5 seconds if you pour the water out, the timer will pause until you finish pouring your water and the 5 second timer will start again and the system goes off after that.
If the child lock feature on for 5 second without any action, it will turn off the system again. My lecturer does not allow me to use the delay() function so I already did my coding using millis().
This is my code so far:
const int redLed = 2;
const int greenLed = 3;
const int yellowLed = 4;
const int greenbigLed = 7;

const int buttonPin1 = 5;
const int buttonPin2 = 6;

int buttonState1 = 0;
int buttonState2 = 0;
float tempC ;
int analogPin = A0;
int yellowLedState = 0;

const long interval1 =0;
const long interval2 = 5000;
unsigned long previousMillis = 0;

void setup() {
  // put your setup code here, to run once:
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,INPUT);
pinMode(6,INPUT);
Serial.begin(9600);
digitalWrite(yellowLed,yellowLedState);

}

void loop() {
  // put your main code here, to run repeatedly:
int analogValue = analogRead(analogPin);
int buttonState1 = digitalRead(buttonPin1);
int buttonState2 = digitalRead(buttonPin2);
int yellowLedState = digitalRead(yellowLed);
tempC = analogValue / 10 ;
Serial.println(tempC);
unsigned long currentMillis = millis();
unsigned long currentMillis2 = millis();

if (tempC <= 89.9 && tempC >= 0){
  digitalWrite(redLed,HIGH);
  digitalWrite(greenLed,LOW);
}else if(tempC == 102){
  digitalWrite(redLed,LOW);
  digitalWrite(greenLed,HIGH);
}

if(currentMillis - previousMillis >= interval2){
  previousMillis = currentMillis;
  if(buttonState1 == HIGH){
   // if(currentMillis2 - previousMillis2 >=interval2){
     if (yellowLedState == LOW) {
          yellowLedState = HIGH;
}
digitalWrite(yellowLed, yellowLedState);
  } else{
  digitalWrite(yellowLed,LOW);
    }
}

if (buttonState2 == HIGH && yellowLedState == HIGH){
  digitalWrite(greenbigLed, HIGH);
}else{
  digitalWrite(greenbigLed,LOW);
}

}

Now, I'm able to pour out water when child lock feature activated, but the problem is the timer (interval) still ticking.
Is there any solution on how can I pause the interval whenever I'm pouring water (button2) and the interval starts back 5 sec when I release button2 (pouring water)?
I would glad if someone can help me. Ask me anything about my code.

Something else to think about in your code: What would happen if somehow the temperature got above 102? Wouldn't you want the heater to shut off in that case? And do you really want the heater to not go on if the water is frozen?

Well in this case I am using potentiometer to appear as my tempC by dividing the reading by 10. Its kinda hard to use LM35 in class, so using potentiometer would give all the temperature I want easily.

Thanks @Arjan for reminding me. I would love to contribute to the community. So this is my final coding and its worked for me :
const int redLed = 2;
const int greenLed = 3;
const int yellowLed = 4;
const int greenbigLed = 7;

const int buttonPin1 = 5;
const int buttonPin2 = 6;

int buttonState1 = 0;
int buttonState2 = 0;
float tempC ;
int analogPin = A0;
int yellowLedState = 0;

const long interval = 5000;
unsigned long previousMillis = 0;

void setup() {
  // put your setup code here, to run once:
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,INPUT);
pinMode(6,INPUT);
Serial.begin(9600);
digitalWrite(yellowLed,yellowLedState);

}

void loop() {
  // put your main code here, to run repeatedly:
int analogValue = analogRead(analogPin);
int buttonState1 = digitalRead(buttonPin1);
int buttonState2 = digitalRead(buttonPin2);
int yellowLedState = digitalRead(yellowLed);
tempC = analogValue / 10 ;
Serial.println(tempC);
unsigned long currentMillis = millis();

if (tempC <= 89.9 && tempC >= 0){
  digitalWrite(redLed,HIGH);
  digitalWrite(greenLed,LOW);
}else if(tempC == 102){
  digitalWrite(redLed,LOW);
  digitalWrite(greenLed,HIGH);
}

if(currentMillis - previousMillis >= interval){
  previousMillis = currentMillis;
      if(buttonState1 == HIGH){
         if (yellowLedState == LOW) {
              yellowLedState = HIGH;
    }
    digitalWrite(yellowLed, yellowLedState);
  } else{
      digitalWrite(yellowLed,LOW);
    }
}

if (buttonState2 == HIGH && yellowLedState == HIGH){
  digitalWrite(greenbigLed, HIGH);
  digitalWrite(yellowLed,HIGH);
}else{
  digitalWrite(greenbigLed,LOW);
  if(currentMillis - previousMillis >= interval){
  previousMillis = currentMillis;
      if(buttonState1 == HIGH){
         if (yellowLedState == LOW) {
              yellowLedState = HIGH;
    }
    digitalWrite(yellowLed, yellowLedState);
  } else{
      digitalWrite(yellowLed,LOW);
    }
}
}
}

source: Stack Exchange

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

sort: votes


text:
How to HTTP post a data to Node express API from a Arduino esp8226?
I am HTTP posting a data to this web API https://morning-cliffs-85779.herokuapp.com/api/users from an Arduino connected to esp8226. I am using the wifiesp library to HTTP_POST data.
The REST APIs are hosted in Heroku.
When I post it the Arduino gives the response

Connected to server
  [WiFiEsp] Data packet send error (2)
  [WiFiEsp] Failed to write to socket 3
  [WiFiEsp] Disconnecting  3

and the Heroku server gives the response

at=error code=H13 desc="Connection closed without response"

Below is the Arduino code:
  if (client.connect(server, 80)) {
    Serial.println("Connected to server");
    // Make a HTTP request
    String content = "id=5bc58842bdfea0153bb27214&volt=7";
    client.println("POST /api/users HTTP/1.1");
    client.println("Host: morning-cliffs-85779.herokuapp.com:80");// ("Host": host:port)
    client.println("Accept: */*");
    client.println("Content-Length: " + content.length());
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.println();
    client.println(content);
  }

This is the Node Express API:
app.post('/api/users', function (req, res) {

console.log('here');

if (req.body.id) {
    DevReading.findByIdAndUpdate(req.body.id, {
        volt: req.body.volt
    }, function (err, reading) {
        if (err) throw err;

        res.send('Update Success');
    });
}

else {

var newDevReading = DevReading ({
    deviceName: 'test',
    volt: req.body.volt
});

newDevReading.save(function (err) {
    if (err) throw err;
    res.send('Reading Post Success');
});
}

});

you must use SSL to connect with https

how can i do it?

see WebClientSSL example

The Host header shouldn't contain the port. Change Host: morning-cliffs-85779.herokuapp.com:80" to Host: morning-cliffs-85779.herokuapp.com"

Did it heres the code
`if (client.connectSSL(server, 443)) {
Serial.println("Connected to server");
// Make a HTTP request
String PostData = content + volt;
Serial.println(PostData);
client.println("POST /api/users HTTP/1.1");
client.println("Host: morning-cliffs-85779.herokuapp.com");
client.println("Cache-Control: no-cache");
client.println("Content-Type: application/x-www-form-urlencoded");
client.print("Content-Length: ");
client.println(PostData.length());
client.println();
client.println(PostData);
}`

Hope it helps some one

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


text:
A recommendation for a fast-response-time-resolution-mp3-module for arduino
I am working with Arduino which activates a box which is similar to a Skinner Box. Some of the output sound stimuli are sine waves with duration of less then 5 milliseconds. I output the sounds using the MP3 module DFR0299.
However there are too much problems using this module: it seems like the module has a wakening delay of around 100 ms, so it is not working well with this duration and below (the response time of the module is important).
So, I was thinking of buying a better module. However, I am far from being an expert in these things..
I can look for other modules in the internet, but, just from looking at the datasheets, I cant tell if the quality of the module is what I need.
I would be grateful if any of you could give me names of modules that might feet my requirements (or even advice me at what to look in the datasheets)
Thanks!

Why do you want to use MP3 for this? Are your sounds complex or just simple sine waves? (The complexity of the sound is rather limited in a time of 5ms) In that case it is easier and faster to generate them on the Arduino without using something as complex as MP3

I think the OP is referring to a hardware module for replay of the mp3 file, which effectively uses arduino only as a control mechanism rather than a processing device.

@chrisl, for now I use simple sine waves using a function generator, triggered by the Arduino. However, in the future I will need to switch to more complex waves.. Thanks

MP3 modules are way to complex for this project. Tracks of 5ms at max may even be stored directly on the Arduino in raw wave format (without any compression)(depending on the resolution and sample frequency), and then outputted by it.
Since the PWM with low-pass filter method is rather noisy and not very accurate (especially for higher frequencies), you may want to use an external DAC chip. These are available with parallel input port or with SPI. I would suggest using SPI, which is fast and does only need 3 pins (+1 for slave select, if needed). Put the raw wave values into an array and send them to the DAC to output. Depending on available memory and number and size of your tracks you may be able to save them directly on the Arduino. If not, you may want to use an SD card, to save a library of tracks, which then get loaded onto the Arduino and played. This way you would only need to hold 1 or 2 (if double buffered) tracks in the Arduino's RAM.

If you have an Arduino with a SAMD21 on it: I have written a small library for doing just that using the built-in DAC. Early days and version yet, but it works. It's here and it's free: https://github.com/ocrdu/Arduino_SAMD21_Audio_Player

I'm going to suggest that you stay away from these mp3 modules. It is perfectly reasonable to use a stand-alone arduino unit to directly generate sound using the digital output pins with a low-pass filter RC circuit. This is the most efficient way of doing this and will give you a very low activation latency.
https://playground.arduino.cc/Code/PwmFrequency/
The other option is to connect a DAC circuit and simply build a sample table for the wave outputs you need for each tone.

OK thanks I will have a look. I tried a similar thing (I think), I created the basic arduino square wave and added resistors and capacitors to "smooth" it to a sine form, But somehow the result (shown in the scope) looked very noisy.. maybe will give it another shot. Thanks

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


text:
Where does this sketch have Undefined Behavior?
Simple sketch and simple question: where does this sketch have undefined behavior?
Note: I don't need a solution to fix the code. I already have code that works. I really need to understand where my thinking is wrong.
Background: some kids were writing a program for a line follower robot which has 3 digital sensors. Many of them bricked their Arduino. I reduced the affected sketches to quite a minimum so that it still reproduces the problem. The sketch is pretty self-explanatory I hope.
It gives no warnings in Arduino IDE 1.8.9, 1.8.15 and 2.0.4 even with all warnings enabled.
Still, this code bricks all the Arduino clones (9 instances of Elegoo Smart Robot Car Kit 3.0 Plus) and I spent several hours to find a reliable procedure to unbrick them. Therefore I have strong belief that this code must have undefined behavior - except that I can't see it.
The unbrick procedure is:

Remove the shield, if not removed yet
Disconnect Arduino from USB
Connect Arduino to USB
Press Reset button on the Arduino board
Disconnect Arduino from USB again (!)
Connect Arduino to USB
Compile and upload an empty sketch

long PIN_LINE_LEFT = 10;
long PIN_LINE_MID = 4;
long PIN_LINE_RIGHT = 2;
long DATARATE = 115200;

void setup() {
  pinMode(PIN_LINE_LEFT, INPUT);
  pinMode(PIN_LINE_MID, INPUT);
  pinMode(PIN_LINE_RIGHT, INPUT);
  Serial.begin(DATARATE);
}

void loop() {
  byte leftValue = digitalRead(PIN_LINE_LEFT);
  Serial.println(leftValue);
}

Here's my analysis:
IMHO, the sketch is unusual just in one way: instead of #defineing the pin numbers and other stuff, it declares them as global variables of type long.
According to the Arduino reference about data types a long is 32 bit. Printing sizeof(long) confirms that. Therefore, 115200 will not overflow at 65536 (16 Bit).
For Serial.begin(), the DATARATE will be converted into an unsigned long, which IMHO should not be a problem here, since the number is positive.
Sure enough, the pin numbers needn't be long and should be declared as uint8_t to better match the pinMode() and digitalRead() function. But I still think the implicit conversion down to uint8_t should be fine, since there is no overflow either.
Next, digitalRead() officially returns an int. The result is assigned to a byte which is an alias for uint8_t. It seems that this also gets converted implicitly. However, the values should only be HIGH or LOW, i.e. 1 or 0, which does not generate a signed overflow either.
What I tried:
Changing DATARATE to the more appropriate unsigned long DATARATE = 115200UL; doesn't change anything.
Changing byte leftValue = digitalRead(PIN_LINE_LEFT); to the more appropriate int leftValue = digitalRead(PIN_LINE_LEFT); also didn't change anything.
Changing long PIN_LINE_MID = 4; and all others to the more appropriate uint8_t PIN_LINE_xxx = xxx; also doesn't change anything.
IMHO with these changes, there's basically nothing left to fix and this should be a super valid C/C++ program without any implicit dangerous casts.
A Serial.flush(); in the loop is not needed according to the documentation of Serial.write(). So there will not be a buffer overflow.

Comments have been moved to chat; please do not continue the discussion here. Before posting a comment below this one, please review the purposes of comments. Comments that do not request clarification or suggest improvements usually belong as an answer, on [meta], or in [chat]. Comments continuing discussion may be removed.

Your sketch does not have undefined behaviour. It works:

I already have code that works.

Your problem apparently is that after loading this sketch you have trouble uploading a new sketch:

this code bricks all the Arduino clones

They aren't "bricked" as you say:

But your method works in ~9 out of 10 cases. I can't believe this.

Your sketch, which outputs repeatedly to the serial port, apparently makes it hard for a clone to respond to a new upload. The cheaper USB interface which the clones use, to save a few cents, evidently don't react as well as the genuine Arduino to attempts to upload a new sketch.
The suggested method in the comments (referencing my post Have I bricked my Arduino Uno? Problems with uploading to board) indicates the solution, and I quote:

Take these steps:

Power off the board completely (remove the USB cable).
Hold down the Reset button, and keep it held down (or, run a jumper wire from the RESET pin to the GND pin). This stops the problem sketch from starting, and thus activating the watchdog timer
Still holding down Reset, reconnect the USB cable.
Start uploading a sketch that does not have this problem (eg. Blink)
Once the IDE reports "Uploading" release the Reset button (or remove the jumper wire).
It should now upload OK - as the sketch which activated the watchdog timer never started.

The solution above is to not let the current sketch run at all, thus avoiding whatever-it-is that it does to stop new sketches from uploading.
The references to the watchdog timer are from the original post, they are not relevant here.

It gives no warnings in Arduino IDE 1.8.9, 1.8.15 and 2.0.4 even with all warnings enabled.

That's because there are no problems with the sketch per se. The hardware? Well, you buy cheaper hardware, you may get some problems. The technique described above helps you work around those problems.

With some USB to TTL Serial chips it is a problem to start the upload if there is too much input from the MCU on the Serial side. In this case it is the Holtek UART Bridge which is not common for Arduino boards.
To stop the sketch, hold the reset button until the upload from IDE starts. When the reset button is released, the bootloader starts and receives the upload.


text:
What type of Arduino is this?
I found a bunch of Arduinos (seemingly), but I can't identify the type.
I first thought of a Micro, but the chip is a MEGA328PAU and the Micro should have a MEGA32U4 instead:

I know it's also not a Nano, because the Nano is a bit longer:

Next, I looked up the List of Board Specs. Based on the chip, the following models remain:

Lilypad, can easily be excluded due to its shape
Lilypad SimpleSnap, can easily be excluded due to its shape
Uno, can easily be excluded due to its size
Ethernet, can easily be excluded, because of the Ethernet port
Mini
Pro
Pro Mini

So I am left with Mini, Pro Mini and Pro. The back of the board is not very helpful, since it IMHO misses the markers in the silk sceen:

It definitely looks like the Pro Mini from Arduino Store, but the Arduino store seems not to offer the Mini and Pro, so I don't have a comparison.
What type of Arduino is this? And, if possible, do you have a visual comparison of the three remaining types?

The voltage regulator is BAPG (sure) and the quartz has A.8 on it (very hard to see)

the only info about the marking I found, has 8 for 8 MHz and X for 10 MHz. I would guess A is 16 MHz. my 16 MHz Nano has A as first letter on the resonator too https://www.murata.com/en-us/support/faqs/products/timingdevice/ceralock/char/cch0005

did my answer help?

@Juraj: sort of. It strengthens my opinion that it is a Pro Mini, but it does not eliminate the other two options: Mini and Pro.

It is a version of Pro Mini.
here in DIY MORE shop
The Mini has regulator. Power it over RAW pin with 7 to 12 V and measure the Vcc pin if it shows 5v or 3.3 V.
To determine the frequency, look at the resonator (the component next to pin 2).
EDIT: the resonator markings are hard to read and very cryptic. to determine the frequency you could install Sparkfun boards package. There you can select the different variants of Pro Mini. Upload Blink. If the upload is successful and it Blinks in 1 second intervals, you have the right setting.

Unfortunately, the marks on the back are missing. If it's really a 8 MHz version, it might allow Vcc = 3.3V only.

@DataFiddler The only difference between the 8Mhz and 16Mhz version is the crystal and the regulator. You can run a 8Mhz 3.3V Pro Mini fine on 5V. Though not the other way around, since the ATMega328 requires at least 3.8V to run at 16Mhz (higher speeds, require a higher supply voltage).

Do you think the Mini and Mini 05 are just one thing? If so, this would be the Mini: https://store.arduino.cc/arduino-mini-05

there are different revisions of Mini, but the Pro is different. Pro has A6 and A7

here is yours https://www.diymore.cc/products/pro-mini-atmega328-3-3v-5v-16m-replace-atmega128-for-arduino-nano?_pos=6&_sid=8931d4b6d&_ss=r

@ThomasWeller, and the voltage and frequency?


text:
ESP8266 BearSSL performance
I am playing with a minimal https server on an ESP01S, using BearSSL::ESP8266WebServerSecure.

With 2048bit RSA keys it takes ~5 seconds to serve a "hello" request.
Using 256bit EC keys it takes ~2 seconds.

I wonder whether it is possible to make key exchange faster without giving up on reasonable security level.
I am struggling with trying to set ec_all_m15 implementation (see Key Exchange) to make it faster without any luck - I have actually no idea how to do it properly .
I tried something like
...
BearSSL::X509List *cert = new BearSSL::X509List(serverCert.c_str());
BearSSL::PrivateKey *key = new BearSSL::PrivateKey(serverKey.c_str());
server.setECCert(cert, BR_KEYTYPE_EC, key);
server.begin();
br_ssl_server_context sc;
br_ssl_server_init_full_ec(&sc, cert->getX509Certs(), 1, BR_KEYTYPE_EC, key->getEC());
br_ssl_engine_set_ec(&sc.eng, &br_ec_all_m15);
br_ssl_server_reset(&sc);

Could someone help pls?

it always going to be slow. what have you tried?

@dandavis I have added to the post.


text:
MD5 hash for Arduino Uno [-Wshift-count-overflow]?
I tried to test out this MD5 library (https://github.com/tzikis/ArduinoMD5 ) as a hash function on arduino uno.
What I have done is that I placed the MD5.cpp and MD5.h to the folder below:
C:\Program Files (x86)\Arduino\libraries\MD5
And launched arduino IDE 1.8.9 to test the example provided (https://github.com/tzikis/ArduinoMD5/blob/master/examples/MD5_Hash/MD5_Hash.ino):
#include <MD5.h>
/*
This is en example of how to use my MD5 library. It provides two
easy-to-use methods, one for generating the MD5 hash, and the second
one to generate the hex encoding of the hash, which is frequently used.
*/
void setup()
{
  //initialize serial
  Serial.begin(9600);
  //give it a second
  delay(1000);
  //generate the MD5 hash for our string
  unsigned char* hash=MD5::make_hash("hello world");
  //generate the digest (hex encoding) of our hash
  char *md5str = MD5::make_digest(hash, 16);
  free(hash);
  //print it on our serial monitor
  Serial.println(md5str);
  //Give the Memory back to the System if you run the md5 Hash generation in a loop
  free(md5str);
}

void loop()
{
}

However when run verify and compile, it works but got the warnings below:
...\sketch_may02a_MD5_test.ino.ino: In function 'void setup()':

sketch_may02a_MD5_test.ino.ino:15:51:
warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]

   unsigned char* hash=MD5::make_hash("hello world");

                                                   ^

C:\Program Files (x86)\Arduino\libraries\MD5\MD5.cpp:
In static member function 'static void MD5::MD5Update(void*, const void*, size_t)':

C:\Program Files (x86)\Arduino\libraries\MD5\MD5.cpp:207:21:
warning: right shift count >= width of type [-Wshift-count-overflow]

  ctx->hi += size >> 29;

                     ^

I know little of c++, can anyone help to fix this? Thanks a lot!!

size is of type size_t, which seems to be an unsigned int on the Uno, meaning 16 bits. Shifting it by 29 bits would always result in zero, I think. And that seems a complicated way to write 0.

@chrisl: Shifting by too much does not result in 0. It results in undefined behavior.

You better don't mess with the arduino system files at C:\Program Files (x86)\Arduino. Can you uninstall arduino, delete C:\Program Files (x86)\Arduino and reinstall it? Are your sketches located at Documents\Arduino? There is a libraries folder in that folder alongside the folders of your projects. That libraries folder is meant to put libraries into that you have downloaded. When using the arduino library manager and a library is downloaded, it will be put there as well.

@Jot Thanks for the tips. I noticed that it will also grab the libraries from the Document\Arduino\libraries which I thought it was only used with the arduino installed from windows app store. As you suggest, I should just use it for all the libraries to be deployed in the future.

....\sketch_may02a_MD5_test.ino\sketch_may02a_MD5_test.ino.ino:15:51: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]

That is a flaw in the library. The author defined the function as taking a char * instead of a const char *.  You can ignore it, it's just a warning - however maybe raising the issue with the author could be a good idea.

C:\Program Files (x86)\Arduino\libraries\MD5\MD5.cpp:207:21: warning: right shift count >= width of type [-Wshift-count-overflow]

This one is a little more awkward.  The size variable is defined as type size_t.  That varies in length depending on the architecture the software is compiled on.  On the 8-bit Arduinos that's a 16 bit variable. On 32-bit Arduinos, like the Due, it's a 32-bit variable.
It is probable that the author developed the library using a 32-bit Arudino (or Arduino-compatible) device - in which case he would never see that warning (since 29 is less than 32).  However anyone that then uses an 8-bit Arduino gets the warning, and probably a corrupt hash.
However, it looks like it should only be a problem if size is too big - and it can't be on an 8-bit Arduino. So again you can ignore it, but the author should really be made aware of the issue.

OK, before I consider this is answered. Can it be fixed by a couple lines such as replacing the size_t with something else from the .cpp file? If so, I would perhaps give it a try and push it to a public github project.

Shifting past bitwidth is undefined behavior. It should not be ignored.

@EdgarBonet While I agree it shouldn't be ignored in general terms, but in this situation it will be shifting nothing anyway, so with nothing to shift it doesn't really matter. Raising an issue with the author should still be done, of course.

@Harry You could do a search and replace of size_t to uint32_t, and change the parameter of make_hash() to const char *.


text:
LCD not working with Arduino Uno
I am a new learner on Arduino. I am trying to learn how to control the LCD. I looked in the article, "Hello World!", and followed the instructions but it did not work (I checked it many times). The result I got is shown below (the text is not showing).
Please help me. Any help is appreciated.

Here is my code:
    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 5,4,3,2);

    void setup() {
      // set up the LCD's number of columns and rows:
     lcd.begin(16, 2);

    lcd.print("hello, world!");
    }

    void loop() {
      // set the cursor to column 0, line 1
      // (note: line 1 is the second row, since counting begins with 0):
      lcd.setCursor(0, 1);
      // print the number of seconds since reset:
      lcd.print(millis() / 1000);
    }

It could be the fact that you are not using a soldered header pins. Any slightly movement may break your connections. Do you have any male pins you can solder to LCD?

There are 3 things you can try.
1.
If you have any male pins, solder those to the lcd screen, then stick it in the breadboard. After that you can stick the wires in the breadboard appropriately. The first time I tried this the wires were either touching or not connected enough to the lcd screen.
2. Double check all the connections made. This also happened to me, just make sure all the wires are in their right places.
3. Have you tried adjusting the potentiometer? Thats what its there for. Try turning it slowly both directions to adjust the background and letter brightness.
From the looks of the picture, number 3 may be your problem. Try that step first, and if it doesn't work you can try the other two. Hope this helps!

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


text:
Arduino millis() won't work
This is my program. The LED should turn off after four seconds.
int vraag = 7;
int gloeikaars = 5;
unsigned long previousMillis3;
boolean gloeistate = true;

void setup() {
    pinMode(gloeikaars, OUTPUT);
}

void loop() {
    int x = digitalRead(vraag);
    if (x == 0) {
        digitalWrite(gloeikaars, !LOW);
    } else {
        Gloeikaars();
    }
}

// *********************************************************************
// Gloeikaars aansturing
// *********************************************************************
void Gloeikaars() {
    unsigned long huidig = millis();
    digitalWrite(gloeikaars, !HIGH);
    if ((gloeistate == true) && (huidig - previousMillis3 >= 4000)) {
        huidig = previousMillis3;
        digitalWrite(gloeikaars, !LOW);
        gloeistate = false;
    }
}

Can someone help me because it won't work?

At the moment your code doesn't know when you turned the LED on - so how can it know when 4 seconds have passed?

you are doing pinmode with a function. How do you conclude millis doesn't work?

@Patrick, I'm also Dutch, but I code in English, not only does it spice up your English, it also works better when working with international people (or StackExchange websites).

(Dutch, to avoid language barriers) Patrick, het is beter om je programma ook in het Engels te schrijven, zo kunnen internationale collega's ook je programma lezen/begrijpen (of mensen op stack-exchange).
Je vertelt er namelijk ook niet bij dat je een "glowing-candle" probeert te maken, wat uiterst interessant kan zijn voor mensen die je code proberen te begrijpen. Over het algemeen zijn vragen als: "Dit is mijn code, het werk niet" ook geen goede vragen. Beschrijf wat je probeert te doen, welk gedrag je verwacht en wat er gebeurt (dat niet zo zou moeten zijn).

Your previousMillis variable is never set.  Two changes:
In setup:
...
previousMillis3 = millis();
...

In loop:
...
previousMillis3 = huidig;
...

Not needed in setup, as both the millis() counter and previousMillis3 are initialized to zero.


text:
Uploading code to Mega 2560 is stuck
I'm trying to upload code from a Mac (online Arduino editor) onto an Arduino Mega2560, to connect a motor to pin 52 and Ground to get it to move. But at the top it says busy (like it does when it uploads) and doesn't do anything else. Refreshing the page doesn't work. The code is verified, and here's the code:
void setup() {
}

void loop() {
  digitalWrite(52,HIGH);
}

The Arduino application (with same code copied in) comes up with this error:
Arduino: 1.8.4 (Mac OS X), Board: "Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)" Sketch uses 1190 bytes (0%) of program storage space. Maximum is 253952 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 8183 bytes for local variables. Maximum is 8192 bytes.
avrdude: ser_open(): can't open device "COM1": No such file or directory
ioctl("TIOCMGET"): Inappropriate ioctl for device
ioctl("TIOCMGET"): Inappropriate ioctl for device
avrdude: ser_send(): write error: Bad file descriptor
avrdude: stk500_send(): failed to send command to serial port
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer
the selected serial port avrdude: stk500v2_getsync(): timeout communicating with programmer does not exist or your board is not connected

I hope someone can work out why it doesn't upload!

What specific online Arduino editor? There are more than one. Also, the Arduino pin cannot supply enough power to drive a motor.

It's https://create.arduino.cc/editor. The motor works when I connect it to the power section GND and 5/3.3v pins. Because of the error codes, have I damaged the port?

The power pins are can supply much more energy than the IO pins.  Your error text notes COM1, but Macs don’t call ports COM1. You need to set the port correctly to upload. But you won’t get the motor to work on a data pin anyway.

Ok I'm new to Arduino so that really helps thanks. But still why won't the code upload?

You have to figure out the right serial port. I’m not familiar enough with the online editor to help you on that. I just know COM1 is wrong on a Mac.

I would suggest to download the Arduino app (https://www.arduino.cc/en/Main/Software).
Download both the latest version and an a legacy build (https://www.arduino.cc/en/Main/OldSoftwareReleases#00xx). Within the DMG for the legacy you'll need to install the FTDI drivers to allow Arduino app to see the Arduino in ports.


text:
How to get rid of the second tab in Arduino IDE 2?
For a reason unknown to me, Arduino IDE 2.0.3 opens two tabs with the same name for this sketch. I'm not able to reproduce how to get into this situation.
Changes in one tab immediately changes the other tab as well.
How can I get rid of the second tab?

Things I tried:

File / Close (Ctrl+W) closes the whole sketch, i.e. Arduino IDE exists.
The usual key combination to close tabs (Ctrl+F4) does not work either.
I deleted all %AppData%\Local\Temp\.arduinoIDE-unsaved*.gfv2 folders
I deleted all %AppData%\Local\Temp\arduino-sketch-* folders
I deleted all %AppData%\Local\Temp\arduino-language-server* folders
I deleted all %AppData%\Local\Temp\arduino-ide2-* folders
I used Streams to check the INO file for alternate data streams
I deleted the folder %UserProfile%\.arduinoIDE

Maybe interesting: when I rename the sketch to HelloWorld2.ino, it opens only one tab. If I rename it back, I have two tabs again.
When I change the preferences to show the files in Sketchbook view, I only see one file:

The other sketches have been created when trying to reproduce the problem. They are not affected
The tooltip which shows the full file name is identical on both files:

The Registry does not contain suspicious information. I found only one occurrence of HelloWorld in
HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\TypedPaths

Can give exact instructions on reproducing this? I downloaded 2.0.3 (though on Linux) and tried creating and opening essentially blank sketches in various ways and didn't observe this problem.

@timemage: unfortunately I can't (yet). I have also created a virtual machine and wanted to reproduce it, but it didn't happen.

@jsotola: the content changes in both tabs (seemingly instant)

@jsotola: updated the question: it shows only one file

@timemage: I have recorded a video when this issue occurred. From that video I can see that it started with a duplicate file name called sketch_dec27a.ino https://i.sstatic.net/IgHxa.png However, the video just shows this right after starting the IDE, nothing done.

@jsotola: the other one has a space in the name. It's a different sketch which is not affected and has no impact one the one without space. I deleted it and updated the screenshot. The problem still persists

search the windows registry for all instances of the text HelloWorld if you feel comfortable exploring the registry

For what it's worth I believe you. But, until I can reproduce the problem I don't think I'm going to have much luck finding a solution. The IDE seems to have had a recurring problem with this stemming from different causes some of which have supposedly been fixed. The IDE 2.0.X IDE definitely still has a lot of problems. In fact I just noticed another (unrelated) one trying to reproduce yours.

It seems there is a new bug for this issue: https://github.com/arduino/arduino-ide/issues/1791 I can't recall having used libraries yet, though.

How can I get rid of the second tab?

Press F1,
Type: View: Reset Workbench Layout into the Command Palette,
Press Enter,
IDE reloads.

If it does not help, get the layout data from the logs.

Open the DevTools with Ctrl/⌘+Alt+I built-in command,
Open the Console if it's not opened with Esc,
Right-click in the console and Save as...,
Share the data with the devs.

For example:
{"version":5,"mainPanel":{"main":{"type":"tab-area","widgets":[{"constructionOptions":{"factoryId":"code-editor-opener","options":{"counter":0,"kind":"navigatable","uri": ...

Absolute abuse of the F1 button for such a purpose, but anyway, resetting the workbench layout did it.

Seems a perfectly good use to me. =) Upvote.


text:
Can I use [[__progmem__]] instead of PROGMEM?
In pgmspace.h, PROGMEM is defined as __ATTR_PROGMEM__, which is defined as __attribute__((__progmem__)). AFAIK, __attribute__ is GNU only. Since C++ 11, we have the attribute specifier sequence.
I can't use [[__progmem__]] instead of PROGMEM. The error is

warning: '__progmem__' attribute directive ignored [-Wattributes]

Shouldn't that work equally?
Why would I want to do that?

Clarity: When I first read code that used PROGMEM, I thought that this is the variable name (being a constant, we have a conding guideline that it should be upper case, which matched). Reading on, I found the real variable name, which confused me. Putting it into square brackets would immediately have made clear that it's an attribute and not a name.
Portability: [[ ]] is Standard C++, whereas __attribute__ is not.

Maybe I should just read the complete documentation...
Under Standard Attributes, we see the attributes that come with the C++ Standard. __progmem__ isn't one of them.
Following the example for syntax 2, I tried [[gnu::__progmem__]], which compiles. So this helps with Clarity, but since it now has the gnu namespace, it doesn't help with Portability.

Re “it doesn't help with Portability”: According to the documentation of PROGMEM, “These functions are an attempt to provide some compatibility with header files that come with IAR C, to make porting applications between different compilers easier.” I doubt PROGMEM could be a lot more portable than that. How many C compilers (let alone C++) support the AVR architecture? How many of those support keeping constants in flash memory?

And the macro approach has the nice effect that you can provide a macro without replacement text for systems that do not support such attributes, for example if you simulate on a PC.


text:
Using LDR and RGB Led to get R,G,B values
Has anyone tried using a setup of RGB LED directed to cuvette and the LDR on the opposite side? using arduino to and get the RGB values..
Currently having problems with calibration... I was able to get R,G,B values of colored papers... however with colored liquids inside a cuvette I'm not getting any good results (i.e the Red/Blue/Green values goes way up like 5000++)
Used white and black paper for callibration..
No idea for liquid...

You gave us nearly no information. Please show your circuit and your code. And what does "not getting any good results" mean? Explain what you expected and what you actually see.

Never tried with a cuvette, but that is exactly how (though with an array of photodiodes) modern cheap flatbed scanners work.

Also, what do you hope to achieve doing this? The results will be, from a spectrophotometric point of view, meaningless. You are only testing 3 wavelengths within a whole spectrum of colour.

As for the RGB values, I needed it for the computation of vector values at different concentration perentages

https://www.instructables.com/id/Using-an-RGB-LED-to-Detect-Colours/  Im using this exact circuit to get the RGB values

Your are probably doing the white calibration with some clear liquid,
like water. The LDR is then lit directly by the LEDs, and is getting too
much light. It's resistance is then very low compared to the pull-down
resistor in series with it. You end up measuring something very close to
5 V.
You should try to reduce the amount of light hitting the LDR. A neutral
density filter (the kind used in photography) would be ideal.
Alternatively, you could increase the distance between the LEDs and the
LDR, and put some translucent paper in between. You could also add a
diaphragm (a small hole). Then, you can also lower the resistance of the
pull-down in order to get lower voltage readings, but beware not to draw
too much current.
A comment about the instructable you linked to: owing to the highly
non-linear characteristic of the readings you get, it is quite likely
that you get unequal RGB vales from a neutral grey. Some kind of
linearization (estimating actual light fluxes) would be needed if you
want neutral greys to be measured as neutral greys.


text:
(Arduino Uno reflashed as USB HID) How to send Scroll Lock key?
I am having a hard time finding documentation on how to properly use USB HID buffers, so the issue may lie there instead of with my code.
To get 0x47, I used this table: https://www.usb.org/sites/default/files/documents/hut1_12v2.pdf
Here's code that is loosely based off of http://mitchtech.net/arduino-usb-hid-keyboard/
    /* Arduino USB Keyboard HID demo
 * Cut/Copy/Paste Keys
 */

#define SCRLCK  0x47
//#define KEY_LEFT_SHIFT  0x02
//#define KEY_RIGHT_CTRL  0x10
//#define KEY_RIGHT_SHIFT 0x20

uint8_t buf[8] = {
  0 };  /* Keyboard report buffer */

#define PIN_PTT 2
//#define PIN_CUT 6
//#define PIN_PASTE 7

int state = 1;
int prevState;

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

  pinMode(PIN_PTT, INPUT);
  //pinMode(PIN_CUT, INPUT);
  //pinMode(PIN_PASTE, INPUT);
  // Enable internal pull-ups
  digitalWrite(PIN_PTT, 1);
  //digitalWrite(PIN_CUT, 1);
  //digitalWrite(PIN_PASTE, 1);

  delay(200);
}

void loop()
{
  state = digitalRead(PIN_PTT);
  if (prevState != state) {
    buf[0] = SCRLCK;   // Scroll Lock
    // buf[2] = 27;    // Letter X
    // buf[2] = 123;    // Cut key: Less portable
    Serial.write(buf, 8); // Send keypress
    prevState = state;
    releaseKey();
  }
}

void releaseKey()
{
  buf[0] = 0;
  Serial.write(buf, 8); // Release key
  delay(100);
}

Using a keyboard testing application, the green keys (minus mouse) are the buttons that appear to be pressed when the Arduino is using the USB HID firmware:
Upon using Passmark Keyboardtest, it looks like it's pressing Shift, Ctrl, Left alt, and right alt when I press the button.
My assumption is that I am writing to the 'modifier key' buffer instead of the 'other key' buffer. How would I define the correct key?

about the defines at top of your sketch ..... convert 0x02,  0x10, 0x20 and 0x47 to binary ......  what do you see when you do  that?


text:
How to get the esp32s2 recognized as USB device?
I have an esp32-S2 saola and I am trying to use it as a MIDI usb device. I am trying to use this github repository: https://github.com/chegewara/EspTinyUSB. I am able to run the code on the esp32s2 saola and I am connecting to a mac with a USB cable to pins 19 and 20 but don't get any MIDI input in my computer (mac), in fact my computer is not recognizing the device.
So I guess my actual question is about how to get the esp32s2 recognized as a USB device by the mac. Any clues of what might be happening? Or should connecting  to pins 19 and 20 be enough and I am dealing with a hardware bug?
For the usb cable I took a usb only-power cable apart and then rewired it so it was only data (two middle cables connected to pins 19 and 20). As it was not working I then connected also the usb's power and ground cables with no luck:

EDIT: This the documentation for the USB driver on the esp32-S2 and why I think the power cables might not be needed at all (which I tried but didn't work): https://docs.espressif.com/projects/esp-idf/en/latest/esp32s2/api-reference/peripherals/usb.html

Pretty grizzly looking.  I'm not really following the whole scheme.  It would be helpful to see everything a diagram.  As is, I'm only guessing you swapped the power for data on both sides of the cable.  That you actually have a ground back to the USB port etc.  You are not seeing anything like an overcurrent event on the USB host?

On the other side of the cable (not shown in the picture) I removed a micro usb male header and ended up with bare cable going to pins 19 and 20 as per the diagram I found in the documentation: https://docs.espressif.com/projects/esp-idf/en/latest/esp32s2/api-reference/peripherals/usb.html

This goes back to what I said above.  "That you actually have a ground back to the USB port etc."  Circuits work better when they're.... circuits.


text:
How to set timeout?
Want to implement timeout for RPS counter after for instance 1 second. Since here I use status change for RPS calculation, I suppose that if the state is either HIGH or LOW for more than one seconds then rps should return 0.
However, it does not work. What is the problem.
float rps[4]={0.00,0.00,0.00,0.00};
unsigned long int PRINT_PERIOD = 1000;
unsigned long int lastTimePrinted = 0;
int lastReedState[4];
unsigned long lastTransition[4]={0,0,0,0};
//int reedState[4];
//unsigned long now[4]={0,0,0,0};
float rps_result[4]={0,0,0,0};
float rps_resul[4];
//unsigned long revolutionTime[4]={0,0,0,0};

unsigned long int LT;  // Last Time
unsigned long int PT;  // Passed Time
unsigned long int TT;  // Time

void setup(){

 Serial.begin(9600);

 DDRD &= ~_BV (7); // pinMode (7, INPUT);       // rps_1
 DDRB &= ~_BV (0); // pinMode (8, INPUT);       // rps_2
 DDRC &= ~_BV (1); // pinMode (A1, INPUT);      //  rps_3
 DDRD &= ~_BV (2); // pinMode (2, INPUT);       //  rps_4

delay(85);

}

float rps_out(int k){

    //static int lastReedState;
    //static unsigned long lastTransition;
    //static float rps_result;
    //float rps_result;
    int reedState;
    unsigned long now;
    unsigned long revolutionTime;

   if ( k == 0 )     reedState = (PIND & _BV (7)) == 0; // digitalRead (7);
   else if ( k==1 )  reedState = (PINB & _BV (0)) == 0; // digitalRead (8);
   else if ( k==2 )  reedState = (PINC & _BV (1)) == 0; // digitalRead (A1);
   else if ( k==3 )  reedState = (PIND & _BV (2)) == 0; // digitalRead (2);

    // On a rising transition of the reed switch:
    if (reedState == HIGH && lastReedState[k] == LOW) {                   // HIGH  LOW   measuring the low period    // LOW HIGH measuring the high period
        // Compute time since last valid transition.
        //unsigned long now = micros();
        //unsigned long revolutionTime = now - lastTransition;       // measuring the High period
         now = micros();
         revolutionTime = now - lastTransition[k];       // measuring the High period
        // Compute the rps

        //if(revolutionTime[k] == 0 ) return 0;

        if(revolutionTime == 0 ) rps_result[k] = 0;     // avoid deviding by zero

         rps_result[k] = 1.00 / (12.00*revolutionTime) *1000000.00;  // 12 is rotary encoders resolution

        // Remember this transition.
        lastTransition[k] = now;

    }

    // Remember last state.
    lastReedState[k] = reedState;

////////////////////////////////////////////////////////////   timeout

    if(reedState == HIGH || reedState == LOW  ) {

       PT = millis();
       TT = PT - LT;
    if( TT > 1000)  rps_result[k] = 0;

     LT = PT;

}

//////////////////////////////////////////////////////////////////

    if(rps_result[k] < 1) return 0.00;
    return rps_result[k];

}

void loop() {

   rps[0] = rps_out(0);
   rps[1] = rps_out(1);
   rps[2] = rps_out(2);
   rps[3] = rps_out(3);

    if (millis() - lastTimePrinted >= PRINT_PERIOD) {

     Serial.print(rps[0]);
     Serial.print(',');
     Serial.print(rps[1]);
     Serial.print(',');
     Serial.print(rps[2]);
     Serial.print(',');
     Serial.println(rps[3]);

      lastTimePrinted = millis();

     }

}

Please post a Minimal, Complete, and Verifiable example

Since you need less that 1 second between changes, the minimal RPS would be 60.
So just change if(rps_result[k] < 1) return 0.00; to if(rps_result[k] < 60) return 0.00;


text:
Powering up LED strip - How many amps?
I want my Arduino to drive a LED strip.
The LED strip in particular is the 3528 non-waterproof type.
To power this up, I need a 12V power supply.
My LED strip is going to be 5 meters.
Now my questions are:

Is it important on how many amps, my powers supply will feed? One guy did it with 12V, 5A power supply. Considering the length (5m), is a particular amperage value necessary?
Can I power up the Arduino Nano with the power from the power supply? Voltage wise, I am clear, since the nano can handle 12 volts... What I am scared of is the amperage... Considering that I need a particular value of amps to power up my LED strip, can the nano handle this many amps? Is there a limit to how many amps the power supply line that I will feed my Arduino has to be?

Usually strips have not individual LEDs, but are composed of a lot of "pieces" in parallel, and each piece is composed by three leds in series along with a resistor.
Usually the strips are composed by 60 leds/m (i.e. pieces of 5cm), but sometimes also 120 leds/m or 30 leds/m. Let's assume it is the 60 leds/m version (you can check the length of the piece you can cut - which should be 5 cm - and that it contains 3 leds).
This means that in 5m there are 100 pieces. Now, usually the 3528 leds absorb 20mA of current for each segment (the 5050 version should be rated at 60). This means that the whole led strip should absorb 2A @ 12V.
Now the power supply. 2A is the nominal current the whole strips should absorb. Add about 200mA for the nano, and increase a bit the current requirement not to stress the power supply: you get a 12V 3A power supply at least (note that, while 12V should remain the same, you can take any current greater than this value - if for instance you have a 12V 5A power supply it is perfectly fine).
Now, the nano. It surely can't handle the 2A current. This means that you can power the arduino nano from the 12V. BUT beware: you should connect the 12V power to the VIN input (so the onboard regulator lowers it to 5V). Then you can't power the LEDs directly from the nano, but you need a transistor to decouple them. You can take any nMOS with a drain current greater than 3A or an NPN with collector current >3A and build the appropriate curcuit to drive them, then connect the + terminal of the strip to the +12V wire, the transistor source (or emitter) to the ground wire and the gate (base) should be driven by the nano.

Thank you so much! Out of ignorance, i didn't mention that these are UV LEDs for PCB production. So each led, has not three leds inside, that means even less power consumption! Something like this: http://www.ebay.com/itm/UV-Night-Fishing-Lights-Ultraviolet-LED-Blacklight-3528-5050-SMD-Boat-Strip-Lamp-/291998937499?var=&hash=item43fc7e319b:m:mM3H6Aq5GewFdtLfYOWNaDA

@user1584421 The 5050 version of LED has three leds inside each package, that  is why the 5050 is rated at 60mA and the 3528 at 20mA. If you look at the photos you will see that they are different. Usually the color does not matter a lot, since the limiting resistors are trimmed to get 20mA out of each segment. As you can also read from the description, the input should be "12V 2-3 A for 5meters 3528 300LED light strip", which is what I told you (2A is the minimum, but use a bigger one).

One more thing: when I built my bromograph they discouraged me from using LEDs, because tubes are more homogeneous. With 5m of LEDs you can glue them very close, so probably you will get a nice exposure also with leds, but try to glue them very close, make a "zig zag" pattern and place the PCB a bit far, so the light can spread evenly..

Thanks a lot! On a slightly unrelated note, given this setup, and with a 2.5A power supply, how much the exposure time you think should be for a PCB?

@user1584421 Probably you are asking the wrong person, because I was never able to obtain a truly good PCB this way ;) anyway I know that exposire time varies with a LOT of factors, including primarily the photosensitive film you are using, its "freshness", the developer concentration and type, even the climatic conditions (even if these should have a little impact). What I suggest is to make a "trial" piece, with some small traces and gaps, cover almost all the board and start it. Then after 10 seconds uncover the board some more, in order to have different exposures in the board. continue...

... for instance this page has the methodology I used (it's in italian, but there is a video and at about 10 minutes it shows how he used the template). Download the "Test bromografo 1" template and use it. Once you know the approximate (+/- 10s) time, well, that is your exposure time...

1) Is it important on how many amps, my powers supply will feed?

Yes.  You need the PSU to be able to supply as much current as you will need for everything you are powering form it.
You don't say how many LEDs will be on this strip (only the length of the strip) and I am not sure how much current/power a single one consumes, but for illustration let's imagine there are 100 LEDs on your strip and each one takes 0.8W.
100 LEDs x 0.8W per LED = 80W.
P = VI, where P=Power, V=voltage, I=current.
So I = P/V = 80 / 12 = 6.66A -- call it 7A.
The amount taken by the Nano will be small in comparison - if you said 0.5A you'd be safe.
So with these figures you'd need a 7.5A PSU.

Considering that i need a particular value of amps to power up my LED strip, can the nano handle this many amps?

You can power the Arduino from the same power supply, yes.  The Arduino will draw whatever current it needs.  (Think of it this way: mains sockets are 13A - a desk lamp won't draw 13A.)  What matters is that the supply can supply at least enough current, and that the voltage is correct.
As mentioned in the comments, you can't drive 3528s directly from the Nano - but you don't ask about that so presume you either know how to do it, or will ask another question.

Because there are three LEDs in series, you cannot drive these LEDs from a 5V supply. The LED strips say "+12V" on them to mark the anode and that's the maximum voltage we suggest. We've found that if you're ok with them being a little dimmer, even 9VDC works very well.
Each segment of 3 LEDs draws approximately 20 milliAmperes from a 12V supply, per string of LEDs. So for each segment, there is a maximum 20mA draw from the red LEDs, 20mA draw from the green and 20mA from the blue. If you have the LED strip on full white (all LEDs lit) that would be 60mA per segment.
To find the total maximum current draw per meter, we would multiply 60mA x 10 (ten segments per meter for the 30/LED per meter strip) = 0.6 Amps per meter OR 60mA x 20 (twenty segments per meter for the 60/LED per meter strip) = 1.2 Amps per meter. Again, that's assuming you would have all the LEDs on at once and that you are powering it from 12V. If you're going to be PWM-fading between colors, maybe 1/2 of that is what you'll be drawing. Still, you do need to have a fairly decent power supply to run this strip, all those LEDs add up!


text:
Having issues with Arduino + Bluetooth
I am working with a combination of Teensy++ 2.0 and Sparkfun Bluetooth Modem.
The Arduino program, inside the loop, continuously reads a sensor value. If the value read is above a threshold, the Arduino transmits a "CHARACTER" over Bluetooth for any receiver.
So, inside the same loop, I check for the availability of data, and print the received character. The problem is, the received character is not what is transmitted. The received character is some garbage value.
Please let me know what is going wrong here.
#include <SoftwareSerial.h>

#define bluetooth Serial1

#define BAUDRATE 9600

// Analog read 0 is pin 38
int sensorValue = 0;
int SENSOR_ANALOG_READ_PIN = 0;
int LED = 17;

char toPrint = '\0';
bool sent = false;
char state = ' ';

void setup()
{

// put your setup code here, to run once:

  pinMode(LED, OUTPUT);

  Serial.begin(BAUDRATE);

  bluetooth.begin(BAUDRATE);

}

void loop() {

  // put your main code here, to run repeatedly:

  sensorValue = analogRead(SENSOR_ANALOG_READ_PIN);

  if(value > 500)

  {
      //Serial.println("HIGH");

      digitalWrite(LED, HIGH);

      bluetooth.write(state);

      bluetooth.flush();

      sent = true;

      digitalWrite(LED, LOW);

  }

  else

  {

      delay(100);

  }

  ///////////////////////////////////////////////////////////
  if((bluetooth.available()) && (sent == true))

  {

        Serial.println("printing : ");

        toPrint = (char)bluetooth.read();

        Serial.println((char)toPrint);

        sent = false;

   }

}

Output:
printing :
1
printing :
ˆ
printing :
Ì
printing :
¦
printing :
È
printing :
Ì
printing :
Ì
printing :

The code is really hard to read as it is right now - namely because it's not formatted. Could you go through your code and ensure it's properly formatted? It would make it much easier for us to help you.

@Mlagma The code is now formatted by Gerben .

Try without the sensor value first by sending known exact values (so you only test the bluetooth connection.

The default baud rate for HC-05 is 38400 bauds. I was trying to set it to 9800.  For some reason, that was not accepted by HC-05.
Solution:
I changed the line
#define BAUDRATE 9600

to
#define BAUDRATE 38400

This solved my problem.

Is the device on the other side of the bluetooth connection running at 9600 baud too ?
You say you transmit the state of the sensor - which BTW is only ever a space ' ', and never changes.
So that value gets written out via the bluetooth connection.
But then you read data in from the other party to the bluetooth communications.
It sounds like you expect the data written to the bluetooth output serial line to also be echoed back from the bluetooth input.  The serial transmit and receive are separate channels.  You are receiving on the bluetooth.read() whatever the device connected to it is sending, not what you write yourself.
What you are sending goes only to the other side of the conversation.  The remote device would need to echo whatever it sees back for it to work how you describe.

Are you sure you have defined your pins properly? I don't see anywhere where you define SENSOR_ANALOG_READ_PIN as an input. If this is the Tx/Rx pin (I forgot the pin configuration), you can define the input pin to be somewhere else to test using the SoftwareSerial library.
This is what I did and it worked for me, hope it helps.
This link isn't for your module but the concept should be the same: Arduino AND Bluetooth HC-05 Connecting easily.


text:
Arduino Due and BNO055
For a physical activity monitoring project, I am developing a prototype based on an Arduino Due and several IMUs (BNO055 from Bosch).
I have to collect the data from the sensors simultaneously (3 for the moment). I want to use a Serial connection (Since the Arduino Due has 4 hardware serial ports).

Here comes the first issue : I use the shuttleboard BNO0055, and because of my limited knowledge, I'm not sure I did the right wiring. As I understood in the datasheets, the PS0 pin must be connected to the GND and PS1 to the incoming voltage. The COM0 to the RX of the Arduino and COM1 to TX. I am confused by the documentation, I can't figure out which pin of the shuttleboard are the COM0 and COM1. (I can't post the pictures of my wiring since it's my first post here).
And now there is a second problem: If the wiring is good, how can I communicate with the sensor to get the Euler angles? The BNO055 sensor does the fusion data itself, and gives the quaternions or the Euler angle. Bosch provides a library. I have never used a library, and I don't know the syntax to ask the sensor to give the Euler angles. Can someone give me a code to do this? Or at least explanations on the syntax I should use?

PS0 pin must be connected to the GND and PS1 to the incoming voltage. The COM0 to the RX of the Arduino and COM1 to TX. according to figure 10 that would be correct. The library you linked to only works for I2C, so that won't work. Is there any reason to use UART over I2C?

At the end of the project I should have 5 IMU connected. With the Arduino due I know I can have 4 IMUs, but I would miss one. For now I can use I2C, I tried, and It's the same problem, I don't know if my wiring is good, I tried several wiring and each time I used the I2C Scanner and it failed everytime

Update : The I2C Scanner found the device at address 0x29, only when I link I2C_MODE_ADR_SEL to the incoming voltage


text:
Sending GPS data through a WiFi module
I'm trying to send GPS data using a neo-6m GPS module through WiFi using esp8266 module, I have both of the modules working alone, but when I try using both the WiFi works but won't send the data from the GPS.
I call the GPS and save the latitude, longitude, date and time to separate variables, then try sending those variables using the WiFi to the server on the Arduino Uno, but they just show up as 0's.
#include <TinyGPS++.h>
#include "WiFiEsp.h"

// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(6, 7); // RX, TX
#endif

char ssid[] = "UPC9080883";            // your network SSID (name)
char pass[] = "OYKXVYND";        // your network password
int status = WL_IDLE_STATUS;

int ledStatus = LOW;

WiFiEspServer server(80);

// use a ring buffer to increase speed and reduce memory allocation
RingBuffer buf(8);

static const int RXPin = 4, TXPin = 3;
static const uint32_t GPSBaud = 9600;

// The TinyGPS++ object
TinyGPSPlus gps;

// The serial connection to the GPS device
SoftwareSerial Serial2(RXPin, TXPin);

double  latitude, longitude;
int days, months, years, hr, mins, secs;
void setup()
{
  pinMode(LED_BUILTIN, OUTPUT);  // initialize digital pin LED_BUILTIN as an output.
  Serial.begin(115200);   // initialize serial for debugging
  Serial1.begin(9600);    // initialize serial for ESP module
  WiFi.init(&Serial1);    // initialize ESP module

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  // attempt to connect to WiFi network
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }

  Serial.println("You're connected to the network");
  printWifiStatus();

  // start the web server on port 80
  server.begin();
}

void loop()
{
  Serial1.end();
  Serial2.begin(GPSBaud);
  GPS();
  Serial2.end();
  Serial1.begin(9600);
  WiFiEspClient client = server.available();  // listen for incoming clients
  if (client) {                               // if you get a client,
    Serial.println("New client");             // print a message out the serial port
    buf.init();                               // initialize the circular buffer
    while (client.connected()) {              // loop while the client's connected
      if (client.available()) {               // if there's bytes to read from the client,
        char c = client.read();               // read a byte, then
        buf.push(c);                          // push it to the ring buffer

        // printing the stream to the serial monitor will slow down
        // the receiving of data from the ESP filling the serial buffer
        //Serial.write(c);

        // you got two newline characters in a row
        // that's the end of the HTTP request, so send a response
        if (buf.endsWith("\r\n\r\n"))
        {
          sendHttpResponse(client);
          break;
        }
      }
    }

    // close the connection
    client.stop();
    Serial.println("Client disconnected");
  }
}
void GPS() {
  while (Serial2.available() > 0) {
    gps.encode(Serial2.read());
    if (gps.location.isUpdated()) {
      // Latitude in degrees (double)
      latitude = (gps.location.lat(), 6);
      // Longitude in degrees (double)
      longitude = (gps.location.lng(), 6);

      // Day (1-31) (u8)
      days = (gps.date.day());
      // Month (1-12) (u8)
      months = (gps.date.month());
      // Year (2000+) (u16)
      years = (gps.date.year());

      // Hour (0-23) (u8)
      hr = (gps.time.hour());
      // Minute (0-59) (u8)
      mins = (gps.time.minute());
      // Second (0-59) (u8)
      secs = (gps.time.second());
      Serial.println(longitude);
      Serial.println(latitude);
      Serial.println(days);
      Serial.println(months);
      Serial.println(years);
      Serial.println(hr);
      Serial.println(mins);
      Serial.println(secs);

    }
  }
}

void sendHttpResponse(WiFiEspClient client)
{
  // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
  // and a content-type so the client knows what's coming, then a blank line:
  client.println("HTTP/1.1 200 OK");
  client.println("Content-type:text/html");
  client.println();

  // the content of the HTTP response follows the header:
  client.println("
");
  client.println("
");
  client.print("Latitude= ");
  client.print(latitude);
  client.print(" Longitude = ");
  client.println(longitude);
  client.println("
");
  client.print("Date: ");
  client.print(days);
  client.print("/");
  client.print(months);
  client.print("/");
  client.print(years);
  client.println("
");
  client.print("Time: ");
  client.print(hr);
  client.print(":");
  client.print(mins);
  client.print(":");
  client.print(secs);
  // The HTTP response ends with another blank line:
  client.println();
}

void printWifiStatus()
{
  // print the SSID of the network you're attached to
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print your WiFi shield's IP address
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // print where to go in the browser
  Serial.println();
  Serial.print("To see this page in action, open a browser to http://");
  Serial.println(ip);
  Serial.println();
}

SoftwareSerial can't listen on two instances. There is a .listen() function to switch between SoftwareSerial instances.
The esp8266 AT firmware doesn't wait until you listen on the SoftwareSerial instance. If there is a connection to the server it sends +IPD and data. If the SoftwareSerial instance doesn't listen the information about client connection is lost.
You must listen to esp8266 all the time, so you can't use two SoftwareSerial instances.
You could use the RX pin of Uno to receive data from GPS module over hardware Serial.


text:
Input value constantly
The code is for a DC motor position control PID system. I need the angle I need to move to "setpoint" and change it throughout the process. Though it is only changing once and then nothing happens if I insert a new value unless I upload the code again. I need help in finding the problem, thank you.
Code:
double count = 0; //set the counts of the encoder
double angle = 0;//set the angles
boolean A,B;
byte state, statep;

double pwm = 9;// this is the PWM pin for the motor for how much we move it to correct for its error
const int dir1 = 6;//these pins are to control the direction of the motor (clockwise/counter-clockwise)
const int dir2 = 7;

double    setpoint = 0;
double Kp = 0.2;// you can set these constants however you like depending on trial & error
double Ki = 0.25;
double Kd = 1;

float last_error = 0;
float error = 0;
float changeError = 0;
float totalError = 0;
float pidTerm = 0;
float pidTerm_scaled = 0;// if the total gain we get is not in the PWM range we scale it down so that it's not bigger than |255|
String readString;

void setup() {
   Serial.begin(9600);
  pinMode(2, INPUT);//encoder pins
  pinMode(3, INPUT);
  attachInterrupt(0,Achange,CHANGE);//interrupt pins for encoder
  attachInterrupt(1,Bchange,CHANGE);

  pinMode(pwm, OUTPUT);
  pinMode(dir1, OUTPUT);
  pinMode(dir2, OUTPUT);

}

void loop(){

   if (Serial.available()) { //Check if the serial data is available.
    delay(3);                  // a small delay
    char c = Serial.read();  // storing input data
    readString += c;         // accumulate each of the characters in readString
  }

  if (readString.length() >0) { //Verify that the variable contains information

   Serial.println(readString.toInt());  //printing the input data in integer form
    setpoint = readString.toInt();   // here input data is store in integer form

  }
   PIDcalculation();// find PID value

  Serial.print("         ");
Serial.print(setpoint);
Serial.print("         ");

  if (angle > setpoint+0.5) {
    digitalWrite(dir1, LOW);// Forward motion
    digitalWrite(dir2, HIGH);
  }
else if  (angle < (setpoint-0.5)) {
    digitalWrite(dir1, HIGH);//Reverse motion
    digitalWrite(dir2, LOW);
  }
  else{
      digitalWrite(dir1, LOW);//Reverse motion
    digitalWrite(dir2, LOW);
  }
  analogWrite(pwm, pidTerm_scaled);

  Serial.println("WHEEL ANGLE:");
  Serial.print(angle);  // here input data is store in integer form;
  delay(100);

}

void PIDcalculation(){

  angle = (0.9 * count);//count to angle conversion
  error = setpoint - angle;

  changeError = error - last_error; // derivative term
  totalError += error; //accumalate errors to find integral term
  pidTerm = (Kp * error) + (Ki * totalError) + (Kd * changeError);//total gain
  pidTerm = constrain(pidTerm, -155, 155);//constraining to appropriate value
  pidTerm_scaled = abs(pidTerm);//make sure it's a positive value

  last_error = error;
}

void Achange() //these functions are for finding the encoder counts
{
  A = digitalRead(2);
  B = digitalRead(3);

  if ((A==HIGH)&&(B==HIGH)) state = 1;
  if ((A==HIGH)&&(B==LOW)) state = 2;
  if ((A==LOW)&&(B==LOW)) state = 3;
  if((A==LOW)&&(B==HIGH)) state = 4;
  switch (state)
  {
    case 1:
    {
      if (statep == 2) count++;
      if (statep == 4) count--;
      break;
    }
    case 2:
    {
      if (statep == 1) count--;
      if (statep == 3) count++;
      break;
    }
    case 3:
    {
      if (statep == 2) count --;
      if (statep == 4) count ++;
      break;
    }
    default:
    {
      if (statep == 1) count++;
      if (statep == 3) count--;
    }
  }
  statep = state;

}

void Bchange()
{
  A = digitalRead(2);
  B = digitalRead(3);

  if ((A==HIGH)&&(B==HIGH)) state = 1;
  if ((A==HIGH)&&(B==LOW)) state = 2;
  if ((A==LOW)&&(B==LOW)) state = 3;
  if((A==LOW)&&(B==HIGH)) state = 4;
  switch (state)
  {
    case 1:
    {
      if (statep == 2) count++;
      if (statep == 4) count--;
      break;
    }
    case 2:
    {
      if (statep == 1) count--;
      if (statep == 3) count++;
      break;
    }
    case 3:
    {
      if (statep == 2) count --;
      if (statep == 4) count ++;
      break;
    }
    default:
    {
      if (statep == 1) count++;
      if (statep == 3) count--;
    }
  }
  statep = state;

}

your code is unreadable as it is ..... please use the {} button to  format the code ...... just select all of the code text and click {}

Since you have all that Serial calling in your sketch, please copy and paste the serial output, that you get to the question. Also specify what exactly you entered into the serial monitor to get to these results.


text:
Help with Arduino Micro Keypress Algorithm
Greeting, first time Arduino user here.
So I am using the Arduino Micro as an HID keyboard device. It accepts arbitrary input from a Node-JavaScript program I am running (so I have full freedom in in the data transferred to the micro).
The goal is for the data transmitted to the micro to include information about a keypress: whether it was pressed or released and which key it is. The serial connections are all fine and dandy - I just have questions regarding the key pressing logic.
As far as the JavaScript program goes, a key down is detected based on the keyCode, not the character code so when tapping “a”, character code  97, the Arduino micro is receiving “A”, character code 65 since the JavaScript detected keyCode is 65. So that all sounds like problems with JavaScript (which it is), but remember that I have freedom in portraying the information sent to the micro.
That being said, instead of detecting by keyCodes and character codes in JavaScript, I could just transmit the letter e.g. “a” with some identifier for press/release such as “+a” for release and “-a” for press. My problem here is how would I handle modifier keys using the Keyboard library.
Should I handle character keys and modifiers keys separately i.e. Keyboard.write for characters and Keyboard.press/release for modifiers or are there cases where it would make sense to press and hold “a” (which would also be different than pressing and holding “A”)?
Below is my original code using keyCodes and “u/d” identifiers to denote up or down (which I am thinking now that “u/d” could be easily confused as a letter if I decide to transmit characters as characters:
/*
  Receives from the hardware serial, sends to software serial.
  Receives from software serial, sends to hardware serial.

  The circuit:
   RX is digital pin 10 (connect to TX of other device)
   TX is digital pin 11 (connect to RX of other device)

  Not all pins on the Leonardo and Micro support change interrupts,
  so only the following can be used for RX:
  8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).
*/

#include <SoftwareSerial.h>
#include <Keyboard.h>

SoftwareSerial rpiSerial(10, 11); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  // Set the data rate for the SoftwareSerial port
  rpiSerial.begin(115200);
  // initialize control over the keyboard:
  Keyboard.begin();
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  Serial.println("Keyboard Serial Connection Established");
}

String keyCode = "";
char state;

void loop() {
  while (rpiSerial.available() > 0) {
    // "Type" via keyCodes (recommended for modifiers)
    // https://www.arduino.cc/en/Reference/KeyboardWrite not behaving as expected

    int data = rpiSerial.read();
    if (isDigit(data)) {
      keyCode += (char)data;
    }

    if (isAlpha(data)) {
      state = (char)data;
    }

    if (data == '\n') {
      Serial.print(state);
      Serial.println(keyCode.toInt());

      if (state == 'd') {
        Keyboard.press(keyCode.toInt());
      }

      if (state == 'u') {
        Keyboard.release(keyCode.toInt());
      }

      keyCode = "";
      char state;
    }
  }
}

I have also noticed that the data from the serial connection parsed by the micro is sometimes incorrect i.e. a keyCode will be misidentified. For instance, by repeatedly pressing “a” through my JavaScript program, the JavaScript program will consistently identify keyCode 65 yet Arduino will identify the received data as keyCode 65 most of the time and then randomly keyCode 64. This happens with other keys as well and the keyCode doesn’t always happen to be just one less nor does it always occur after “n” presses.

SoftwareSerial is not reliable at 115200. use 9600 baud

Good to know! I will try that @Juraj

ASCII code for 'A' is 65 and for 'a' it is 97. http://www.asciitable.com/ the key on keyboard is 'A', not 'a'.

So how would you recommend identifying with the micro that the key has been pressed/released?

what do you want to do in Arduino sketch while the key is pressed?

@Juraj I guess nothing aside from leaving the key pressed until it is released.

What do you mean?

sorry. I didn't know the press/release functions work for any key

Maybe there are some idiosyncrasies

Modifier keys are treated no different to normal keys.
The Arduino Keyboard library contains code to map different keys from the internal list of macros to specific keypresses:

If the key value is >= 138 it's a non-printing special key (subtract 138)
If the key value is >= 128 it is a modifier key (1 << (k - 128))
Otherwise look the code up in a mapping table.

That means you can use:
Keyboard.press(KEY_LEFT_SHIFT);

or
Keyboard.release(KEY_RIGHT_GUI);

The full list of modifier keys is:
#define KEY_LEFT_CTRL   0x80
#define KEY_LEFT_SHIFT    0x81
#define KEY_LEFT_ALT    0x82
#define KEY_LEFT_GUI    0x83
#define KEY_RIGHT_CTRL    0x84
#define KEY_RIGHT_SHIFT   0x85
#define KEY_RIGHT_ALT   0x86
#define KEY_RIGHT_GUI   0x87

So to do a capital A you can use:
Keyboard.press(KEY_LEFT_SHIFT);
Keyboard.press('a');
Keyboard.release('a');
Keyboard.release(KEY_LEFT_SHIFT);

There is also a shortcut, and that is:
Keyboard.press('A');
Keyboard.release('A');

The character 'A' is the same in the lookup table as character 'a' except the high bit of the result is set, which triggers a "Press or release the shift key" addition in the mapping code.
A USB keyboard report consists of 8 bytes:

Up to 8 modifier keys (bitmap)
One reserved byte
6 bytes to indicate pressed keys

This means that you can have up to 6 keys pressed at once, plus modifier keys. Never any more than that. So you don't need to handle any more than that in your code.
The current list of pressed keys is maintained by the keyboard and is sent in every report. There's no concept as such of "pressed" or "released" - only the list of what is currently pressed. If a key is released it's just removed from that list of pressed keys.
So what you need is some way of transferring that data in such a way that the Arduino can interpret it properly.
Since the data is not high throughput you can afford to be quite wasteful in your protocol.  I would suggest using a fairly verbose ASCII based protocol.

All the protocol data is using ASCII characters between 32 and 127 inclusive
This frees up control characters (<32) for controlling the protocol.

The simplest thing is to use a single control character (such as \n) to act as a line ending to break your data up into packets.  Each packet can then contain a list of instructions.
For example, you might choose to have a protocol that looks like:
P,129\n
P,97\n
R,97\n
R,129\n

By treating each line as a complete entity you know that you want to Press key 129 (#define KEY_LEFT_SHIFT    0x81), press key 97 ('a'), release 97, then release 129.
There's no confusion, since commands are all a single upper-case character, and keys are all a decimal number.
For your application, though, a "raw" access interface would be of more use, since you don't really want the Arduino interpreting things for you. However, the API doesn't provide that kind of thing.  So you just have to make the best of what you have and work around it.


text:
Receiving junk values in Arduino serial monitor console
I want to send a character from a Zigbee transmitter to an Arduino Mega 2560. After the character is received, Arduino should send some data back to Zigbee. But Arduino is always receiving junk values at the console. If I send a character, suppose 'a', instead of 'a', Arduino console is always showing 'y'. It is the same for every character I send.
#include <EEPROM.h>
#include <SoftwareSerial.h>
SoftwareSerial XBee(19, 18); // RX, TX
int addr = 0;
unsigned long startMillis;  //some global variables available anywhere in the program
unsigned long currentMillis;
const unsigned long period = 1000;  //the value is a number of milliseconds
void setup()
{

  XBee.begin(9600);
  Serial1.begin(9600);
  Serial.begin(9600);
  startMillis = millis();  //initial start time
 }
void loop()
{
  int id = 1;
  EEPROM.write(addr, id);
  if (Serial1.available()>0)
    {
      currentMillis = millis();  //get the current "time" (actually the number of milliseconds since the program started)
  if (currentMillis - startMillis >= period)  //test whether the period has elapsed
  {
    char recbyte=Serial.read();
    Serial.print(recbyte);
    // delay(1500);
    Serial1.write(id);
    Serial1.write(" 30 ");
    Serial1.write(" 99 ");
    Serial1.write(" 72 ");
    Serial1.write(" 1098 ");
    Serial1.write(" 728 ");
    Serial1.write(" 578 ");
    // Serial1.write("$");
    Serial1.write('PS=1\r\n');
    Serial1.end();
    startMillis = currentMillis;
  }
    }
}

There is a code formatting button on the editor toolbar but your code indentation is a big mess. If you are that careless then you can expect trouble. Use the edit link under your question to fix it and check the preview before you press "Save Edits".

@King: I approved your edit but it's still not right. Look at the close braces at the bottom. There are other problems too. The author should fix the question.

Whatever your actual issue is, having an EEPROM write in the the outermost uncondition part of your loop() is a mistake.

Your problem however is likely that you seem to be trying to take serial input from the PC.  Perhaps you mean to take it from Serial1 to which it seems you have the XBEE connected?

You have created a SoftwareSerial instance called XBee which is taking pins 17 and 18. You then use Serial1 which is pins 17 and 18.
You do not want, nor need, the XBee SoftwareSerial instance, since you are using hardware serial pins.  Delete it and all references to it.
Also, you are turning off Serial1 after using it, which means it will never work again:
Serial1.end();

You would only use that instruction in very very specific circumstances.  Delete it.
After checking to see if there is data available to read on Serial1 you then proceed to try and read it from Serial:
char recbyte=Serial.read();

That should be:
char recbyte=Serial1.read();

You are writing to EEPROM on every single iteration of loop:
EEPROM.write(addr, id);

It is likely that you have already killed your EEPROM.  C'est la vie...


text:
Guideline in library creation
According to this example, creation of an Arduino library is quite understandable.
But a few things I would like ask (mostly regarding to what to be defined where) when a library is not that simple:

Where to put additional libraries (such as <Wifi.h>) in .h or .cpp, since it works when defined in each one of them?
What is the purpose of defining variables in the :private section? Since they can be defined inside constructor, and as far as I know/tested, it works as well.
In a .cpp file, does it matter when instances or variables are defined outside a class (at the beginning of code ), since again, it works the same?

Where to put additional libraries (such as ) in .h or .cpp, since it works when defined in each one of them?

It doesn't really matter as long as the parts of your library that need to see the headers can see them.  Personally I put all headers in the master .h file and then that gets included in the .cpp file(s). It just keeps it all in one place and is easier to manage.

What is the purpose of defining variables in the :private section? Since they can be defined inside constructor, and as far as I know/tested, it works as well.

You need to understand "scope".  Defining a variable inside the constructor means that it's only available within that constructor.  This is "local" scope.  Defining the variable in the class, within the "private" section makes that variable available to every function within the class.  Putting it in "public" makes it available to anyone anywhere.

In a .cpp file, does it matter when instances or variables are defined outside a class (at the beginning of code ), since again, it works the same?

Again this is a matter of "scope".  A variable declared outside the class is in "global" scope. There is only one copy of each of these variables, and all instances of the class share the same physical variable. It is the same as declaring a class variable as "static" - it makes it common to all instances of the class.  If the data you need to store is specific to a class instance (which most of the time it is), you do not want to use global variables. In general it's bad form using global variables if you don't have to.
Incidentally, you may see variables defined both in the class and at the top of the CPP file.  This is a special case where you have static variables in your class, which don't have any storage space allocated to them (normally a variable has its storage space allocated when you create an instance of the class, but that doesn't happen with static variables for obvious reasons), so you have to manually provide the storage space with a separate entry in the CPP file.

Thank you very much. Now it is clearer. Regarding include external libraries in .h file : As far as I understand, this file only defines the structure of a class, and not for actual coding, right? If so- why should I define libraries in .h file?

Another thing: I was not aware that a library can hold more than one class, so that explain the locale of variables more clearly, but as far as I understood- lib file and class had to be the same, isn’t?

A header file is not a library. It is just a file. It gets included verbatim wherever the #include is. Including a library's header file does not get you the library code, only the header. It's down to the IDE to then find the CPP files and compile them for you. The name of a header file does not have to match the name of the class. It's not like Java. You can have as many classes as you like in a header file. Or none if you so wish.

Where to put additional libraries (such as <Wifi.h>) in .h or .cpp, since it works when defined in each one of them?

Any library can reference any other library. So including another library in your library is the same as including in the sketch. They should be on standard locations.
Include the other libraries .h in the file where you need it. If you use something from the other library in your .h, include it there. If you need it only in .cpp include it there.

What is the purpose of defining variables in the :private section? Since they can be defined inside constructor, and as far as I know/tested, it works as well.

With declaring a class member as private, the author of the class tells: don't use it, it is for internal use and can change in future versions.

In a .cpp file, does it matter when instances or variables are defined outside a class (at the beginning of code ), since again, it works the same?

If the variable is not a member of the class, then if you create two instances of the class they will share the variable. A variable in constructor is restricted to the constructor's scope.

thank you, 1) but where should it be placed ? .h or .cpp ? 2) the basic meaning of private I understand, but variables ( private) can be declared inside .cpp file also... so what is the difference ?

where should be placed your library or the libraries it uses? the libraries it uses should be placed the same way as for sketch. installed with Library Manager or copied in libraries subfolder of the sketches folder

how inside .cpp?

I know where to place to folder containing .cpp and .h file. My question is where is declare the use of a certain library ( such as <Wifi.h>'), in .hor.cpp`

you use it. nothing more. the user of your library should have them installed

I guess I don’t explain we’ll- let’s say that in my library I wish to use external, installed library (which operates as needed in a sketch ). Now I wish it will be declared in my library, so where should I WRITE ‘#include <lib.h’ ? In ‘.h’ file ? Or in ‘.cpp’ file ?

where you need it. if you need it only i cpp, pu it there. if you need it in .h put it there

Regarding 1: prefer to add it in the sketch/.cpp file only. If this is not possible (because you need the class to be known in the header file, only than add it in the header.
Reason: a header file is typically included by many other files and adding an include results in more coupled code, making later maintenance more difficult.
Regarding 2/3: See also the somewhat related answer of me in why-to-store-a-function-parameter-value-in-a-class-private-variable.


text:
Can I configure the highlighting for escaped characters in a string?
Given a simple mistake like
void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.println("\");     // note: " is escaped, so this won't compile
}

This is rendered in Arduino IDE 2.0.3 as

and the problem is hard to spot.
The Jetbrains IDEs have special highlighting for escaped characters like

which makes the problem more obvious because the two quotation marks have different color.
Any chance that this can be configured in the new Arduino IDE 2.0.3 as well?
Because it was asked in the comments: no, the syntax highlighting does not highlight the escaped character when the string is complete. The backslash and quotation mark are both still green.

@hcheung "\" is not a string as it does not have a closing quotation mark. \" is an escaped character in a string.

"\" is an escape " without closing ", you might get the correct syntax highlight if you do "\"".

use a text editor that supports it

@jsotola: I'm working with children at the age of 10. I can't simply tell them to switch the editor.

@hcheung: No, it's not highlighted when the string is complete: https://i.sstatic.net/Dbb6x.png

Any chance that this can be configured in the new Arduino IDE 2.0.3 as well?

Yes. You'll need to enable the Arduino language features provided by the language server. They're disabled by default.

Press F1,
Type Preferences: Open Settings (JSON),
Press Enter,
The settings.json file opens.

Add the following to the JSON and save it if you do not have auto-save enabled:
{
  "arduino.language.realTimeDiagnostics": true
}

My settings.json with the Arduino language features enabled.

Select a board. You can ignore the port selection if you like. The language feature should start, and you will see the error in the editor.

More details on the Advanced Settings are here.

Thanks. Undoubtedly, this is very helpful. The color of the escaped character is still the same, though.

In the JetBrains IDE, you wrote Serial.println("\"); and in the Arduino IDE Serial.println("\");     // note: " is escaped, so this won't compile. Can you please update your question about the syntax coloring in JetBrains with the longer example? Thanks! I compared the built-in C++ extension in VS Code with Arduino IDE, and they behave the same. The compiler error seems valid: Expected expression clang(expected_expression). I do not think you will be able to tweak the syntax highlighting in Arduino IDE.

My VSCode has syntax highlighting in strings: https://i.sstatic.net/Tq9iS.png Haven't used it for a long time, but IMHO I only use it for Typescript, not C++, so I don't think I have any C++ specific extensions installed and it even asks me whether I want to install some..

I am sorry I could not help you with this. This conversation only leads if we compare the same snippets in different IDEs and editors. I did not say VS Code, Arduino IDE, or other tools cannot apply different syntax coloring on a regex token, but your initial use case is different; it's a pure compiler error. Even the built-in StackOverflow snippet highlighting shows the same result as the Arduino IDE; please look at your original question and check the snippet.

I did another check and can confirm a bug in the Arduino IDE that does not highlight the regex matches. If there are no compiler errors, VS Code correctly highlights \d in the "\d+" string. Arduino IDE 2.0.3 fails to do it.

One more update. The regex syntax coloring works in the Arduino IDE with both the Light (Theia) and Dark (Theia) themes, not with the Arduino ones. Steps to reproduce. Your sketch: void setup() {} void loop() { Serial.println("\d"); }. \d is not highlighted. Open settings with Ctrl/⌘+,. Select one of the Theia themes from the dropdown, and close the dialog with OK. \d is highlighted. If I select any of the Arduino themes, it does not work. This is a theme bug.

If you want to give that an an additional answer, I'm happy to upvote and accept it.


text:
Which C++ standard does the Arduino language support?
The "Arduino language" (as they call it) of the Arduino IDE 1 is obviously C++. Which C++ exactly?
I tried to figure it out myself (Arduino IDE 1.8.13 for Arduino Uno), but I can't conclude what C++ standard it supports.
From these tests, it seems to support C++14

C++ 14 variable templates are supported (template<typename T> constexpr T pi = T(3.1415926535);)

C++ 14 lambda captures are supported (auto lambda = [value = 1] {return value;};)

C++ 14 deprecated is supported ([[deprecated]]int fdep(){return 5;})

But not fully:

C++ 14 digit separators are not supported (int j = 2'000;)

From these tests, it even seems to support some C++17:

Nested namespace definitions are supported (namespace X::Y {int func(){ return 1; } })

But also not fully:

UTF-8 characters are not supported (char x = u8'a';)

If it partially supports everything, is there an overview like a list or table where I can look it up?

It supports whatever the particular core and compiler you are using supports and is configured to support. Turn on verbose compilation and you will see the commands it is running including the command line flags (-std*, etc).

look around here https://arduino.github.io/arduino-cli/0.19/platform-specification/#recipes-to-compile-source-code

I expect your tests to give different results on different versions of Arduino IDE and different boards.

The Arduino "language" is nothing more than a set of C++ functions and classes. It does not mandate any particular C++ standard.
The standard is dictated purely by the compiler that the core you are using happens to support (and is configured to use through command line flags).
Different cores use different compilers. Different versions of the same core use different compilers. Different compilers provide different C++ standard levels.
Most cores use GCC or some variant thereof. That could be anything from GCC 3.x.x through to the most recent release (whatever that is this week).
Currently the AVR core uses GCC 7.3.0 and is configured to use the gnu++11 standard by default (though avr-gcc and the associated libraries lack a full STL implementation). You can of course change that in the configuration files if you want.

"nothing more than a set of C++ functions and classes" -> And the very important preprocessing, which is missing for example in PlatformIO.

@AndreKR That's not really part of the language - more a bit of convenience fudging that really shouldn't exist anyway (and until fairly recently was broken horribly anyway).

Without that preprocessing you would need something called "Header Guards", a technique so strange I find it hard to explain why it needs to exist.

@AndreKR No, that's wrong. All the preprocessing does is scrape your code for functions and insert prototypes for you at the top of your sketch. It does nothing with header guards, which is something you should always have in your header files regardless.

Arduino language isn't even fully C++11 because it doesn't support std::erf() in C99 and C++11. https://godbolt.org/z/dP1W1xfW6

@phuclv you're confusing the compiler and the STL which are two different things. True avr-gcc lacks the full STL but it is still C++11 (with GCC extensions) syntax.