text:
How to write a program to do 2 different loop | Task?
I wanna write a program for rc-plane navigation
The plane must navigate to 2 waypoints waypoint_1 & waypoint_2
When it reaches to waypoint_1 (with miss-distance =< 5) then navigate to waypoint_2
But i have a problem.
First look at this :
void loop(){

    if (distance-to-waypoint_1 > 5 meters) {
        Navigate to waypoint_1
    if distace-to-waypoint_1 < 5 meters :
        Navigate-to-waypoint_2

If i use a code like this, plane will navigate to waypoint_1 and when it reaches somewhere that has  less than 5 meters distance to waypoint_1, then will navigate to waypoint_2, but if plane fly away and the distance between it's location and waypoint_1 goes greater than 5 meters, plane return to previous navigation and will navigate to waypoint_1 again and ignore navigation to waypoint_2
So, i need a form of programme to first do a loop for navigation to navigate the plane to waypoint_1 and when it reaches the waypoint_1 , do another loop to navigate the plane to waypoint_2
Thanks

When distance between the plane position and waypoint_1 will be equal or less than 5 meters, then will navigate to waypoint_2 but the problem is that when the plane moves away from waypoint_1 to go to waypoint_2, its distance from waypoint_1 will be more than 5 meters, and the first if condition will be established again and it will navigate to waypoint_1 again.

Because of the problem with if condition, if condition will not work for this purpose and it will be established again because of distance

Ok let's say i wanna use the distance as a criterion to know where am i and where I'm not, somehow i measure the distance between my position and Bob's house and if will be greater than 5 meters, i know that I'm not reached Bob's house, so i will use the direction to reach Bob's house. When the distance (only criterion that i use) between my position and Bob's house will be equal or less than 5 meters, i know that i reached Bob's house then, i will use another direction to reach out Mary's house but when i walk away from Bob's house to go to Mary's house, the distance between

My position and Bob's house will be greater than 5 meters (because the only criterion that i use is distance between my position and Houses) so i'll use a new direction to go back to Bob's house again.

Let us continue this discussion in chat.

I think you should use a different logic by using a variable to hold the current target waypoint and separate the code to reach a waypoint and to change it.
Something like this (in pseudocode):
declare variable target_waypoint and set it to waypoint1
loop
    Fly towards target waypoint
    if distance to target waypoint lower than 5
        change target_waypoint to waypoint 2

You can easily extent that for more waypoints by using an array of waypoints and a variable holding the index of the next waypoint:
declare waypoints as array
declare index variable, initialize with zero
set target_waypoint to waypoints[index]
loop
    Fly towards target waypoint
    if distance to target waypoint lower than 5
        increment index
        if index greater than max index
            Either set to zero to loop through all waypoints again
            or do whatever you want to do after the waypoints
        set target_waypoint to waypoints[index]

The code that moves you to the waypoint doesn't care about what waypoint is next. It's only doing this one job. And when you reached a waypoint you simply move the target of that code to a different position.
Much like you yourself would walk between different waypoints. Setting first waypoint as target, walking towards it until you reached it, setting the next waypoint as target and doing the walking again.


text:
Bitwise Operator in Arduino Code Question
What is the below Arduino code doing?
I am not familiar with the '+' with regard to bitwise operations. Just getting familiar with this stuff.
return ((four << 0) & 0xFF) + ((three << 8) & 0xFFFF) + ((two << 16) & 0xFFFFFF) + ((one << 24) & 0xFFFFFFFF);

This isn't really Arduino code. Arduino uses C++, so questions like this can be answered by consulting C++ tutorials. There is no special "Arduino" language.

+ is the addition operator. It is used to add numbers. For example,
2+3 yields 5.
For analyzing your expression, let's call “a”, “b”, “c” and “d” the bits
of one, two, three and four respectively, like this:
one    = aaaaaaaa
two    = bbbbbbbb
three  = cccccccc
four   = dddddddd

These numbers may have more than 8 bits, but in that case the extra bits
will be discarded by the & operations. Now, let's compute the terms of
the sum, and then the whole sum:
(one   << 24) & 0xFFFFFFFF = aaaaaaaa000000000000000000000000
(two   << 16) & 0x00FFFFFF = 00000000bbbbbbbb0000000000000000
(three <<  8) & 0x0000FFFF = 0000000000000000cccccccc00000000
(four  <<  0) & 0x000000FF = 000000000000000000000000dddddddd
─────────────────────────────────────────────────────────────
sum                        = aaaaaaaabbbbbbbbccccccccdddddddd

As you see, only one bit in each column of this addition can be
non-zero, and that column's sum can only be 0 or 1. This means that
there will be no carries, and the columns will add independently of one
another. The sum is then made of the bits of one, two, three and
four concatenated.
The exact same result could be computed by using the bitwise OR operator
(|) instead of +. In fact, I would prefer using |: to my eyes it
makes the programmer's intent clearer.

Amazing explanation. Thank you so much!

You are better off using | for bitwise operations. Whilst + will work under certain circumstances, | is better. For example:
a = 1 + 1 + 1 + 1;  // a will be 4
a = 1 | 1 | 1 | 1;  // a will be 1

For code where you are just trying to set a single bit, using | is much preferable, as if the bit is already set and you use + then you will clear the bit and set the next one along.

That makes sense. Thank you!

source: Stack Exchange

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

sort: votes


text:
ADXL345 to detect sudden and large changes in acceleration
I am working on school project to develop, basically, a shock sensor when the object containing the ADXL345 is thrown to the ground.
I have used the Adafruit ADXL345 sensortest from the library but I am not sure how to code it such that the reading will only appear when there is a sudden and large change in in acceleration in either the x/y/z direction.
Any tips on how to do so?

same way that you would code it so that a reading only appears when you press a button

Build an enclosure for the Arduino and the sensor in such a way that you
can keep connected the USB cable that links the Arduino to the computer.
Then run the sensortest sketch provided as an example with the
library, and look at (or better yet, record) the acceleration data.
Now turn the enclosure around, shake it, hit it, drop it to the
ground... all while monitoring the sensor's output. I recommend that you
plot the acceleration curves: it should make things clearer. What do you
see? Can you tell the difference between the enclosure being dropped to
the floor and other forms of shaking just by looking at the output data?
How do you tell the difference? Is it the magnitude of the acceleration
or is it the rate of change? If you think the rate of change is more
relevant, then modify the sketch in order to also print this rate of
change. In either case, can you find a threshold of magnitude (or rate
of change) of acceleration that could be used to discriminate between a
drop and other forms of movement? If so, write it down.
I am asking all the questions above to show you the path to solving your
problem. The purpose is not only to have you do all the work: I do not
have the answers to those questions, and you will really have to do all
this work yourself.
You should be able to come up with a criterion of the form: the object
has been dropped if such function of the measured acceleration is higher
than such threshold. The function would likely be either the Euclidean
norm of the acceleration or the Euclidean norm of its time derivative (I
cannot tell which is better). Now code the function in your sketch, then
you can write something like:
if (computed_criterion >= drop_threshold) {
    signal_that_the_object_has_been_dropped();
}

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


text:
How to architect streaming data from multiple plant monitors to single Arduino?
Premise:
I'm trying to determine a good way to architect getting data from 4 plant monitors to a single Arduino. For context, that Arduino will have a Wifi connection that will transmit the data from the plant monitors to a web server internally.
Setup
Where I'm struggling to make a decision is how to go about hooking the sensors up.  Here's my plant setup:

Materials
Tools I have at hand:

Many Arudino Micros
Arduino Unos
Arduino Mega
Raspberry Pi 4 B
4x Monk Makes Plant Monitors
Wiring stuff and power supplies, basic electronics prototyping collection.

Solutions?
I would like to place 4 monitors into different plants (doesn't matter which ones at the moment, if it does, I can specify).  What I've considered:

All 4 plant monitors directly wired to the Arduino Mega.  This requires a 1k resistor in line of the data pin, which I'm not sure I have a good solution for that without a breadboard.  Also, I wasn't sure if the length of data line would be a problem.
Each Plant Monitor is hooked up to an Arduino micro and then use the USB of the micro to the RPI.
Like #2 but use I2C to send data to Arduino Mega. I would need to supply power to these minis then.
There are some options without using Arduinos, but since is the Arduino SE, I'm happy to keep it with this.

I'm open to other options as well, as well as possibly needing to purchase/make another part to optimize the solution some.

i would just hook each plant sensor to an ESP01 (programmable in Arduino) so that you only need to run 3.3v+gnd to each sensor, and you can use the Pi for something a little more worthy of it's power. It avoids collisions, signaling, IDing, etc, and makes it trivial to add more sensors or move sensors around without changing code or re-cutting wires. You only need 4 dupont 10cm wires for the ESP+sensor and then give it power with the "BBC" connectors up top. If you hate Wifi. use ESP-NOW to talk to a 4th ESP, connected to the Pi via UART.

for curios about the diamond next to Avogador's name. Avogador works for SE on a position which grands moderator access to all SE sites.

@dandavis I was looking at the ESP8266 board from  Adafruit.  However I noticed that it had a max current on it's serial port of 12mA where the Maximum current
consumption on the plant monitor's data sheet says 15mA.  I would think this could mean I'd have some dead 8266's every now and then?

@Juraj This is correct, and I plan to do 0 moderation because I'm definitely a community member here not a moderator.

there's no real current on the serial port, afaik. the plant monitor probably uses 15ma total, but that doesn't matter as they are both powered by the same 3,3v source. i'm assuming the  large terminals up top have continuity to the pins, but even if not, just make a splitter by splicing dupont cabled together. also not sure what paydafruit charges, but you can get ESP01Ss for under $2/each free shipping on amazon.

@dandavis Thanks for bringing my feet back down to Earth.  Yeah, the serial won't be anything and I'll power it separately from the 3.3v bus.  So that can work.  I don't think there's anything wrong with your solution as an answer if you wanted to write it up.

i'm overbooked the next day or two, but i'll see what i can do later, just glad to help...

The distances between the plants on the shelf are in general too long for TTL level communication and soon you may want to connect more sensors at plants elsewhere in the room or even in other rooms.
In my opinion the solution proposed by dandavis, using esp-01 with WiFi or esp-now is the most simple and universal solution. I see no problems with the implementation. The esp-01 is small and will play nice with the 3.3 V sensor. Maybe it can be even made battery powered and then there are no cables between plants.
If wired solution was required, I would recommend to use RS485 bus. With RS485 modules with AutoDirection control the sensors could be directly connected to the RS485 module without a MCU at every sensor.

couldn't have said it better. +1


text:
600VDC measurement with Arduino (voltage divider)
I need to detect quick (~200ms) voltage drop, so I am thinking of making an oscilloscope with Arduino. Problem is - can I reliably read 600V DC voltage and what resistor values should I choose for voltage divider? Can I apply same rules as for lower voltage (150k and 1k ohm)?

I think this would be better suited for electrical stackexchange

I'm probably going to regret asking, but: what is the actual application of this?

Welcome to SE/Arduino! -- Is the ground (reference) of the 600 VDC safe to touch? Like, you are measuring tram (public transport) power?

I think first of all you need a circuit to bring down the voltage to about 5volt otherwise 600volts will blow up your Arduino.

Here is the code
int vin=A2;
int inputstate;
float inputvalue;

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

void loop()
{
inputstate=analogRead(vin);
inputvalue=(inputstate*5.5)/(11.7)/0.8;
Serial.println(inputvalue);
}

It might works but it is hard for me to get the actual calculation  but you need to change this for your liking make this calculation,,
inputstate(which is your analogread pin maximum readings (1023)) × 5.0(you need to cange this on your calculation) / 11.7( or any number it can divide to give you 600.0)
So your calculation will be
1023 × 5.0 (or whatever number) / 11.0(or whatever number to get 600.0)
Once you have gotten your right calculation
You input  the numbers you calculated with in place of 5.0 and 11.0
You can remove 0.8 i added it base on my calculation to get 600.0.

I have put 1Mohm and 10Kohm resistors, which seem to work.

This should work but, if the 119 kΩ resistor ever fails short, one may end up with deadly voltage reaching the computer (and the user). It would be wise to split the circuit into a possibly-having-unsafe-voltage part, and a safe part, with some galvanic isolation between them. And have the design checked by someone qualified to handle high voltages.

@EdgarBonet nice idea edgar, 600v dc is deadly and might cause damage to not only the computer but also to the user

Try to design in an opto-coupler instead of using solutions which results in the Arduino sharing a ground and otherwise directly connected with a 600 Volts DC system. This will, however, detect only 600V or zero. For intermediate voltages it is not appropriate. There are, however, methods of using a PWM signal to represent a voltage which can cross an opto-coupler.

If the ground (reference) of the 600 VDC is safe to touch, multiple resistors in series are a good and common solution. Only one of them will break or get short, leaving the others as safety measure.

Be aware that resistors have a maximum voltage rating. It is normal to use a chain of smaller resistors to spread the voltage between them. For instance ten 75V 100kΩ resistors in series would give 1MΩ at 750V rating. Assuming you design your PCB layout with the correct clearances etc. At 600V you need to be very careful with your PCB design.


text:
How to control PWM and digital pins at the same time over ethernet in arduino
I am using Controllino Maxi. It has an Arduino Uno inside it. I am trying to control the PWM pin D0 and digital pin R0 via python code. Below is the code I have upload on arduino:
Arduino Code:
#include <Ethernet.h>
#include <EthernetUdp.h>
#include <SPI.h>
#include <Controllino.h>

byte mac[] ={};
IPAddress ip(192, 168, 0, 200);
unsigned int localPort = 5000;
char packetBuffer[UDP_TX_PACKET_MAX_SIZE];
String datReq;
int packetSize;
EthernetUDP Udp;

void setup()
{
  Ethernet.begin( mac, ip);
  Udp.begin(localPort); //Initialize Udp
  pinMode(CONTROLLINO_D0, OUTPUT);
  pinMode(CONTROLLINO_R0, OUTPUT);

}

void loop() {
  packetSize =Udp.parsePacket(); //Reads the packet size
  if(packetSize>0)
  {
    Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE); //Read the data request
    String datReq(packetBuffer);
    if (datReq == "R0")
    {
      digitalWrite(CONTROLLINO_R0, HIGH);
      delay(2000);
      digitalWrite(CONTROLLINO_R0, LOW);
    }
    else
    {
      analogWrite(CONTROLLINO_D0, datReq.toInt());
      delay(2000);
      analogWrite(CONTROLLINO_D0, 0);
    }
  }
 }

In above code, if I receive R0 over ethernet, then I am turning on/off R0 pin, else whatever PWM I am receiving, I am setting it using analogWrite. Below is my python code:
from socket import *
import time

address = ('192.168.0.200', 5000)  # define server IP and port ((0x12, 0x02, 0x00, 0x00, 0xEA, 0x03))
client_socket = socket(AF_INET, SOCK_DGRAM)  # Set up the Socket
client_socket.settimeout(1)

data = "R0".encode("utf-8")
client_socket.sendto(data, address)
time.sleep(5)

data = ("{}".format(200)).encode("utf-8")
client_socket.sendto(data, address)
time.sleep(5)

data = ("{}".format("R0")).encode("utf-8")
client_socket.sendto(data, address)

In above code, I am first sending R0 to turn on/off R0 and then sending 200 for PWM and then again sending R0 to turn on/off R0. When tested I can see R0 getting high and low, then I can see 200 on PWM but then again R0 should be high/low but it stays low. If  I re run the python code, R0 doesnt work and only PWM works. If I power off the board and power it again, then R0 works only for first time and it didnt work in second time.
I am a bit confused at this stage. Is there any bug in my arduino code as I am not very experienced in it. Is there any way to debug it? Please help. THanks

You Arduino sketch is storing the received UDP packet in a char array
named packetBuffer, then converting this array to a String object
like this:
String datReq(packetBuffer);

The problem is that this String constructor expects a NUL-terminated
array, and you have no guarantee that this array is NUL-terminated.
Well, actually you have this guarantee, but only at the beginning: as
the program starts, the array will be filled with zeros by the C
initialization routine. This is why the first request is correctly
processed. The second request sends a packet larger than the first one,
so the array is still NUL-terminated. On the third request, however, the
received bytes are immediately followed by the leftovers of the previous
request. In this case it is the digit '0'.
The simple solution is to ensure that the buffer is always properly
terminated. Start by making it wider by one byte:
char packetBuffer[UDP_TX_PACKET_MAX_SIZE + 1]; // +1 for the '\0'

Then, whenever you receive a packet, add the terminating NUL character:
Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE); //Read the data request
packetBuffer[packetSize] = '\0'; // properly terminate the buffer


text:
What should happen when sending analogWrite signal to a non-PWM pin?
I'm a very new to Arduino and any electrical engineering, I'm learning through some Youtube tutorials.
Based on my understanding though, sending analog signals to a non-PWM pin would just check for a threshold and send either LOW or HIGH, as opposed to being able to send variable voltages to a PWM pin.
BUT ... that's not what I'm seeing in practice...
Using Arduino UNO, I made a little project, for changing a blue LED's brightness. At first I did it through a PWM pin (pin 9) and it worked flawlessly. But then I tried seeing what would happen in a non-PWM pin (pin 8), you know cause you learn by trying and experimenting. So I switched to a non-PWM pin and ... it works the same exact way ...
I can change the brightness of the LED 5 different levels ... using analogWrite ... to a non-PWM pin ...
Thanks in advance

I guess your code switches the pin by calling analogWrite repeatedly. add your test sketch to the question

You might want to check the output signal with an oscilloscope. Perhaps they enhanced their library to use a timer and its interrupt to generate PWM by software.

I would also guess that you are just doing the dimming in code somehow. I just tested this with an Arduino Nano and the latest Arduino AVR core (1.8.6) and it is switching exactly between 2 levels: HIGH and LOW. And the code in wiring_analog.c is reflecting that. Please show us the code with which you got those 5 levels.

You need to show your code. Please edit the question and do that. I can change the brightness of the LED 5 different levels ... using analogWrite ... to a non-PWM pin ... . Show us!

Based on my understanding though, sending analog signals to a non-PWM pin would just check for a threshold and send either LOW or HIGH, as opposed to being able to send variable voltages to a PWM pin.

On the Uno you do not send analog signals anywhere. The PWM pins are merely digital outputs which turn on and off rapidly at a frequency and duty cycle that you specify.
You can, therefore, do the same thing to non-PWM pins by sending HIGH/LOW at a variable rate.
To comment more on why your code appears to be "working" we would need to see it.

What is the point of PWM pins if its also possible to send variable high/low signals to non-PWM pins?

Well, the PWM pins output high/low signals asynchronously. That is, without code having to do it. So, if you set up a timer (which is connected to the PWM pins) to output 100kHz then it will do that, regardless of what the code is doing at the time. You might be calculating prime numbers, but the hardware timers will mindlessly toggle that PWM pin on and off at the specified frequency.
If you try to make your own PWM in code, then the code has to do that and nothing else if it is going to output a consistent signal.

Hi Nick, thanks for the response. Yes I understand that concept of what PWM pins do by rapidly sending digital signals. My question was mostly theoretical stuff that's why I didn't show code. Based on your answer it is possible to also send variable signals (high/low) to a non-PWM pin, which is what had me confused. What is the point of PWM pins if its also possible to send variable high/low signals to non-PWM pins?
(This is the only part that has me confused about that)

@BlueStarXD See updated answer. In a lot of coding there is the easy way and the hard way. Manually doing PWM through code is the hard way.

I've got a page about the hardware timers which might help your understanding.


text:
char * variable - Handle correctly to avoid overflow
I'm trying to understand if a char * variable can be updated down the code (since it only stores a pointer) or over-flow can occur.
For example:
char *A="/file.txt";
char *B;
void print_filename(char *filename="/defname.txt"){
Serial.println(filename);

Is is the right way to use char* variable, so down the road I assing new values :
A="/anyOtherfile.txt";
B="This_is_not_empty";
print_filename("/logfile.txt");

No overflow can occur when using char pointers like you did in your question.
You use a number of different string literals (the strings enclosed by double quotes). These automatically get placed in RAM by the compiler, but they are not meant to be writable. When you do
char *A="/file.txt";

the compiler will place the literal in RAM (not in stack, but in the read-only section, even if the literal is used inside of a function (Thanks to Edgar Bonet for the comment)) and then set the pointer A to the address of that literal. Writing to that address is undefined in the C++ standard and should not be done.
When you then do something like this
A = "some other literal";

then you are not changing the literal. Instead you are just changing the pointer to a different literal placed in RAM. So no overflow can occur, since the compiler just takes all string literals, places them in RAM (immutable) and only handles their memory addresses. So there is no writable buffer in the first place.
With
void print_filename(char *filename="/defname.txt"){
Serial.println(filename);

you are setting the default value of the filename pointer to the address of that specific literal. Setting the parameter to an address of another literal or an existing char array will just change the pointer. If you at another pointer again set filenameto that exact literal, the literal still lies in RAM and the compiler will usage again its address (so multiple uses of the same literal will not result in higher memory use).
If you - at some point - want to write data to that pointer, you first need to set it to a char array, either the address of a static array or creating a new dynamically allocated array with the new keyword:
char my_static_array[10];
A = my_static_array;
// now you can write to the array my_static_array by using A
A = new char[15];
// now you can write to a newly created array by using A

Though for the dynamic allocation you need to keep in mind, that especially AVR based Arduinos (like the Uno/Nano/Mini) don't have much memory and often dynamically declaring and deleting memory can lead to memory fragmentation (essentially the delete operations free memory, but these holes with free memory are often too small for the next allocations, so they don't get used and your memory gets like swiss cheese). That is also the reason why using the Arduino String class in the wrong way is really bad.

So passing another string literal will not cause any overflow, since you are only passing the parameter, if I get it right ?

It cannot cause overflow, because you only pass the pointer to an already existing string in memory. It doesn't get copied to another place

+1, Nice answer! But note that the string literals are not stored on the stack: they are statically allocated in the .data section of the program (or .rodata, for “read-only data”, if available on the platform). This is the case even if, in the source code, they appear within a function body.

@EdgarBonet Ah, thanks. Thought it would be on the stack, now I learned otherwise. I will edit my answer to reflect that


text:
for loop crashes program
Just started out with tinyduino(tinycircuits) and I am trying to develop a hangman game. I have this chunk of code that randomly picks a word from my array. I've omitted some code for readability.
char* words[] = {"Fortran", "Cobol", "Python", "Java", "Javascript", "Kotlin", "Swift", "Golang", "Typescript"};
long word1;
char* generatedWord1;
int k;
int i;
int wordLength;

void setup(void) {
  randomSeed(analogRead(5));
  hangman();

void hangman(){
  word1 = random(sizeof(words)/sizeof(char*));
  k = 1;

  if (k == 1) {
    display.setCursor(10, 50);
    generatedWord1 = words[word1];

    for (i = 0; generatedWord1[i]; i++) {
      generatedWord1[i] = "_";
    }
}

When I upload this to my board, it would not display the underscores based on the randomly chosen word's length. Re-uploading it does not work and usually requires me to reboot the tinyduino after that. Hence, I concluded my code crashes it. But, when I replace the generatedWord1[i] = "_"; in the for loop with display.print("_"); the program carries on and it prints the correct amount of underscores.
However, this does not fit my purpose of replacing the letters with underscores, as display.print("_"); just prints underscores based on the random word's length instead. I need it to be in a manner where I can still compare a user input against the random word and replace the underscore if the letter input matches any letters in the word.
What and how do I modify my code to work as such?
Note: For the context of this whole sketch, I am trying to use get an input from a user through bluetooth and compare whether or not the input matches any of the letters from the random word and then replace the underscore with the input letter. Completing the word means winning the game as per hangman.
EDIT: I've added the whole sketch below for reference just in case I missed out something important for my question.
#include <SPI.h>
#include <STBLE.h>
#include <Wire.h>
#include <SPI.h>
#include <TinyScreen.h>
#include <string.h>

//Debug output adds extra flash and memory requirements!
#ifndef BLE_DEBUG
#define BLE_DEBUG true
#endif

#if defined (ARDUINO_ARCH_AVR)
#define SerialMonitorInterface Serial
#elif defined(ARDUINO_ARCH_SAMD)
#define SerialMonitorInterface SerialUSB
#endif

uint8_t ble_rx_buffer[21];
uint8_t ble_rx_buffer_len = 0;
uint8_t ble_connection_state = false;
#define PIPE_UART_OVER_BTLE_UART_TX_TX 0

TinyScreen display = TinyScreen(TinyScreenDefault);

// declarations
const char* words[] = {"Fortran", "Cobol", "Python", "Java", "Javascript", "Kotlin", "Swift", "Golang", "Typescript"};
long word1;
const char* generatedWord1;
int k;
int i;
int length;

void setup(void) {
  Serial.begin(9600);
  randomSeed(analogRead(5));
  BLEsetup();

  Wire.begin();
  display.begin();
  display.setBrightness(10);
  hangman();
}

void hangman(){
  display.clearScreen();
  display.setFont(thinPixel7_10ptFontInfo);
  display.setCursor(10,20);

  display.print("Ready to hang?");
  delay(2000);

  display.setCursor(5,20);
  display.print("generating word...");
  delay(1000);

  display.clearScreen();

  // word1 is my index, so printing out word1 will give you a random index from the array
  word1 = random(sizeof(words)/sizeof(char*));
  k = 1;

  if (k == 1) {

    display.setCursor(10, 50);
    generatedWord1 = words[word1];

    length = strlen(generatedWord1);
    char user_input[length+1] = "";

    for (i=0; i < length; i++) {
      user_input[i] = "";
      user_input[length] = 0;
    }

    display.setCursor(30, 30);
    display.print("|");

    display.setCursor(30, 20);
    display.print("|");

    display.setCursor(30, 10);
    display.print("|");

    display.setCursor(30, 0);
    display.print("____");

    // remember to move this away from the if statement
    // If user guesses wrong letter (1)
    display.setCursor(50, 10);
    display.print("|");

    // If user guesses wrong letter (2)
    display.setCursor(49, 15);
    display.print("o");

    // If user guesses wrong letter (3)
    display.setCursor(50, 25);
    display.print("|");

    // If user guesses wrong letter (4)
    display.setCursor(43, 21);
    display.print("-");

    // If user guesses wrong letter (5)
    display.setCursor(54, 21);
    display.print("-");

    // IF user guesses wrong letter (6)
    display.setCursor(43, 30);
    display.print("/");

    // If user guesses wrong letter (7)
    display.setCursor(52, 30);
    display.print("\\");
  }

}

void displayScreen(char phone_input[21]) {

  display.clearScreen();

  int width=display.getPrintWidth(phone_input);
  display.setFont(thinPixel7_10ptFontInfo);
  display.setCursor(48-(width/2),32);
  display.fontColor(TS_8b_White,TS_8b_Black);
  display.print(phone_input);
}

void loop() {
  aci_loop();//Process any ACI commands or events from the NRF8001- main BLE handler, must run often. Keep main loop short.
  if (ble_rx_buffer_len) {//Check if data is available
    delay(10);
    displayScreen((char*)ble_rx_buffer);
    ble_rx_buffer_len = 0;//clear afer reading
  }

}

Funny, I just wrote an answer about the problem, that you have here, about 45min ago. And the problem is, that you are trying to modify a string literal. That is undefined behavior in C++.
When you declare your words array with
char* words[] = {"Fortran", "Cobol", "Python", "Java", "Javascript", "Kotlin", "Swift", "Golang", "Typescript"};

you are actually defining an array of pointers. The compiler will place these strings in the RAM and place their memory addresses in the array. Then you are declaring another char pointer and set it to one of the words:
char* generatedWord1;
generatedWord1 = words[word1];

So now generatedWord1 will also point to one of the string literals. And then you are trying to write to this string literal:
generatedWord1[i] = "_";

But - as already mentioned - string literals are not meant to be changed. Trying so is undefined behavior and yes, it can lead crashes.
What to do now? You can define an array of char (not char pointers) as a buffer and fill it with the number of underscores that equals the length of the string literal. When defining the array you can choose the length of the string literal (plus 1 to accommodate the null character) as size, though - depending on your program flow, that you didn't show - it might be better to just declare a buffer with a fixed size bigger than the longest of your words.
You can get the length of the string literal with the strlen() function:
int length = strlen(generatedWord1);

Defining the char buffer:
char user_input[length+1] = "";

Filling it with underscores
for(int i=0;i<length;i++){
    user_input[i] = '_';
}
user_input[length] = 0; // terminating null character

I still can't get the desired output I would like. Also it keeps throwing me an error of invalid conversion from 'const char*' to 'char'.

The following part is wrong:
for (i=0; i < length; i++) {
    user_input[i] = "";
    user_input[length] = 0;
}

First: You misunderstood what is in the loop and what not. I changed my snipped above to use curly braces. Terminating the string with the null character can be done outside of the loop.
Second: You wanted to fill the buffer with underscores. If you look at my code snippet I assigned an underscore here.
The warning that you are getting from the compiler also lies in this line. You have used double quotes. Those mark a string literal. But here we are assigning a single character, so you need to use single quotes, which mark single characters.
The message invalid conversion from const char* to char means, that you used a string literal (which is a pointer to a constant character) and assigned it to a single character variable (one element of the char array).

Hi @chrisl, after trying out the code you've provided, I still can't get the desired output I would like. Also it keeps throwing me an error of invalid conversion from 'const char*' to 'char'.

You can add your new code to the end of your question. Then I will have a look at it.

@IsaacAgatep: 1. chrisl's code works for me. If it doesn't work for you, show us how you integrated it into your program. 2. The “invalid conversion” message is a warning, not an error. You can fix it by using the type const char * (meaning: “pointer to immutable characters”) for all pointers meant to point to string literals. In this program, both words and generatedWord1 need the const qualifier.

Hello @Edgar Bonet, I've tried both of your suggestions but to no avail. I've added my whole sketch at the bottom of the question just in case I missed out anything important that might be causing my mistakes.

@IsaacAgatep I have added a paragraph to my answer to address this.

@chrisl much thanks to your help and explanations. I can't confidently say I understand it but I will now take the time to digest. Will accept your answer!

@IsaacAgatep It might help to do a tutorial on pointers, so that you understand what the * means in this code.


text:
Is there any way to efficiently code reading of four sensors and sending a serial output once it does detect a reading?
I am actually wondering if there's a way to efficiently do this block of code. There are two things in my specifications and these are:

Four IR Sensors that detects blockage. Basically just to trigger it HIGH or LOW
Once one of the sensors got tripped/triggered, it sends a Serial output

In order to do that, I made this code. Basically just stuffing digitalRead and their if conditions in the loop. Is there any way to make the code shorter all the while make it faster for the Serial to get sent?
#define IRSignal1 2
#define IRSignal2 3
#define IRSignal3 4
#define IRSignal4 5

int IRVal1;
int IRVal2;
int IRVal3;
int IRVal4;

void setup() {
  // put your setup code here, to run once:
  pinMode(IRSignal1, INPUT);
  pinMode(IRSignal2, INPUT);
  pinMode(IRSignal3, INPUT);
  pinMode(IRSignal4, INPUT);

  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  IRVal1 = digitalRead(IRSignal1);
  IRVal2 = digitalRead(IRSignal2);
  IRVal3 = digitalRead(IRSignal3);
  IRVal4 = digitalRead(IRSignal4);

  if (IRVal1 == LOW) {
    Serial.print('1');
  }
  if (IRVal2 == LOW) {
    Serial.print('2');
  }
  if (IRVal3 == LOW) {
    Serial.print('3');
  }
  if (IRVal4 == LOW) {
    Serial.print('4');
  }
}

If you have tips, or a go-to resource for efficient coding practices that also helps with memory allocation, shorter code, and speed, I would also love to hear them if that's alright with you.
I use both arduino mega and uno in case this information is useful.

For what are you optimizing? The code as you posted it should be fast enough to track moving things. If they are really fast you might wanna increase the baudrate (since at 9600 baud the duration of the transmission will be in the lower millisecond range). Or do you actually have more code and this is only the part with the IR sensors? This is important, since that other code might change the frequency at which the loop() function is executed and more.

is there any way? almost always has a yes answer ... in your program., you could send the state of the four sensors as bits of one byte ... use the four spare bits to signal a sensor state change

@chrisl Hello! For this system, I really just use 4 IR Sensors. However I am curious about what it does to the sketch if there are going to be more to the code than IR Sensors (Motors or actuators for example). How will it affect the frequency? For example if an IR Sensor (IRSignal1) is tripped then it turns a DC Motor (Motor1) for example as a response. While Motor1 is turning, one of the other IR Sensors (IRSignal2) was triggered. Will it trigger another DC Motor (Motor2) simultaneously or will it have to wait until Motor1 is done?

@fireblazer10 That depends entirely on how you program these actions, not on the sensor code, since that is already rather fast. You would need to write the action code in a non-blocking way, so that it doesn't block everything else. Though that is not specific to your sensor code, but a general programming paradigm

There are always other ways to code something (at least if it's non-trivial). What does 'efficiency' mean to you, in this case? If speed is a concern, increase the baud rate. Whenever at least one sensor is HIGH for longer than one loop iteration, the serial output time will be controlling. Other ways to optimize speed would be to put your loop code in an infinite loop inside either the loop() function or the end of the setup() function, saving the call and and return and function entry code of the loop function. Likewise, you can read the input registers directly and save the four calls to digitalRead().
But either of your Arduinos is more than fast enough (i.e., way faster than the phenomena it would be tracking), that there's little point in optimizing.
Update:

As for my second statement under my code about efficient coding practices, its about memory allocation, speed, and shorter code because what if in the future there's going to be a dozen of IR Sensors there, sill it still maintain speeds?

Even your Uno is still fast enough, with enough memory, to manage a dozen such sensors to the level of processing demonstrated in your supplied code - and then some!
However, I would already be thinking ahead to processing multiple sensors without multiple repetitions of your code, which brings up another kind of efficiency: the best use of your time.
If you kept an array of sensor data and looped over it, processing each sensor in turn, one set of code that works correctly once, will work correctly 'n' times. It will be more easily read by someone else (or your future self who, if you're like me, has forgotten some of the details), and it will be easier to fix or expand if you only have to get it right in one place instead of 'n' places.
Want to change what the terminal output looks like when your project has grown to 12 or 14 sensors? It's easy, when you only have to get it right in one place!
I'd be thinking about an array of sensor data containing, for each sensor, its pin number, present state, and any information that might be relevant in the future - sensor location, for example.
Depending on how you expand your processing, you could conceivably run out of speed or memory, but based on your presented code, that day looks a ways off. And you did mention there is a Mega standing by ...  :-)

as I understand the question OP wants to solve as first to print to Serial only if the state of the sensor changes

No device spec is given. The code as written properly detects and reports the 'triggered' state (apparently a LOW signal). If a state-change report is wanted, that was neither stated nor coded. I've answered the question that was asked - regarding efficiency. If the OP hasn't received the help he wants, editing his question to be more specific will elicit more specific help.

Oh apologies, I just realized that I haven't explained what efficiency means in the context of my post. I will edit it properly but what I actually mean is speed and making the code shorter. As for my second statement under my code about efficient coding practices, its about memory allocation, speed, and shorter code because what if in the future there's going to be a dozen of IR Sensors there, sill it still maintain speeds? But I am not sure if it warrants another thread for that?

As others have noticed, this code will be more than fast enough for
its intended purpose, so you should not feel obliged to optimize it
further. That being said, I do see an inefficiency that you may be
interested in hearing about, hence this answer.
If an IR sensor turns LOW and stays LOW, the program will send the
appropriate message repeatedly, as fast as it can. Since the code runs
way faster than the serial port, this will soon fill up the serial
port's output buffer. When this happens, Serial.print() will not be
able to put its message into that buffer anymore. Facing this situation,
it will switch from its regular non-blocking more of operation to a
different, blocking mode. In this mode, it will block the program
while waiting for the serial port to make some room in the buffer, and
only then will it put its message there and return. The end result is
that the program will be slowed down and match the speed of the serial
port: only 960 executions of the loop() function per second.
An interesting side effect of this situation is that, when the sensor
stops detecting some blockage, the Arduino will nevertheless continue
sending the messages that say that a blockage is detected. It will
continue doing so for about 66 ms: the time needed to empty the
63-byte serial output buffer.
If you are concerned about this issue, an easy way to alleviate it would
be to increase the baud rate. This will not change the qualitative
behavior, but it will make these things happen faster. I suggest you
consider to instead change the communication protocol you have defined
for the Arduino: instead of repeatedly sending information about the
current state of the sensors, it could send information about the state
changes. That is: one message is sent when a detector turns HIGH, and
a different message is sent when it turns LOW. Alternatively, it could
send the full state information (what sensors are LOW or HIGH)
periodically, or every time that state changes, or a combination of
both. I do not know what you are doing with this information on the
other side of the serial link, so I cannot say which option may be the
more appropriate for you.
You wrote in a comment that you may consider in the future driving a
motor instead of sending serial messages. If you go this way, you will
definitely have to work on state changes. In order to run
continuously, a motor does not require you to repeatedly press the “ON”
button a thousand times per second, and it will not turn off all by
itself just because you stopped turning it on. Instead, you turn it on
once and leave it alone, and it will stay on. When you want it to stop,
you have to actively turn it off. The turn on/turn off actions are
required only to change the state of the motor, not to keep the
current state.

The simplest way to do this is with digital interrupt, however the limitation here is that the standard Uno has only 2 interrupt capable pins (2,3) so it would not work with 4 sensors. However other boards like the ESP8266 support interrupts on nearly all pins (just needs ICACHE_RAM_ATTR declaration in the function called)
void setup() {
  Serial.begin(9600);
  pinMode(2, INPUT);
  pinMode(3, INPUT);
  //attach interrupts to trigger function on pin state change
  attachInterrupt(digitalPinToInterrupt(2), pinAtriggered, CHANGE);
  attachInterrupt(digitalPinToInterrupt(3), pinBtriggered, CHANGE);
}

void loop(){
}
//if using ESP8266 it would look like this:
//ICACHE_RAM_ATTR void pinAtriggered() {
void pinAtriggered(){
  Serial.println("triggered");
}
void pinBtriggered(){
  Serial.println("triggered");
}

Though on the Uno one could use the PinChangeInterrupt, which is available for way more pins.

It is generally a bad idea to Serial.println() from an interrupt service routine.


text:
generate x item long list for gyverportal drop-down selection
I am trying to make a drop down selection with gyverportal. The issue is that I don't know how many items there are so the list cannot be hard coded. Here is an example from github:
GP.SELECT("sel", "val 1,val 2,val 3", valSelect);
//where sel is the name of the field and valselect is the currently selected item.

I am very confused with the different types of text (char, char*, const char, const char*, String, char array[10]...just to name a few) and the operations with them seem a nightmare.
I think gyverportal expects a "char*" for the list.
for context:
The items are loaded from EEPROM and the number is stored in Length.
what I need is:
for 0 items: "none"
for 5 items: "1,2,3,4,5,none"
for 10 items: "1,2,3,4,5,6,7,8,9,10,none"
int Length=5; //I have five items to select from
char* dropdownoptions= "";
  if (Length<1){
    dropdownoptions="none";
  }else{
    char Answ[60]="1,";
    for (int i=1; i<=Length; i++){
      char part[3];
      String str=String(i+1);
      str.toCharArray(part, 3);
      strcat(Answ,part);
      strcat(Answ,",");
    }
    strcpy(dropdownoptions,Answ);
    strcat(dropdownoptions,"none");
  }
  Serial.println (dropdownoptions);

This code has been rewritten like 30 times and compiles, but crashes the board (esp8266) aka boot-looping
Ideally this is what I would like to do
dropdownoptions= "";
    for (int i=1; i<=Length; i++){
      dropdownoptions+=i;
      dropdownoptions+=",";
    }
    dropdownoptions+="none";

Use stncpy() and strncat() to guard against overflowing character arrays. Google them. dropdownoptions is two bytes long and you're copying longer strings into it. It needs to be large enough to store the longest string you're copying into it.

@romkey This is a bit misleading. dropdownoptions is two bytes long, since its a pointer and not a character array. It is not meant to hold a string, so it wouldn't be a solution to just make it bigger.

@chrisl I agree :)

As explained by chrisl in his answer, you have to declare
dropdownoptions as an array of char large enough to hold the whole
string, including the terminating '\0'. If you know beforehand the
maximum value of Length, you could size the array accordingly.
Otherwise, you may compute the required size as a function of Length:
int str_length;  // size of the string, including the final '\0'
if (Length < 10)
    str_length = 2 * Length + 5;
else
    str_length = 3 * Length - 4;  // assume Length < 100
char dropdownoptions[str_length];

Then you have to write the contents into this array. One way to do it
would be to write each individual piece into a temporary array, then
copy it to the array dropdownoptions by using string concatenation. My
preferred way of filling the array, however, is the “zero-copy” method
consisting of writing the pieces straight into the right place of the
final array. This requires some pointer manipulation. If you are too
uncomfortable with pointers, you may skip this answer. But if you want
to learn and get some practice, please read on.
Let p be a pointer to the current array position where you want to
write. You can pass this pointer to sprintf() in order to write a
piece of data into the buffer at the right place. sprintf() returns
the number of bytes written, not counting the terminating '\0', and
you can then advance the pointer p by this exact amount in order to
know where to write the next piece. In code:
char *p = dropdownoptions;  // current write position
for (int i = 1; i <= Length; i++) {
    p += sprintf(p, "%d,", i);
}
sprintf(p, "none");

There is one drawback to using sprintf() though: if you get the size
of the array wrong and too short, you will end up writing past its end
and corrupting your memory. If you want to be defensive, you should keep
track of the amount of available space remaining, and use the function
snprintf() instead. This function takes, as a second parameter,
the number of bytes available in the buffer, and it will never overflow
that buffer. I find that the easiest way of keeping track of the
remaining space is to initialize a pointer to the end of the array
(technically, “one past the end” of the array), and compute the
available space as end-p:
char *p = dropdownoptions;  // current write position
const char *end = dropdownoptions + str_length;  // end of the array
for (int i = 1; i <= Length; i++) {
    int count = snprintf(p, end - p, "%d,", i);
    p += min(count, end - p);
}
snprintf(p, end - p, "none");

The reason of min() being used here is that snprintf() may return a
number larger than the available space: if the buffer is too small, this
function returns the number of characters that would had been written
(not counting the terminating '\0') had the buffer been large enough.

Thanks for the detailed introduction to pointers, I have a lot more to learn.
The EEPROM has 20 items that I store so now the code works with char dropdownoptions[60];
I do not expect to ever overflow it (there are many checks in place) so I used sprintf.

The reason why your code crashes is, that you are trying to write to a non-valid pointer.
With the line
char* dropdownoptions= "";

you are declaring a pointer to a character (meaning a 2 bytes big memory address) and let it point to a string literal. All string literals are placed in the read-only section of the RAM by the compiler and cannot be changed. Thus with this line you only have a pointer (memory address), but not a buffer/memory space to write to. Later you are trying
strcpy(dropdownoptions,Answ);

which wants to write to the memory location/address, where dropdownoptions points to. But it is in the read-only section, it cannot be written, so your code crashes. And its better, that it crashes than writing data to some random memory location, where something important might be placed.
Doing
dropdownoptions="none"

is ok, since the literal string "none" is also placed in the read-only section. So in this case only the pointer changes, not the underlying data.

If you want to write to dropdownoptions, you need to declare it as a character array:
char dropdownoptions[70] = "";

Make it big enough, that it can hold the biggest string, that you expect. The rest of your code should then work like it is. Though the conversion from the integer i to a string can be done shorter:
char part[3];
itoa(i+1, part, 10);

Then part contains the number as null-terminated string, thus you can use the strX functions on it.


text:
Constantly Stream data vía Bluetooth to monitoring
I am using a Bluetooth module HC-05 to Stream data from Arduino to My computer. In they computer I am using a python script to receive
They specifications:
Baud rate: 9600
But I am getting an error. The right data got in the computer should be:
b'123.098x726.8393x123x\r\n'
Which I almost always get, but sometimes I get the following:
b'123.098x726.8393x123x123.098x726.8393x123\r\n'. wrong
So I don't know happens, in python I use the method reset_input_buffer() and reset_output_buffer() and in Arduino ide I use Serial.flush()
The error keep happens, would it be the baudrate? I increase it would it be the solutionn?
Thanks in advance
String str;
String strs[8];

int pwm=9;

int tech;
String sync_fromApp = "?";
String sync_ok = "okx";

int cyc_num;
int PWM_0;
int PWM_i;
int PWM_f;

float volt;
float cur;
int t;

void setup() {
  // put your setup code here, to run once:
  TCCR1B = TCCR1B & B11111000 | B00000001;
  Serial.begin(9600);
  Serial.setTimeout(5);
  pinMode(A0, INPUT);
  pinMode(pwm, OUTPUT);
  analogWrite(pwm, 130);
  delay(1000);
}

void loop() {
  // put your main code here, to run repeatedly:
  int strCount = 0;
  if (Serial.available() > 0) {

    str = Serial.readString();
    str.trim();

    if (str == sync_fromApp) {
      Serial.println(sync_ok);
      //Serial.flush();
    }

    while (str.length() > 0) {
      int index = str.indexOf('x');
      if (index == -1) {
        strs[strCount++] = str;
        break;
      }
      else {
        strs[strCount++] = str.substring(0, index);
        str = str.substring(index + 1);
      }
    }

    tech = strs[0].toInt();
    float E0 = strs[1].toInt() / 1000.0;
    float Ei = strs[2].toInt() / 1000.0;
    float Ef = strs[3].toInt() / 1000.0;
    cyc_num = strs[4].toInt();
    int scan_rate = strs[5].toInt();
    int t_chro = strs[6].toInt();
    int t_step_chro = strs[7].toInt();
    float e00 = ((995.0 / 1986.0) * 5.06 + (995.0 / 1004.0) * E0);
    PWM_0 = e00 * (255 / 4.99); //Starting Voltage
    float eii = ((995.0 / 1986.0) * 5.06 + (995.0 / 1004.0) * Ei);
    PWM_i = eii * (255 / 4.99)-1; //Min Voltage
    float eff = ((995.0 / 1986.0) * 5.06 + (995.0 / 1004.0) * Ef);
    PWM_f = eff * (255 / 4.99)+1; //Max Voltage
    long t = (4990000L) / (256L * scan_rate); //delay scan rate
    //default:
    analogWrite(pwm, PWM_0);
    switch (tech) {
      //---Cyclic voltammetry---
      case 1:
        delay(3000);
        for (int n = 1; n <= cyc_num; n++) {
          for (int val = PWM_0; val < PWM_f; val++) {
            analogWrite(pwm, val);

            volt = 0.01974563 * val - 2.558; //0.01974563
            cur = 0.51469 * (analogRead(A0)) - 255.226; //254.226

            Serial.print(volt, 3);
            Serial.print('x');
            Serial.print(cur, 3);
            Serial.print('x');
            Serial.print(val);
            Serial.println('x');
            Serial.flush();
            delay(t);
          }

          for (int val = PWM_f; val > PWM_i; val--) {
            analogWrite(pwm, val);

            volt = 0.01974563 * val - 2.558;
            cur = 0.50669 * (analogRead(A0)) - 255.226;
            //cur_ave = analogRead(A0);
            Serial.print(volt, 3);
            Serial.print('x');
            Serial.print(cur, 3);
            Serial.print('x');
            Serial.print(val);
            Serial.println('x');
            Serial.flush();
            delay(t);
          }
          PWM_0 = PWM_i;
          //Serial.println(n);
        }
        Serial.println("Nx");
        Serial.flush();
        analogWrite(pwm, 130);
        tech = 0;
        break;
      default:
        break;
    }
  }
  else {
    digitalWrite(13, HIGH);
    delay(200);
    digitalWrite(13, LOW);
    delay(200);
  }
}

Above left the arduino sketch.
Below is the python code
            self.ser.write(self.parametersToArduino.encode()) #command to start stream
            pass

        self.ser.reset_input_buffer()   #flush input buffer
        self.ser.reset_output_buffer()   #flush output buffer
        COM.stop_button["state"] = "active"

        while self.threading:
            try:
                data.RowMsg = self.ser.readline()  # read data from arduino
                data.DecodeMsg()                   #decode data from arduino
                if len(data.RowMsg)>0:
                    if b'N' in data.RowMsg:
                        #print("It's over")

                        self.threading = False
                        break
                    data.upXData()  #update a list to plot
                    data.upYData()  #update a list to plot
                    self.ser.reset_input_buffer()
                    self.ser.reset_output_buffer()
                    pass
                pass
            except Exception as e:
                print(e)
                pass

DecodeMsg is the code below
    def DecodeMsg(self):
        temporal = self.RowMsg.decode('utf8')
        if len(temporal)>0:
            if "x" in temporal:
                self.msg = temporal.split("x")
                del self.msg[-1]
                pass
            print(self.msg) #debugg
            pass
        pass

The problem could be on the Python side. Do you have some other means of monitoring that serial stream? The Arduino serial monitor, PuTTY, picocom, or even cat?

Thanks for the answer. Yes, I use serial monitor of Arduino IDE as well but I still got the error. It is like if the next data of the stream was send at the same time that the previous data

Do you still have the same error if you remove the Bluetooth module and run the serial flow through USB? If this is the case, it could be a bug in the Arduino sketch, and we may be able to help finding it if you share the code.

I haven't still tested with USB. I could test, but let me upload My Arduino sketch.

Ready, the Sketch is already uploaded, thanks.

reduce your code to continually sending b'123.098x726.8393x123x\r\n

Sorry I don't understand, what do You mean? You suggest that I delete the other operations? And My code is only with lines of Serial.print()?

I don't really understand what you're doing. In particular what input you're feeding this code. What I notice is that there doesn't seem to be much keeping strCount from overflowing strs

The behavior of input works fine, the problem is the output.

Post the python code.

Of course, let me post it

Update: I have uploaded the python code.

I'm not sure that this an answer, but it is easy to implement and may help you figure out what is going on.
I don't think it is a baud rate problem because the characters appear to be intact, but some are missing. I think it is a serial buffer overflow resulting in a mix of old and new characters.
To test this out, I would insert a counter into the beginning of the "packet" being sent. My suspicion is that when you see the error, you will be able to see that one packet is being messed up when it overflows. So, you might get something like this (where the first 3 digits are the packet number):
b'001123.098x726.8393x123x\r\n'
b'001123.098x726.8393x123x123.098x726.8393x123\r\n
b'003123.098x726.8393x123x\r\n'
It may not be definitive, but might help to more clearly see what is happening.
Before doing this, I would probably comment out:
TCCR1B = TCCR1B & B11111000 | B00000001;
which is increasing the PWM frequency on 9. That, just to see if this changes the behavior since it is so easy to test out.
Hope it helps, but I admit that it is just a suggestion.
BTW: interesting problem and I hope you will tell us what happens.


text:
OLED screen goes blank on delay() - U8G2 library + Arduino Nano
Description
I'm currently trying to get this SSD1306 0.91" OLED screen with an Arduino Nano with the U8G2 library (as per seller's guide), and in any code I run, as soon as a delay() is executed, the screen goes blank and doesn't show any further text or image.
What is the possible cause?
Wiring

Code
To first make sure the OLED module works, I'm using one of the HelloWorld examples from the U8G2 library, from which (with comments removed) I'm executing the next code:
#include <Arduino.h>
#include <U8g2lib.h>

#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif

U8G2_SSD1306_128X32_UNIVISION_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ SCL, /* data=*/ SDA, /* reset=*/ U8X8_PIN_NONE);

void setup(void) {
  u8g2.begin();
}

void loop(void) {
  u8g2.clearBuffer();                   // clear the internal memory
  u8g2.setFont(u8g2_font_ncenB08_tr);   // choose a suitable font
  u8g2.drawStr(0,10,"Hello World!");    // write something to the internal memory
  u8g2.sendBuffer();                    // transfer internal memory to the display
  delay(1000);
}

Expected Result
The OLED Screen should always show "Hello World!" text, as per this youtube video with the same setup.
Actual Result
At startup, it shows the "Hello World" text for a fraction of a second and it disappears.
I've found out that as soon as the delay() is executed, screen goes blank forever and doesn't reload any text. I don't want this approach if possible since:

I plan on using a battery to power the Arduino and the screen, and a permanent screen refresh would decrease autonomy
When doing so, the screen is a little bit flickery.

Troubleshooting executed

I used a different Arduino Nano, and result was the same.
I'm using a 5V 2A power supply for the entire circuit.
I tried different U8G2 example sketches, with the same result (only working if no delay()).
I tried using another OLED module of the same specs, and result is the same.
I've tried to use Adafruit SSD1306 library, and screen doesn't show anything.

What I can tell you is that if I substitute an UNO for your Nano (which should make no difference) and an x64 display for your x32 display (which may make a difference, but I doubt it), your code works verbatim. It does not blank the display. I can modify it to display a counter and it counts as predicted. Include version numbers of everything involved (ide, libraries, core) and links to your actual display and arduino board.

Well. I found my display that's appears to be identical to what you have (assuming what you really have is what you linked) and it continues to work. There is a minor difference in how it displays, but it still essentially works as expected. So, add details.

I do see something a little odd here - the screen is being redrawn every second since you have that code in loop(). But that should still show the text again too, even if it's refreshed. Does this still happen if only the delay is left in loop and the rest is moved to setup()?

Thanks a lot. In the last week I had little time, but I'll do a test later today and come back with further findings and update this comment/post.

Just did some additional testing and here's some more info:

IDE's: tried with Arduino IDE 2.0.1 and VSCode 1.73.0 with Arduino extension v0.4.12

Just tested with an original Uno and same result.
If I put a delay(50), the screen keeps the HelloWorld! word although blinking is more visible.
Moving everything except delay() or delay(50) to setup results in the same behavior (it shows HelloWorld for a fraction of a second and screen goes blank).

I finally found the root cause. I was using a breadboard for this setup, and as soon as I took the components out and used different cables, everything started working as expected. Lesson learnt: do not always rely on the breadboards being 100% functional; when everything else fails, remove the breadboard from the equation.


text:
Is it possible to save and restore the Arduino IDE "Tools" settings somehow?
I'm using quite a few different types of microcontrollers with the Arduino IDE (v 1.8.19). Several AVR-based boards, but also ESP32 and Arduino Due. Particularly the newer boards have a quite long set of options in the tool menu, as seen in this screen shot (for an ESP32-Dev module).

Each time I swap boards, the settings revert back to defaults and I have to remember updating them according to my needs. Is there a way to save the current IDE configuration, so that I can easily load all the settings I need for e.g. "ESP32"? When I haven't used a certain board for some time, I often even fail to remember exactly what settings I needed.

I didn't find a way

@Juraj Thanks for trying. Maybe someone knows a way to backup a settings file or something. Because at least the IDE remembers the last settings.

even the IDE 2 doesn't have it. only the WebEditor and CLI have it https://arduino.github.io/arduino-cli/0.28/sketch-specification/#sketchjson

IDE remembers the settings in global preferences.txt with many other IDE settings

a workaround could be to define own board in boards.local.txt with all the settings predefined

One of the many reasons people switch to VS Code + platformIO plugin for Arduino programming. It configures the setting on each project with platformio.ini file.


text:
Issues Uploading Code to ATTiny84 with Sparkfun AVR Pocket Programmer and ATTinyCore
I am getting back into programming with Arduino and built a POV fidget spinner inspired by an instructable by MakersBox. I am using the SparkFun AVR Pocket Programmer and an ATTiny84 (8MHz internal clock) with ATTinyCore as the board manager.
I was able to upload the code without error a few days ago using the 'USBTinyISP (ATTinyCore) FAST, for parts running >= 2MHz' programmer selection but it stopped working. Now the below error shows:
avrdude: Version 6.3-20201216
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\Franklin Marquette\AppData\Local\Arduino15\packages\ATTinyCore\hardware\avr\1.5.2/avrdude.conf"

         Using Port                    : usb
         Using Programmer              : usbtiny
         Setting bit clk period        : 0.3
avrdude: usbdev_open(): Found USBtinyISP, bus:device: bus-0:\\.\libusb0-0001--0x1781-0x0c9f
         AVR Part                      : ATtiny84
         Chip Erase delay              : 15000 us
         PAGEL                         : P00
         BS2                           : P00
         RESET disposition             : possible i/o
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65     6     4    0 no        512    4      0  4000  4500 0xff 0xff
           flash         65     6    32    0 yes      8192   64    128  4500  4500 0xff 0xff
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00

         Programmer Type : USBtiny
         Description     : USBtiny simple USB programmer, http://www.ladyada.net/make/usbtinyisp/
avrdude: programmer operation not supported

avrdude: Setting SCK period to 1 usec
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

Failed programming: uploading error: exit status 1

NOW if I upload using the "USBtinyISP (ATtinyCore) SLOW, for new or 1 MHz parts" programmer option, the code does upload. It is 8x slower though. I uploaded the Blink sketch to a separate ATTiny84 on a breadboard and the connected LED stayed on for ~7.75s when it was programmed to stay on for 1s.
I have no idea what is going on and would really appreciate any help that I can get. Thank you!
For reference, the code is below.
/*

Not all Attiny cores support the tone() function. Try this one
https://github.com/SpenceKonde/ATTinyCore

// ATMEL ATTINY84 / ARDUINO
//
//                           +-\/-+
//                     VCC  1|    |14  GND
//             (D  0)  PB0  2|    |13  AREF (D 10)
//             (D  1)  PB1  3|    |12  PA1  (D  9)
//                     PB3  4|    |11  PA2  (D  8)
//  PWM  INT0  (D  2)  PB2  5|    |10  PA3  (D  7)
//  PWM        (D  3)  PA7  6|    |9   PA4  (D  6)
//  PWM        (D  4)  PA6  7|    |8   PA5  (D  5)        PWM

*/

#include <EEPROMex.h>
#include <avr/pgmspace.h>
#include "font.h"
#include "textAndShapes.h"

const int charHeight = 8;
const int charWidth = 5;
int rows= 8;                // Total LED's in a row
int LEDS[] = {0, 1, 2, 3, 4, 5, 7, 6};
bool STATES[] = {LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW};

char charArray[6];              // holds characters to display
unsigned long lastTimeUs;                // time (us) magnet sensed
unsigned long revTimeUs;                 // time (us) of last full rotation
unsigned long dwellTimeUs;               // time (us) between LED changes (based on rotation speed)
volatile unsigned long revolutions = 0;  // track number of revolutions since last start
long totalRevolutions;          // track total number of revolutions (stored in EEPROM)
bool spinning = true;          // track reset of time & counts
unsigned long startTimeUs;               // time (us) current spinning started

int mode;                       // current operating mode, stored in EEPROM
int modes = 8;                  // number of modes available
  // 0 -> text "Hello World!"
  // 1 -> RPM
  // 2 -> time in seconds
  // 3 -> spin count
  // 4 -> spin count (total)
  // 5 -> "lilly pad" pattern
  // 6 -> shape 1 (heart)
  // 7 -> shape 2 (smile)

byte ledPin = 0;
byte magPin = 0;                // Hall effect sensor, pulled-up, goes low when magnet passes
byte magPullUp = 10;            // Pin A0 / D10
byte touchPin = 1;              // Push button A1 / D9
byte touchPullUp = 9;

volatile boolean rotationFlag = false;  // modified by ISR

void setup(){
  // setup inputs
  pinMode(touchPin, INPUT);
  digitalWrite(touchPullUp, HIGH);
  pinMode(magPin, INPUT);
  digitalWrite(magPullUp, HIGH);

  // setup other LEDs
  for(int LED=0; LED<(sizeof(LEDS)/sizeof(int)); LED++){
    pinMode(LEDS[LED], OUTPUT);
    digitalWrite(LEDS[LED], STATES[LED]);
  }

  // Interupt setting
  GIMSK  = bit (PCIE0);  // Pin change interrupt enable
  PCMSK0 = bit (PCINT0); // Enable interupt on PCINT0 (D10)
  sei();                 // enables interrupts

  // get saved mode from eeprom
  mode = EEPROM.read(0);
  if (mode >= modes) {
    mode = 0; // may be very large first time
  }

  // get saved revolution total from eeprom
  totalRevolutions = EEPROMReadlong(1);
  if (totalRevolutions < 0 || totalRevolutions > 999999UL){ // will be -1 first time.
    totalRevolutions = 0;
    EEPROMWritelong(1, 0);
  }

  // show we are alive and what mode is active
  blipLEDs();

  lastTimeUs = micros();
}

void loop(){
  int sigFigs = 6;               // number of significant figures to deplay
  unsigned long curTimeUs;
  int seconds;
  unsigned int rpm;

  checkButton();
  if (((micros() - lastTimeUs) > 1000000UL)){ // less than 1 rev / sec
    if (spinning){
      spinning = false;
      totalRevolutions = totalRevolutions + revolutions;
      EEPROMWritelong(1, totalRevolutions);
      revolutions = 0;
      clearArray();
      blipLEDs();
    }
    else {
      //digitalWrite(LEDS[mode], LOW);
    }
  }

  if (mode == 5){  // lilly pad pattern, show regardles of magnet.
    for(int LED=0; LED<(sizeof(LEDS)/sizeof(int)); LED++){
       digitalWrite(LEDS[LED], HIGH);
       delay(1);
       digitalWrite(LEDS[LED], LOW);
    }
    for(int LED=(sizeof(LEDS)/sizeof(int))-1; LED >= 0; LED--){
       digitalWrite(LEDS[LED], HIGH);
       delay(1);
       digitalWrite(LEDS[LED], LOW);
    }
  }

  else if (rotationFlag){ // we are spinning!
    rotationFlag = false;
    if (!spinning){
      spinning = true;
      startTimeUs = micros();
    }
    curTimeUs = micros();
    revTimeUs = curTimeUs - lastTimeUs;
    dwellTimeUs = revTimeUs * 3UL / 360UL;   // 3 degrees
    seconds = (curTimeUs - startTimeUs) / 1000000UL;
    rpm = 60000 * 1000 / revTimeUs;
    lastTimeUs = curTimeUs;
    clearArray();
    if (mode == 0){
      strcpy (charArray, text);
      //sprintf(charArray, "%lu", dwellTimeUs);
    }
    else if (mode == 1){
      sprintf(charArray, "%d", rpm);
      sigFigs = 2;
    }
    else if (mode == 2){
      sprintf(charArray, "%d", seconds);
    }
    else if (mode == 3){
      sprintf(charArray, "%lu", revolutions);
    }
    else if (mode == 4){
      sprintf(charArray, "%lu", totalRevolutions + revolutions);
    }
    else if (mode == 6){ // shape 1 (heart)
      for(int k=0; k< sizeof(shape_1);k++){
        if (rotationFlag){
          break;
        }
        char b = pgm_read_byte_near(&(shape_1[k]));
        for (int j=0; j<charHeight; j++) {
          digitalWrite(LEDS[j], bitRead(b, 7-j));
        }
        dwellTimeUs = revTimeUs * 4UL / 360UL;   // 5 degrees
        delayMicroseconds(dwellTimeUs);
      }
    }
    else if (mode == 7){ // shape 2 (smile)
      for(int k=0; k< sizeof(shape_2);k++){
        if (rotationFlag){
          break;
        }
        char b = pgm_read_byte_near(&(shape_2[k]));
        for (int j=0; j<charHeight; j++) {
          digitalWrite(LEDS[j], bitRead(b, 7-j));
        }
        dwellTimeUs = revTimeUs * 4UL / 360UL;   // 5 degrees
        delayMicroseconds(dwellTimeUs);
      }
    }

    // Text in top half
    if (mode < 5) {
      int digits = 0;
      for(int k=0; k< sizeof(charArray);k++){
        char c = charArray[k];
        if (rotationFlag){
          break;
        }
        if(c){
          if (digits < sigFigs){
            printLetter(c);
            //digits += 1;
          }
          else{
            printLetter('0');
          }
          digits += 1;
        }
      }

      // Handle display in lower section
      clearArray();
      if(1 && (revTimeUs < 200000)){
        char * ptr = (char *) pgm_read_word (&string_table[mode]);
        //char buffer [6]; // must be large enough!
        strcpy_P (charArray, ptr);

        // wait for it . . .
        while((micros() < (lastTimeUs + revTimeUs / 2)) && !rotationFlag){};

        // show it
        for (int k=sizeof(charArray)-1; k>=0; k--){
          if (rotationFlag){
            break;
          }
          printLetterLower(charArray[k]);;
        }
      }
    }
  }
}

ISR(PCINT0_vect){  // Magnet sensed
  if (!digitalRead(magPullUp)){
    rotationFlag = true;             // Increment volatile variables
    revolutions += 1;
  }
}

void dwellDelay(){ // avoid glitch on first rotation having erronious value
  if (dwellTimeUs > 2000){
    dwellTimeUs = 2000;
  }
  if (dwellTimeUs < 100){
    dwellTimeUs = 100;
  }
  delayMicroseconds(dwellTimeUs);
}

void printLetter(char ch){
// https://github.com/reger-men/Arduion-POV-clock/blob/master/clock.ino
  // make sure the character is within the alphabet bounds (defined by the font.h file)
  // if it's not, make it a blank character
  if (ch < 32 || ch > 126){
    ch = 32;
    }
  // subtract the space character (converts the ASCII number to the font index number)
  ch -= 32;
  // step through each byte of the character array
  for (int i=0; i<charWidth; i++) {
    char b = pgm_read_byte_near(&(font[ch][i]));

    for (int j=0; j<charHeight; j++) {
      digitalWrite(LEDS[j], bitRead(b, 7-j));
    }
    dwellDelay();
  }

  //clear the LEDs
  for (int i = 0; i < rows; i++)
    digitalWrite(LEDS[i] , LOW);
  dwellDelay();
}

void printLetterLower(char ch){
  // make sure the character is within the alphabet bounds (defined by the font.h file)
  // if it's not, make it a blank character
  if (ch < 32 || ch > 126){
    ch = 32;
    }
  // subtract the space character (converts the ASCII number to the font index number)
  ch -= 32;
  // step through each byte of the character array
  for (int i=charWidth-1; i>-1; i--) {
    char b = pgm_read_byte_near(&(font[ch][i]));
    for (int j=0; j<charHeight; j++) {
      digitalWrite(LEDS[j+1], bitRead(b,j));
    }
    dwellDelay();
  }
  //clear the LEDs
  for (int i = 0; i < rows; i++)
    digitalWrite(LEDS[i] , LOW);

  // space between letters
  dwellDelay();
}

bool touched(){
  // returns true if touched, false if not.  Light LED until touch released
  bool touchVal = digitalRead(touchPullUp);
  if (!touchVal){
    while(!digitalRead(touchPullUp)){ // wait till touch release
      delay(10);
      digitalWrite(LEDS[mode], LOW);
    }
    //digitalWrite(LEDS[0], LOW);
    return (true);
  }
  else{
    return (false);
  }
}

void checkButton(){
  // check button for mode change and display current mode
  if (touched()){
    mode += 1;
    if (mode >= modes){
      mode = 0;
    }
    EEPROM.write(0, mode);
    blipLEDs();
  }
}

void blipLEDs(){
  // something to show we are alive
  for(int LED=0; LED<(sizeof(LEDS)/sizeof(int)); LED++){
    digitalWrite(LEDS[LED], HIGH);
    delay(10);
    digitalWrite(LEDS[LED], LOW);
  }
  for(int LED=sizeof(LEDS)/sizeof(int); LED>mode; LED--){
    digitalWrite(LEDS[LED], HIGH);
    delay(10);
    digitalWrite(LEDS[LED], LOW);
  }
  digitalWrite(LEDS[mode], HIGH);
}

void EEPROMWritelong(int address, long value)  {
  //This function will write a 4 byte (32bit) long to the eeprom at
  //the specified address to address + 3.
  //https://playground.arduino.cc/Code/EEPROMReadWriteLong

  //Decomposition from a long to 4 bytes by using bitshift.
  //One = Most significant -> Four = Least significant byte
  byte four = (value & 0xFF);
  byte three = ((value >> 8) & 0xFF);
  byte two = ((value >> 16) & 0xFF);
  byte one = ((value >> 24) & 0xFF);

  //Write the 4 bytes into the eeprom memory.
  EEPROM.write(address, four);
  EEPROM.write(address + 1, three);
  EEPROM.write(address + 2, two);
  EEPROM.write(address + 3, one);
}

long EEPROMReadlong(long address){
  //Read the 4 bytes from the eeprom memory.
  long four = EEPROM.read(address);
  long three = EEPROM.read(address + 1);
  long two = EEPROM.read(address + 2);
  long one = EEPROM.read(address + 3);

  //Return the recomposed long by using bitshift.
  return ((four << 0) & 0xFF) + ((three << 8) & 0xFFFF) + ((two << 16) & 0xFFFFFF) + ((one << 24) & 0xFFFFFFFF);
}

void clearArray(){
  for(int i=0; i<sizeof(charArray); i++){      // clear array
    charArray[i] = 0;
  }
}

I'm probably missing something. I'll just point out that the selection of the board/options sets the IDEs expectations for compiling the code and it sets the configuration that it would burn if you did "burn bootloader". If you tell the IDE that you have an 8mhz configuration when you in fact have a 1mhz configuration, your delays will be 8 times longer and your serial rates 1/8th.  I don't know what that has to do with failing to upload though. Max ISP rate is either 1/4 so 1/6 actual clock rate. You can't use a 1mhz isp bitclock with a 1mhz clocked chip. Are you doing that? no idea.

When you first get one of those chips, it's always internally configured to down-clock the internal oscillator by 8. So, it's still running at 8MHz physical, but the actual chip clock speed is 1 MHz.
If you tell the IDE it's the 8 MHz version (divider turned off), it will take ~8x longer to run any sort of delay (which is why you're seeing the 7.75s LED pulse rather than 1s).
To fix this problem, set the IDE to the chip settings you want (8 MHz internal oscillator*), then click "Burn Bootloader." This won't actually set the bootloader, as this chip doesn't use one, but it will set the internal fuses so the clock divider is turned off and it will work at 8 MHz as expected.
Note that the programmer will still need to be set to the low speed (why it says "SLOW, for new [emphasis mine] or 1 MHz parts") when you do the "Burn Bootloader" as the chip will otherwise be running too slowly at 1 MHz to receive the commands at the programmer's default speed (the other cause of the rc=-1 error, aside from bad wiring).
Note that sometimes the programmer will also fail to work if any of the programming pins have LEDs or switches attached - are you removing the chip before programming, or is it still attached to the circuit? If the latter, also try isolating it before programming.
*Make sure you do not select any of the external clock options unless you know what you're doing. Doing this will brick your chip unless you happen to have an external clock source of that type or a high voltage programmer. I'm not sure how those work, but they're a special (expensive) variant that uses a higher-than normal voltage to override the fuse settings even if the chip won't clock.


text:
ESP32-WROOM-32 Wifisecureclient read() result in gibberish data
We are testing our own library with ESP32-wroom-32.
In the .cpp file we have:
void HttpDownstreamClient::tokenCreate(char* URL, char* Subname, char* Suber, int expiretime) {

  Serial.print("The subscription is associated with the Subscripter: ");
  Serial.println(Suber);

  StaticJsonDocument<200> root;

  root["subscriber"] = Suber;
  root["subscription"] = Subname;
  root["expiresInMinutes"] = expiretime;
  String body2send = "";

  serializeJsonPretty(root, body2send);

  if (_networkClient->connect(URL, 443)) {
    Serial.println("Connected to the server to request token!");
    // Make a HTTP request:
    _networkClient->println("POST /notification2/token HTTP/1.1");
    _networkClient->print("Host: ");
    _networkClient->println(URL);
    _networkClient->print("Authorization: Basic ");
    _networkClient->println(_base64);
    _networkClient->println("Content-Type: application/json");
    _networkClient->print("Content-Length: ");
    _networkClient->println(body2send.length());
    _networkClient->println("Accept: application/json");
    _networkClient->println();
    _networkClient->println(body2send);

  }

while (_token.length() == 0) {
    String msg = "";
    while (_networkClient->available()) {
      char c = _networkClient->read();
      msg += c;
    }
    Serial.println(msg);
    int start_init = msg.indexOf("\"token\"");
    int start = msg.indexOf(":",start_init);
    int until_n = msg.indexOf("\"", start + 3);
    Serial.println(until_n);
    if (start != -1 && until_n != -1 ) {
      _token = msg.substring(start + 2, until_n);
      Serial.print("Token is: ");
      Serial.println(_token);
     }
  }

}

_token is an internal string style variable where the token shoud be stored.
In .h we have the following:
class HttpDownstreamClient{

 private:

 String _token;
 char* _base64;
 //char* _msgToken;
 //String _deviceID;

#if defined(ARDUINO_ARCH_ESP32)
  //Base64 encoder for ESP32
  void base64ESP(char* username, char* password);
#else
  //Base64 encoder for none ESP32 board
  void base64(char* username, char* password);
#endif

 public:

 Client* _networkClient;

The .ino file is as following:
#include <HttpDownstream.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>

WiFiClientSecure wifisecure;
HttpDownstreamClient c8yclient(wifisecure); //initiate the HttpDownstreamClient

char* host = "hello.cumulocity.com";
char* username = "hello";
char* password = "hello";
char* device_id = "13225";

//Subscription Test
char* SubscriptionName = "NotificationV2Test11";
char* SubscriberName = "Test2Sub1";
char* APIs = "measurements";
char* typeFilter= "";
char* fragmentsToCopy= "";
int expiretime = 1100;

char ssid[] = "hello";        // your network SSID (name)
char pass[] = "hello";    // your network password (use for WPA, or use as key for WEP)
int status = WL_IDLE_STATUS;

void setup()
{
    Serial.begin(115200);
    delay(10);

 wifisecure.setInsecure();
 while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(ssid, pass);

    // wait 5 seconds for connection:
    delay(5000);
  }

 Serial.println("Connected to WiFi");

  c8yclient.tokenCreate(host, SubscriptionName, SubscriberName, expiretime);
  //delay(6000);
  //c8yclient.connectWSS(host,SubscriberName);
  //delay(5000);

}

void loop()
{
  while (wifisecure.available()) {
    char c = wifisecure.read();
    Serial.print(c);
  }

}

The problem is that I will get a result like following:
21:31:57.993 -> The subscription is associated with the Subscripter: Test2Sub1
21:31:58.033 -> Connected to the server to request token!
21:31:58.073 -> ⸮

I really don't know that how does the gibberish "⸮" come from. The baud rate is 115200 in both begin() method and serial monitor.
What is causing this?

Shouldn't Client* _networkClient; be WiFiClientSecure* _networkClient? How do you initialise the _networkClient as your HttpDownstreamClient doesn't seem to have a constructor to initialise the _networkClient?

@hcheung WiFiClientSecure wifisecure;
HttpDownstreamClient c8yclient(wifisecure);

@hcheung But the WifiClientSecure is the subclass of Client. I have tried with other boards, it is not a problem.


text:
74HC595N breaks when not connected to 5V
I'm trying to build a simple LED controller using this shift register, however when I remove the 5V power source, the device breaks down. The error message was : "This device broke because of: Voltage at pin STCP is 5v, while maximum is Vcc = 0v". There isn't any current in the circuit to break it down. Can anyone explain to me why it behaves that way?
Basically, I connected the output of the register to resistors and LEDS. Here is my wiring diagram:

Here is my code:
const int SER  =8;   //Serial Output to Shift Register
const int LATCH =9;  //Shift Register Latch Pin
const int CLK  =10;  //Shift Register Clock Pin

void setup()
{
 //Set pins as outputs
 pinMode(SER, OUTPUT);
 pinMode(LATCH, OUTPUT);
 pinMode(CLK, OUTPUT);

 digitalWrite(LATCH, LOW);                //Latch Low
 shiftOut(SER, CLK, MSBFIRST, B10101010); //Shift Most Sig. Bit First
 digitalWrite(LATCH, HIGH);               //Latch High - Show pattern
}

void loop()
{
 //Do nothing
}

Where are you getting this error message? Are you using a simulator? Which one? This is probably because the voltage limits on the signal pins depend on Vcc (supply voltage). Having powered signal lines connected to an unpowered chip can backfeed the power through the signal pins, which is bad.

This set up doesn't work in real life so I rebuild it in TinkerCad and get that error message. So next time if I want to rewire something, should I just turn all the power off?

Are you talking about a real life circuit? Yes, you should turn the power off when rewiring. The circuit in your question does not work because it is not complete and unpowered, hence the error message when you try to build it in a simulator. What is the actual problem?

@StarCat I intentionally disconnect the shift register from the 5v power source. This makes the shift register breaks down and I'm trying to understand why.

Yes, you should not disconnect Vcc from a chip as long as you have active signal lines running to it, which have a voltage level different than ground. To be safe: Just remove the power from your whole circuit before removing the power lines - or only remove the power lines once you have removed all other connections.
This depends on the used chip. But most chips with digital data/signal lines have internal protection diodes connected to the pins. If you provide a voltage above the limit, then a current can flow through the protection diode into the Vcc line of the chip. This is done to protect the internal hardware connected to the pin (since the whole chip can endure more than a single pin by its own).
With removing the Vcc connection to the chip you are lowering Vcc to ground level, so way below the level of a HIGH signal line. Thus the current can flow through the pins protection diode to Vcc and feed power to the chip through the signal pin. But the protection diodes are not made for enduring a significant power draw for more than very short spikes. So when doing that you can fry the protection diodes. And you cannot predict, if it will fail short (creating a short between the pin and Vcc, preventing further communication through this pin) or fail open, in which case the chip might still work (if the pins internal hardware is still OK).
For that reason some datasheets will define the voltage limits of the digital input pins dependent on Vcc. In the datasheet of the 75HC595 section 7.3 "Recommended Operating Conditions" you will see the "V_I Input voltage" with the limits to be 0V and Vcc.


text:
Writing to ADMUX on 3.7V from battery restarting chip
Given: arduino nano (atmega328P) with nrf24l01.
What am I trying to do: Measure battery drain.
What am I doing for that.
So I made a small research of how could I measure the battery voltage without using any additional pins (already printed the board and suddenly realized it would be good to also measure the battery drain). And found samples with almost always similar code:
long readVcc() {
  long result;
  // Read 1.1V reference against AVcc
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  delay(2); // Wait for Vref to settle
  ADCSRA |= _BV(ADSC); // Convert
  while (bit_is_set(ADCSRA,ADSC));
  result = ADCL;
  result |= ADCH<<8;
  result = 1126400L / result; // Back-calculate AVcc in mV
  return result;
}

It works okey when I have batteries charged but once it get to 3.7 volts writing to ADMUX seems to be crashing the whole program and restarts chip. Everything else is working fine before this operation though.
Several questions:

Could anyone explain me why does it crash?
How to prevent it?
Would reflashing bootloader and setting oscillator to 8Mhz help with this problem?

add debugging code... the program may not be crashing ... it may be getting into an endless loop ... the while line may be the endless loop

I'm pretty sure it is crashing. Because it restarts and sends data again with nrf24l01. I checked it by sending counter which I increment each loop. And when it is crashing it is always 0. So it is crashing.

could be the power supply browning out when the NRF24L01 activates its radio

Not really sure how can it be possible. With a slightly higher power everything works alright. Also if I connect temp sensor everything works alright. It is failing exactly on writing to ADMUX.

How did you figure out it was failing exactly on writing to ADMUX?

@Fahad pretty easy. I just left this operation and checked the behaviour.


text:
Serial communication between python and Arduino nano BLE sense 33 for running six DC motor
I am controlling six DC motors by varying their voltage. I have figured out the voltage required for each motor in python; now it's time to send this voltage through Arduino Nano BLE Sense 33 to run the six DC motors via serial communication.
Can anyone help me to figure out its solution?
Python Code:

from time import sleep
import serial
import struct
ser = serial.Serial('COM7', 9600)

while True:
     ser.write(struct.pack('BBBBBB',200,210,220,230,240,180))  ## PWM
     ser.readline()
     sleep(.5)

Arduino Code:
const int ledPin[6] = {4, 7, 8, A5, 13, A0};
const int ledPin1[6] = {2, 6, 9, A4, 12, A1};
const int ledPin2[6] = {3, 5, 10, A3, 11, A2};

int x;
void setup() {
  Serial.begin(9600);
  for (int k = 0; k < 6; k++) {
    pinMode(ledPin[k], OUTPUT);
    pinMode(ledPin1[k], OUTPUT);
    pinMode(ledPin2[k], OUTPUT);
  }
  Serial.setTimeout(1);
}
void loop() {
  for (int i = 0; i < 6; i++) {
    while (!Serial.available());
    x = Serial.readString().toInt();
    dir(ledPin[i], x, ledPin1[i], ledPin2[i]);
  }
}

float dir(int Pin, float x, int Lpin1, int Lpin2) {
  analogWrite(Pin, abs(x));
  if (x < 0) {
    digitalWrite(Lpin1, HIGH);
    digitalWrite(Lpin2, LOW);
  }
  else if (x > 0) {
    digitalWrite(Lpin1, LOW);
    digitalWrite(Lpin2, HIGH);
  }
  else {
    digitalWrite(Lpin1, LOW);
    digitalWrite(Lpin2, LOW);
  }
}

what have you tried?  ... what failed? ... serial communication is not related to motor control ... the two functions are completely separate

I want to send voltage data from python to Arduino

By using serial communication, we can transfer data from python to Arduino. Here, in my program, that data is PWM. Once it comes in Arduino, I can run the DC motor.

Now, it will get clear. Please read the question once again.

Here, I have determined the voltage required for the DC motor(actuator). Now, I cannot operate the DC motor through python, so I am transferring data from python to Arduino IDE via serial communication. I know how to handle a single DC motor, but I have to run six DC motors here. In python, I have figured out the voltage for each motor, so it is in the form of an array. So, now I want to transfer this array from python to Arduino IDE, where I can run six DC motors.                 I hope you understand now.

The python code you have is sending six bytes of data in binary form as b'\xc8\xd2\xdc\xe6\xf0\xb4', while you are reading it as a String (that is, a series of ASCII) in your Arduino. You need to read each byte like byte x = Serial.read(); and deal with each data received.

Only one Dc motor is running, and the others are not running. I think it may be because they are not getting PWM values. Can you resolve it?

Thank you @hcheung.  I will try, and let you know.

Sorry @jsotola, I did not read your post carefully. I got now your question. I have already posted my code. It works for only one DC motor, and others are not running.

Here is your Arduino loop() should look like:
void loop()
{
    if(Serial.available() > 0)
    {
        for (int i = 0; i < 6; i++)
        {
            while (!Serial.available());
            int x = Serial.read();
            dir(ledPin[i], x, ledPin1[i], ledPin2[i]);
        }
    }
}

Haven't tested it though.

It works. Thanks

@VishalNaik Please accept it as an Answer. Thanks! :)


