text:
NRF24 receiving data while turned off
The code to set up the nrf24 is from Electronoobs. The further if-clauses are suposed the drive a motor. The problem I am facing is, that if ther is no data transmission (emitter turend off; or receiver antenna unplugged) the Arduino-Nano-Chip is receiving random values, but there should not be anything at all. I need something which sets the variables left/right to 512 as long as there is no data transmission, when the remote/controller is turned off for example.
//Emitter-Code
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

//const uint64_t my_radio_pipe = 0xE8E8F0F0E1LL; //Remember that this code should be the same for the receiver
const uint64_t my_radio_pipe = 0xE8E80000E1LL; //Remember that this code should be the same for the receiver

RF24 radio(9, 10); //CSN and CE pins

// The sizeof this struct should not exceed 32 bytes
struct Data_to_be_sent {
  byte ch1;
  byte ch2;
};

Data_to_be_sent sent_data;

void setup()
{
  radio.begin();
  radio.setAutoAck(false);
  radio.setDataRate(RF24_250KBPS);
  radio.openWritingPipe(my_radio_pipe);
  sent_data.ch1 = 119;
  sent_data.ch2 = 58;
}

/**************************************************/

void loop()
{
  /*If your channel is reversed, just swap 0 to 255 by 255 to 0 below
  EXAMPLE:
  Normal:    data.ch1 = map( analogRead(A0), 0, 1024, 0, 255);
  Reversed:  data.ch1 = map( analogRead(A0), 0, 1024, 255, 0);  */

  sent_data.ch1 = map(analogRead(A1), 0, 1023, 0, 255);
  radio.write(&sent_data, sizeof(Data_to_be_sent));
  sent_data.ch2 = map(analogRead(A3), 0, 1023, 0, 255);
  radio.write(&sent_data, sizeof(Data_to_be_sent));
}

//Receiver-Code
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

const uint64_t pipeIn = 0xE8E8F0F0E7LL;     //veränderter
//const uint64_t pipeIn = 0xE8E80000E1LL; //echter
RF24 radio(9, 10);  //CSN and CE pins

// The sizeof this struct should not exceed 32 bytes
struct Received_data {
  byte ch1;
  byte ch2;
};

int ch1_value = 0;
int ch2_value = 0;
Received_data received_data;

/**************************************************/
//PIN-Deklaration
short enB = 5;
short enA = 6;
short in1 = 1;
short in2 = 2;
short in3 = 3;
short in4 = 4;

//Variablendeklaration
short linker;
short rechter;
short vLinker;
short vRechter;
short ivLinker;
short ivRechter;
short gem;
short gemRest;
short rest;
short mitte = 512;
short ober = 561;
short unter = 462;
short orest;
short urest;

void lV(){
  digitalWrite(enA,LOW);
  digitalWrite(in1,HIGH);
  digitalWrite(in2,LOW);
  digitalWrite(enA,HIGH);
}

void lR(){
  digitalWrite(enA,LOW);
  digitalWrite(in1,LOW);
  digitalWrite(in2,HIGH);
  digitalWrite(enA,HIGH);
}

void lF(){ //links aus / Leergang
  digitalWrite(enA,LOW);
}

void rV(){ //rechter Motor vorwärts
  digitalWrite(enB,LOW);
  digitalWrite(in3,HIGH);
  digitalWrite(in4,LOW);
  digitalWrite(enB,HIGH);
}

void rR(){ //rechter Motor rückwärts
  digitalWrite(enB,LOW);
  digitalWrite(in3,LOW);
  digitalWrite(in4,HIGH);
  digitalWrite(enB,HIGH);
}

void rF(){ //rechts aus / Leergang
  digitalWrite(enB,LOW);
}

void lrF(){ //beide aus / Leergang
  digitalWrite(enA,LOW);
  digitalWrite(enB,LOW);
}

void setup(){

  Serial.begin(9600);

  //Pinfestlegung
  pinMode(enA,OUTPUT);
  pinMode(enB,OUTPUT);
  pinMode(in1,OUTPUT);
  pinMode(in2,OUTPUT);
  pinMode(in3,OUTPUT);
  pinMode(in4,OUTPUT);

  //We reset the received values
  received_data.ch1 = 119;
  received_data.ch2 = 58;

  //Once again, begin and radio configuration
  radio.begin();
  radio.setAutoAck(false);
  radio.setDataRate(RF24_250KBPS);
  radio.openReadingPipe(1,pipeIn);

  //We start the radio comunication
  radio.startListening();

}

/**************************************************/

unsigned long last_Time = 0;

//We create the function that will read the data each certain time
void receive_the_data()
{
  while ( radio.available() ) {
  radio.read(&received_data, sizeof(Received_data));
  last_Time = millis(); //Here we receive the data
}
}

/**************************************************/

void loop(){

  while(true){ //!!!receiving two analog values, and storing them in left and right
     lrF();
     ch1_value = map(received_data.ch1,0,255,0,1023);
     ch2_value = map(received_data.ch2,0,255,0,1023);
     linker = ch1_value;
     rechter = ch2_value;
     Serial.print("left: ");
     Serial.println(left);
     Serial.print("right: ");
     Serial.println(right);
  } //why is the Serial print showing ramdom values, even if there should not be a transmission

  //beide vorerst aus
  lrF();
  linker = 512;
  rechter = 512;

  //Receive the radio data
  receive_the_data();

  //Übernahme der Analogreferenzwerte für beide Knüppel
  //ch1_value = received_data.ch1;
  ch1_value = map(received_data.ch1,0,255,0,1023);
  ch2_value = map(received_data.ch2,0,255,0,1023);
  //Überschreibung der Werte in Variablen links/rechts
  linker = ch1_value;
  rechter = ch2_value;

  for(int i = 200; i > 0; i--){ //PWM-Signalanlegung

  if((linker <= ober && linker >= unter) && (rechter <= ober && rechter >= unter)){ //Leergang
    lrF();
    delayMicroseconds(463);
  }

  if((rechter == linker) && (linker > ober)){ //geradeaus
    vLinker = linker - ober;
    gem = vLinker;
    rest = 463 - gem;
    lV();
    rV();
    delayMicroseconds(gem);
    lrF();
    delayMicroseconds(rest);

  }

  if((linker > ober) && (rechter > ober) && (linker > rechter)){ //linksvorwärts
    vLinker = linker - ober;
    vRechter = rechter - ober;
    gem = vRechter;
    gemRest = vLinker - vRechter;
    rest = 463 - gem - gemRest;
    rV();
    lV();
    delayMicroseconds(gem);
    lV();
    rF();
    delayMicroseconds(gemRest);
    lrF();
    delayMicroseconds(rest);
  }

  if((rechter > ober) && (linker > ober) && (rechter > linker)){ //rechtsvorwärts
    vLinker = linker - ober;
    vRechter = rechter - ober;
    gem = vLinker;
    gemRest = vRechter - vLinker;
    rest = 463 - gem - gemRest;
    rV();
    lV();
    delayMicroseconds(gem);
    rV();
    lF();
    delayMicroseconds(gemRest);
    lrF();
    delayMicroseconds(rest);
  }

  if((rechter == linker) && (linker < unter)){ //rückwärts
    vLinker = linker;
    ivLinker = 463 - linker;
    gem = ivLinker;
    rest = 463 - gem;
    lR();
    rR();
    delayMicroseconds(gem);
    lrF();
    delayMicroseconds(rest);
  }

  if((linker < unter) && (rechter < unter) && (rechter > linker)){ //linksrückwärts
    vLinker = linker;
    vRechter = rechter;
    ivRechter = 463 - rechter;
    ivLinker = 463 - linker;
    gem = ivRechter;
    gemRest = ivLinker - ivRechter;
    rest = 463 - gem - gemRest;
    lR();
    rR();
    delayMicroseconds(gem);
    lR();
    rF();
    delayMicroseconds(gemRest);
    lrF();
    delayMicroseconds(rest);
  }

  if((linker < unter) && (rechter < unter) && (rechter < linker)){ //rechtsrückwärts
    vLinker = linker;
    vRechter = rechter;
    ivRechter = 463 - rechter;
    ivLinker = 463 - linker;
    gem = ivLinker;
    gemRest = ivRechter - ivLinker;
    rest = 463 - gem - gemRest;
    lR();
    rR();
    delayMicroseconds(gem);
    rR();
    lF();
    delayMicroseconds(gemRest);
    lrF();
    delayMicroseconds(rest);
  }

  if((linker < unter) && (rechter > ober) && (463 - linker >= rechter - ober)){ //linker rück rück, rechter vor
    ivLinker = 463 - linker;
    vRechter = rechter - ober;
    gem = vRechter;
    gemRest = ivLinker - vRechter;
    rest = 463 - gem - gemRest;
    lR();
    rV();
    delayMicroseconds(gem);
    lR();
    rF();
    delayMicroseconds(gemRest);
    lrF();
    delayMicroseconds(rest);
  }

  if((linker < unter) && (rechter > ober) && (463 - linker < rechter - ober)){ //linker rück, rechter vor vor
    ivLinker = 463 - linker;
    vRechter = rechter - ober;
    gem = ivLinker;
    gemRest = vRechter - ivLinker;
    rest = 463 - gem - gemRest;
    rV();
    lR();
    delayMicroseconds(gem);
    rV();
    lF();
    delayMicroseconds(gemRest);
    lrF();
    delayMicroseconds(rest);
  }

  if((linker > ober) && (rechter < unter) && (463 - rechter <= linker - ober)){ //linker vor vor, rechter rück
    ivRechter = 463 - rechter;
    vLinker = linker - ober;
    gem = ivRechter;
    gemRest = vLinker - ivRechter;
    rest = 463 - gem - gemRest;
    lV();
    rR();
    delayMicroseconds(gem);
    lV();
    rF();
    delayMicroseconds(gemRest);
    lrF();
    delayMicroseconds(rest);
  }

  if((linker > ober) && (rechter < unter) && (463 - rechter > linker - ober)){ //linker vor, rechter rück rück
    ivRechter = 463 - rechter;
    vLinker = linker - ober;
    gem = vLinker;
    gemRest = ivRechter - vLinker;
    rest = 463 - gem - gemRest;
    rR();
    lV();
    delayMicroseconds(gem);
    rR();
    lF();
    delayMicroseconds(gemRest);
    lrF();
    delayMicroseconds(rest);
  }

  if((linker > ober) && (rechter > unter) && (rechter < ober)){ //linker allein vor
    vLinker = linker - ober;
    gem = vLinker;
    rest = 463 - vLinker;
    lV();
    rF();
    delayMicroseconds(gem);
    lrF();
    delayMicroseconds(rest);
  }

  if((rechter > ober) && (linker > unter) && (linker < ober)){ //rechter alleine vor
    vRechter = rechter - ober;
    gem = vRechter;
    rest = 463 - vRechter;
    rV();
    lF();
    delayMicroseconds(gem);
    lrF();
    delayMicroseconds(rest);
  }

  if((linker < unter) && (rechter > unter) && (rechter < ober)){ //linker alleine rück
    ivLinker = 463 - linker;
    gem = ivLinker;
    rest = 463 - ivLinker;
    lR();
    rF();
    delayMicroseconds(gem);
    lrF();
    delayMicroseconds(rest);
  }

  if((rechter < unter) && (linker > unter) && (linker < ober)){ //rechter alleine rück
    ivRechter = 463 - rechter;
    gem = ivRechter;
    rest = 463 - ivRechter;
    rR();
    lF();
    delayMicroseconds(gem);
    lrF();
    delayMicroseconds(rest);
  }
  }

}

