text:
Firmata: how to set a particular pin to high on boot?
I'm working on a project that use J5, so is using the standard firmata, this project is using an opto 4 channel relay, when the board is booting the pins state are set to low, so as soon as I power the board my relay goes to a close state and make my motor run... this is a wrong behaviour for my purpose. How can I avoid that? By googleing around I stumble acros this:
A possible solution
but I can't uderstand if this is what I'm looking for.. plus I need only the PIN 7 to be set high on boot, any help please?
EDIT: SCHEMATICS
4 Channel 5V Relay Module

What makes you believe it boots with all pins LOW? They should be high impedance. Could you share the schematic of how you connect the Arduino to the optocoupler, to the the relays and to the motors?

@EdgarBonet added schematics in the question ;)

This is not a schematic. And it only shows how you are powering your relay module, not how you are driving it, nor how it works internally (reference please).

@EdgarBonet added the references link to the constructor wiki page

@EdgarBonet I forgot in the schema above to connect the pin 7 to the ch1, sorry

It would seem you are right. If I understood the source correctly,
Firmata initializes all digital pins as OUTPUT LOW. Hard to believe, as
this seems like a silly thing to do... My understanding is that:

setup() calls systemResetCallback() in order to set the initial
pin configuration (line 779)
systemResetCallback() loops over all pins and calls
setPinModeCallback(i, OUTPUT) for every pin i that is not an
analog pin (line 732)
setPinModeCallback() calls pinMode() to set the pin to OUTPUT
(line 325).

If my understanding is correct, then the simplest solution would seem to
patch systemResetCallback() and replace OUTPUT by INPUT on
line 732.

yep, my same conclusion but I think that setting all the pins to INPUT will cause the same but opposite problem for other components.. best would be set the desired pin number

Irrespective of how you patch Firmata, the pins will be set to INPUT when you power the Arduino, and during the time the bootloader runs. You should manage for you circuit to accommodate that initial state. A pullup or pulldown resistor may be suitable for the pins driving those other components.

how does it take to boot less than a second would be acceptable

Just put digitalWrite(anyPin,HIGH) in void setup() this will make that specific pin HIGH to reset. It works for me.
void setup()
{
  digitalWrite(8,HIGH);
  Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION);

  Firmata.attach(ANALOG_MESSAGE, analogWriteCallback);
  Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback);
  Firmata.attach(REPORT_ANALOG, reportAnalogCallback);
  Firmata.attach(REPORT_DIGITAL, reportDigitalCallback);
  Firmata.attach(SET_PIN_MODE, setPinModeCallback);
  Firmata.attach(SET_DIGITAL_PIN_VALUE, setPinValueCallback);
  Firmata.attach(START_SYSEX, sysexCallback);
  Firmata.attach(SYSTEM_RESET, systemResetCallback);

  // to use a port other than Serial, such as Serial1 on an Arduino Leonardo or Mega,
  // Call begin(baud) on the alternate serial port and pass it to Firmata to begin like this:
  // Serial1.begin(57600);
  // Firmata.begin(Serial1);
  // However do not do this if you are using SERIAL_MESSAGE

  Firmata.begin(57600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for ATmega32u4-based boards and Arduino 101
  }

  systemResetCallback();  // reset to default config
}


text:
code wont upload to arduino starter kit
My operating system : OS X EL CAPITAN
Please help I was trying to do project 05 Mood cue of the arduino starter kit. I completed setting up my board and writing the code and when I tried to upload I got this error message:
Arduino: 1.7.10 (Mac OS X), Board: "Arduino Uno"

Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
avrdude: ser_open(): can't open device "/dev/tty.usbmodem1411": Device not         configured
ioctl("TIOCMGET"): Inappropriate ioctl for device
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

Can someone please help me?

Try to use the official and original Arduino software from arduino.cc current version