text:
How many stepper motors can you run on one Arduino Uno? Ideas on how to run 9?
I am in middle school and new to Arduino. I just learned to set up and code a stepper motor on my Arduino Uno from watching YouTube videos.  I want to set up 9 stepper motors to all run at the same time and at the same rotation speed for a science project I am working on. Right now I have the Arduino Uno with a 830 breadboard, ULN2003 stepper motor driver and 28BYJ-48 stepper motor.  I think I will need to use something different because I can see that my driver doesn't have more than one set of plugs for the wires. I got a budget for my science project so I am allowed to buy some new equipment. But I am confused about what I need to run 9. If anyone can help to suggest the best and simplest way to do this, I would be very happy. I feel like once I have the equipment, I can try to figure out how to put it together and figure out the code. Thanks for the help!

Each step motor need 4 phase driving pins, so you will need 4x9 GPIO pins, and you already tag 'arudino-mega', so I think you know what you want already. If you are looking for driver other than ULN2003, you can research on this page, please note that this is not product recommendation, but to give the idea of the variaties available, before you make any decision on your hardware, check the availability of library for a specific driver IC.

9 stepper motors to all run at the same time and at the same rotation speed ... connect them in parallel ... control them same as one motor

You can use 4 N-Channel MOSFETs, get the logic level avalanche rated ones. Get something in the 5A or higher current range (lower RDSon). Your motors draw 240mA each. The higher the amperage rating the of the MOSFET the cooler the MOSFET will run. I am a firm believer silicon in place of heatsinks. In small it is not that expensive and you do not have the hassle of a heatsink.
You can then drive the MOSFETs from four port pins through a 50 Ohm resistor to each of the gates. Then put a 10K pull down resistor on the port pin, not the gate. Putting the pull down on the gate creates a voltage divider for the gate voltage. This is to guarantee the MOSFETs are all off when the system is first turned on and during initialization until your code takes over. I use the low gate resistors one to control oscillation and two to drive it hard so it switches faster keeping it out of the linear range where it will get hot. Be sure the Source of each output is connected to the ground of the motor power supply and that the arduino ground is also connected to this ground.
You then connect all of the motors in parallel and connect them to the drains of the MOSFET. I am assuming 4 leds (Pink, Yellow, Orange and Blue) from the motor to the MOSFETs drain and a common (Red) for +5 power.
This will give you about 1.4V more per phase when operating not dropping across the driver thereby increasing the efficiency. Also the wiring is much simpler.