Transmit a checksum with your data. If the checksum doesn't check out then it's garbage and you throw it away, setting your "no signal" values in the process.

Add a 10K ohm resistor between each pin and the GND pin to avoid them floating.


text:
Low Power Pin Change Detection (ATtiny)
I want to use an ATtiny as data logger for the opening and closing of a door/window. For that I am using a reed-switch. Since I want to run it from a 3V coin battery, long term power consumption is crucial. Therefore the ATtiny (currently 13A) is in system down mode most time and is only listening to Pin-Change-Interrupts. Depending on the state of the reed-switch the power consumption differs in an order of magnitude.

switch open:    0.1µA
switch closed: 74.5µA
my Multimeter has a tolerance of ±0.1µA

This is a difference of an order of magnitude. But it is plausible as the datasheet of the ATtiny13A states in chapter 10 that a GPIO pin can only be pulled up and is otherwise dangling. The pull-up resistor is somewhere between 20k and 50k as stated in chapter 18.2.
So in my setup the pin is pulled up and the reed-switch is grounded.
How can I reduce the power consumption in the case where the switch is closed?
Alternatively: Can I somehow revert the state of the switch, as windows and doors are closed most of the time?
The MCU is running with the 128kHz internal Clock with CKDIV8 so practically running @ 16kHz.
The minimum viable code:
/*
  3V0               SW0
   |     |     |     |
 -----------------------
 |                     |
 |                     |
 |      ATtiny13A      |
 |                     |
 |                     |
 -----------------------
   |     |     |     |
               TX   GND
 */

#include <avr/interrupt.h>
#include <avr/sleep.h>
#include <iso646.h>
#include <stdbool.h>
#include <util/delay.h>

#define BIT_SET( PORT, BIT_FIELD ) PORT |=  BIT_FIELD
#define BIT_CLR( PORT, BIT_FIELD ) PORT &= ~BIT_FIELD

#define TX_PIN          PB4
#define SW0_PIN         PB0
#define INT0_MASK       PCINT0

// MARK: - POWER

static void power_down(void) {
    BIT_SET(GIFR, _BV(PCIF));       // Clear interrupt signal
    BIT_SET(GIMSK, _BV(PCIE));      // Pin Change Interrupt Enabled
    sleep_enable();
    sleep_cpu();                    // Enter sleep mode
    sleep_disable();
    BIT_CLR(GIMSK, _BV(PCIE));      // Pin Change Interrupt Disabled
}

ISR(PCINT0_vect) {}

// MARK: - Setup

static void setup(void) {
    cli();

    // Set up output pins
    DDRB = _BV(TX_PIN);
    BIT_CLR(PORTB, _BV(TX_PIN));

    BIT_SET(PORTB, _BV(SW0_PIN));        // pull up interrupt pins
    BIT_SET(PCMSK, _BV(INT0_MASK));   // set PCINT0 to trigger interrupt
    BIT_SET(GIFR, _BV(PCIF));       // Clear interrupt signal
    BIT_SET(GIMSK, _BV(PCIE));      // Pin Change Interrupt Enabled
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);

    sei();
}

static void loop() {
    BIT_SET(PORTB, _BV(TX_PIN));
    _delay_ms(1);
    BIT_CLR(PORTB, _BV(TX_PIN));

    power_down();
}

int main(void) {
    setup();

    while (true) {
        loop();
    }
}

To be honest, your figures sound far too high. See ATtiny85: Power consumption vs clock speed You should be able to get down to 200 nA - please post your code and schematic.

Once the switch is closed, set the pin to INPUT. Once in a while, revert to INPUT_PULLUP and, if still closed, go back to INPUT to save battery. You can use the watchdog as a low-power timer for this periodic polling.

75µA at 3V means the pull-up resistor is 40k. Which is pretty much what's specified in the datasheet. You could switch to a NC reed-switch. So you pin will only be pulled LOW when the door is open, not closed. Depending on how long the door can be open, this could still be a less than ideal solution.

You could also try a higher value external pull-up resistor, optionally with a small capacitor.

@NickGammon: you are right. I had the WDT running which draws 5µA.

@EdgarBonet: I tried it and noticed that the power consumption spikes up randomly. Having a floating input does not look like a robust solution to me. But the idea to use just the WDT and not the Pin-Change-interrupt sounds more like a feasible idea. Wake up from WDT, set the input to high, look at the input, set input to low, go to bed...

I intend to use the WDT anyway to log the state every 256 * 8s (about 30 minutes)

However the WDT uses a lot more power than an external interrupt. I would only use the watchdog if I had to do something periodically, whereas logging when a window opens only has to be done when it opens.

To avoid the floating input, you can set the pin to OUTPUT LOW. But beware that you cannot switch between INPUT PULLUP and OUTPUT LOW atomically: you will have to go through either INPUT HiZ (safe) or OUTPUT HIGH (very bad).

I'm tempted to suggest two reed switches (one NO and the other NC). Then depending on the window state you change to use the switch which gives you the lowest drain (you could use a spare couple of pins to activate one or the other).
Failing that, you can just sleep when the switch is open (the low-power condition) and if it is closed use the watchdog timer to check it from time to time (in other words, drop the power to the switch while asleep). The WDT only uses around 5 µA so that isn't too bad (the coin battery probably self-discharges at about that rate anyway). That would be a lot better than a constant drain of around 70 µA.
I've got an ATtiny85 sitting in my hallway flashing an LED every couple of seconds. I can't recall when I replaced the battery, possibly once since I made it two years ago.

This is a brilliant idea. I didn't even know there are different types of reed switches. And there are also 3 pin ones wich are NC and NO at once. I'll try that out.

The additional 80uA drain is almost certainly coming from the pull-up resistor being shunted to ground though the reed switch.
https://www.wolframalpha.com/input/?i=(3+volts)+%2F(50k+ohm)+in+uA
As suggested by @Edgar Bonet, one way to greatly reduce this drain is to disable the pull-up immediately when you wake from the pin going low. At this point it is possible for the pin to stay low even if the switch is no longer grounding the pin, so you need to periodically check it using a watchdog.

Wake from pin going low pin change interrupt
Disable pull-up (stops current flowing though resistor)
Do your logging operation.
Enable a watchdog wake up
Go back to sleep.

At this point you can wake either from (1) a watchdog or (2) pin change if the pin goes high again.
If you wake from a pin change...

re-enable the pull-up
disable the watchdog
go back to sleep

If you wake from the watchdog...

re-enable the pull-up.
if the pin is high now, disable the watchdog and go back to sleep.
if the pin is low, disable the pull-up and leave the watchdog running and go back to sleep.

The watchdog timer on this part should only use single digits of uA while running, and it should only need to be running while the switch is grounding the pin. You can set the watchdog timeout to be quite long- on the order of seconds even, to reduce the frequency you  wake to check with the pull-up (and therefore the net power used, at the cost of latency for detecting pin changes). The main downside to this strategy is that you can miss activations that happen inbetween your watchdog wake-ups, so for example if the pin goes low and then you set the watchdog for 8 seconds, and then the pin changes high and then low again during the next 8 seconds, it is possible (but not assured) that you could miss the second event, so set the watchdog timeout to be short enough that you will not miss consecutive events that you care about (you might not care if the door is opened twice in the same minute anyway).
Also, as noted by the famous @nick gammon, you might be able to get lower than 5uA when sleeping without the watchdog. Check to make sure you are disabling everything in the power register and that all unused pins are in input mode (these will be disabled when sleeping as long as there is not a pin change interrupt on them).  There are lots of googleable articles on minimizing ATTINY power during sleep.
You also mentioned that your dominant case is that the switch is closed rather than opened. Since this is the higher-power case with the current switch consider using a normally open switch rather than normally closed one if possible.
Finally, if you just want simplicity and you only care about events of a minimum duration (saym then door much be open for at least 1/2 second to be noticed), then you can skip the pin change interrupt completely and only use an always-running watchdog to wake periodically and very quickly enable the pull-up and check for the desired pin state, and then disable the pull-up and go back to sleep. You should be able to do this in less than a dozen cycles so the net power usage should be almost as low as the watchdog timer drain by itself.

or connect the switch to the high side and use an external pull-down resistor how would this help? If the switch is closed most of the time, there will be a current coming from vcc, though the switch, through the pull-down to ground. It's the same as the other solution, except that you swapped the resistor and switch. Or am I missing something.

@Gerben True, true. Mixed up reasoning fixed now. Thanks!

source: Stack Exchange

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

sort: votes


text:
Does the Sparkfun ESP32 Thing is compatible with generic modules like DHT11 sensor?
First of all I am kind of a noob working with microcontrollers, by the way I am using Arduino IDE 1.8.13
I fallowed the hookup guide to set up Arduino IDE to work with Sparkfun ESP 32 Thing board, and actually I was able to run the Arduino examples "Blink" and "Wifi" with no problem.
But my problem is when I tried to use the DHT11 sensor, I did fallowed several tutorials like this one but for my bad fortune I did not succeed, instead I was getting NaN reading from the temperature and humidity sensor, at first I thought it might had something to do with the libraries version, which I installed and uninstalled several times, including the IDE, then using those same libraries I was able to do the exact same example on an Arduino Uno microcontroller.
Then I realized I did not find any example, tutorial or document using the Sparkfun ESP32 Thing with the DHT11 sensor, since most of the examples that I found are for the generic ESP32.
Which makes me wonder, how can I know if those two components are compatible at all?
Does any one has faced something similar using ESP32 Thing with DHT11 or any another sensor?, if yes, how did you make it work or what did you do instead?
However any piece of advise is welcome.
Thanks in advance!

An ESP32 is an ESP32 regardless of what shape board it's soldered on to.

Could it be what is not compatible is the library,? DHT sensor library by Adafruit

Unlikely. The DHT11 is pretty simple and doesn't require anything special.

Well it requires the library that I just mentioned and the dependecy to Adafruit Unified Sensorl, however do you happen to know any site or document showing those two components working together,  I wonder if sparkfun board is not very common?

There are many DHT11 libraries. Only one needs that Adafruit thing. Try using one of the simpler libraries.

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


text:
GPS Ublox neo-6mv2
I'm trying to get gps data from ublox neo-6mv2 module via arduino. Should ublox's neo-6mv2 light blink after power up by 5v from arduino ? Or is there any other sign that tells the module isnt dead ?
Module is connected to 5v, gnd for few hours - still no blink / light.

With respect to your question, your Arduino seems to be serving the purpose of a 5V power source.  It should be more integral to the question.

Is there any serial (NMEA) output from the GPS? Have you put it outside with a good part of the visible? Is this an original Ublox or a (cheap) clone?

The Ublox is just the part with the Ublox sticker.  Unless you call out the PCB it is soldered to, we don't have much to go on with respect to LEDs lighting up.

I have uploaded the picture of my module and code. Yes my arduino mega 2560 is only power supply now. I havent try to get serial output yet - I'm waiting for any sign that the module isnt dead :( It's connected as I said - 5v,gnd, 8 and 9 pin

You should be able to output the raw NMEA data coming out of the GPS and see if it is “alive”, see here, for example. The cheap/generic GPS modules I know only start blinking an LED after they’ve acquired an initial position, which can take a very long time.