@Personagem i tried to download it and it still would not work this is the error it gave me now :
Sketch uses 444 bytes (1%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
avrdude: ser_open(): can't open device "/dev/tty.usbmodem1411": Device not configured
Problem uploading to board.
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

It sounds like there is an issue with your USB serial connection.

@harry_p_6 thanks for the response harry. What do i do now? is there a away to fix it? im very new to all this

@harry_p_6 Thank you Harry i managed to fix it by downloading CH341SER_MAC.zip just in case someone has the same problem http://www.wch.cn/downfile/178

your arduino kid may not be connected properly else configure the board

@PendukeniPandeni Glad you managed to find the solution. Add your comment as an answer and mark it as accepted solution.

You're welcome. As @Personagem said, please answer your own question and accept the answer so that it does not count as an unanswered question.

Thank you Harry i managed to fix it by downloading CH341SER_MAC.zip just in case someone has the same problem wch.cn/downfile/178

source: Stack Exchange

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

sort: votes


text:
Shift registers. What, how and why?
I'm making a project and I'm using multiple 1 digit 7 segment displays. I haven't plugged them all on my arduino because currently I'm just testing. The problem is on the I/O ports. Obviously I need to use shift registers and since it's my first time ever using them I need to know more about them. After googling, I found that the specific model I bought outputs 8 pins and you can stack up to 8 in series. So lets do the math. 8 shift register x 8 pins each SR = 64 new pins It seems cool but assuming I'm using 28 displays let's do the math again.
28 displays, each display has 8 pins (8 for segments and 2 as common cathode)
28 x 8 = 224 required pins.
Is is possible to expand the I/O pins by 224 pins? How many shift registers can I stack together? Also which is better, the single digit display or the 4 digit display?

You can chain as many shift registers as you want.
Most commonly, these displays are multiplexed. Only one digit is lit at a time, cycling though all the digits fast enough, so the eye can't tell. This is however not very good practice for 28 digits, as the brightness will become 1/28th (though you could create groups of digits, and multiplex those groups separately).
There are specialized chips that do this multiplexing for you. E.g. the Max7219. This chip can multiplex 8 digits, with 8 segments. So you'd need 4 of these to light up 28 digits.

Is the Max7219 using an SPI pin? If yes since im using an ethernet shield how can i make it work?

http://datasheets.maximintegrated.com/en/ds/MAX7219-MAX7221.pdf
SPI, QSPI and Microwire. You should check the datasheet first and then ask.
You can make it work by using the slave-select pins, to choose one of the devices to send to. http://arduino.cc/en/Reference/SPI

You can buy these displays on eBay for a few dollars. A bit of soldering and you are done (although also pre-assembled ones are available). They can be daisy-chained. Example:

You only need 5 wires to the Arduino: Gnd/5V/MOSI/SCK/SCK.

Also, 64-dot displays for displaying arbitrary text:

Again, only 5 wires.
I have Arduino libraries for driving both sorts of display on
Interfacing LED displays with the MAX7219 driver .

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


text:
How to switch on and off an HD44780 LCD Display?
I have an LCD Display HD44780 model and I was reading his datasheets
I saw the it has the functionality to be switched on/off as stated:

Display on/off control: D = 0; Display off // C = 0; Cursor off // B = 0;
  Blinking off

and by continue reading it states:

Then he states again:
Display On/Off Control

D:  The display is on when D is 1 and off when D is 0. When off, the
  display data remains in DDRAM.

But I can't reaaly understand what I fisically need to do, can anyone help me out to better understand?
EDIT:
For better clarify myfinal goal is to completely (power OFF) the LCD screen, I have some NPN transistors and if this would be the best solution, how about the wiring? do I have only to stop suppying VDO?

At the end I manage to control the complete poweroff of the screen by connecting the pin 15 of the lcd to the Arduino and with a simple HIGH an LOW set of the arduino pin I was able to power it ON/OFF.

Assuming that display is initialized in 8-bit mode: to send command such as "Turn display on/off",

set RS to LOW first (meaning it is command, not data)
set command bits on DB7-DB0 (in your case it could be 0x08 - DB2/DB1/DB0 all LOW to turn off following: display, cursor and blinking)
make a pulse on EN pin LOW-HIGH-LOW (take a 40uS delay before further communication)

Thanks for the reply, assuming that your answer is correct how would you implement such portion of code?

There are tons of HD44780 libraries on the Internet. For example LiquidCrystal library for Arduino. Or this one - https://github.com/aostanin/avr-hd44780


text:
How to correctly code a LED STRIP?
I recently bought a 5050 RGB 12V 3A LED strip and I set it all up with my Arduino and run this code (from adafruit website), everything is good:
Example Code
Once you have the strip wired up, it is easy to control the color of the strip by using PWM output, for Arduino you can use
#define REDPIN 5
#define GREENPIN 6
#define BLUEPIN 3

#define FADESPEED 5     // make this higher to slow down

void setup() {
  pinMode(REDPIN, OUTPUT);
  pinMode(GREENPIN, OUTPUT);
  pinMode(BLUEPIN, OUTPUT);
}

void loop() {
  int r, g, b;

  // fade from blue to violet
  for (r = 0; r < 256; r++) {
    analogWrite(REDPIN, r);
    delay(FADESPEED);
  }
  // fade from violet to red
  for (b = 255; b > 0; b--) {
    analogWrite(BLUEPIN, b);
    delay(FADESPEED);
  }
  // fade from red to yellow
  for (g = 0; g < 256; g++) {
    analogWrite(GREENPIN, g);
    delay(FADESPEED);
  }
  // fade from yellow to green
  for (r = 255; r > 0; r--) {
    analogWrite(REDPIN, r);
    delay(FADESPEED);
  }
  // fade from green to teal
  for (b = 0; b < 256; b++) {
    analogWrite(BLUEPIN, b);
    delay(FADESPEED);
  }
  // fade from teal to blue
  for (g = 255; g > 0; g--) {
    analogWrite(GREENPIN, g);
    delay(FADESPEED);
  }
}

I tried to find a way to achieve the same effect but only with two colors...red to yellow..red fade to yellow and fade to red and so on..
EDIT:
Thanks to @majenko I achieved this...Fade from Red to Yellow and back on:
    for (int r = 0; r < 256; r++) {
        analogWrite(REDPIN, r);
        analogWrite(GREENPINPIN, 255 - r);
        analogWrite(BLUEPIN, 0);
        delay(FADESPEED);
    }

    // Fade red down and blue up
      for (g = 0; g < 256; g++) {
        analogWrite(REDPIN, 255);
        analogWrite(BLUEPIN, 0);
        analogWrite(GREENPINPIN, G);
        delay(FADESPEED);
      }

What kind of arrangement are you after? Assuming red and blue are your two colours, do you want "NONE -> R -> R+B -> B -> NONE..." or "R -> B -> R -> B...", or what?

@Majenko R ....fade to B....fade to R...fade to R and so on...

The main difference between what you want and what that code does is that you want to fade both colours at once, but that code is aimed at only fading one colour at a time.
You want to fade R up whilst fading B down, and then fade R down whilst fading B up. The simplest way is with just two loops:
// Fade red up and blue down
for (int i = 0; i < 256; i++) {
  analogWrite(REDPIN, i);
  analogWrite(BLUEPIN, 255 - i);
  delay(FADESPEED);
}

// Fade red down and blue up
for (int i = 0; i < 256; i++) {
  analogWrite(REDPIN, 255 - i);
  analogWrite(BLUEPIN, i);
  delay(FADESPEED);
}

One fade value (i) per loop, and a little bit of maths to turn 0-255 into 255-0 for the value you are fading down.

For Red->Yellow->Red you just need to keep red on and fade green on and off.  You already have code to fade green on and off in your original program:
  // fade from red to yellow
  for (g = 0; g < 256; g++) {
    analogWrite(GREENPIN, g);
    delay(FADESPEED);
  }

  // fade from teal to blue
  for (g = 255; g > 0; g--) {
    analogWrite(GREENPIN, g);
    delay(FADESPEED);
  }

Couple that with setting the red and blue to on and off respectively, and you have:
#define REDPIN 5
#define GREENPIN 6
#define BLUEPIN 3

#define FADESPEED 5     // make this higher to slow down

void setup() {
  pinMode(REDPIN, OUTPUT);
  pinMode(GREENPIN, OUTPUT);
  pinMode(BLUEPIN, OUTPUT);

  analogWrite(REDPIN, 255);
  analogWrite(BLUEPIN, 0);
}

void loop() {
  int g;

  // fade from red to yellow
  for (g = 0; g < 256; g++) {
    analogWrite(GREENPIN, g);
    delay(FADESPEED);
  }

  // fade from yellow to red
  for (g = 255; g > 0; g--) {
    analogWrite(GREENPIN, g);
    delay(FADESPEED);
  }
}

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


text:
How to pass value of a function from the RFID-RC522 library into a variable then be sent into either serial or ethernet?
I'm using an RC522 RFID reader with an Arduino UNO. There is a function?? (or whatever it's called :)) in Miguel Balboa's new MFRC522.h library which is mfrc522.uid.uidByte[i] that prints the bytes of the unique ID. The repetition of the function results in 8 piece of HEX digits that are from the 2 numbers that each function outputs (2+2+2+2=8). Whenever I use the line of codes that are commented out, the serial monitor outputs them successfully. So for example, 12345678 is the unique id, each array displayed 12, then 34, then, 56, then 78 which is 12345678 in the serial. which is fast and unnoticeable besides that there are no spaces included when on output. The thing is, I want to output all of these into a single variable.(Please help me also on how to concatenate) How can I do this? An attempt was done below (not commented out) but it outputs only the number 16, consistently, which is I think due to a data type problem. The variables are initialized as int. The "function" which I found in the library is initialized as byte (correct me If I'm wrong). But when the variables are initialized as byte, I cannot upload the sketch since there are errors. Please help. :( (The reason I need it to be saved into a single variable is because I am placing it in the GET method of an Ethernet Client. I don't think the bare function can do that. (Or if it can, can you please help with the code? :)) Thanks

// Dump UID
        //Serial.print("Card UID:");

            //Serial.print(mfrc522.uid.uidByte[0], HEX);
            //Serial.print(mfrc522.uid.uidByte[1], HEX);
            //Serial.print(mfrc522.uid.uidByte[2], HEX);
            //Serial.print(mfrc522.uid.uidByte[3], HEX);

            serNum0={mfrc522.uid.uidByte[0], HEX};
            serNum1={mfrc522.uid.uidByte[1], HEX};
            serNum2={mfrc522.uid.uidByte[2], HEX};
            serNum3={mfrc522.uid.uidByte[3], HEX};
            Serial.print(serNum0);
            Serial.print(serNum1);
            Serial.print(serNum2);
            Serial.print(serNum3);

As far as I can understand, you expect to receive byte data from the RFID reader, you would like to store this data into a single variable, and eventually print its content, or manipulate it in some way. You could do this maintaining a byte array (or uint8_t array).
Let's suppose, for example, to receive a unique ID of length 4 from the RFID reader. In this case you could simply store it into a serNum[serNum_size] array, where serNum_size is just the number of data you are expecting to receive, and later access its content for whatever manipulation you would like to do.
int serNum_size = 4;        // reader data size
byte serNum[serNum_size];   // reader data content

for(int i = 0; i < serNum_size; i++){
 serNum[i] = mfrc522.uid.uidByte[i]; // store reader data block
 Serial.print(serNum[i], HEX);       // hexadecimal form
}

As far as the print is concerned, you can simply print the byte entry and apply the HEX format. In this way, the stored value will be considered as its hexadecimal value.

Welcome to Arduino SE! Can you add a bit of explanation to your answer explaining how this works, etc.? Thanks!


text:
How to round up millis() when divided into minutes?
unsigned long milliseconds=millis();
// if at time of reading the above milliseconds = 599999 ie 1 millisecond short of 600000 ie 10 minutes
unsigned long minutes = (milliseconds/1000)/60;
// this will return 9 instead of 10.

How do you round the result to 10 minutes? I don't mean adding 1 to final result. It has to be within the calculation.

To round to the nearest X in fixed point arithmetic: add 1/2 X (in the base units, msec, in this case) and divide by X (again, in the base units) so:
milliseconds = (milliseconds + (30*1000L))/(60*1000L);
The addition of 1/2 X causes a carry of one whole X if the fractional X in the original quantity was 1/2 X or greater. (Likewise, if the fractional X was less than 1/2 X, no carry will result).
Integer division naturally truncates any fractional amounts, so you'll be left with the rounded integer result.

Here is a simple trick how to switch from integer math to floating point math and use round function.
  unsigned long milliseconds = 599999;

  unsigned long minutes_long = (milliseconds/1000)/60;
  // minutes_long = 9

  double minutes_double = (milliseconds/1000.0)/60.0;
  // minutes_double = 9.99998...

  double minutes_rounded = round(minutes_double);
  // minutes_rounded = 10

There also exists a trick that allows calculation of round using integer math. It's perfect if you don't have enough memory for a cast.
  unsigned long milliseconds;

  milliseconds = 600000 - 30*1000 - 1;
  //milliseconds = 569999

  unsigned long minutes_9 = (milliseconds+30000)/60000;
  // minutes_9 = 9

  milliseconds = 600000 - 30*1000;
  //milliseconds = 570000

  unsigned long minutes_10 = (milliseconds+30000)/60000;
  // minutes_10 = 10

try double minutes_double = (milliseconds/1000.0)/60.0;

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


text:
Problem sending GPS coordinates with SMS when requested
I have made a project that sends GPS coordinate but the problem is, when GPRS sends coordinates as 00.0000,00.000. So, I want to know if my code is wrong.
Thank you for your answer.
#include <SoftwareSerial.h>
#include <TinyGPS++.h>

double latitude, longtitude;
char Received_SMS; //Here we store the full received SMS (with phone sending number and date/time) as char
short MSG_OK = -1; //Used later it shows if there's the word "DHT"/"MLX" within the received SMS "-1" means they are not found
String Data_SMS; //Here's the SMS that we gonna send to the phone number, it may contain DHT data or MLX data

TinyGPSPlus gps;
SoftwareSerial mySerial(2, 3); //gps
SoftwareSerial ss2(9, 10); //gprs

void setup() {
  Serial.begin(9600);
  mySerial.begin(9600); //Begin all the communications needed Arduino with PC serial and Arduino with all devices (SIM800L+DHT+MLX)
  ss2.begin(9600);
  Serial.println("GPS Tracking");
  delay(1000);
  Serial.println("Starting ...");
  delay(3000); //Delay to let the module connect to network, can be removed
  ReceiveMode(); //Calling the function that puts the SIM800L moduleon receiving SMS mode
}

void loop() {
  mySerial.listen();
  while (mySerial.available()) {
    gps.encode(mySerial.read());
  }
  if (gps.location.isUpdated()) {
    latitude = gps.location.lat();
    longtitude = gps.location.lng();
  }
  String RSMS;
  ss2.listen();
  while (ss2.available() > 0) { //When SIM800L sends something to the Arduino... problably the SMS received... if something else it's not a problem
    Received_SMS = ss2.read(); //"char Received_SMS" is now containing the full SMS received
    Serial.print(Received_SMS); //Show it on the serial monitor (optional)
    RSMS.concat(Received_SMS); //concatenate "char received_SMS" to RSMS which is "empty"
    MSG_OK = RSMS.indexOf("GET-GPS"); //And this is why we changed from char to String, it's to be able to use this function "indexOf"
  }
  if (MSG_OK != -1) { //If "DHT" word is found within the SMS, it means that DHT_OK have other value than -1 so we can proceed
    Serial.println("found MSG"); //Shows on the serial monitor "found DHT" (optional)
    Data_SMS = ("http://www.google.com/maps/place/" + String(latitude, 6) + "," + String(longtitude, 6));
    Send_Data(); //This function set the sending SMS mode, prepare the phone number to which we gonna send, and send "Data_SMS" String
    ReceiveMode(); //Come back to Receving SMS mode and wait for other SMS
    MSG_OK = -1; //If the DHT is found the variable should be reset to -1 otherwise it will be kept as !=-1 and will send SMS over and over
  }
}

void Serialcom() { //This is used with ReceiveMode function, it's okay to use for tests with Serial monitor
  delay(500);
  while (Serial.available()) {
    ss2.write(Serial.read()); //Forward what Serial received to Software Serial Port
  }
  while (ss2.available()) {
    Serial.write(ss2.read()); //Forward what Software Serial received to Serial Port
  }
}

void ReceiveMode() { //Set the SIM800L Receive mode
  ss2.println("AT"); //If everything is Okay it will show "OK" on the serial monitor
  Serialcom();
  ss2.println("AT+CMGF=1"); // Configuring TEXT mode
  Serialcom();
  ss2.println("AT+CNMI=2,2,0,0,0"); //Configure the SIM800L on how to manage the Received SMS... Check the SIM800L AT commands manual
  Serialcom();
}

void Send_Data() {
  Serial.println("Sending Data..."); //Displays on the serial monitor...Optional
  ss2.print("AT+CMGF=1\r"); //Set the module to SMS mode
  delay(100);
  ss2.print("AT+CMGS=\"+66xxxxxxxxx\"\r"); //Your phone number don't forget to include your country code example +212xxxxxxxxx"
  delay(500);
  ss2.print(" You are here "); //This string is sent as SMS
  delay(500);
  ss2.print(Data_SMS); //This string is sent as SMS
  delay(500);
  ss2.print((char)26);//Required to tell the module that it can send the SMS
  delay(500);
  ss2.println();
  Serial.println("Data Sent.");
  delay(500);
}

if you want an answer, then perhaps you should ask a question

what coordinates is GPS providing?

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


text:
Why doesn't this timer code work?
Why doesn't the code below work? Timer will count 370ms then function called to ON LED. Again 370ms then function called to OFF LED. Basically a toggle function.
int IN0 = 12;
int IN1 = 11;
int OUT1 = 10;
int OUT2 = 9;
int OUT3 = 7;
int OUT4 = 6;
int LED = 13;
unsigned int count = 370;
unsigned int tcount = 0;
bool tflag = 0, mflag = 0, sflag = 0, lflag = 0, rflag = 0;
int a, b;

void setup() {
  pinMode(IN0, INPUT);
  pinMode(IN1, INPUT);
  pinMode(LED, OUTPUT);
  pinMode(OUT1, OUTPUT);
  pinMode(OUT2, OUTPUT);
  pinMode(OUT3, OUTPUT);
  pinMode(OUT4, OUTPUT);
  Timer1.initialize(a); // 370 miliseconds on time
  //Timer1.attachInterrupt(flash);
}

void flash_on() {
  //digitalWrite(LED, !digitalRead(LED));
  digitalWrite(LED, HIGH);
}

void flash_off() {
  //digitalWrite(LED, !digitalRead(LED));
  digitalWrite(LED, LOW);
}

void loop() {
  Timer1.attachInterrupt(flash_on);
  a = count;
  Timer1.attachInterrupt(flash_off);
  a = count;
}

At what point do you give the timer the new value you have put in a? Never.

You should give a a value before calling Timer1.initialize(a).
For example, like this:
void setup() {
  ....
  a = count;
  Timer1.initialize(a); // 370 miliseconds on time
  ....
}

Your loop() code will also not work like you expect it to.
As it is, you will be switching between two different ISRs very fast, without having any control over which of the two will be called once the Timer1 interrupt occurs.
It will be better to stick to one ISR that toggles the LED. That’s kind of the point of a Timer interrupt.

Here, in loop() i've called flash_on() the reason is i've to check the other parameter by polling. Just by toggling in my opinion i cannot do that. If there is any way to do with toggling, request you to please guide me with same.


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

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

Is there any other way than modifying the module itself?

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

@Gerben i removed the resistor.

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

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

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

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

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

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

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

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

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

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


text:
Help to set vertical dcroll on SSD1306
I am trying to set the text to scroll vertically. I have a big chunk of text (example in the code below) to be set to scroll vertically. What I want is to display the complete text on the screen. Presently it scrolls the complete chunk of text. Any help or guidance is heartily welcome.
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
// The pins for I2C are defined by the Wire-library.
// On an arduino UNO:       A4(SDA), A5(SCL)
// On an arduino MEGA 2560: 20(SDA), 21(SCL)
// On an arduino LEONARDO:   2(SDA),  3(SCL), ...
#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3D ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
void setup() {
  Serial.begin(9600);
  display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS);
  display.clearDisplay();

  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(0, 0);
  display.println("Sometimes we dont want to scroll entire display. ");
  display.startscrollright(0x00, 0x0F);

  display.display();

  delay(1000);
}
void loop(){

}

The link to the project is here: https://wokwi.com/arduino/projects/302023407584674313
3rd edit
My question:
My goal is to display the text in the window. The text should not go out of the window.  If the text is too long, it should scroll vertically.
Thanks again, everyone.

I'm not 100% sure what you're asking; your text mentions vertical scrolling, your code does horizontal scrolling of 16 rows, and your text presumably is much wider than the screen. Can you edit the question to be more clear?

So you don't want to scroll, you want to wrap the text?

So... you've abandoned the question about scrolling and instead want to just render some text as large as possible on the screen?

@DaveNewton timemage The whole text should be fit in the screen., It need not become large., It has to be scrollable, when the test is more than what the device can display

The whole text can't fit on the screen--are you saying if the text is larger than the screen it should automatically scroll?

Dear @DaveNewton yes. exactly

And what is the current issue? You may also want to update your question to reflect the information from these comments, because the question asks about vertical scrolling.

okay. I will update the question clearly soon

This line achieved it for me. I stole it from here: Adafruit Forum
display.startscrolldiagright(0x0F, 0x0F);

It sets diagonal scroll, but start and stop positions are multiples of the display width so that in total, it scrolls vertically up.
Alternatively, you edit the display buffer; by removing your content from the current position, deleting the first line of pixels, adding a new last line of pixels, writing it all back to the display buffer and then call display.display().
This is not exactly saving your microcontroller time but it works, too. I asked ChatGpt to do the coding for the second solution, it delivered. I won't post the code here though, as it is against the rules.


text:
Code logic to measure values stored in buffer and created nested array
I am having a difficult time creating some logic in my code.
I have a potentiometer connected to an ESP32 to simulate a load cell and a range sensor. The value for the force is between 0 and 400 newton and for the range between 50 and 0 mm. In the code I have a function that, when the position 40 mm is reached, starts the measure procedure where evenly depending on the  position, the force and the correspondent position would need to be stored in a buffer. When reaching 0 mm a JSON would need to be created with the 5 measure points. If NUM_SAMPLES would be 5, we would start the first measure at 40 mm, the second at 30 mm, the third at 20 mm and so on. Reaching 0 mm the JSON would need to be created from the values from the buffer and printed out. The end result would need to be:
{"range_array":[40,30,20,10,0],"force_array":[82,163,241,322,400]}.
But now I get the JSON created and printed out continuously at 40 mm.
{"range_array":[40,30,20,10,0],"force_array":[82,82,82,82,82]}
If I go out from 40 mm it stops. Code follows.
Thanks in advance for some help.
#include <Arduino.h>            // Required by platformIO
#include <ArduinoJson.h>        // JSON library for embedded C++
#include <WebSocketsServer.h>   // WebSocketServer Bibliothek

const int potPin = 14; // Analog pin connected to the potentiometer
const int rangeMin = 0; // Minimum range of the simulated sensor in mm
const int rangeMax = 50; // Maximum range of the simulated sensor in mm
const int forceMin = 0; // Minimum force of the simulated sensor in newton
const int forceMax = 400; // Maximum force of the simulated sensor in newton

int rangeValue = 0;
int range_reading = 0;
int forceValue = 0;
int force_reading = 0;

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

WebSocketsServer webSocket = WebSocketsServer(81);

int NUM_SAMPLES = 5;

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

void loop() {
  unsigned long currentMillis = millis();

  Read_Range_Sensor();
  Read_Loadcell();

  // Check if position is 40mm, then start measurement
  if (range_reading == 40) {
    performMeasurement();
  }

  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    Serial.print("Range: ");
    Serial.print(range_reading);
    Serial.print(" mm, Force: ");
    Serial.print(force_reading);
    Serial.println(" N");
  }
}