Since the OP already has drivers for each motor, why not using each motor with its own driver and just connecting the 4 signal lines together?

A 50 Ω / 10 kΩ voltage divider will divide its input voltage by 1.005.


text:
Removing spaces between characters in MD_Parola
I'm using ESP8266 and Max7219 module (8*32) and MD_Parola library. To create my own font, at first I used of MDParolaFontEditor and created the following fonts.

I edited file MD_MAX72xx_font.cpp using Arduino IDE and saved them as 150 and 151. I want to have the output as the following.

But, the output is as:

As you can see, there is a space between them! I think this space is automatically added between characters. My problem is that, how can I remove this space?
My code:
void loop () {
char MyText[]={151,150,0};
P.displayText(MyText, PA_CENTER, 0, 0, PA_PRINT, PA_NO_EFFECT);
P.displayAnimate();
delay(3000);
}

add this line in the void setup part
P.setCharSpacing(0);

The matrix with the extra space is 9 (not 8) columns wide (possibly because is was designed to be able to display a colon on a clock).


text:
How does C2 work on the ATMega328P?
What is the purpose of C2 on this schematic below?
How does it work when the microcontroller is being programmed?

what happens to DTR when the microcontroller is being programmed?

If SJ1 is connected, and when DTR go from HIGH to LOW, what do you think will happen on the RESET pin?  Also read this.