[added photo]
I have found a post that on arduino mega is better to use Serial(1/2/3) than SoftwareSerial so I tried it. Now it shows some data so I assume it's alive even without any light blinking on the module. Thanks everyone :)
All the data are the same - it's waiting for the signal right ? :D

Be sure the active antenna is attached and may have to move it around to differnent areas of you work bench. some of these modules are very deaf or prone to inteference from reflections in the room.

Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

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


text:
Issues with Polytone Library?
I'm building a device that uses two ultrasonic sensors to detect objects and provide audio feedback in the form of beeps that get faster the closer an object is. I have two speakers, one for each sensor, but the tone command will only do one set of beeps at a time. I tried to get around this with the Polytone Library and polytone command, but when I go to compile, I get an "exit status 1. Error compiling for board Arduino Uno" message. What am I doing wrong? Is there another way to get both sensors beeping  at the same time? Please help!
I'm very new at coding. I tried to put the polytone code in a couple different ways, which I can show if that helps. There's also gyroscope code in there, but I have that working pretty well, so I guess just ignore that.
    #include <digitalWriteFast.h>
#include <Polytone.h>

#include <Wire.h> //library allows communication with I2C / TWI devices
#include <math.h> //library includes mathematical functions

const int MPU=0x68; //I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ; //16-bit integers
int AcXcal,AcYcal,AcZcal,GyXcal,GyYcal,GyZcal,tcal; //calibration variables
double t,tx,tf,pitch,roll;

const int anPin1 = 0;
const int anPin2 = 1;
int triggerPin1 = 13;

long distance1, distance2;

//Code Part 2: Level LEDS
// Level LEDs
int levelLED_level = 11;
int levelLED_rollpos = 9;
int levelLED_rollneg = 8;
int levelLED_pitchpos = 12;
int levelLED_pitchneg = 10;
int LED_temp = 7;
Polytone poly;
void setup(){
    Serial.begin(9600);  // sets the serial port to 9600
    pinMode(triggerPin1, OUTPUT);

    Wire.begin(); //initiate wire library and I2C
    Wire.beginTransmission(MPU); //begin transmission to I2C slave device
    Wire.write(0x6B); // PWR_MGMT_1 register
    Wire.write(0); // set to zero (wakes up the MPU-6050)
    Wire.endTransmission(true); //ends transmission to I2C slave device
    Serial.begin(9600); //serial communication at 9600 bauds

    pinMode(levelLED_rollneg, OUTPUT);
    pinMode(levelLED_rollpos, OUTPUT);
    pinMode(levelLED_pitchpos, OUTPUT);
    pinMode(levelLED_pitchneg, OUTPUT);
    pinMode(levelLED_level, OUTPUT);
}

void start_sensor(){
  digitalWrite(triggerPin1,HIGH);
  delay(1);
  digitalWrite(triggerPin1,LOW);
}

void read_sensors(){
  /*
  Scale factor is (Vcc/512) per inch. A 5V supply yields ~9.8mV/in
  Arduino analog pin goes from 0 to 1024, so the value has to be divided by 2 to get the actual inches
  */
  distance1 = analogRead(anPin1)*1.35;
  distance2 = analogRead(anPin2)*2.092;
}

void print_all(){
  Serial.print("MB1000");
  Serial.print(" ");
  Serial.print(distance1);
  Serial.print("mm");
  Serial.print(" ");
  Serial.print(" ");
  Serial.print("MB1260");
  Serial.print(" ");
  Serial.print(distance2);
  Serial.print("mm");
  Serial.println();
}

//Front sensor ranges
void midiSlowFront() {
  poly.begin(); // Set up polling timer interrupt
  poly.setPins(4,5); // Connect pins 4-5 to positive terminal of speaker/piezo

  poly.tone(262);
  delay(2000.0);
  poly.end();
}
void midiFront() {
   poly.begin(); // Set up polling timer interrupt
   poly.setPins(4,5); // Connect pins 4-5 to positive terminal of speaker/piezo
   poly.tone(262);
   delay(500.0);
   poly.end();
}
void midiFastFront() {
   poly.begin(); // Set up polling timer interrupt
   poly.setPins(4,5); // Connect pins 4-5 to positive terminal of speaker/piezo
   poly.tone(262);
   delay(150.0);
   poly.end();
}

//Side sensor ranges
void midiSlowSide() {
   poly.begin(); // Set up polling timer interrupt
   poly.setPins(4,5); // Connect pins 4-5 to positive terminal of speaker/piezo
   poly.tone(440);
   delay(2000.0);
   poly.end();
}
void midiSide() {
   poly.begin(); // Set up polling timer interrupt
   poly.setPins(4,5); // Connect pins 4-5 to positive terminal of speaker/piezo
   poly.tone(440);
   delay(500.0);
   poly.end();
}
void midiFastSide() {
   poly.begin(); // Set up polling timer interrupt
   poly.setPins(4,5); // Connect pins 4-5 to positive terminal of speaker/piezo
   poly.tone(440);
   delay(150.0);
   poly.end();
}

void loop(){
    Wire.beginTransmission(MPU); //begin transmission to I2C slave device
    Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H)
    Wire.endTransmission(false); //restarts transmission to I2C slave device
    Wire.requestFrom(MPU,14,true); //request 14 registers in total

    start_sensor();
    read_sensors();
    print_all();

    //Acceleration data correction
    AcXcal = -950;
    AcYcal = -300;
    AcZcal = 0;

    //Temperature correction
    tcal = -1600;

    //Gyro correction
    GyXcal = 480;
    GyYcal = 170;
    GyZcal = 210;

    //read accelerometer data
    AcX=Wire.read()<<8|Wire.read(); // 0x3B (ACCEL_XOUT_H) 0x3C (ACCEL_XOUT_L)
    AcY=Wire.read()<<8|Wire.read(); // 0x3D (ACCEL_YOUT_H) 0x3E (ACCEL_YOUT_L)
    AcZ=Wire.read()<<8|Wire.read(); // 0x3F (ACCEL_ZOUT_H) 0x40 (ACCEL_ZOUT_L)

    //read temperature data
    Tmp=Wire.read()<<8|Wire.read(); // 0x41 (TEMP_OUT_H) 0x42 (TEMP_OUT_L)

    //read gyroscope data
    GyX=Wire.read()<<8|Wire.read(); // 0x43 (GYRO_XOUT_H) 0x44 (GYRO_XOUT_L)
    GyY=Wire.read()<<8|Wire.read(); // 0x45 (GYRO_YOUT_H) 0x46 (GYRO_YOUT_L)
    GyZ=Wire.read()<<8|Wire.read(); // 0x47 (GYRO_ZOUT_H) 0x48 (GYRO_ZOUT_L)

    //temperature calculation
    tx = Tmp + tcal;
    t = tx/340 + 36.53; //equation for temperature in degrees C from datasheet
    tf = (t * 9/5) + 32; //fahrenheit

    //get pitch/roll
    getAngle(AcX,AcY,AcZ);

    //printing values to serial port
    Serial.print("Angle: ");
    Serial.print("Pitch = "); Serial.print(pitch);
    Serial.print(" Roll = "); Serial.println(roll);

    Serial.print("Temperature in celsius = "); Serial.print(t);
    Serial.print(" fahrenheit = "); Serial.println(tf);

    if ((roll < 7.00) && (roll > -7.00) && (pitch > -7.00) && (pitch < 7.00)){
    digitalWrite(levelLED_rollpos, LOW);
    digitalWrite(levelLED_rollneg, LOW);
    digitalWrite(levelLED_level, HIGH);
    digitalWrite(levelLED_pitchpos, LOW);
    digitalWrite(levelLED_pitchneg, LOW);
    }

    if (roll > 7.01) {
    // Turn on Pos Roll LED
    digitalWrite(levelLED_rollpos, HIGH);
    digitalWrite(levelLED_rollneg, LOW);
    digitalWrite(levelLED_level, LOW);
    digitalWrite(levelLED_pitchpos, LOW);
    digitalWrite(levelLED_pitchneg, LOW);
    }

    if (roll < -7.01) {
    //Turn on Neg Roll LED
    digitalWrite(levelLED_rollpos, LOW);
    digitalWrite(levelLED_rollneg, HIGH);
    digitalWrite(levelLED_level, LOW);
    digitalWrite(levelLED_pitchpos, LOW);
    digitalWrite(levelLED_pitchneg, LOW);
    }

    if (pitch < -7.01) {
    //Turn on Neg Pitch
    digitalWrite(levelLED_rollpos, LOW);
    digitalWrite(levelLED_rollneg, LOW);
    digitalWrite(levelLED_level, LOW);
    digitalWrite(levelLED_pitchpos, LOW);
    digitalWrite(levelLED_pitchneg, HIGH);
    }

    if (pitch > 7.01) {
    //Turn on Pos Pitch
    digitalWrite(levelLED_rollpos, LOW);
    digitalWrite(levelLED_rollneg, LOW);
    digitalWrite(levelLED_level, LOW);
    digitalWrite(levelLED_pitchpos, HIGH);
    digitalWrite(levelLED_pitchneg, LOW);
    }

    if ((pitch > 7.01) && (roll > 7.01)){
    digitalWrite(levelLED_rollpos, HIGH);
    digitalWrite(levelLED_rollneg, LOW);
    digitalWrite(levelLED_level, LOW);
    digitalWrite(levelLED_pitchpos, HIGH);
    digitalWrite(levelLED_pitchneg, LOW);
    }

    if ((roll > 7.01) && (pitch < -7.01)){
     digitalWrite(levelLED_rollpos, HIGH);
    digitalWrite(levelLED_rollneg, LOW);
    digitalWrite(levelLED_level, LOW);
    digitalWrite(levelLED_pitchpos, LOW);
    digitalWrite(levelLED_pitchneg, HIGH);
    }

    if ((roll < -7.01) && (pitch < -7.01)){
     digitalWrite(levelLED_rollpos, LOW);
    digitalWrite(levelLED_rollneg, HIGH);
    digitalWrite(levelLED_level, LOW);
    digitalWrite(levelLED_pitchpos, LOW);
    digitalWrite(levelLED_pitchneg, HIGH);
    }

    if ((roll < -7.01) && (pitch > 7.01)){
     digitalWrite(levelLED_rollpos, LOW);
    digitalWrite(levelLED_rollneg, HIGH);
    digitalWrite(levelLED_level, LOW);
    digitalWrite(levelLED_pitchpos, HIGH);
    digitalWrite(levelLED_pitchneg, LOW);
    }

    if (tf > 72.00){
      digitalWrite(LED_temp, HIGH);
    }

    if (tf < 72.00){
      digitalWrite(LED_temp, LOW);
    }

    if((distance1 > 24)){
    midiSlowFront();
    }
    if((distance1 < 24) && (distance1 > 12)){
    midiFront();
    }
    if(distance1 < 12){
    midiFastFront();
    }
    if(distance2 > 24){
    midiSlowSide();
    }
    if((distance2 < 24) && (distance2 > 12)){
    midiSide();
    }
    if(distance2 < 12){
    midiFastSide();
    }
  delay(150);
}