void Read_Range_Sensor() {
  rangeValue = analogRead(potPin);
  range_reading = map(rangeValue, 0, 4095, rangeMax, rangeMin);
}

void Read_Loadcell() {
  forceValue = analogRead(potPin);
  force_reading = map(forceValue, 0, 4095, forceMin, forceMax);
}

void performMeasurement() {
  // Arrays to store positions and forces
  int range_array[NUM_SAMPLES];
  int force_array[NUM_SAMPLES];

  // Start measuring from 40mm to 0mm
  for (int i = 0; i < NUM_SAMPLES; i++) {
    range_array[i] = 40 - i * (40 / (NUM_SAMPLES - 1));
    force_array[i] = map(analogRead(potPin), 0, 4095, forceMin, forceMax);
  }

  // Create JSON object
  StaticJsonDocument<200> doc;
  JsonArray rangeJson = doc.createNestedArray("range_array");
  JsonArray forceJson = doc.createNestedArray("force_array");

  // Populate JSON arrays
  for (int i = 0; i < NUM_SAMPLES; i++) {
    rangeJson.add(range_array[i]);
    forceJson.add(force_array[i]);
  }
  // Serialize JSON to string
  String jsonString;
  serializeJson(doc, Serial);
  serializeJson(doc, jsonString);
}

your code works correctly ... the problem is that the five readings occur within a few microseconds ... add delay code, or pushbutton code, to increase the interval between reads

Let me start of with a few assumptions, because this information / context is missing:

The force will be measured across a non-negligible amount of time (order of milliseconds, seconds)
The potmeter is controlled by either a human or a motor that takes some time to turn (milliseconds to seconds) it from the simulated 0N to 400N.

The codes in its current state, is just measuring the potmeter 5 times in "an instant" (a few microseconds).
I suggest that additional logic be implemented to change the potmeter to the wanted value, and then measure.
I also see a few more inconsistencies / illogical actions in this program, i.e. the same potmeter is used as the force and as the range. Read_Range_Sensor and Read_Loadcell perform exactly the same functionality, as potPin never changes.
The intention is not quite clear here (what needs to be achieved, how).


text:
Help with MPU-6050
I have bought MPU-6050 a month ago for a project, I have got a hang I2C protocol and register maps of MPU. I have learnt how to get raw values of accelerometer and gyroscope. What I needed for my project is roll and pitch angles and acceleration in x,y,z axes. I have tried some algorithms as shown below:
 First I saw a code which uses only raw accelerometer values to get roll and pitch. Here is a small snippet of that code:
x=(AcX)/16384;
y=(AcY)/16384;
z=(AcZ)/16384;
roll = (atan2(y, z)+PI)*57.295779513082320876798154814105;
pitch = (atan2(x , z)+PI)*57.295779513082320876798154814105;

As you can see this uses principle of angle between two vectors, the angles were pretty accurate. But the problem with this code is that as the sensor moves in a particular direction without changing the roll or pitch they still seemed to change (The roll and pitch values are dependent on accel values).
Next, I saw about using Complementary Filter my code:
#include<Wire.h>
const int  MPU_addr=0x68, dt=20;
float AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;
float xa,ya,za,xg,yg,zg;
float gan_x = 0 ,gan_y = 0,aan_x = 0,aan_y = 0, anx = 0, any = 0, gain  =0.95;
int xao = -521 ,yao = 1073 ,zao = 1724 ,xgo = 94 ,ygo =31 ,zgo = 60;                       //offset values
void setup()
{
  Serial.begin(115200);
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x1A);
  Wire.write(0b00000110);
  Wire.endTransmission(true);
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x1B);
  Wire.write(0b00000000);
  Wire.endTransmission(true);
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x1C);
  Wire.write(0b00000000);
  Wire.endTransmission(true);
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);
  Wire.write(0b00000000);
  Wire.endTransmission(true);
}
void loop()
{
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers
  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
  Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
  GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
  GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
  GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
  xa = (AcX-xao)/16384;                                                    //sensitivity adjusting
  ya = (AcY-yao)/16384;
  za = (AcZ-zao)/16384;
  xg = (GyX-xgo)/131;
  yg = (GyY-ygo)/131;
  zg = (GyZ-zgo)/131;
  gan_x = dt * xg + anx;                                                       // integrating
  gan_y = dt * yg + any;
  aan_x = (atan2(ya,za)+PI)*57.295779513082320876798154814105;
  aan_y = (atan2(xa,za)+PI)*57.295779513082320876798154814105;
  anx = (gain) * gan_x + (1-gain) * aan_x;                                     // filtering
  any = (gain) * gan_y + (1-gain) * aan_y;
  //Serial.print(" | GyX = ");
  Serial.print(gan_x);
  Serial.print(" ");
  //Serial.print(" | GyY = ");
  Serial.println(gan_y);
}

This code gives good gyroscope values in terms of angular velocity but I want it in degrees is there any way to change those gyro values to degrees(like in first case)?

I saw Jeff Rowberg's library and I can't seem understand all of the code. Can anyone please provide any reference material explaining the functions present in i2cdevlib.h (Ex: mpu.dmpInitialize(), mpu.setDMPEnabled() etc) it would be a lot of help.

I also would like to know if there are any other alternative IMUs (Gyro+accel) other than MPU6050 which are more of an open source than 6050 (in terms of accessing DMP which seems to be main drawback for MPU) and easier to work with.

I am using Arduino Nano.
-Thank you in advance

This code gives good gyroscope values in terms of angular velocity but I want it in degrees is there any way to change those gyro values to degrees(like in first case)? - And what the angular velocity is measured in?

Angular velocity = Degrees per second, I want gyro values in degrees @EugeneSh.

All the references of Jeff Rowberg's library are in his library. His code is pretty well commented. I used the raw.ino of his examples for one of my projects and it worked perfectly.

Just use Jeff Rowberg's code and go through all the lines in his code, perhaps even open up the .cpp and the .h to get a better understanding what is being done with your code.

Yea I opened and read library and cpp. I will try to go through again :). I got a work around for now thank you  @Len

@TejaAllani also, I get that not understanding the library can be frustrating, but I know for sure that it works really good. Sometimes that's enough and that's also a bit why you'd want a library: you don't have to write and understanding everything yourself because the library will do the hard work for you. Good luck with your project.

@Len, I read through every line of code in .h and .cpp file patiently. I finally got an outline of how it works. The problem when I first saw those files was my C++ programming. I didn't know how library is made and what does .h have to do with .cpp file. I thought they were separate and had no link to each other. After hours of googling finally I was capable of understanding link between .h and .cpp that .cpp had function definitions which were declared in .h file. Now I can use that library with satisfaction :D. Thank you for the help.

hey teja would you mind sharing the code, as I am also stuck on this for quite a while.

@Mahshida, the code is in the Answer

I finally got this working after one sleepless night
#include<Wire.h>
const int MPU = 0x68;
int t = 0,dt = 1;
int AcX,AcY,AcZ,GyX,GyY,GyZ,tmp;
int AcXo,AcYo,AcZo,GyXo,GyYo,GyZo;
float roll = 0,pitch = 0,rollgy = 0,pitchgy = 0,rollac = 0,pitchac = 0,Ax,Ay,Az,Gx,Gy,Gz,gain = 0.95;
void MPUconfig(int Addr,int data)
{
  Wire.beginTransmission(MPU);
  Wire.write(Addr);
  Wire.write(data);
  Wire.endTransmission();
}
void MPUread()
  {
    Wire.beginTransmission(MPU);
    Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
    Wire.endTransmission();
    Wire.requestFrom(MPU,14);  // request a total of 14 registers
    AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
    AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
    AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
    tmp=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
    GyX=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
    GyY=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
    GyZ=Wire.read()<<8|Wire.read();
  }
void offset()
{
  MPUconfig(0x1A,0b00000000);
  int ax = 0, ay = 0,az = 0,gx = 0,gy = 0,gz = 0,i;
MPUread();
MPUread();
ax = AcX;
ay = AcY;
az = AcZ;
gx = GyX;
gy = GyY;
gz = GyZ;
for(i=0;i<1100;i++)
{
    MPUread();
    if(i>100)
    {
      ax = (ax+AcX)/2;
      ay = (ay+AcY)/2;
      az = (az+AcZ)/2;
      gx = (gx+GyX)/2;
      gy = (gy+GyY)/2;
      gz = (gz+GyZ)/2;
    }
    delay(2);
 }
AcXo = ax;
AcYo = ay;
AcZo = 16384-az;
GyXo = gx;
GyYo = gy;
GyZo = gz;
MPUconfig(0x1A,0b00000110);
}
void setup()
{
  Serial.begin(115200);
  Wire.begin();
  MPUconfig(0x1A,0b00000110);
  MPUconfig(0x1B,0b00000000);
  MPUconfig(0x1C,0b00000000);
  MPUconfig(0x6B,0b00000000);
  offset();
}

void loop()
{
  t = millis();
  MPUread();
  Ax = (float)(AcX-AcXo)/16384;
  Ay = (float)(AcY-AcYo)/16384;
  Az = (float)(AcZ-AcZo)/16384;
  Gx = (float)(GyX-GyXo)/131;
  Gy = (float)(GyY-GyYo)/131;
  Gz = (float)(GyZ-GyZo)/131;
  pitchgy = (Gy * ((float) dt/1000)) + pitch;
  rollgy = (Gx * ((float) dt/1000)) + roll;
  pitchac = atan2(Ax,Az) * (float)(180/PI);
  rollac =  atan2(Ay,Az) * (float) (180/PI);
  roll = gain * rollgy + (1-gain)* rollac;
  pitch = gain * pitchgy + (1-gain) * pitchac;
  Serial.print(roll);
  Serial.print(" "); Serial.print(pitch);
  Serial.println(" ");
  dt = millis()-t;
}

Hi, Teja Allani, Thanks for sharing the code. It works. One issue puzzles me though, in the offset subroutine, the code takes the 2nd MPUread() for the initialization. Is there any reason for doing so?  I did some tests by marking the 2nd MPUread out and my tests do reveal different results.

Further, it seems that the code yields angles that are limited to (-45, 45). Where do I need to change for angle computation extended to (-90, 90)?

Hello :) @Jesse , The 2nd MPUread() because the first couple of readings are not stable it takes some time for MPU to give stable results, for this same reason I put i>100 in the loop so 1st 100 readings are not used for calibration.

and for that angles use atan2() instead of atan() to change the limits of the angles. This code still needs some improvement because I found that when roll or pitch cross 90 degrees they seemed to effect each other( I can't explain this phenomenon clearly test it out after replacing atan() with atan2() ) maybe its because the values of Ax and Ay  become negative after crossing 90 degrees and this sudden change from +ve to -ve and effects filter. _Also try changing gain value and observe results _

Thanks for the feedback. I did check that atan() takes one argument and  the angle can be between [-90,90], leading me to think that some improvements are needed.  Anyway, you got most of it in one sleepless night is quite impressive. Best wishes.

After testing this with my project I found out that this program is only helpful for roll and pitch < 90 degrees. So I decided to use Jeff Rowberg's library. After going through code, I found out that it was only way to get perfect values out of sensor.

Hmmm, interesting to know that. My test on your original code showed (-45, 45).  Have you updated your code?

@Jesse Just updated it

used atan2 which takes 2 args. Thanks. Nice learning from you.


text:
How safe is it to use my body as part of a circuit?
I have two polystyrene balls wrapped in copper tape. When the balls touch, the tape completes a circuit from a digital pin on an Arduino inside one of the balls to an Arduino inside the other (both powered by 9v batteries). This allows them to send information to each other via the copper tape path.
I was testing the balls out, and they were working too well. Even when the balls weren't quite touching, the signal was getting through! Turns out that's because the signals were travelling via my body. Even if I held one ball in one hand and the other ball in the other hand, digital reads on one Arduino were correctly reading the digital writes from the other.
This is actually great for my project!... unless it's not safe. So I'm looking for two things:

A reliable reference on what is and isn't safe in terms of voltage/wattage/amperage travelling from hand to hand.
A second opinion on the voltage/wattage/amperage that two Arduinos will actually pump through me (from digital pin to digital pin).

You say the tape completes a circuit when the balls touch ... do the balls have some wires connecting them, besides the tape?  Or are you just doing capacitive signalling?

@jwpat7 I guess "completes the circuit" is the wrong wording. One Arduino sets a pin to 0V or 5V in a recognizable pattern, that pin leads to a pin on the other Arduino (via the copper tape), where the voltage is read. When the balls aren't touching, the pins aren't connected.

So it is like you have two metal globes, with no wires coming out, and when they are connected you are able to detect signals between them?  If so the mechanism is capacitive and current probably is on the order of nanoamps if that.  What's your signalling protocol?  Do you have to have some min or max data rate, Manchester coding, and so forth?

@jwpat7 I haven't decided on the protocol yet. I just confirmed that the distinction between high and low was getting through. The data rate I need is super low (<10bps) so basically anything I use will work. The main complication is cross-talk, or negotiating who sends and who receives.

If you ever switch to a wall-adapter, make sure it's not one of those ultra-cheap chinese ones.

If you are talking about running at 5V, then I doubt there is any safety issue. After all, 9V batteries (the sort you put in your smoke detector) just have bare terminals and no-one tells you not to touch them.
There is quite a bit of related information at How much voltage is “dangerous”?. That link seems to have enough information that there isn't a lot of point of repeating it all here.
There is a reference on that page to someone holding a metal pole connected to a 12V battery wading through water which completed the circuit and he was unable to let go of the pole. But that is 12V (more than twice 5V) and in circumstances where there was good conduction (his body was wet).

In the interests of science I set up a small test. I connected myself to a 5V lab supply via an ammeter. I grasped the terminals firmly (with dry hands) and measured about 3 µA of current. From the page I referenced above there seems to be a consensus that 1 mA would be just noticeable, so this is about 300 times less.
I found if I wet my fingers I got up to about 20 µA of current, still a lot less than 1 mA.
That page mentions that 60V is getting into the range where you might get a shock.

Hopefully it goes without saying that if you are going to touch metal balls then you need to be certain that 5V is the maximum, and that some sort of failure in a power supply might not deliver a lot more. But if the balls are battery powered you should be pretty safe.

You've added that they are powered by 9V batteries. That doesn't change my answer much. The most that could "escape" due to some malfunction is then 9V. Under normal operation you would have 5V from a digital output pin.
I measured my body resistance as being around 1.5 MΩ, which is consistent with getting 3 µA of current through it.
I = V / R
I = 5 / 1500000 = 0.000003 A

Have you tried licking the terminal on a 9V battery, they don't say you shouldn't do that either :)

Yes I did that when I was a lot younger. The pain caused me to stop doing it. :)

In fact the voltage is almost irrelevant. The current is the issue. 30mA is normally considered the limit - this is the value RCD are set to trigger at.
Even low voltages applied to intimate places can be fatal. (I have a couple of wires in my heart, these can certainly cause a significant impact).
There is little risk with the low energy available, but if you want to be safe you can use a series resistor. I have (a very early) touch sensor installed on lights in my house. The touch pad is effectively connected to 240V, but is quite safe as the pad is connected through 2 10MΩ resistors. (2 are needed as they are rated at 500V.)

2 are needed - plus that is a precaution if one fails and becomes closed circuit.

In fact the voltage is almost irrelevant. The current is the issue. - Check out "It's not the volts that kill you, it's the amps"