//function to convert accelerometer values into pitch and roll
void getAngle(int Ax,int Ay,int Az) {
    double x = Ax;
    double y = Ay;
    double z = Az;

    pitch = atan(x/sqrt((y*y) + (z*z))); //pitch calculation
    roll = atan(y/sqrt((x*x) + (z*z))); //roll calculation

    //converting radians into degrees
    pitch = pitch * (180.0/3.14);
    roll = roll * (180.0/3.14) ;
}

EDIT: Here's the stuff before the error message, my bad!

In file included from C:\Users\Documents\Arduino\polytonetest\polytonetest.ino:1:0:

C:\Users\Documents\Arduino\libraries\arduino-polytone-master\src/digitalWriteFast.h:25:0: warning: "digitalPinToTimer" redefined

 #define digitalPinToTimer(P) \

In file included from sketch\polytonetest.ino.cpp:1:0:

C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:180:0: note: this is the location of the previous definition

 #define digitalPinToTimer(P) ( pgm_read_byte( digital_pin_to_timer_PGM + (P) ) )

In file included from C:\Users\Documents\Arduino\libraries\arduino-polytone-master\src\Polytone.h:11:0,

                 from C:\Users\Documents\Arduino\libraries\arduino-polytone-master\src\Polytone.cpp:7:

C:\Users\Documents\Arduino\libraries\arduino-polytone-master\src\digitalWriteFast.h:25:0: warning: "digitalPinToTimer" redefined

 #define digitalPinToTimer(P) \

In file included from C:\Users\Documents\Arduino\libraries\arduino-polytone-master\src\Polytone.h:10:0,

                 from C:\Users\Documents\Arduino\libraries\arduino-polytone-master\src\Polytone.cpp:7:

C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:180:0: note: this is the location of the previous definition

 #define digitalPinToTimer(P) ( pgm_read_byte( digital_pin_to_timer_PGM + (P) ) )

libraries\arduino-polytone-master\Polytone.cpp.o (symbol from plugin): In function `Polytone::begin()':

(.text+0x0): multiple definition of `t'

sketch\polytonetest.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here

C:\Users\Documents\Arduino\libraries\arduino-polytone-master\src\Polytone.cpp:18:15: warning: type of 't' does not match original declaration [-Wlto-type-mismatch]

 unsigned long t = 0;

               ^

C:\Users\Documents\Arduino\polytonetest\polytonetest.ino:12:8: note: type 'double' should match type 'long unsigned int'

 double t,tx,tf,pitch,roll;

        ^

C:\Users\Documents\Arduino\polytonetest\polytonetest.ino:12:8: note: 't' was previously declared here

C:\Users\Documents\Arduino\polytonetest\polytonetest.ino:12:8: note: code may be misoptimized unless -fno-strict-aliasing is used

collect2.exe: error: ld returned 1 exit status

All that text that comes before the "exit status 1" tells you what is wrong. Without that we know less than you do.

Ohhh, I see! Sorry about that! I will edit the post!


text:
What does an Arduino do if the serial connection is closed on the other end?
I have a simple method that simply waits for an input, computes a response, and sends it:
void loop() {
  if (Serial.available() > 0){
    input = Serial.read();

    if (input == 10){
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);

      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);

      duration = PulseDuration(echoPin, HIGH, 6000);
      distance = duration * 0.00034/2;  // 0.00034 m/us is speed of sound

      Serial.println(distance, 4);
      }
  }
}