@NickGammon I didn't "read" the link, because it is to a video. Like most such issues this is not simple, because people are not a simple linear resistance. I bow to the recommendations of the of the Standards authorities, which admittedly only apply to "Low Voltage" (contrary to most expectations this is 1000V - with its own caveats).

If you had "read" the link you would see that he agrees with you. It isn't simple. Higher voltages, however, break down the surface resistance of things like bodies.

@NickGammon, apparently there are no wires coming out of the spheres (see comments to question) so typically any volts or amps occuring will be from capacitive effects as a few nanocoulombs of charge move around.

@jwpat7 - not wires, but he said in the question I have two polystyrene balls wrapped in copper tape.. I count the copper tape as "wires".

@NickGammon, ok, but no additional wires that can complete an electrical circuit per se.  Toggling a bit in the Arduino inside a ball shifts the shell up or down relative to the matter inside the ball, which I think has a capacitive effect.  If no wires come out (besides the shell) then no steady current can flow.

@jwpat7 - yessss, but the OP said When the balls touch, the tape completes a circuit. So I am reading that as "there is conductive stuff on the outside that completes the circuit" - not a capacitance effect. His surprise was that by holding the balls in each hand his body completed the circuit.

@jwpat7 If you want to have a discussion why not do it in Chat, rather than in Comments to this Answer


text:
How do I get sensor values using transmitter and receiver?
I used an HC-SR04 sensor and connected it to an Arduino board (BOARD1) with a 433 MHz transmitter, and the other board (BOARD2) is connected to the 433 MHz receiver. I don't know how to see the sensor value readings from the (BOARD1) in the serial monitor.
HERE IS THE CODE OF THE TRANSMITTER
#include <RH_ASK.h>
#include <SPI.h> // Not actually used but needed to compile

RH_ASK driver;
int echo=11;
int trig=9; int sensorval;
void setup() {
   Serial.begin(9600); // Debugging only
   driver.init();
}

void loop() {
   digitalWrite(trig,LOW);
   delayMicroseconds(10);
   digitalWrite(trig,HIGH);
   delayMicroseconds(10);
   digitalWrite(trig,LOW);
   delayMicroseconds(10);
   sensorval=pulseIn(echo,HIGH);
   const char *msg = sensorval;
   driver.send((uint8_t *)msg, strlen(msg));
   driver.waitPacketSent();
   delay(200);
}

HERE IS THE CODE OF THE RECEIVER
#include <RH_ASK.h>
#include <SPI.h> // Not actually used but needed to compile

RH_ASK driver;
const int sensorval;
void setup() {
    Serial.begin(9600); // Debugging only
    driver.init();
}

void loop() {
    uint8_t buf[4];
    uint8_t buflen = sizeof(buf);
    if (driver.recv(buf, &buflen)) // Non-blocking
    {
    Serial.print("message Received: ");
 Serial.println((char*)buf);
    }
}

First: A short excourse about c-strings
In C a string is an array of characters. Such an array is defined with
char msg[10];

10 being the size of the array. Every valid c-string needs to be terminated with the null character \0. This character is not printable, thus you don't see it normally. But the standard string functions (like printf(), strlen(), etc) use the null character to find the end of the string. So when handling strings as char arrays, you absolutely always need to terminate the string with the null character. The standard functions are incrementing through the array, until they find the null character. If it is missing, they don't stop at the end of the array.
Needing the null character also means, that the above char array can only hold 9 characters (since the 10th is the null character).
The standard functions for creating a string (like printf() and its siblings) already terminate the string correctly with the null character.

You are obviously trying to send an ASCII encoded string. But sensorval is not a string, it is of type int (a number). In C/C++ one does not simply implicitly convert a number to a string (please insert the image of boromir from Lord of the Rings here in your head). You actually have to say the compiler how to convert the number to a string. Also sensorval cannot itself hold that string (as it is an integer number). For that you need a char array (often called c-string) for saving all the characters of your string.
So first we need to define the char array to hold our string:
char msg[10];

This creates a char array with 10 elements, each one can hold a character of your string. So you have space for 9 characters. If you need more, you can increase that number.
Now we need to build a string in msg, that represents the value of sensorval. For that we can use sprintf(), which lets us format a string out of data and save it in a char array.
sprintf(msg, "%d", sensorval);

The first parameter is the char array to put the string in. The second parameter is called format-string. That is a string literal, that defines the format. %d represents an integer value; it is a placeholder for the actual data and describes, how it should be formatted (you can read about the different format options in the C++ documentation if you search for printf()). The following parameters (here only one) are the data values for the placeholders in the format string. Let's take an example: Assume sensorval is 1000. Then msg will be:
1000\0

The \0 being the null character.
So in your code you would replace
const char *msg = sensorval;

with
char msg[10];
sprintf(msg, "%d", sensorval);

What you have done in your code:
This line
const char *msg = sensorval;

will NOT create a string. You are defining msg as a pointer to a constant character (a pointer is a variable, that holds the address another variable in the memory, use google terms like "C pointers" for more info). And then you set the pointer to sensorval, which of course is not a valid pointer (valid meaning pointing to something reasonable here). It just points somewhere in the memory.
The example, that you got it from uses:
const char *msg = "hello";

This works, because the compiler takes all string literals (the strings enclosed by the double quotes) and puts them fixed into the memory, somewhat like a variable without a name. So here the compiler instructs the microcontroller so save the string "hello" in the memory. With the above line we define a pointer to the place in the memory, where this string is saved.
So this works good for string literals, but not, if you first need to actually build the string.

i'm sorry i am new to this so i don't quite understand what to do. From what I have read on your answer, should I replace the const char *msg=sensorval;  to  char msg[10]; sprintf(msg, "%d", sensorval); or before the void setup, I will put a string sensorval;?

@ThomasRaymondSantos I overhauled my answer to explain in more depth, what is happening here and what to do.

okay i'll try to understand, thank you so much for the help!

Otherwise it might be good to do some tutorials about c-strings. I'm sure there are many online

thank you @chrisl appreciate it!


text:
Use TCC1 timer to generate PWM on personnal board built with SAMD21E18A
I'm trying to generate a PWM signal from TCC1. I have a personnal board built with SAMD21E18A. I want to use pin 27 PA30, in my variant.cpp I have this line:
{ PORTA, 30, PIO_PWM, PIN_ATTR_DIGITAL|PIO_SERCOM, No_ADC_Channel, NOT_ON_PWM, TCC1_CH0, EXTERNAL_INT_10 }, // SWCLK

I understand I can use TCC1_CH0 on this pin with PIO_TIMER. Here is what I've tried at the end of my setup:
  pinPeripheral(27, PIO_TIMER);
  pinMode(27, OUTPUT);

  ....

  Tcc* TC = (Tcc*)GetTC(TCC1_CH0);
  TC->CTRLA.reg &= ~TCC_CTRLA_ENABLE;
  TC->CTRLA.reg |= TCC_CTRLA_PRESCALER_DIV1;
  TC->WAVE.reg |= TCC_WAVE_WAVEGEN_NPWM;
  TC->PER.reg = 255;
  TC->CC[0].reg = 128;
  TC->CTRLA.reg |= TCC_CTRLA_ENABLE;

But it's not working: I have nothing on my pin.
Edit: I've also tried this in my setup:
  GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID(TCC1_GCLK_ID) |
                     GCLK_CLKCTRL_GEN_GCLK0 |
                     GCLK_CLKCTRL_CLKEN;
  while (GCLK->STATUS.bit.SYNCBUSY);

  Tcc* TC = (Tcc*) TCC1;
  TC->CTRLA.reg &= ~TCC_CTRLA_ENABLE;

  TC->WAVE.reg = TCC_WAVE_WAVEGEN_NPWM;

  TC->CTRLA.reg |= TCC_CTRLA_PRESCALER_DIV1 |
                   TCC_CTRLA_RUNSTDBY;

  PORT->Group[PORTA].PINCFG[30].bit.PMUXEN = 1;
  PORT->Group[PORTA].PMUX[15].reg = PORT_PMUX_PMUXE_E;

  TC->CC[0].reg = 1000;
  TC->CC[1].reg = 4000;

  // Activer le timer
  TC->CTRLA.reg |= TCC_CTRLA_ENABLE;
  while (TC->SYNCBUSY.bit.ENABLE);

I have something on my oscilloscope, but the signal seems not to be good, HIGH signal is very very quick and low signal very long.

For example, settings for ATSAMR21G18A (it is similar to you MCU), PA08 PWM:
Pin init:
// GPIO PA08 PWM (DO)
PORT->Group[0].PINCFG[8].reg = PORT_PINCFG_PMUXEN;
PORT->Group[0].PMUX[8/2].bit.PMUXE = PORT_PMUX_PMUXE_E_Val; // TCC0/WO[0]

Timer init:
void timer0_init()
{
    GCLK->CLKCTRL.reg =   GCLK_CLKCTRL_ID_TCC0_TCC1 // Gen Clk Sel ID TCC0_TCC1
                | GCLK_CLKCTRL_GEN_GCLK0    // Generic clock generator 0
                | GCLK_CLKCTRL_CLKEN;       // Clock Enable

    PM->APBCSEL.reg = PM_APBCSEL_APBCDIV_DIV1;      // Divide by 1
    PM->APBCMASK.reg |= PM_APBCMASK_TCC0;           // TCC0 APB Clock Enable

    TCC0->WAVE.reg = TCC_WAVEB_WAVEGENB_NPWM;

    TCC0->PER.reg = 80; //TCC0/WO[0] PWM 100kHz DT=50%
    TCC0->CC->reg = 40;

    TCC0->CTRLA.reg = TCC_CTRLA_CPTEN0 | TCC_CTRLA_ENABLE;  // Enable
}

I have tried something similar @Dimitri but it's doesn't work my doubt come from this line in my variant.cpp{ PORTA, 30, PIO_PWM, PIN_ATTR_DIGITAL|PIO_SERCOM, No_ADC_Channel, NOT_ON_PWM, TCC1_CH0, EXTERNAL_INT_10 }, // SWCLKI'm not sure about NOT_ON_PWMcan I useTCC1_CH0for PWM`??


text:
Why is my LED strip value always equal to 255 on my potentiometer?
I'm pretty new to Arduino and this is my first project I'm working on and I'm really struggling with why my code isn't working properly.
The LED strip should be able to adjust the colour with one potentiometer that I can take out to so I don't use 3 potentiometers and just use that can adjust all colours. Then once it's on mode 4 it should keep the colour and blink repeatedly.
I'm using an Arduino Uno but once my project if finished I'll use the Arduino Nano. I don't know if I'll need to change the code but if I do I think I could do that on my own.
I just don't know why my LED strip is always stuck on off (255).
// set pin numbers:
int ledPinR = 11; // the number of the LED R pin
int ledPinG = 10; // the number of the LED G pin
int ledPinB = 9; // the number of the LED B pin
int buttonPin = 7; // the number of the push button pin
int mode = 0; //to change the mode
int bluelev = 0; //save the blue led value
int greenlev = 0; //save thegreen led value
int redlev = 0; // save the red led value

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPinR, OUTPUT);
  pinMode(ledPinG, OUTPUT);
  pinMode(ledPinB, OUTPUT);

  //make the led strip white at boot
  digitalWrite(ledPinR, 0);
  digitalWrite(ledPinG, 0);
  digitalWrite(ledPinB, 0);
}

void loop() {
  // when the button is pressed changes the mode value by one
  if (digitalRead(buttonPin) == LOW) {
    ++mode;
    delay(500);
  }

  if (mode == 1) { //red config
    int adcValue; // Define a variable to save the ADC value
    // Convert analog of A0 port into digital, and work as PWM duty cycle of ledPinR port
    adcValue = analogRead(A0);
    analogWrite(ledPinR, map(adcValue, 0, 1023, 0, 255));
    (redlev = ledPinR); // saves the red led level
  }

  if (mode == 2) { //green config
    int adcValue; // Define a variable to save the ADC value
    // Convert analog of A1 port into digital, and work as PWM duty cycle of ledPinG port
    adcValue = analogRead(A1);
    analogWrite(ledPinG, map(adcValue, 0, 1023, 0, 255));
    (greenlev = ledPinG); // saves the green led level
  }

  if (mode == 3) { //Blue config
    int adcValue; // Define a variable to save the ADC value
    // Convert analog of A2 port into digital, and work as PWM duty cycle of ledPinB port
    adcValue = analogRead(A2);
    analogWrite(ledPinB, map(adcValue, 0, 1023, 0, 255));
    (bluelev = ledPinB); // saves the blue led level
  }

  if (mode == 4) {
    digitalWrite(ledPinR, 255); // switch off LED
    digitalWrite(ledPinG, 255); // switch off LED
    digitalWrite(ledPinB, 255); // switch off LED
    digitalWrite(8, 0); // switch on LED
    delay(1000); //wait 1 second
    digitalWrite(ledPinR, redlev); // switch on LED
    digitalWrite(ledPinG, greenlev); // switch on LED
    digitalWrite(ledPinB, bluelev); // switch on LED
    digitalWrite(8, 225); // switch on LED
    delay(1000); //wait 1 second
  }

  if (mode == 5) {
    mode -= 5; //sets the mode value back to 0
  }
}

Here is the setup.
Pretend the RGB LED is a LED strip and the potentiometers are just slots for one to be put in to change the colour when I want to. So when I'm not changing the colours I can use the potentiometer for other projects and not waste 3.

There are at least these errors in your code:
1. You cannot read back the analog value set to a pin.
You try this:
    analogWrite(ledPinR, map(adcValue, 0, 1023, 0, 255));
    (redlev = ledPinR); // saves the red led level

You correctly set the analog value at the pin for the red LED. But then you try to read it back. Look at the definition of ledPinR: It is an int with the fixed value of 11. So redlev is always 11.
Note 1: The output is not really analog, but pulse width modulated.
Note 2: You don't need the parentheses in the second statement.
Instead, store the mapped value in redlev:
    redlev = map(adcValue, 0, 1023, 0, 255);
    analogWrite(ledPinR, redlev);

Note 3: Use good variable names, like redLevel. Some time or later you will confuse things because of abbreviated names.
2. You are not repeating the analog write in mode4.
You wrote this, which is apparently wrong:
  if (mode == 4) {
    digitalWrite(ledPinR, 255); // switch off LED
    // other statements...
    delay(1000); //wait 1 second
    digitalWrite(ledPinR, redlev); // switch on LED
    // other statements...
    delay(1000); //wait 1 second
  }

Instead you want this (if 255 is really "off"):
  if (mode == 4) {
    analogWrite(ledPinR, 255); // switch off LED
    // other statements...
    delay(1000); //wait 1 second
    analogWrite(ledPinR, redlev); // switch on LED
    // other statements...
    delay(1000); //wait 1 second
  }

There are more issues, but this will take you a step forward. Most important, keep an indentation style, I cleaned up your source in the question to make it readable.

thank you so much

You're welcome! BTW, you are supposed to mark the answer that fits you best as "accepted" instead of commenting a "thanks"...

My first project was also the same, to set the strip color with one potentiometer. I used the function getColorValue, that returns you a Struct. This struct contains the value for red, green, and blue. Here is the example code:
#define PIN_POTENTIOMETER A0

struct RGB
{
    uint8_t red;
    uint8_t green;
    uint8_t blue;
} color;

RGB getColorValue(uint16_t inputValue);

void setup()
{
    Serial.begin(9600);
    pinMode(PIN_POTENTIOMETER, INPUT);
}

void loop()
{
    uint16_t inputValue = analogRead(PIN_POTENTIOMETER);
    color = getColorValue(inputValue);

    Serial.print("R: ");
    Serial.print(color.red);
    Serial.print(" G: ");
    Serial.print(color.green);
    Serial.print(" B: ");
    Serial.println(color.blue);
    delay(100);
}

RGB getColorValue(uint16_t inputValue)
{
    RGB color;
    color.red = 0;
    color.green = 0;
    color.blue = 0;

    map(inputValue, 0, 1023, 0, 255);

    if (inputValue <= 42.5)
    {
        color.red = 255;
        color.green = inputValue * 6;
        color.blue = 0;
    }
    else if (inputValue <= 85)
    {
        color.red = 255 - (inputValue - 43) * 6;
        color.green = 255;
        color.blue = 0;
    }
    else if (inputValue <= 127.5)
    {
        color.red = 0;
        color.green = 255;
        color.blue = (inputValue - 85) * 6;
    }
    else if (inputValue <= 170)
    {
        color.red = 0;
        color.green = 255 - (inputValue - 127.5) * 6;
        color.blue = 255;
    }
    else if (inputValue <= 212.5)
    {
        color.red = (inputValue - 170) * 6;
        color.green = 0;
        color.blue = 255;
    }
    else if (inputValue <= 255)
    {
        color.red = 255;
        color.green = 0;
        color.blue = 255 - (inputValue - 212.5) * 6;
    }

    return color;
}

If you need any further help, you can comment here or contact me directly with my mail in the bio.
Regards
Dario

analogWrite and analogRead doesn't require pinMode.

@Juraj You are right, my fault.

thank you so much


text:
DHT20 and OLED display not working together
I am trying to get my DHT20 and OLED (both from the Arduino Sensor Kit) to work at the same time. I am able to get them working separately with their respective test codes, but when I try to combine the codes the OLED display no longer works. Both are I2C connections but I checked and each device has a different address so that shouldn't be a problem.
Here is my DHT20 test code:
#include "Arduino_SensorKit.h"

//uncomment line below if using DHT20
#define Environment Environment_I2C

void setup() {
  //uncomment line below if using DHT20
  Wire.begin();
  Serial.begin(9600);
  Environment.begin();
}

void loop() {
  Serial.print("Temperature = ");
  Serial.print(Environment.readTemperature()); //print temperature
  Serial.println(" C");
  Serial.print("Humidity = ");
  Serial.print(Environment.readHumidity()); //print humidity
  Serial.println(" %");
  delay(2000);
}

Here is my OLED display test code:
#include "Arduino_SensorKit.h"

void setup() {
  Oled.begin();
  Oled.setFlipMode(true);
}

void loop() {
  int random_value = random(0, 1023); // create a random value
  Oled.setFont(u8x8_font_chroma48medium8_r);
  Oled.setCursor(0, 3);
  Oled.print("Value: ");
  Oled.print(random_value);
  delay(1000);
}

This is the code where I tried to get both devices working at the same time:
#include "Arduino_SensorKit.h"

#define Environment Environment_I2C

void setup() {
  Oled.begin();
  Oled.setFlipMode(true);
  Wire.begin();
  Serial.begin(9600);
  Environment.begin();
}

void loop() {
  Oled.setFont(u8x8_font_chroma48medium8_r);
  Oled.setCursor(0, 3);
  Oled.print("Testing");
  Serial.print("Temperature = ");
  Serial.print(Environment.readTemperature()); //print temperature
  Serial.println(" C");
  Serial.print("Humidity = ");
  Serial.print(Environment.readHumidity()); //print humidity
  Serial.println(" %");
  delay(2000);
}

When I use this code the temp and humidity values are printed in the serial monitor but the OLED does not display anything.
Any help is much appreciated!

what happens if you reverse the order of the two module intialization in setup()?

Unfortunately reversing the order of the initialization in setup() doesn't change anything.

The basic problem
I don't have this sensor kit. But am able to observe what you're describing with substitutes and stand-ins. There seem to be two things you can do.
The basic problem is that the Arduino_SensorKit library is written to use software/bit-banged I2C for the display. Or rather, it tells U8G2LIB to do this, for what reason I don't know. When the ATmega328P I2C peripheral is enabled the GPIO hardware is no longer driving the pins. So the moment you enable the hardware I2C (via the DHT20 code) the GPIO bit-banging code in U8G2LIB cannot work correctly.
So, there are at least two ways this can be made to work.

Modifying your code so it works with how the Arduino_SensorKit library is written.

The other is modifying the Arduino_SensorKit library to use hardware I2C, in which case your original code works verbatim.

Modifying the sketch
You can modify your sketch as follows:
#include "Arduino_SensorKit.h"
#define Environment Environment_I2C

void setup() {
  Oled.begin();
  Oled.setFlipMode(true);

  Serial.begin(9600);

  Wire.begin(); // only here to match the subsequent .end()
}

void loop() {
  Wire.end();  // make I2C release control back to GPIO
  {
    Oled.setFont(u8x8_font_chroma48medium8_r);
    Oled.setCursor(0, 3);
    Oled.print(millis()); //Oled.print("Testing");
  }
  Wire.begin(); // re-enable I2C for use by DHT20 ("Environment")

  Serial.print("Temperature = ");
  Serial.print(Environment.readTemperature()); //print temperature
  Serial.println(" C");
  Serial.print("Humidity = ");
  Serial.print(Environment.readHumidity()); //print humidity
  Serial.println(" %");

  delay(2000);
}

For the most part the AVR Wire library doesn't care if you use repeated begin() or repeated end() calls. It may affect your speed setting though. The braces around the Oled usage are just there for visual effect.
Anyway, it works when you make sure Oled can use GPIO.
Modifying Arduino_SensorKit
With the following changes to Arduino_SensorKit library version 1.2.1 (current as of writing) I am able to use your sketch code verbatim. I also modified it to print millis() rather than "Testing" to be sure it was continuing to update the display.
Arduino_SensorKit.h
On line 24 of the libraries Arduino_SensorKit.h file, change:
extern U8X8_SSD1306_128X64_NONAME_SW_I2C Oled;

to
extern U8X8_SSD1306_128X64_NONAME_HW_I2C Oled;