My question: What happens to the arduino if I close the serial connection from the receiving end while it's printing out data (in the last line of the loop)?
Context and motivation:
The program works well most times. I can open a python program that sends the requests and prints out the reply using pyserial. After I close the python side and reopen it, connection is set and I can start listening on the side nicely just like the first time. Sometimes, however, when I try to restart the python program, I get a connection error saying that the port is already opened (I'm running in Windows.. there are tons of posts about this problem, but none of them have been helpful). Some other times, when connecting with the python program (which connects with connection = serial.Serial(self.arduino_port, 9600, timeout=0) it just blocks and doesn't connect, it doesn't give the "port already opened" error, and it doesn't advance to the next statement.
I am confident I did close the previous python run before attempting a new one (process explorer shows no active python programs running, it also shows no open processes using a serial handler). I'm not here to solve that problem directly, though, just to ask a related question.
I'm also confident running connection.close() does not terminate the arduino program, as I have been able to restart my python program without having to reset the arduino or anything, suggesting the arduino kept running its loop after I closed the connection on the python side.
All that to say that my latest hypothesis is that these issues arise when I close the serial connection connection.close() while the arduino is printing, but because the port is closed, that Arduino is stuck and cannot do the Serial.println(), as the USB never asks to flush the data in its buffer.
Is this possible/does it make sense? What happens to the arduino if I close the serial connection while it's printing out data?
I'm not posting my python program here as it's not directly relevant to the question and I can't seem to make a minimum reproducible program that doesn't expose confidential code.

Which Arduino? Please tag your question with that information. There are lots of Arduino models, and some have different ways of interfacing with USB than others.

the question is not about Arduino

@NickGammon It's an Arduino/Genuino 101

@Juraj He is asking what the Arduino does if the serial connection is closed so I think that is a relevant question. However the bulk of the question appears to be about the behaviour of Windows.

Yeah, I wanted to explain why I wanted to know what the arduino did, and perhaps got too much into the weeds of my overall problem (sorry), when all I wanted is to know what happens when the arduino tries Serial.println(..) while the other end is disconnecting.

That's some strange Intel monstrosity. It's impossible to know what it does or how. Intel's foray into the Arduinosphere was brief and somewhat abortive.
In general though (for most cores) the DTR signal (and sometimes the RTS signal too) of the CDC/ACM protocol is used to "gate" the serial data - if it's asserted then serial data gets sent through to the host PC. If it's not asserted then it just gets thrown away.
I have seen cores where if DTR is not asserted the data gets buffered until the TX buffer is full and then blocks, but that is rare.
You might find your answer if you delve into the core's source code, but you may find that big chunks of it are hidden away in closed source pre-compiled libraries, and the fact it seems to run some custom RTOS means it'll be even more obfuscated. YMMV...

or try it .....

Thank you @Majenko, that is helpful.

@Juraj, try what? I already am trying something (described in the post) and observing some behavior. I asked this question to see if my reasoning for said observation made sense. If you have suggestions for lower level tests to understand the behavior in this scenario, I’m all ears. I don’t know how to go lower level than what I’m doing now. How can I see the result of the arduino code if the test itself is to disconnect its serial communication? How can I tell whether the arduino is blocking or running its loop if I can’t re-connect to it?

@polortiz4, add Serial printing to the Blink sketch.

Hmm that’s a good and simple idea. Thanks


text:
MKR 1010 disconnects COM-port on each upload
Each time I attempt to upload to the MKR WiFi 1010 board the COM-port gets disconnected, usually at one of the following points:

Either it disconnects just after compiling/verifying. In this case the LED_BUILTIN pulsates slowly, and the USB-cable needs to be reconnected in order to try again. The next attempt usually results in 2..

Or, it disconnects after a successful upload. The next attempt to upload will always result in 1. occurring. When this happens the COM-port is still visible in Windows Device Manager but it can't be found by a Serial Monitor.

Any ideas what could be causing this or what could be done to have it stay connected? With an UNO this doesn't happen.

does it happen only with your sketch or with Blink too? Uno has external Serial chip. on MKR the MCU handles the USB so as it resets the port disconnects

This was due to using a virtual machine (VMware) which apparently doesn't handle the MKR board COM-port so well. Moving the development environment to the host solved the problem. It still disconnects the COM-port after upload but then consistently reconnects to the same COM-port and that's good enough.


text:
Interfacing SPI (MCP3903)
I'm trying to interface MCP3903. I haven't really don't any SPI interfacing before and I can't seem to find clear enough answer for newbs. Please bare with me.
I'm trying to use this library. http://www.kerrywong.com/2014/05/10/mcp3903-library/
On the website there is the following circuit diagram.

I can see SDI, SDO pins on the ESP module, how do I connect the SCK and CS pins? If they can be any pins how do I declare them on the test program on the website?
Thank you

Which ESP module are you using?

it's wroom ESP-32

SPI0 and SPI1 are used internally to access the ESP32’s attached flash memory. SPI2 and SPI3 are general purpose SPI controllers, sometimes referred to as HSPI and VSPI, respectively. They are open to users.
A quick google search shows:

So you can use IO5, IO18, IO19 and IO23.


text:
Accessing start up bits of SRAM from MicroBit for PUF
https://infocenter.nordicsemi.com/pdf/nRF51822_PS_v3.4.pdf
The aim is to extract (output in serial monitor) the start up bits from  the SRAM of this microbit which is located at memory address 0x20000000, given by the datasheet above, all done in the arduino IDE.
After some searches I emerged on this code
void setup()
{
  uint8_t const * p;
  uint8_t i;

  Serial.begin( 115200 );

  p = 0;
  i = 0;

  do
  {
    Serial.print( *p, HEX );
    Serial.print( ' ' );

    ++i;
    ++p;

    if ( (i & 0xF) == 0 )
    {
      Serial.println();
    }
  }
  while ( i != 0 );
}

void loop()
{
}

From this link https://forum.arduino.cc/t/accessing-sram-on-arduino-uno/267777/6
However this pertains to an arduino uno and I'm not entirely sure how I would transfer it to my microbit.


text:
Software debouncing a button when released
I'm having some trouble with software debouncing on Arduino UNO. There is a condition in my code where an unwanted debounce registers as a button push.
I'm using an interrupt for my button press, since my main loop has occasional long delays if certain conditions are met. I've attached pin 2 to my interrupt like so:
#define BTN 2
pinMode(BTN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(BTN),buttonClick, FALLING);

And my interrupt function:
volatile unsigned long _lastClick = 0;
void buttonClick()
{
  unsigned long _clickTimer = millis();
  if (_clickTimer - _lastClick > DEBOUNCE)
  {
    _timer = 0;
    _count++;
    _lcd.setCursor(0, 1);
    _lcd.print(_count);
    _softSerial.println("stuff");
  }
  _lastClick = _clickTimer;
}

This works just fine when pressing the button. However, this doesnt account for the bounce when the button is released. So occasionally, if I hold the button down for long enough and then let go, the bouncing from depressing the key also registers as a falling edge.
Everything works just fine if my button press is brief enough to fall within the limit set by DEBOUNCE. What would be the best way to ensure the interrupt isn't called when depressing the button? Without adding passives to my circuit like capacitors?

Untested idea: acknowledge a button press only on a falling edge that
follows a long HIGH period. For this you will have to:

attach the interrupt handler to the CHANGE events

update _lastClick on every such event

acknowledge a press if the DEBOUNCE time has elapsed and the
input line reads LOW.

Side note: it is bad practice to do lengthy stuff (like printing to
SoftSerial or an LCD) in interrupt context.


text:
Connected the 3.3v output and the 5v output together
I accidentally connected the 3.3v output and 5v output to the same connection. How bad is that and what issues could that cause?
I was busy with making my first project which uses a module which runs on 3.3v and all other logic and lcd screen and such which run on the 5v but when rearranging I put both of the outputs on the same part of the circuit.
Luckily it all still seems to work but I am quite curious what issues this could cause to both the components and the Arduino.
Edit Added a very basic version of the schematic as I don't have a good software for that yet. Left out all stuff not connected to the problem of the circuit.

Which outputs? Which pins? Do you have a schematic showing where the short was?

Have added a schematic, hope this clarifies my question. Also, the question more meant as I know I should not do it but what is exactly going wrong when combining both of the voltage pins.

The 3.3v parts are the more likely to suffer, as the accidental connection presented it with an overvoltage - 5v, where it expected only 3.3v.
If that part or parts doesn't present a short-circuit or almost short-circuit, the nano's power-supply is probably tolerant enough to survive it. But your DVM is your friend; power up the nano by itself (nothing external connected to it) and test the +5v and +3.3v outputs. If they still present the right voltages your nano is probably still healthy.


text:
I want to code a transmitter with the help of Arduino. I am getting the error given
    // 1 Channel Transmitter | 1 Kanal Verici
    // Input pin A5

      #include <SPI.h>
      #include <nRF24L01.h>
      #include <RF24.h>
      const uint64_t pipeOut = 000322;    // NOTE: The same as in the receiver 000322 | Alıcı kodundaki adres ile aynı olmalı
      RF24 radio(9, 10);                          // select CE,CSN pin | CE ve CSN pinlerin seçimi

      struct Signal {
      byte aux1;
      byte aux3;

    };
      Signal data;
      void ResetData()
    {
      data.aux1 = 0;                       // Signal lost position | Sinyal kesildiğindeki pozisyon
      data.aux3 = 0;
    }
      void setup()
    {
                                           //Configure the NRF24 module  | NRF24 modül konfigürasyonu
      radio.begin();
      radio.openWritingPipe(pipeOut);
      radio.setChannel(100);
      radio.setAutoAck(false);
      radio.setDataRate(RF24_250KBPS);    // The lowest data rate value for more stable communication  | Daha kararlı iletişim için en düşük veri hızı.
      radio.setPALevel(RF24_PA_MAX);      // Output power is set for maximum |  Çıkış gücü maksimum için ayarlanıyor.
      radio.stopListening();              // Start the radio comunication for Transmitter | Verici için sinyal iletişimini başlatır.
      ResetData();

    }
                                          // Joystick center and its borders | Joystick merkez ve sınırları
      int Border_Map(int val, int lower, int middle, int upper, bool reverse)
    {
      val = constrain(val, lower, upper);
      if ( val < middle )
      val = map(val, lower, middle, 0, 128);
      else
      val = map(val, middle, upper, 128, 255);
      return ( reverse ? 255 - val : val );
    }
      void loop()
    {
                                         // Control Stick Calibration for channels  |  Her bir kanal için kumanda Kol Kalibrasyonları
      data.aux1 = Border_Map( analogRead(A5), 0, 512, 1023, true );   // "true" or "false" for change signal direction | "true" veya "false" sinyal yönünü değiştirir.

      data.aux3 = digitalRead(7);
      radio.write(&data, sizeof(Signal));
    }

You haven't told us, what error you got. Please copy the complete error message (including the information, where in the code the error occurred) into the question-

Even when the specific error you are getting has been made clear to us you'll have another problem. You are transmitting data at loop() speed and this will almost certainly be too fast for the receiver part to process.


text:
Does changing the prescale for Timer 0 or Timer 2 affect the micros() function?
I am using an ATTiny88 to drive a PWM device. First of all, digging through the literature, it's hard to tell what the differences between the ATTiny85 and ATTiny88 are, and the vast majority of references are for the ATTiny85.
In this particular case, I am using D10 on the ATTiny88 for PWM output. The PWM frequency needs to be above 5KHz, so I am going to issue the command:
TCCR1B = TCCR1B & 0b11111000 | 0x01;

which I am given to understand will set a PWM frequency of 31KHz on D10. Please let me know if this is not correct. Meanwhile, I also need to use the micros() function:
const int pulseDelay = 183;
unsigned long MicroSeconds = micros();
while(micros() - MicroSeconds < pulseDelay){}   // 1/2 period of Bell
if (Enable) {digitalWrite(14, 1);}      // If Enable = True, send high pulse to Bell, else Bell is silent
while(micros() - MicroSeconds < pulseDelay){}   // 1/2 period of Bell
digitalWrite(14,0);

In this case, it is probably best not to use an interrupt blocking call.
EDIT: I wrote a short driver to test things out:
#include <Arduino.h>

#define True 1
#define False 0
#define Bell 14     // Bell port
#define LED 10      // Intensity Port

int Intensity = 25;
void Beep(bool Enable, float Delay)
{
    const int pulseDelay = 183;         // 1/2 period of Bell pulse in microseconds
    int Span = Delay * 2732;
    for (int  x = 0; x < Span; x++)
    {
        unsigned long MicroSeconds = micros();
        while(micros() - MicroSeconds < pulseDelay){}   // 1/2 period of Bell
        digitalWrite(Bell, 1);              // Send high pulse to Bell
        while(micros() - MicroSeconds < pulseDelay){}   // 1/2 period of Bell
        digitalWrite(Bell,0);               // Send low pulse to bell
    }
}
void setup()
{
    pinMode(LED, OUTPUT);
    analogWrite(LED, Intensity);        // Set initial Intensity
    pinMode(Bell, OUTPUT);          // Set Bell as output
//  TCCR1B = TCCR1B & 0b11111000 | 0x01;  <=========== remove comment  to test the call
}
void loop()
{
    Intensity += 25;
    if (Intensity > 255) {Intensity = 25;}
    analogWrite(LED, Intensity);
    Beep(True, 2);
}

When I remove the comment, the Arduino runs extremely hot.  D10 goes to 1 Volt with a lot of very high frequency noise and stays there. D10 outputs a 5 KHz signal with a very narrow but fairly constant pulse width.

The micros() function relies on the Timer0 overflow interrupt to increment the microseconds counter. If you disable interrupts, micros() won't update correctly.

If the MCU gets hot, and if an output stays midway between LOW and HIGH, then you have an electrical problem. Typically an excessive load (too low impedance) on the pin. Unplug whatever is connected to D10, then look at what is coming out of that pin.

You are making a number of unwarranted assumptions.  The main one is D10 is connected to something.  The Arduino is not connected to anything but USB power during this testing.  It turns out the Arduino is bad - internally shorted.  I am fairly certain the unit was good prior to testing.  Either this is a coincidence, or issuing TCCR1B = TCCR1B & 0b11111000 | 0x01; caused something inside the Arduino to fry.  I don't want to try changing any prescalers again until the issue is resolved.

The ATTiny85 and ATTiny88 are pretty different devices. The ATTiny85 is
an 8-pin MCU, whereas the ATTiny88 has 28 pins, and is pretty
similar (but slower) to the ATmega328P you would find on an Uno.
Regarding the effect of the prescaler on micros(), it all depends on
the core you are using. I am not Aware of a standard Arduino core for
the ATTiny88, but most AVR cores use Timer 0 for millis(),
micros() and delay(). If you change its prescaler, all these
functions will be affected. The other timers don't pose this problem.

Edit 1: If I understand correctly, you are using this core frm MH-ET
LIVE. This is very similar to the standard AVR Arduino core. It
also configures the Timer 0 prescaler to 64. If you
change this prescaler, micros() and friends will count wrong with an
error factor that is exactly 64/prescaler. For example, if you set the
prescaler to 1 (i.e. no prescaler), micros() will count
64 times too fast.
You asked:

Exactly how will using TCCR1B = TCCR1B & 0b11111000 | 0x01; affect
the micros() function?

It will not affect it at all. The TCCR1B register belongs to
Timer 1, whereas, as explained above, the Arduino timing function
rely on Timer 0.

Edit 2: Answering the new questions that appeared in a comment.

which timer controls the PWM on port 10 on the ATTiny88

There is no pin that is unambiguously named “pin 10” on the ATtiny88.
Then, the answer to this question depends on what you mean by “pin 10”,
which in turn depends on the core you are using. You wrote you are using
the “MH-ET LIVE Tiny88(16.0MHz) core”. I found no core with that exact
name (a link to your core would have been helpful!). The closets matches
I found are the one I already mentioned from MH-ET LIVE, and Spence
Konde’s ATTinyCore. The latter defines a board named “ATtiny88
(Micronucleus, MH-ET t88 w/16MHz CLOCK)”.
If you are indeed using one of these, they both define “pin 10” as
PB2, which is the same as OC1B (output compare of
Timer 1, channel B). Hence, it’s PWM capability is controlled
by Timer 1.

what command should I use to get 5KHz PWM on that port.

There are various options, depending on the choice of PWM mode and
prescaler. Here is one possibility:
/* Configure Timer 1 for phase correct PWM at 5 kHz. */
void setup() {
    DDRB  |= _BV(PB2);    // set pin 10 = PB2 = OC1B as output
    TCCR1A = _BV(COM1B1)  // non-inverting PWM on pin OC1B
           | _BV(WGM11);  // select mode 10: phase correct PWM...
    TCCR1B = _BV(WGM13)   // ...with TOP = ICR1.
           | _BV(CS10);   // clock at F_CPU
    ICR1   = 1600;        // period = 2 * 1600 clock cycles = 0.2 ms
}

For controlling the duty cycle, you have to write a number between 0
(for a signal continuously LOW) and 1600 (continuously HIGH) to the
register OCR1B. For example:
/* Ramp the duty cycle from 0% to 100%. */
void loop() {
    for (int duty = 0; duty <= 1600; duty++) {
        OCR1B = duty;
        delayMicroseconds(1000);
    }
}

I tested this on an Uno, which has a very similar pinout as the ATtiny88
and, as far as I can tell, identical Timer 1 implementations.

Why slower?  Supposedly the ATTiny88 uses the ATmega328, at least if I am reading the ads correctly.  I also gather only D9 and D10 are hardware PWM (plus my board design already uses D10).  I am using the MH-ET LIVE Tiny88(16.0MHz) core.  It is the only one I have been able to get to work with these boards.  If there is a different core that will work better, I am game to try it.  Exactly how will using TCCR1B = TCCR1B & 0b11111000 | 0x01; affect the micros() function?  I can handle if the function counts in 8, 16, 32... μseconds rather than 1 as long as I know what the factor is.

According to its datasheet, the ATtiny88 can be clocked up to 12 MHz. Looks like the board you mention is overclocking it. It may still work just fine.

The main question essentially remains unanswered.  Stipulating that Timer0 controls the millis() and micros() registers for the ATTiny88, should the prescaler be set for timer0 or timer1 to control the PWM frequency on the ATTiny88?  Right now, I am getting 490Hz on the PWM port (D10).  I need 16 times that.

@LesRhorer: I think I clearly answered the question in the title: changing the prescaler for Timer 0 affects micros(); changing the prescaler for Timer 2 does not.

Well, OK, fair enough, I suppose.  The wording was not perhaps direct to the eventual point.  The salient questions are which timer controls the PWM on port 10 on the ATTiny88 and what command should I use to get 5KHz PWM on that port.  Perhaps the ultimate question is whether I should switch to an Arduino Nano, instead of the ATTiny88?

@LesRhorer: See expanded answer.

The core I am using is from https://raw.githubusercontent.com/MHEtLive/arduino-boards-index/master/package_mhetlive_index.json

That works perfectly!  Thank you, sir.  The device calls for a minimum of 5Kz, so I will probably set ICR1 to 1000, instead of 1600, which should give me a period of 125us, or a frequency of 8KHz and duty cycle steps of .1%, instead of 0.0625%.


text:
Sending data using Bluetooth SPP-C Module without a Breakout-Board
tl;dr
I can't send data using the raw SPP-C Bluetooth module without a breakout board.
The communication via UART works fine as I am able to issue AT commands and get proper responses.
But when connected over Bluetooth the data passed over UART does not show up on my computer while the other direction works fine.
Has anyone tried that module yet without using a breakout board?
The long story:
I started my project by using a regular HC-05 module on a breakout board. The prototype worked just fine as there are also plenty tutorials available. The drawback using that breakout module is that it works with two voltages, 5V for power and 3V3 for communication. I have also more components in my project that run best at 3V3. That is why it came to my mind to use 3V3 as the only voltage. The raw HC-05 module without breakout board is also powered with 3V3. So everything looked just perfect.
Looking at the specs to the HC-05 I noticed that there is also more on that module like SPI and USB (page 12 bottom). So I got curious and off track.
Anyway. Instead of ordering raw HC-05 modules without breakout board I ordered cheaper SPP-C modules that don't have all this fancy stuff but just UART communication.
Following the description from Martyn Currey I was quicky able to issue AT commands and receive data over bluetooth. But I am not able to send data over Bluetooth.
I am using the same setup as it is shown on page 4 in the Chinese datasheet. (no I can't read that crazy symbols but I can read and understand the images)

This is unanswerable until you clearly document in the body of the question itself what is different between the two cases.  Also consider if the computer may be paired to the unique ID of the old module and not the new, or even that the new module might be faulty.

The pairing is not an issue as I can transmit data from my computer. Just the other direction does not work (but works flawlessly with HC-05). I also considered a faulty module so I ordered a SPP-C module on a breakout board for reference. I'll post the results here.

I found a solution myself.
The modules are working as they are supposed to and are not faulty.
Also I did nothing wrong.
The Problem are my development machines. Mac mini (Late 2009) and MacBookPro (Mid 2009), both having a Broadcom 2046 Bluetooth host chip. I used those to connect via Bluetooth and open a tty session using minicom. Running macOS and using "Hardware IO Tools" to log Bluetooth packets I saw that there was clearly nothing coming in.
After that I turned over to my Windows and used Hype! Terminal. Everything worked!
Then I went to my Raspberry Pi and Linux. After pairing using bluetoothctl and issuing a few commands from Bluetooth as ttyUSB. Everything worked as well.
Then I tried BlueSPP on an Andriod phone. And again, it worked as it was supposed to.
So my conclusion is that there is some sort of incompatibility between the SPP-C module and the Broadcom 2046 host controller.

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


text:
Arduino ESP8266 HTTPS Request returning empty response
I want to get some JSON data from a HTTPS secured Webserver using a ESP8266.
For some reason I'm getting an empty response, I believe there's an error parsing the GET request.
In Chrome I get the JSON response without problems.
GET Request:
httpsClient.print(String("GET ") + path + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");

Host and Path:
const char *host = "www.adler-mannheim.de";
const char *path = "/jsonapi/game/current";

UPDATE:
I tried fetching some JSON from another Server and it worked finde, so i can rule out my code.
Fiddling around with the host and path I observe this:

Hostname without "www" results in a 301

Hostname with "https://www" results in no HTTPS connection at all

So it seems that a "www" is required although it unfortunately leads into a empty response.
The output is as follows:
headers received
reply was:
==========
==========
closing connection

In the first case, without using "www" in ahead of host there's some 301 HTML in between the two lines of "=".
Whole function:
void connect() {
  WiFiClientSecure httpsClient;    //Declare object of class WiFiClient

  Serial.println(host);
  httpsClient.setInsecure();

  Serial.print("HTTPS Connecting");
  int r=0; //retry counter
  while((!httpsClient.connect(host, httpsPort)) && (r < 30)){
      delay(100);
      Serial.print(".");
      r++;
  }
  if(r==30) {
    Serial.println("Connection failed");
  }
  else {
    Serial.println("Connected to web");
  }

  String getData, Link;

  //GET Data

  Serial.print("requesting URL: ");
  Serial.println(host+Link);

  httpsClient.print(String("GET ") + path + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");

  Serial.println("request sent: ");
  Serial.println(String("GET ") + path + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");
  while (httpsClient.connected()) {
    String line = httpsClient.readStringUntil('\n');
    if (line == "\r") {
      Serial.println("headers received");
      break;
    }
  }

  Serial.println("reply was:");
  Serial.println("==========");
  String line;
  while(httpsClient.available()){
    line = httpsClient.readStringUntil('\n');  //Read Line by Line
    Serial.println(line); //Print response
  }
  Serial.println("==========");
  Serial.println("closing connection");

  delay(2000);  //GET Data at every 2 seconds
}

UPDATE 2:
I tried the following code from the ESP8266HTTPClient Library examples:
void connect2() {

  WiFiClientSecure client;

  //client.setFingerprint(fingerprint);
  client.setInsecure();

  HTTPClient https;

  Serial.print("[HTTPS] begin...\n");
  if (https.begin(client, "https://github.com/esp8266/Arduino/issues/3417")) {  // HTTPS

    Serial.print("[HTTPS] GET...\n");
    // start connection and send HTTP header
    int httpCode = https.GET();

    // httpCode will be negative on error
    if (httpCode > 0) {
      // HTTP header has been send and Server response header has been handled
      Serial.printf("[HTTPS] GET... code: %d\n", httpCode);

      // file found at server
      if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
        String payload = https.getString();
        Serial.println(payload);
      }
    } else {
      Serial.printf("[HTTPS] GET... failed, error: %s\n", https.errorToString(httpCode).c_str());
    }

    https.end();
  } else {
    Serial.printf("[HTTPS] Unable to connect\n");
  }

  Serial.println("Wait 10s before next round...");
  delay(10000);
}

This one gives me a 200 but no payload. Other sites work
UPDATE 3:
I had a look on the headers.
https.headers()

This gives me 0 headers on every page, even when there's a payload.
I also had a closer look at the payload that returns from my desired api and its filled with NULL.
In a weird way this is only the case with my desired page and only my desired subpages.
Requesting something more at top level e.g "https://www.adler-mannheim.de/jsonapi" which is basically a SilverStripe Welcome page, I get a fully fetched beautiful HTML payload.
I got literally no Idea why. Do I have to set a specific User Agent or something so that the Server responds?

I assume it's an empty response since it says Reply (nothing in between), whereas from other sites theres a response in between. I'll edit the question to make it clear

https:// is not part of the hostname. It's the protocol indicator for a URI.

The 301 response will also have a "Location:" header which tells you the real URI you should be accessing. 301 is permanently moved, so it is safe for you to replace your URI in your code with the one provided in the Location header.

The 301 points to the exact URL which I'm trying to access (https://www.adler-mannheim.de/jsonapi/game/current). It also works fine in a Browser.

I guess you don't wait for the response long enough

How do I make it wait longer then? Insert a delay? Also since it claims that it received headers, the response should be ready, right?

I added the code to the post. It does get to "headers received" so I figure it did receive at least something, right?

The other example function gives me a 200 with also no payload.

and the headers? is there a content-type or content-length?

if the https.headers() function is correct for checking the headers, theres none.

Okay I have no Idea what I changed apart from deleting some imports which might have collided, but now it works. Regular call with "https://www" does the thing.
Thanks anyways

It would be better to have a more complete answer, assuming it can be of use to someone else.  Otherwise the question and answer both are probably better off deleted.

the version with WiFiClient or the version with HttpClient?

I had this same problem and I realized it was because I was using an WiFiClientSecure to try to an endpoint over HTTP instead of HTTPS. If anyone else is having this same problem, I would check that.


text:
Substring: What is causing my output to be truncated?
I suspect that I might be using too many resources, because of the strings, but I am new to Arduino, so not sure where I am going wrong.  Any help would be appreciated.
What it should do when complete:
"Birthday Reminder"

Read the SD card for a "birthday" file ("MM-DD.txt" ) that matches
"today".
The file contains the Name of the person and year of
birth.
Flash LED's and display the person's name and age on the
OLED.
The unit will not displayed anything until someone's birthday.

I am using the SD card with a simple format, to easily add new birthday's.
Output:
⸮Initializing SD card...
card initialized.
25
111
opening: 04-25.txt
2020"Test Person"
bYearStr: 20

The sd card file:
Name: MM-DD.txt
Example: 04-25.txt

Contents: Birthyear, Name
Example: 2020"Test Person"

The Sketch
#include <SPI.h>
#include <SD.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include "RTClib.h"

RTC_DS3231 rtc;

int age;
int led;
int dly;
String bName;
String bYearStr;
int bYear;
int currentDay;
int  tDy;
int  tMth;
int  tYr;

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_RESET -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

void setup() {
  Serial.begin(9600);
  delay(3000); // wait for console opening

  // Setup Candle pins
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (rtc.lostPower()) {
    Serial.println("RTC lost power, lets set the time!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  }

  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  display.clearDisplay();
  display.display(); // this command will display all the data which is in buffer
  display.setTextColor(WHITE, BLACK);

  const int SdCardPin = 10;
  Serial.println("Initializing SD card..."); // Verifying SD Card.
  //  if (!SD.begin(SdCardPin)) {
  if (!SD.begin(10)) {
    Serial.println("Card failed, or not present"); // don't do anything more:
    while (1);
  }
  Serial.println("card initialized.");

  currentDay = 111;
}

void loop() {
  age = 0;

  DateTime now = rtc.now();
  tDy = now.day();
  tMth = now.month();
  tYr = now.year();
  Serial.println(tDy);
  Serial.println(currentDay);

  if (currentDay != tDy) {
    String fileName;
    String m = String(tMth);
    String d = String(tDy);

    if (tMth < 10) {
      String mm = m;
      m = "0" + mm;
    }
    if (tDy < 10) {
      String dd = d;
      d =  "0" + dd;
    }
    fileName = m + "-" + d + ".txt";

    //String fileName = "01-01.txt";
    Serial.println("opening: " + fileName);
    File f = SD.open(fileName);
    delay(3000);

    if (!f) {
      Serial.println("open failed");
    } else {
      while (f.available()) {
        String line = f.readStringUntil('\n');
        Serial.println(line);
        bYearStr = line.substring(0, 4);
        bName = line.substring(4);
        delay(1000);
        currentDay = tDy;
        break;
      }
      f.close();
    }

    Serial.print("bYearStr: ");
    Serial.println(bYearStr);
    Serial.print("bName: ");
    Serial.println(bName);
    int bYear = bYearStr.toInt();
    age = tYr - bYear;
    Serial.print("Age: ");
    Serial.println(age);

  } else { // Start current day equal
    display.setTextSize(1);
    display.setCursor(38, 10);
    display.print("Birthday!");
    display.println();

    display.setTextSize(1);
    display.setCursor(0, 30);
    display.print("Name: ");
    display.print(bName);
    display.setCursor(0, 40);
    display.print("Age: ");
    display.print(age );
    display.println();

    led = random(3, 6);
    dly = random(80, 250);
    digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
    delay(dly);              // wait
    digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  } // End current day

  display.display();

} // End void Loop

There is no  more Serial output after the 2 first characters of the String "2020" ?
Very strange. You might simplify your sketch to a test environment only, without all the display stuff, eventually even without RTC.

Don´t use String class. Replace it with char arrays. You are probably running out of heap memory.

Thanks.  @DataFiddler I have done that and it works to the serial print.  The sketch also works when I don't us the SD card, but put the birthday's in an smaller test array (3 names).  I run into problems with larger arrays (13 names).  I broke it apart and have been building it back up. For info, I am not getting the display at all, it appears the script stops at the output.

Thanks, @SBF I was afraid that is what was happening.

It is quite likely you're out of memory. To know, really you need to keep track of the stack pointer and heap structure. There's enough going on in your code, that I'm not reasonably going to be able to set up an identical scenario to prove it.
Display Library
The greatest use of SRAM in your project comes from the Adafruit SSD1306 library.  It's allocating a buffer for the entire frame, which is 128 * 64 == 8192 bits, or 1024 bytes, half your Nano's SRAM.  It will use more than that for other data, though probably not a lot more by percentage.
You may be able to mitigate this usage with a library like trades some SRAM usage for extra execution time or lower frame rates.  One is the U8g2 library.  You can read about how it can use half-buffer in some documentation to the older version of the library; the concept carries over to the newer library.
SD Library
The next largest usage is the SD card libraries sector buffer, which is 512 bytes.
So between the two of them, there go 3/4 of your SRAM in just the two buffers, nevermind anything else.
You may be able to avoid this buffer by using a different library.  You could try PetitFS.  The library it wraps says it uses something like 44 bytes plus whatever call stack is needed.
String Literals
You have at least 206 bytes of string literals in your sketch alone, assuming the compiler can't determine that any of them are in fact unused.  There may be others in the libraries, though probably not many. So now we're down to at least 306 bytes or less SRAM.

Size
String

35
"RTC lost power, lets set the time!"

28
"Card failed, or not present"

24
"Initializing SD card..."

18
"Couldn't find RTC"

18
"card initialized."

12
"open failed"

11
"bYearStr: "

10
"opening: "

10
"Birthday!"

10
"01-01.txt"

8
"bName: "

7
"Name: "

6
"Age: "

5
".txt"

2
"-"

2
"0"

206
Total

The "0" is only counted once in the above, even though you have two of them.  Fun fact: the C and C++ languages allow identical string literals to be colocated or overlap.  I don't know whether or not avr-gcc will combine "Name: " into "bName: ", since you have bigger problems to worry about, I'm just pretending it won't without looking.
Mitigation can include use of the F() macro to move some of these string literals into PROGMEM (flash).  You can't do this to every string literal, but the ones where you're involving them in a String(F("we're trying to avoid these right?")) constructor or in Serial (or other Stream/Print instances)'s .print(F("Hello World"));
The guts of the F() macro is another called PSTR(), which does the actual work of putting the string literal into PROGMEM.  F() tags the resulting pointer with a dummy type that is used in function overloading in Arduino libraries.  The only reason why I mention this is because below, you'll see me use PSTR to do the same thing, only with a function that belongs to avr-libc rather than Arduino.
Note when you're initializing a String object from a regular string literal, you're paying the SRAM cost twice for the lifetime of the String object.  One copy is in SRAM for the literal used to call the String constructor, the other copy is in the dynamic memory allocated to the String object.
String class
This was pointed out in the comments; and it's true that it's better to avoid them.  Although, I think not actually the greatest problem in your case.
I see you've avoided unnecessarily adding them together for Serial output and instead are using separate .print() calls, so you're ahead of the game there.
For your filename, mitigation could be using fixed size local char array and snprintf_P() to cobble together your filename, something like:
char filename[sizeof "MM-DD.txt"];
snprintf_P(
    filename, sizeof filename,
    PSTR("%02u-%02u.txt"),
    tMth, tDy
);

or if you wanted to avoid pulling the beast of printf into your sketch, assuming it's not already there, you could do something like:
const char filename[] = {
    '0' + tMth / 10,
    '0' + tMth % 10,
    '-',
    '0' + tDy  / 10,
    '0' + tDy  % 10,
    '.',
    't',
    'x',
    't',
    '\0'
};

Serial
What Serial?  Yup, I mean, there's not a lot you can do about it, but I bring it up because the last conservative figure above was 306 bytes, and we didn't try to account for the what String is doing in the heap at all.  Well Serial takes 157 bytes according to a simple test here, which makes sense, because on the UNO it has two ring buffers for transmit and receive that are 64 bytes in size each, half a dozen pointers for configuring hardware registers to use, and head and tail indices for those buffers.  There's also another 12 bytes that are used for HardWareSerial's vtable.
So that puts you down to conservatively 137 bytes of SRAM for well, everything else.
Everything Else
There's a lot not accounted for here. Your globals, the libraries globals, other vtables, the String data on the heap, and the stack.  Those are just the ones coming to mind.  I mean just the millis()/micros() counter variables and fract take 9 bytes.  If you really want to dig into the details here, besides looking at the stack pointer and heap structure, the avr-nm command run on your sketch's .elf file with its -D, -S, and --size-sort is helpful for locating global variable usage and similar things.

Actually you could modify the core files (or possibly the board definition) to get HardwareSerial to use a smaller buffers.  So, it's not completely out of your control.  Not sure if it's worth editing in; it's kind of lower on te list.


text:
Custom library for Arduino to encode and decode JSON Web Tokens
So I have been recently been trying to create a library for Arduino to encode and decode JSON Web tokens(JWT) using HMAC-SHA256.
For those unfamiliar, JWT has 3 parts - The header, body and signature. The header and body are in JSON format.
The header contains the hashing algorithm and token type while The body contains the data to be transmitted.
The header and body are converted to base64 format and arranged as "[header].[body]". The signature is created by running the hashing algorithm (HMAC-SHA256 in my case) on the "[header].[body]" and converting the result to base64 format.
Finally, the token is arranged as "[header].[body].[signature]"
More information can be found on - https://jwt.io/introduction
So far, I successfully managed to create the encoding part. I wanted to test the code for consistency, so I tried to run the code on an Arduino UNO and kept on calling the encoding function in void loop. Initially, the results were as expected -

The long line of text is the expected output. But suddenly, it does this -

Then there is a period where the output is blank and finally, this comes-

For some reason, only the signature part gets printed. Also, I have no idea what the last 2 outputs are. Finally, it goes blank for a second and then repeats the entire process
Can anyone please help me in figuring out what is going on and how do I solve it?
This is my code in the library-
custom_jwt.h
#ifndef _CUSTOM_JWT_H_
#define _CUSTOM_JWT_H_

#include <Arduino.h>

class CustomJWT{
private:
    char* secretKey;

public:
    char* header;
    char* payload;
    char* signature;
    String out;

    CustomJWT(char* secret);

    char* getSecret();

    void changeSecret(char* secret);

    void encodeJWT(char* string);

    void decodeJWT(char* string);

};

#endif //_CUSTOM_JWT_H_

custom_jwt.cpp
#include "custom_jwt.h"
#include "sha256.h"
#include <Arduino.h>

const char b64[]  = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const char head[] = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9";

void decodeblock(unsigned char in[], char *clrstr) {
    unsigned char out[4];
    out[0] = in[0] << 2 | in[1] >> 4;
    out[1] = in[1] << 4 | in[2] >> 2;
    out[2] = in[2] << 6 | in[3] >> 0;
    out[3] = '\0';
    strncat(clrstr, reinterpret_cast<const char *>(out), sizeof(out));
}

void b64_decode(char *b64src, char *clrdst)
{
    int c, phase, i;
    unsigned char in[4];
    char *p;

    clrdst[0] = '\0';
    phase = 0; i=0;
    while(b64src[i]) {
        c = (int) b64src[i];
        if(c == '=') {
            decodeblock(in, clrdst);
            break;
        }
        p = strchr(b64, c);
        if(p) {
            in[phase] = p - b64;
            phase = (phase + 1) % 4;
            if(phase == 0) {
                decodeblock(in, clrdst);
                in[0]=in[1]=in[2]=in[3]=0;
            }
        }
        i++;
    }
}

void encodeblock( unsigned char in[], char b64str[], int len ) {
    unsigned char out[5];
    out[0] = b64[ in[0] >> 2 ];
    out[1] = b64[ ((in[0] & 0x03) << 4) | ((in[1] & 0xf0) >> 4) ];
    out[2] = (unsigned char) (len > 1 ? b64[ ((in[1] & 0x0f) << 2) |
                                             ((in[2] & 0xc0) >> 6) ] : '=');
    out[3] = (unsigned char) (len > 2 ? b64[ in[2] & 0x3f ] : '=');
    out[4] = '\0';
    strncat(b64str, reinterpret_cast<const char *>(out), sizeof(out));
}

void b64_encode(char *clrstr, char *b64dst) {
    unsigned char in[3];
    int i, len = 0;
    int j = 0;

    b64dst[0] = '\0';
    while(clrstr[j]) {
        len = 0;
        for(i=0; i<3; i++) {
            in[i] = (unsigned char) clrstr[j];
            if(clrstr[j]) {
                len++; j++;
            }
            else in[i] = 0;
        }
        if( len ) {
            encodeblock( in, b64dst, len );
        }
    }
}

void b64_encode(unsigned char *clrstr, char *b64dst)
{
    unsigned char in[3];
    int i, len = 0;
    int j = 0;

    b64dst[0] = '\0';
    while(j < 32) {
        len = 0;
        for(i=0; i<3; i++) {
            in[i] = clrstr[j];

            if(clrstr[j] && j < 32) {
                len++; j++;
            }
            else in[i] = 0;
        }
        if( len ) {
            encodeblock( in, b64dst, len );
        }
    }
}

CustomJWT::CustomJWT(char *secret)
{
    CustomJWT::secretKey = secret;
}

char * CustomJWT::getSecret()
{
    return CustomJWT::secretKey;
}

void CustomJWT::changeSecret(char *secret)
{
    CustomJWT::secretKey = secret;
}

void CustomJWT::encodeJWT(char *string)
{
    //Create header and body
    int len = (strlen(string) + 2)/3*4;
    char str[len];
    b64_encode(string, str);
    while(str[strlen(str) - 1] == '=')
        str[strlen(str) - 1] = '\0';
    String temp = head;
    temp = temp + ".";
    temp = temp + str;
    //Convert passkey to unsigned int
    char* msg1 = CustomJWT::secretKey;
    size_t length = strlen(msg1 + 1);
    char* beg = msg1;
    char* end = msg1 + length + 1;
    uint8_t* key = new uint8_t[length + 1];
    size_t i = 0;
    for (; beg != end; ++beg, ++i)
    {
        key[i] = (uint8_t)(*beg);
    }
    //Initialise HMAC
    Sha256.initHmac(key, length + 1);
    //Convert string to char array
    char temp1[temp.length() + 10];
    temp.toCharArray(temp1, temp.length() + 10);
    //Obtain result
    Sha256.print(temp1);
    uint8_t* hash = Sha256.resultHmac();
    //Encode to b64
    len = ((32 + 2)/3)*4;
    char str1[len];
    b64_encode(hash, str1);
    while(str1[strlen(str1) - 1] == '=')
        str1[strlen(str1) - 1] = '\0';
    temp = temp + ".";
    temp = temp + str1;
    CustomJWT::out = temp;
}

This is the code on the Arduino:
#include <custom_jwt.h>

int i;
char key[] = "tester";
char string[] = "{\"temp\":22.5,\"speed\":25.1}";
CustomJWT jwt(key);

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

void loop()
{
  jwt.encodeJWT(string);
  Serial.println(jwt.out);
}

I have used the SHA256 library that I found in this link with some minor modifications as mentioned here HMAC SHA256 in Arduino use case? so that it can compile:
https://github.com/Cathedrow/Cryptosuite
Any help will be appreciated.

Is the Serial tx buffer overrunning? Try if (Serial.availableForWrite() >= sizeof(jwt.out)) Serial.println(jwt.out);

Nope. Didn't work.

Could it be a memory related issue? Cause the behavior is consistent irrespective the delay() used.

It could be your temp variable causing your heap to turn into swiss cheese. You should re-factor that to use a static buffer.

Yeah, that is possible. I was just writing the JWT decoding script. It worked fine until I got strings involved after which it started showing similar problems. I think I need to rewrite the code to not use strings.

Unrelated, but "JWT" stands for JSON Web Tokens.

Noted. I'll just fix that. Thanks.

As @Majenko had pointed out in the comments, it was temp variable causing the problem. Or rather, strings in general seem to have a bad effect on the memory of the Arduino UNO. After I rewrote the code without using any strings at all, the problem was fixed and the program gave a consistent output.


text:
Arduino + Solar Charger Shield V2.2: Battery and Solar panels selection
first of all I would like to apologize for the, probably very basic and stupid questions for you, but I'm not an electronic expert..
I'm implementing my project using an Arduino Mega 2560 (I need more pins.. this is the most important reason that it drives the Arduino choice)
I'll put my project in an external environment without the electricity source. For this reason my idea is to use a battery with a solar panel as power input to charge the battery.
I also applied some low-power techniques in order to reduce energy consumption as much as possible.
Regarding the solar panel and battery connections I purchased this Arduino Solar Shield.
Solar Charger Shield V2.2 - Seeed Wiki
And here I'm a bit (a lot) confused about the choice of the battery and the solar panel(s) to be purchased.
First of all, my idea is to use multiple (2 or 4) solar panels in order to exploit as much as possible the solar light (multiple positions) but I'm not able (I'm not sure) about the solar panel selection to purchase.
Considering that the maximum current that the solar shield could be delivered is 700mA can I use 4 solar panels like this
https://www.seeedstudio.com/1W-Solar-Panel-80X100.html
(applying also 4 applying 4 diodes to avoid reverse current)?
About this the possible number or size of the solar panels Do I need to consider the amount of th Current at Peak Power?
For example, using 4 solar panels with 170mA as Current at Peak Power, 4*170 = 680 that it's > of the current of the solar shield.
So, is this wrong? Do I reduce the amount of the panels or do I use a different panel?
About the Solar input voltage it's 4.8~6V.
These are the specifications about the solar panel:
Dimensions: 100x80x2.5(±0.2) mm
Typical voltage: 5.5V
Typical current: 170mA
Open-circuit voltage: 8.2 V
Maximum load voltage: 6.4V
Maximum load voltage, Open-circuit voltage are > Solar input voltage. Is it a risk?
About the lipo battery, can I use a battery 3.7v and about the mAh value as high as possible (for example this https://www.amazon.it/2100mAh-Lithium-Polymer-Replacement-Bluetooth/dp/B095BTSMYH/?th=1 ?)
What about the maximum current value (in this case 5A)? Is it ok?
In case, can you suggest me something else?
** *********** EDIT *********** **
As suggested I'm updating my question in order to give additional info about my scenario.
My project will be installed in an external environment (with some atmospheric protections IP67).
The location, from solar irradiation point of view, it's a good place: https://globalsolaratlas.info/detail?m=site&c=40.283716,17.586365,9&a=18.056138,39.997805,18.056138,40.420456,18.535172,40.420456,18.535172,39.997805,18.056138,39.997805&s=40.11799,18.382874
About my project:

I'll have to take the measurements from more sensors:
starting from 1 to 10/15 humidity/temperature (DHT22) sensor;
starting from 1 to 10/15 load cells (4 load cells for each HX711);
I'll send the data using some transmissions using a LORA Shield.

I don't need to retrieve the measurements continuously or in very short periods.
The idea is to sleep my Arduino (in low power with all power sensors disconnected) and, using a RTC DS3231 module, to wake-up it on regular intervals, read the data, send it via LORA and go to sleep again.
The idea is to wake-up every 15 minutes. The time that I imagine about the measurements and the send will take a few seconds (around 30s in case I can approximate it to 1 minute).
And at the moment I don't have the exact measurements about the used current (because I can connect all here.. but I need to purchase the solar panels and the battery in order to make a real test also)..So, the idea now is to approximate.. In case I can adjust something later.
At the moment, measuring the current I have.
around 0.35mA when the Arduino is sleeping.
I probably can reduce it again because I have to remove 2 power led indicators (1 on my DS3231, one on my LORA shield... and, in case, also the power led on my Arduino).
When the Arduino works (live mode) probably I can consider around 90/100mA (probably this is too much) for 30s).
I'm not expert but, using this values I calculated the average about the used current in 1 hour:
((100mA * 4 minutes) + (0,35mA * 56 minutes)) /60 = 7mA/m
420 mA/h
I'll need 5v about the voltage.
I don't have any limitation about the size or the space.
I think that considering 7days without solar power supply or bad water conditions could be enough (in my opinion it's too much)

This is a question that's better suited for the electrical engineering SO, but I can give you some pointers to reword and re-post your question so it's not as broad.
Right now you have a few unknown variables to juggle, so you should be jotting down your thoughts on all of the following:

Where will the unit be placed and/or located? How long do you expect it to go without needing to have its battery recharged?
What is the continuous power consumption? You should know your approximate continuous current consumption and at which voltage you will be running the Arduino and the sensors that you connect to it
What environmental conditions do you expect the unit to experience? Do you have a limiting factor on size or space?
How much are you willing to pay?

You can definitely use multiple solar panels, but you'd have to connect them in parallel (so they maintain the same voltage), and even then, the linked charger shield can only go up to 900 mA of charging current. The 600-700 mA is the supported power output of the battery, or the max current that the shield can provide to your system thru the shield. It can be larger if you lower the system's voltage and stay within the maximum limits of the charger shield.
With regards to your second question, yes, current at peak power is a good metric for your approximations. If you go thru my questions, you will know how much your systems consumes in a day and choose a battery that can discharge no more than X amount of percent per day (depending on the type of battery). Your goal is to be able to charge that battery back at least close to its full capacity--your solar panels or the amount of thereof, as well as your charger, will be dictated by that.
For the Voc of the solar panel - ideally, it would be less than the solar input voltage. It's the voltage of the panel without a load connected to it. Of course, you will have a load connected to the solar panel and thus the typical voltage will be around what's stated, but if you don't want to damage your charger, you have to make sure your SP will be properly loaded under most conditions! It will be safer to connect multiple smaller SPs to get the current that will keep the system up and charge your battery.
With regards to the battery current - you have to check which current it is. Is it the charging current? Output current? Be mindful that you are limited by your charger in this case (3W output, 900 mA charging current).
Hope this gives you a start! It's a good question, but you need to do some more reading and you need to have a better idea of the design for your system before we can be more helpful.
Edit:
Per the updated information...
I will use your estimates, but do consider that for sensors that require power, you can add them and make your calculations more accurate. Also, while LoRA is low-power, it will consume some power too, and you can factor that in.
Let's assume your numbers are correct and the average current consumption averages out to ~ 420 mA/h. Then, if you want to  keep the system alive for 7 days, you'll need a battery with a capacity of 420 mA/h * 24 hours/day * 7 days -> 70,560 mAh or 70.560 Ah. At 5 volts, your system effectively requires 0.420 A/h * 5 V -> 2.1 Watts/hour  (finicky units here, eh?). That would translate to ~353 Watts/week. Also, 5V means you will need a battery that can provide that voltage - a lower voltage battery will not support your system.
The next thing you have to consider then is the battery type - there are a few, but the ones I'd go for are either Li-ion or VRLA (valve-regulated lead acid). There is a tradeoff between cost - Li-ion batteries cost more, but they are typically better in the majority of factors rather than SLA (sealed lead acid) batteries. Doing some googling, you could get a 70-100 Ah SLA/VRLA for ~$200-300 and a Li-ion for ~$400-500. Do note, however, that you can discharge Li-ion batteries more deeply than VRLA ones - it's recommended to keep the charge on the VRLA batteries around ~50% and preferably around ~75% to extend its life. You can discharge Li-ion batteries up to 80% or a bit more and that's fine, they don't suffer as extensive reduction in their lifetime like SLAs.
To put that into perspective, if you have an application that requires ~8 Ah, then ideally for a VRLA you'd need to size a battery such that it doesn't go below 50% for your worst-case application scenario. That is, if you think you'll need the device to run for 7 days without any sun, then you'll need a battery of a 16 Ah capacity or more. Even bigger if you want to extend its lifetime. For Li-ion, aiming at a bit higher than 8 Ah should be fine. For your application, that means getting a SLA battery that's > 140 Ah (unless it's a deep discharge SLA battery) or a Li-ion battery that's close to 70 Ah.
Now, it must be noted that most batteries that provide those capacities typically come in 12V, so you would have to add a buck-converter to convert from 12V to the battery voltage your charger needs (3-4.5V). The charger you linked states that it can provide up to 3W out, which is 600 mA max at 5V. That would support your application as your average current draw is less than 600 mA.
For charging, however, you have to keep in mind that your system, on average, draws 420 mA/hour. So the charger's charging capabilities would actually be 900 - 420 -> 480 mA/hour. That means that based on worst-case considered direct solar irradiation hourly data in the link you provided, you'd get ~ 8 hours of direct sunlight (again, worst case!). So 8 hours you can charge -> 480 * 8 = 3840 mAh and you'll lose 6720 (420 * 16) mAh. That is not good, because you're losing the charge on the battery each day.
That means 2 things -  you have to get a charger that permits a larger charging current within the maximum charging current of the battery rating AND you have to get enough panels (OR a big enough panel) to be able to provide that current. With the panels that you linked, the max current per panel is ~170 mA for the typical voltage of 5.5V. To provide a charging current of ~ 900 mA, you'd need 5 panels, but as mentioned above, that still wouldn't be enough. So, back to the drawing board...
I hope this is enough to help you make more progress on your design.

Thanks for your useful advice. I'll update my question in order to give some additional inputs as you suggested.

I updated my answer as well based on your numbers. Depending whether you truly want to power the system for 7 days without sun (which, based on the link you provided, is probably unlikely, but I didn't look too deeply into the location's weather), you'd have to update your design. Even then, you have to do it. It's an iterative design and maybe creating an Excel sheet/Python script to help you keep track of things will probably make this easier.

Wow, thanks a lot for this info!
Honestly, I didn't get one point: suppose that I would like to use (and suppose that it could be a valid solution)  the solar shield that I linked to in the post. What do I have to consider to understand how many solar panels I can use?
Eg: try to suppose that I have to use the linked solar panel, can I use in parallel how many SP I want?So, What could happen if I connect 5 sp (170mA * 5)? Is it a risk? Would I risk burning it?

It would not be a valid solution for 7 days. It could maybe help you keep the system up for a day, granted that you're getting the 8 hours of sun a day. Each panel can provide 1 watt and in the spec sheet for the charger circuit, it says that it can handle up to 1080 mA (the current resistor is set for the charging current to be 900 mA). 5 SP should be good. If you want to be conservative, you can go with 4 SP - that for sure won't damage the charger. To know for sure you'll have to see what's the typical voltage of the panel at the brightest time of the day and how much current is produced.