Note HW (hardware) rather than SW (software).
Arduino_SensorKit.cpp
Likewise make the counterpart change to the definition of Oled corresponding to above change in extern declaration of Oled, from:
U8X8_SSD1306_128X64_NONAME_SW_I2C Oled(/* clock=*/ _PIN_SCL, /* data=*/ _PIN_SDA, /* reset=*/ U8X8_PIN_NONE);

to:
U8X8_SSD1306_128X64_NONAME_HW_I2C Oled(/* clock=*/ _PIN_SCL, /* data=*/ _PIN_SDA, /* reset=*/ U8X8_PIN_NONE);

You can probably remove the arguments from the constructor call here; the ATMega328P has no options with respect to configuring TWI/I2C for more than one set of pins.

There's also nothing stopping you from leaving it as U8X8_SSD1306_128X64_NONAME_SW_I2C, but changing the pins so that the software I2C uses pins other than A4/A5 so as not to conflict with the DHT20 libraries use of hardware I2C.

For reference the U8G2LIB version I tested with was 2.33.15. arduino-cli version 0.32.2. arduino:avr core 1.8.7. I don't think you need these. I'm just being complete in case someone finds this 5 years from now or whatever.

Thank you so much! I modified the sketch and it works perfectly now!

I use a variable to store the readings.
#include "Arduino_SensorKit.h"

#define Environment Environment_I2C

void setup() {
  Oled.begin();
  Oled.setFlipMode(true); // Sets the rotation of the screen
  // uncomment line below if using DHT20 (black sensor)
  Wire.begin();
  // uncomment line below if you're connecting your DHT20 to pin a different than 3
  Serial.begin(9600);
  Environment.begin();
}

void loop() {
  Wire.begin();

  // You need variable to keep the reading because Enviroment will not work when LED in operation
  float temp= Environment.readTemperature();
  float hum= Environment.readHumidity();
  Serial.print("Temperature = ");
  Serial.print(temp); //print temperature
  Serial.println(" C");
  Serial.print("Humidity = ");
  Serial.print(hum); //print humidity
  Serial.println(" %");

  delay(2000);

  // int random_value = analogRead(A0);
  Wire.end();

  {
    Oled.setFont(u8x8_font_chroma48medium8_r);
    Oled.setCursor(0, 0);    // Set the Coordinates
    Oled.print("temp: ");
    Oled.print(temp); // Print the Values

    Oled.setCursor(0, 3); // Set the Coordinates
    Oled.print("Humidity: ");
    Oled.print(hum); // Print the Values
    Oled.refreshDisplay(); // Update the Display
  }
}


text:
Importing content of text file as string into Arduino code
Is there any macro for importing the content of a file (for example html code) located in the sketch folder as a string for the Arduino IDE during compilation time?

For ESP32 (and ESP8266), you can partition part of the Flash memory to be used as the file system and creating a data/ folder in your project for storing files. Take a look at arduino-esp32littlefs-plugin (used for uploading the data to the partition) on how to install the plugin in Arduino IDE, and the LittleFS library or SPIFFS on how to use it to store and retrieve data.
I have a project on my github showing how the SPIFFS is used for storing webpages (html, JavaScript, CSS, icon, etc.) and serve it via an Async ESP32 Server. Following the link on the github for more detail explanation on the blog.

This is a very nice little project: modern and straightforward approach, the code is short and simple, very clear explanations in your blog… It could make a good “reference example” of sorts for people aiming to build a Web server for a hardware project.

Thank you @EdgarBonet for your compliments.

Try using the C++ Raw String Literal.
It's in the form of
const char *myLiteralText=R"abc123~~~(
   this is
   literal text
   which includes all spaces
   and newlines
)abc123~~~"

The abc123~~~ is a delimiter.
The test.h file must be modified by adding the first and last lines.
Actually, the last line can be in the test.ino file after the #include line, so only the first line has to be added to the test.h file.
Example at https://wokwi.com/projects/384484092370522113
test.ino
void setup() {

  Serial.begin(9600);

  const char *index_html=
    #include "test.h"
  ;

  Serial.print(index_html);

}

void loop() {}

test.h
R"html(

<!DOCTYPE html>
<html lang="en">
  <head>
      <meta charset="UTF-8">
      <title>VIPSDK MONITOR</title>
      <meta http-equiv="refresh" content="10">
  </head>
  <style type="text/css">
  </style>
</html>

)html"

In short, no. That I'm aware of the IDE, languages, and build system don't provide anything to do that automatically. It would be nice if C++ had something like Rust's include_str or include_bytes but so far as I know it still doesn't.
Your question is tagged with esp32. You may want to put strings on on your data partition if they're large.
There are other ways to do it, but the usual way to build arbitrary data into a C++ or C program is to run a utility that converts it into source code. Either into a string literal or an initialized array of some character type.
The xxd utility that usually comes with VIM is one such utility. It's normally used to generate hex dumps of files, but can be told to produce source code of an initialized array. Utilities like that are often run in a pre-build stage of a more conventional build process for C++. You could probably hack something into platform.txt that would do it. Or into something like a git hook. But the IDE doesn't have that sort of flexibility.
Here's a webpage that does the same sort of thing. You may have to manually null terminate the array if you want to do this.


text:
Which sketch was this?
With ESP32 being so plentiful here (3 more for Christmas) I am at a loss to determine which sketch I used for a particular unit. Has anyone devised a record keeping scheme or even a serial monitor feedback with the sketch details available when plugged back in to the PC?

What information do you want to see there exactly? You could just do a Serial print with some custom message (defined by you) inside setup(). Is that what you want?

I set up a precompile trigger that will run a shell script that grabs the current git hash and puts it in a file as a #define.  From my sketch I print that.  Then I know which file and which version is loaded.

Early in setup() I print one line to the terminal with the .ino file's name, revision, and date. I keep all projects under source-code control which maintains that line without any effort from me, as long as I've included the small snippet of data and  and the Serial.println() call to print it.
Update:

Can you show some code how you include the automatic revision identification into the Arduino Build Chain?

Here's an example. Note that the build-chain isn't modified; everything happens in the source code, RCS, in my case. You'll probably have to tweak the keyword that gets the revision data, ($Id$ in RCS) for whatever source control you use. If you aren't using source control, you could print the compile-time macros suggested by @DataFiddler.
/*
 * Macro to tell ::println() & family to expact a pointer to Flash memory
 * #define this in your library's local.h file, or where ever you'd
 * put your personal, site-unique, or non-public macros like your
 * WiFi password:
 *
 * #define FLSTR_HLP(str) (const __FlashStringHelper *)str
 * (Look up __FlashStringHelper for more information)
 *
 */
// ----------------------------------
// Your .ino file would start here:

#include <local.h>                        // gets the above #define

// Define one of these in each .ino file:
// const char IdString[] PROGMEM = $Id$
// RCS expands or updates it to something like this,
//  every time you check out any version:
//  (Other source control systems will have similar facilities)
const char IdString[] PROGMEM = "$Id: HowTo_IdString.ino,v 1.1 2023-12-26 18:16:06-05 jrobert Exp $";   // def an IdString in Flash

void setup() {
   Serial.begin(115200);
   Serial.print("");
   Serial.println(FLSTR_HLP(IdString));   // prints the IdString from Flash

   // .. more setup ..
}

void loop() {
   Serial.print(F("Run time: "));
   Serial.println(millis());
   delay(5000);
}

Interesting. Can you show some code how you include the automatic revision identification into the Arduino Build Chain?

Serial.println(__DATE__);   Serial.println(__TIME__);  shows compilation date and time. Should be close to source file save time.

If you want just a simple way of identification, use some of the compiler's predefined macros* as automagic source of information:
void setup() {
  while (!Serial);
  Serial.begin(115200);
  Serial.print("(");
  Serial.print(__VERSION__);
  Serial.print(") ");
  Serial.print(__FILE__);
  Serial.print(": ");
  Serial.print(__DATE__);
  Serial.print(", ");
  Serial.println(__TIME__);
}

void loop() {
}

The output of the sketch is:
(7.3.0) /home/XXXXXXXX/name_of_sketch.ino: Dec 27 2023, 23:03:58

*) In my case (Arduino IDE version 1.8.19) the version of G++ is 7.3.0.


text:
LED control with a string variable
I would like to control three LEDs with a string variable using an Arduino Mega.
I have connected the three LEDs to pins 10, 11 and 12 of the Arduino.
If my string equals Red, the red LED should turn on. If my string equals Yellow, the yellow LED should turn on. If my string equals Green, the green LED should turn on.
I wrote the following program, and I expect the following: When I type Red, I expect the Red LED to turn on, and so on for the others. But no LED turns on.
You can check the following video: https://www.youtube.com/watch?v=MAnAc_t0OrM&t=1583s
int redPin=10, yellowPin=11, greenPin=12;

String my_Color;
String msg1="Which LED do you want to turn ON?";
String msg2="Red, Yellow or Green?";
String msg3="You chose LED:";

void setup() {
  pinMode(redPin, OUTPUT);
  pinMode(yellowPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  Serial.println(msg1);
  Serial.println(msg2);
  while(Serial.available()==0) {}
  my_Color=Serial.readString();
  Serial.print(msg3 );
  Serial.println(my_Color);
  Serial.println('Red', BIN);
  Serial.println('my_Color',BIN);
  if(my_Color == "Red") {
    Serial.print("Red True");
    digitalWrite(redPin,HIGH);
    digitalWrite(yellowPin,LOW);
    digitalWrite(greenPin,LOW);
  }
  if(my_Color=="Yellow") {
    digitalWrite(redPin,LOW);
    digitalWrite(yellowPin,HIGH);
    digitalWrite(greenPin,LOW);
  }
  if(my_Color=="Green") {
    digitalWrite(redPin,LOW);
    digitalWrite(yellowPin,LOW);
    digitalWrite(greenPin,HIGH);
  }
}

Could anyone check the sketch and correct me?

This question originated on electronics.stackexchange.com, copying my answer from there: There are three main areas where your system may be failing: the LEDs, the string input, and the logic evaluations. Right now it's a black box - you enter some input, and you don't see an output. But you have no idea where the system is failing between those two points. You should first narrow down to find which one the problem is. This is very good practice for learning how to debug systems in general.
Start with the string input. After you read in the string from Serial, print it back out. Verify that it matches what you entered. (I expect this to be the problem. Like I said in my comment, your string is probably being read in as "Red\r \n ". Print the string twice, and if it prints "Red" twice with a line break in between, than that is your problem. You need to run my_Color.trim() to fix that.)
Then, check the logic evaluations. Add a Serial.print() command with some string in it after each if evaluation. If your program prints out the string after you enter a valid LED color, than you know that your code is executing correctly. If not, there is some difference between the my_color String and the String you are checking it against.
Thereafter, if it is still not working then the problem is with the LEDs. I don't have your circuit so I can't tell you what to debug there.

The program works as it is expected when I used the trim() function. Could you please explain to me why it needs the trim() function in this case ?

@learndesign: In the description of the video you linked to, there is a big warning written in all caps: “GUYS MAKE SURE YOUR SERIAL MONITOR IS SET TO 'NO LINE ENDING'!!!”. Does that ring a bell?

@learndesign there are certain special characters associated with the String data type. Two such characters are "\n" and "\r". When the '' and 'r' or 'n' are next to each other in a string, they actually correspond to a line break (cursor moves down a line) and a carriage return (cursor moves all the way to the left of the current line). For a lot of serial monitors, when you enter a string, it automatically appends "\r\n" onto the end of the string, possibly with whitespace as well. Since "Red \r\n" != "Red", your if statements were never triggering. The trim() function removes that for you.


text:
Function pointers that call one function
I'm reading a library file timer.h for STM core library that I just installed in Arduino hardware folder.
Of course, there has to be a lot of questions for me as a beginner about many approaches/stratgegies that programmers rule in writing the code.
One thing is that calling a function with a function pointer that only call one function, but the difference is that the function pointer is declared/defined as an inline function.

Edit: I deleted the code and posted a link for it in github.
stm32/timer header file
OK, the part that I started to think about starts from line 595.
It's functions declarations.
In line 598, it's a declaration for a function that receiver a pointer to a function.
In later lines, starting from line 634, these functions have only one line to execute. So my question is why to develop a function to only execute one line ?
Why they didn't just put that line directly instead of putting it inside function ?

Could you please post a link to the complete file?

Where exactly is the function pointer here, that is called? bb_perip is not a function pointer, I think, but a function, that returns a pointer to a variable. Though I cannot be sure from this snippet of code alone

...\Program_Files\Arduino\hardware\Arduino_STM32-master\STM32F1\system\libmaple\include\libmaple for example depending on the root file location on my computer.

I posted like most the inline functions. Couldn't post the complete code that is far more that the character limitations over 30000 character.

Again I don't see a function pointer being used here. Please point us, where exactly you are seeing the problem. Also can you please give a link to your used STM32 core, so that we can read this file on the web. I personally don't have a STM32-core installed, also we don't know, which core you used. Best case would be a github link to the file in question.

OK, I added the information in the main post. It's much easier for me, but I don't know which is better to add the required information here or edit the main post ?

@R1S8K - Please edit the question and add new information to it.

bb_perip is a function that returns a pointer to a bit from a register that is related to a specific timer peripheral (there's more than one).  That pointer is then dereferenced with the * operator to make *bb_perip(...).
What bb_perip returns is dependent on what timer you are using and what value you are interested in.
bb_perip is not a pointer to a function, it is a normal function that happens to return a pointer.

Something new to me is that there is an integer passed to this function ! It's my first time to encounter this feature. *bb_perip(&(dev->regs).bas->CR1, TIMER_CR1_CEN_BIT) = 0; there is a 0 passed to this function, how this is done ?

No, the integer is not being passed to the function. The integer is being assigned to the dereferenced pointer returned from the function.

oooh I'm sorry my mistake I wanted to say "assigned" not "passed" :) totally different approaches. Yeah, I meant it's a new feature to me to assign anything to a function.

Or because it's a function pointer, where the pointer is a variable basically, so I can assign a value for it. is that correct ?

You are not assigning anything to the function.  The function returns a pointer to somewhere in memory. You take that pointer, then use it to place a value into memory at that address.  Once the function has returned the pointer it has no further role to play.  You can just as well use (in pseudocode) *func() = 4 as you can pointer = func(); *pointer = 4; - all you're doing is leaving out the middleman.

Oh yeah I understand now they put 0 because the function role is to pause the timer. static inline void timer_pause(timer_dev *dev) {     *bb_perip(&(dev->regs).bas->CR1, TIMER_CR1_CEN_BIT) = 0; }


text:
How to get readings on serial monitor in every 10s?
I am doing my final year project and here I am attaching the code I am using. According to the code, I will get the sensor output in serial monitor. But I want to get reading once n 10ms. Since serial monitor can't work with that resolution, I need to save the reading in an array and then output the array in serial monitor or any other way. Please help me in modifying the code.
The code is as follows:
/*
   The circuit:
  * VCC connection of the sensor attached to +5V
  * GND connection of the sensor attached to ground
  * TRIG connection of the sensor attached to digital pin 2
  * ECHO connection of the sensor attached to digital pin 4
 */

const int trigPin = 2;
const int echoPin = 4;

void setup() {
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop()
{
  long duration, cm;

  pinMode(trigPin, OUTPUT);
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);

  cm = microsecondsToCentimeters(duration);

  Serial.print(cm);
  Serial.print("cm");
  Serial.println();

  delay(100);
}

long microsecondsToCentimeters(long microseconds)
{
  return microseconds / 29 / 2;
}

At 9600 bps there should be no problem sending up to 9 bytes every 10 ms.

There is one fundamental error with your code that I feel I should point out - one that I see time and time again.
The basic structure of your code is:

Forever:

Send a ping
Wait for the pong
Print the result
Delay for 100ms (or whatever time you choose)

And you expect to get a result every (delay) milliseconds.
However, you won't.  What you will actually get is a result every so often, where that time is defined as 100ms + the time to send and receive a ping.
So if it takes 11.6ms (200cm, the limit of most pin sensors) to receive the pong, then you also delay for 100ms, you're going to end up with 111.6ms between each print. It's even worse if the pong never arrives back - then pulseIn() will wait for up to a second before returning. You can, of course, reduce that to say 15ms by adding the timeout parameter as per the manual
When you reduce your printing delay to just 10ms you actually run the risk of delaying for more than double the time you expect to (21.6ms instead of 10ms).
Instead you need to use millis() to check to see if it is time to print something so that it doesn't matter how long the pong took to arrive, as long as that never exceeds the amount of time you want between prints, otherwise it's going to get delayed regardless.

Yeah it shouldn't be an issue, remember delay(time) is a millisecond command, so if you want to get a reading every 10ms, simply put delay(10), and not delay(100). Like the comment above mentions, you should have no problem with a 9600 baud rate serial monitor link showing data every 10ms.
Also, I would highly reccomend checking out the NewPing library (https://bitbucket.org/teckel12/arduino-new-ping/wiki/Home)
which is an update library for the ultrasonic distance sensor which I assume you are using based off your code. With that, you can send up to 30 "pings" per second, so if the above solution doesn't fix it for you, this definitely should.


text:
String input to character array
I am in between of project where i am getting string like "hello world" via Bluetooth to arduino I want to list this string into individual character so that I can call any of the character when required, this is not working i am getting only zeros in serial monitor
please suggest what i am doing wrong
char s;
int k[10];

void setup () {
  Serial.begin(9600);
}
void loop () {
  if (Serial.available() > 0) {
    s = Serial.read();
  }
  k[10] = s;
  for (int x = 0; x < 10; x++) {
    Serial.println(k[x]);
    delay(200);
  }
}

There are a few problems with your code sample:

You check for Serial.available()>0, but then assume/grab only one character:
if (Serial.available() > 0) {
  s = Serial.read();
}

It is possible that the serial receive buffer has more than one byte waiting, but you only capture one.

k[10] = s;

You assign the captured character to the last element of the byte array, regardless of all else. This presents two main problems

A C-style string must be terminated with a null character ('\0'), and you have immediately put real data in the position that should contain the terminating byte.
There is no possible way that bytes 0-9 can ever have any data written to them by this code.

Your code assumes that the entire string exists in k[] every time through loop(). Instead, you should assume that it might take hundreds or thousands of times through loop() just to finish receiving your string. The input string should have some kind of end-of-string marker like a newline ('\n') or carriage-return ('\r') (or both) so that your program can look for that and know when the input is fully received.
Below is a simple program that receives a string. Note that it has a portion labeled for when to process the recieved data. That block of code is only entered once a newline and/or carriage return are received.
#DEFINE MAX_INPUT 90

char inputBuffer[MAX_INPUT+1]; // Handles up to 90 bytes in a c-style string, with a null character termination.

void setup()
{
  Serial.begin(115200); // initialization
  inputBuffer[0] = '\0'; //Initialize string to emtpy.
  Serial.println("Begin:");
}

void loop() {

  if (Serial.available()>0)
  {
    char input = Serial.read();
    static int s_len; // static variables default to 0
    if (s_len>=MAX_INPUT) {
      // Have received already the maximum number of characters
      // Ignore all new input until line termination occurs
    } else if (input != '\n' && input != '\r') {
      inputBuffer[s_len++] = input;
    } else {
      // Have received a LF or CR character

      // INSERT YOUR CODE HERE TO PROCESS THE RECEIVED DATA //
      // YOU COULD COPY TO A NEW VARIABLE WITH strncpy() OR //
      // SET A FLAG TO SAY TO START SOME OTHER TASK         //
      Serial.print("RECEIVED MSG: ");
      Serial.println(inputBuffer);

      memset(inputBuffer, 0, sizeof(inputBuffer));
      s_len = 0;             // Reset input buffer here if you
                             // have already copied the data.
                             // If you don't reset here, then
                             // you can't start receiving more
                             // serial port data. This is your
                             // 'software' serial buffer, contrast
                             // with the hardware serial buffer.
    }
  }
}


text:
HC-05 Bluetooth module got virus
We have a problem. Our HC-05 Bluetooth module got virus. We checked it in serial monitor and found out that the output is wrong. It has a mirrored question marks(⸮)and variables(b⸮, bW⸮, k⸮, U) which is not included in our codes. How can we fix it?

It is unlikely this module got a virus. It sounds more like a data rate mismatch or a noisy connection.
If you get ONLY the strange characters and nothing that you would expect, even in part, then confirm that the serial port speeds are equal on both the Arduino and the HC-05 module.
If you get some expected data, with junk characters mixed in, then check that your wires are secure and that you have connected all grounds from the Arduino and HC-05 module together with the power supply ground.

Your module does NOT have a virus (Who would waste their time writing a virus for a bluetooth module...?!?!). You either have a bad baud rate setting, bad wiring, or you are trying to use a high baud rate coupled with SoftwareSerial.

Sorry because it's our first time to encounter this kind of problem so thank you guys for helping me out. Thank you very much!


text:
MkrWan freezes after short power outage
My MkrWan running on 5v 3A external adapter without battery. When short time(15-20 second) power outage happens Mkrwan still seems running. I think it consumes power on capacitors on adapter but voltage value drops. When electric comes back, it doesnt work anymore. Why it doesnt reset itself ?
How to solve this problem ?

"Mkrwan still seems running" how do you see this? "When electric comes back, it doesnt work anymore" how do you see this?

Because of the led on it seems on and light does not go out.

What is the firmware programmed to do? Please edit to show the code.

a brownout can cause all sorts of unexpected and hard to diagnose issues. Maybe add brownout detection, uses a less buffered PSU, use a bleeder resistor, or a battery backup.

dandavis as you said it looks like brownout problem(I never heard before you). To solve it, ordered Lipo batteries, I will test and will inform if it solves.

I connected Lipo battery to device. On power outages it supply power to board and brown out problem solved. Thanks a lot

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