text:
Voltage from batteries in series operating on 3 ATTiny, 3 Buttons, and 3 Piezo buzzers
I intend to power three ATTiny45 chips (each requiring around 3.5V) in parallel with 2 pill batteries (namely Maxwell's CR2032) in series (which would come to around 6V). They will each play a sound with a piezo buzzer when a button is pressed.
Now maybe my thinking is wrong but I think dividing the power between the three chips may result in only around 2V delivered to each chip? Does the other components play a role?
So my question is this:

How much voltage is delivered across elements in parallel?
What changes should I do to the wiring to make the most of the voltage?
What kind of resources should I get to make sense of what to do? Cause I thought I was more advanced but this stomped me.

In any case I've added the schematic of what's intended.
[This schematic used to contain resistors to pull the switch but this need was removed with the help of jsotola's input_pullup comment]

simulate this circuit – Schematic created using CircuitLab

the Vcc pin of all three ATTiny45 chips are connected to the same power point ... what voltage would you expect to appear at each Vcc pin?

why don't you enable data pin internal pullup resistor, remove the external pulldown resistor, and connect the switch between data pin and ground?

At first I was hoping for 6V but it looks like it's going to be 2V if I understand well, so would need more power. I actually did not think input_pullup was possible for them AtTinies! Giving it a try now :D

if you are measuring 2 V, then it is because the battery is overloaded ... your schematic shows all three ATTinys connected to the same voltage, which is 6 V

I unfortunately don't own a measuring tool. But ok so that means the voltage does not get divided in 3 because of the parallel chips?

it is the same arrangement as all of the lightbulbs and power outlets in your house ... they all have the same voltage no matter how many are turned on

Alright, I must admit I was dumb for a moment, sorry -_- In terms of amperage though, are 3 chips and 3 piezo disc going to put too much of a strain on 2 pill batteries? How can I find out? In any case @jsotola thank you for the input_pullup you just helped me simplified the process and wiring!

The term "pill battery" is pretty ambiguous.  Please update your question and add the specific batteries being used.  Also, why are you using 100 Ohm resistors on the switches?  When you close the switch you are going to pull WAY more power from the battery than you need to signal an input.  Try something more reasonable like 10K Ohm.

https://www.allaboutcircuits.com/textbook/direct-current/chpt-6/kirchhoffs-voltage-law-kvl/

6V is the absolute maximum rated voltage for the ATTiny45, according to the datasheet. So your at the edge. The ATTiny45 will run just fine at only 3V. So maybe that's an option. Depending on what the piezos require to produce the volume you want.

Coin-cell batteries can't supply a lot of current. If your systems requires more current, you could put additional batterie(s) in parallel. But I'd probably switch to AA batteries instead. 3 AA (Alkaline) batteries in series would give you around 4.5V. Or 4 MiNH AA giving you around 4.8V.

@jwh20 thanks for pointing out! The pill battery I was thinking about is Maxwell's CR2032, added in the question now. Based on jsotola's answer I turned the input as input_pullup and it works fine without the resistor so I will change the schematic shortly.

@Majenko Thank you I am reading on it and it helps make more sense. of how this works. I guess I was closer to Square 1 than I thought ^^"

@Gerben This is very useful comments. I actually don't know what kind of amperage a piezo buzzer require to make louder sounds which is one of my queries, and I will see how to use parallel batteries vs serial. I didn't realize one could actually parallel batteries. I'm actually going for the pill size as it fits better the item, but may have to switch to AAA

Gerben suggested AA batteries, not AAA. AAA batteries don't store very much energy. Better than a CR032 button cell, but still not very much.

If you connect the AtTiny chips in parallel, they will all receive the full voltage from your battery. If you exceed the current output of your battery the voltage will droop.
If the AtTiny chips need 3.5V and you give them 6V instead, it will likely destroy the chips.
The short answer: Don't try to drive microcontrollers directly from batteries. You should get a 3.5V switching power supply. Then you will be able to drive all 3 chips cleanly from your battery. (Switching power supplies are very efficient. They don't waste much power at all.)
Note that button cells produce very small total power (in milliwatt/hours) so they won't drive your processors for very long before they are exhausted. I suggest using 4 AA batteries and a switching regulator instead. The 4 AA batteries would give you a 6V VIN to your voltage regulator, but a lot more total power.

Thank you! I am looking into switching power supplies but they do seem bulky. I also understand that button cells are not very powerful, but what is your thoughts on its lifespan if, say, the chip is mostly asleep?

The math is pretty easy. Calculate current drawn over time. If you draw 1/10 amp for an hour, you have consumed 100 milliamp-hours (mAh) of power from the battery. Batteries are rated by their capacity in milliamp-hours. Voltage regulators waste a little, so you should add some slop for that (look up a given regulator's efficiency to figure out how much waste to calculate.) Look at the "in use" current of your system, and the "asleep" current. Figure out what percentage of the time it will be in each state, and do some algebra to figure out the current used over time.

Here is an article that talks about using sleep mode on an AtTiny45 to reduce power: https://www.re-innovation.co.uk/docs/sleep-modes-on-attiny85/. Note that you also need to turn off various subsystems and set the digital pins to input mode in order to get the lowest power consumption in sleep mode. It sounds like if you do all that, you can get the power consumption down to around  0.2mA. So yes, you can greatly increase the lifespan of your button cells if the AtTiny spends most of its time asleep.

thank you kindly for such a complete answer with side quests too! I've researched a bit the subject around sleep modes but I didn't know it was best to turn pins to input, will do that! Unfortunately the article at https://jira.kdc.capitalone.com/browse/AOM-1290 can't connect? Says Server not found. Thanks a lot again!

Sorry, that was the wrong link.Here is what I meant to post: Note that the more current you draw from a battery, the shorter its lifespan. That is a complex subject. Check this article if your interested: https://www.embedded.com/how-much-energy-can-you-really-get-from-a-coin-cell/


text:
avrdude fuse error when programming ATMEGA328 without crystal
I built several boards with an ATMEGA328 and no crystal a couple of years ago. I programmed them successfully with a bootloader using usbasp, and with a sketch using the Arduino serial interface. I have now made some more, but I get an error message from AVRDUDE when I try to burn the bootloader:

***failed;
avrdude: WARNING: invalid value for unused bits in fuse "efuse", should be set to 1 according to datasheet
This behaviour is deprecated and will result in an error in future version
You probably want to use 0xfd instead of 0x05 (double check with your datasheet first).

I followed the instructions here and I am using the hardware configuration archive referenced on that page: breadboard-1-6-x.zip.
If I reprogram the bootloader on a device that does have a crystal, it works if I select Arduino Pro/Pro Mini (3.3V, 8MHz), but fails with the message above if I select the breadboard specified in the boards.txt from  breadboard-1-6-x.zip.
There are no other error messages, but... if I turn on verbose, it works.. turn verbose off and it stops working again. Maybe verbose mode modifies the timing enough to make it work.
I know that you can use the -B option to slow down avrdude when you run it from the command line: is there a way of doing the same thing from within the Arduino environment?

The above message is simply a warning, not an error.  I believe there is some other error showing earlier in your console that you have not shown.  Please check for that.

@jwh20 I did some more tests, and have added the results to my question.

Just FYI and in case you don't know it already: there's a very useful tool here: https://www.engbedded.com/fusecalc/

The ATMega328P datasheet has the following table in it:

The top 5 bits of the of the Extended Fuse Byte are default 1 and are reserved.  You're not really supposed to change them, since they might be used in the future for a 328P-like part and setting them to something other than 1 could have unexpected results.  In the 328PB variant bit number 3 is used for "Disable Clock Failure Detection".
The lower three bits of 0xFD and 0x05 are both 0b101.  In other words, taking into account only the bits you should be setting, for the BODLEVELn fuses, they would have the same effect.  But you are being WARNED that you should be using 0xFD rather than 0x05 for the above reason.
The boards.txt that comes in the breadboard-1-6-x.zip has a line that looks like this:

atmega328bb.bootloader.extended_fuses=0x05

You could change this yourself by editing the file, but really for what you're doing I'd recommend MCUdude MiniCore which is comparatively up to date.  If nothing else, its boards.txt file has been written with the correct fuse values.  You can see there for a plain 328P (not PB) which does not support clock failure detection, the CFD bit is just hardcoded to 1 in the file.
The message you're seeing is a "WARNING" through, rather than "ERROR".  The distinction being that warnings don't actually stop you from continuing.  It is likely that if you're having a problem isn't not really because they've incorrectly specified the high-order bits of the fuse.  If it's halting, it may be arduino-builder see a non-zero exit code for avrdude and thinking this means "ERROR" rather than "WARNING", in which case this problem will go away if you edit the boards.txt file (or adopt MiniCore) such that no longer produces the warning.
Unless you've brought the effective system clock below 1MHz, probably lower still, it's not likely that you'll need to change from the default ISP clock rate.  If you do though, that can also be done by editing board package files.

source: Stack Exchange

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

sort: votes


text:
sdFat and Serial conflict?
I am using the sdFat library to manage an SD card with an ATmega1284p @ 8MHz internal clock. I have come across a strange issue in my system, and I created the smallest sketch that shows the problem: What I do is, that i call sd.begin() in the setup(), and then in Loop, I open a file and write the word "test". After that, I close the Serial and I turn off the SDcard's power (TLV_EN signal). After a while I re-enable the power and restart Serial. The second time I try to open the file to write "test", it fails. If I, however, comment out the Serial.end() and Serial.begin() commands, everything works as expected.
Here is the code:
#include <Arduino.h>

//Power Management Libraries
#include <avr/power.h>
#include <avr/wdt.h>
#include <avr/sleep.h>

//SD Card
#include "SdFat.h"
#include "sdios.h"
#include "FreeStack.h"
#define SD_FAT_TYPE 1
const uint8_t SD_CS_PIN = 3;              //SPI CS pin of SD card
#define SPI_CLOCK SD_SCK_MHZ(2)

// Try to select the best SD card configuration.
#define SD_CONFIG SdSpiConfig(SD_CS_PIN, SHARED_SPI, SPI_CLOCK)
SdFat32 sd;
File32 file;

const char fileName[]="COMPMEAS.TXT";     //8.3 supported filenames: https://en.wikipedia.org/wiki/8.3_filename
int count=1;

//PSU Enables
const uint8_t TLV_EN=1;

// Serial output stream
ArduinoOutStream cout(Serial);
//------------------------------------------------------------------------------
// Store error strings in flash to save RAM.
#define error(s) sd.errorHalt(&Serial, F(s))
//------------------------------------------------------------------------------

void setup() {
  pinMode(TLV_EN, OUTPUT);    // sets the digital pin 13 as output
  digitalWrite(TLV_EN,HIGH);      //TLV high enable
  delay(100);
  Serial.begin(38400,SERIAL_8N1);
  Serial.println();
  Serial.println();
  Serial.println(F("Hello!"));
  Serial.println();

  //SD Setup
  Serial.print(F("- Initializing SD card..."));
  while (!sd.begin(SD_CONFIG)) {
    Serial.println();
    Serial.print(F("SD initialization failed. Retrying in 2 seconds..."));
    delay(2000);
  }
  Serial.println(F("done."));

  Serial.println(F("- Setup Complete."));
  Serial.println(F("=================================================="));
  Serial.println();
  delay(5000);
}

void loop(){
  Serial.print("Loop: ");
  Serial.println(count);
  count++;
  if (!file.open(fileName, O_RDWR | O_CREAT | O_APPEND )) {
    Serial.println(F("- SD open failed!"));
  }
  else{
    Serial.println(F("- SD open success!!!"));
    if(file.write("test", strlen("test"))!=strlen("test")){
      Serial.println(F("- SD write failed!"));
      error("write failed");
    }
    else{
      file.flush();
      Serial.println(F("- SD write success!!!"));
    }
    file.close();
  }
  delay(1000);
  Serial.end();
  delay(1000);
  digitalWrite(TLV_EN,LOW);      //TLV high enable
  delay(1000);

  digitalWrite(TLV_EN,HIGH);      //TLV high enable
  delay(1000);
  Serial.begin(38400,SERIAL_8N1);
  while(!Serial){
  }
  delay(1000);
  Serial.println("----------");
  delay(5000);
}

Here is the result on console:
Hello!

- Initializing SD card...done.

- Setup Complete.
==================================================
Loop: 1

- SD open success!!!
- SD write success!!!
----------

Loop: 2

- SD open success!!!
- SD write failed!
error: write failed
SdError: 0X1D,0XFF

I tested your code almost verbatim using an SDCard shield that was designed to work with the UNO and so I used an UNO.  The only change to the code was to SD_CS_PIN.  This was using SdFat 2.0.4.  I have run it for at least 20 iterations reporting success on both open and write.  I have not investigated further yet.  Thought I'd just contribute that information for now anyway.  It seems unlikely that being a ATMega1284P will play into this, but perhaps.  If I happen to find one I may try it later.

Regarding your SdError: 0X1D,0XFF, this is apparently a read timeout.  Not sure what to do with that information though.  Maybe seeing how you've wired it would help.

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


text:
Host a webserver on an ESP32D that has a hyperlink that triggers an Arduino song through a buzzer
I would like to use my ESP32D to create a wireless access point and host an HTML page that has a hyperlink and a few other things on it that triggers an Arduino song (rickroll), and plays it through a buzzer.
I just need to know how to host the webserver and make the trigger hyperlink work, right now the HTML is set to send "trigger" whenever the link is pressed.
HTML file: https://pastebin.com/sGmPPVYG
Arduino-song: https://github.com/robsoncouto/arduino-songs/blob/master/nevergonnagiveyouup/nevergonnagiveyouup.ino

Just to be clear the hyperlink is supposed to make the song play

this might help ... http://www.martyncurrey.com/esp8266-and-the-arduino-ide-part-6-javascript-and-ajax/

this is more current technology ... https://randomnerdtutorials.com/esp32-websocket-server-arduino/

Re “Rick Roll!/a>”: you mean “Rick Roll!”.

This is a partial answer. I assume you already know how to build a Web
server on you ESP32, and how to react to client requests. If not, there
are tutorials available on the Internet. Here I will specifically
discuss the issue of the hyperlink.
You wrote:
Click Here To Trigger The Rick Roll!/a>

Not only the closing tag is incorrect (it should be ), but such a
link is likely not what you want. The semantics of an hyperlink is “go
fetch that resource and display it here, replacing the current page”.
Unless you do have a displayable resource (Web page, image...) on your
server actually named “trigger”, you do not want an hyperlink. You want
a clickable item that may look like an hyperlink and, when clicked,
triggers a request to the server, but without replacing the current
page.
So I would start by replacing the link by a generic container:

Click Here To Trigger The Rick Roll!

Then, style it like a link. I don't quite like the underlining, but you
can add it if you wish:
#trigger {
  color: blue;
  cursor: pointer;
}

Then, within a


text:
What pins to use on a Teensy to get data from multiple peripherals?
I'm using a Teensy to keep records on the location, speed, altitude, and direction of a weather balloon I'm hoping to launch. I have an Adafruit LSM9DS1 and a Ublox NEO-M8N with compass (HMC5833L) so to get all the data from these I need to connect to a total of 6 pins to get the data. I also want to use a Pixhawk radio telemetry unit to send these data to the ground so I can see them in realtime, so that will involve at least 2 more pins I believe.
The Teensy appears to have plenty of IO pins for all of this, but I've noticed that in all the libraries I've installed to try to use with these things, the pins to use aren't explicitly set. The libraries I've played with include the Adafruit LSM9DS1 library, NeoGPS, Pixhawk Arduino link, RadioHead, Grove HMC5833L, and others. I've been able to get some serial data in by using pins 18 and 19, but I can't attach all the periperhals to the same pin.
It feels like I'm missing something very basic here but I haven't been able to figure out how to use these libraries with inputs on different pins. Even when I look into the code of the libraries themselves, I can't find where the pins are being set. Most of the documentation that mentions which pins things use is written for specific Arduino models, like the Uno, and don't mention the Teensy.
What pins do I use if I want to read and write on more than one peripheral from my Teensy? How can I get data on more than just the two "default pins" that these libraries seem to expect?

You need to look at each device/library, there is no standard for changing default pins. You might not even need to change them for e.g. I2C where several peripherals can be on the same bus if no address conflict.

The first thing to look at when determining which pins to connect a peripheral to is what protocol that peripheral uses - e.g. I2C, SPI, analog voltage via ADC, etc. The Teensy pinout for the version you have (e.g. the 3.2 pinout) lists which pins can function as which protocol functions. For example, pin 19 can act as an analog input (A5) or as part of the 0th I2C unit, SCL0. Your LSM9DS1 can use I2C, so you could connect it to that I2C unit. Typically Arduino libraries will default to using the default peripheral type. In Arduino, an I2C bus is called Wire, so a library for an I2C device will typically use the Wire device. Well-written libraries will also let you pass in your own peripheral, which is how you change the pins. Each library will do this differently.


text:
MAX31865 & NodeMCU RTD Low Threshold and Exception
I've got a NodeMCU V1 and a MAX31865 with a PT100 attached.  When using the example arduino code, it seems to log out the correct values but with an RTD Low Threshold error like so:
RTD value: 8068
Ratio = 0.24621582
Resistance = 105.87280273
Temperature = 15.09
Fault 0x40
RTD Low Threshold

The loop will continue for a few iterations and then throw an exception, before resuming logging out of the values above
The exception reads:
--------------- CUT HERE FOR EXCEPTION DECODER ---------------

Soft WDT reset

>>>stack>>>

ctx: sys
sp: 3fffed00 end: 3fffffb0 offset: 01a0
3fffeea0:  38fe9521 00000000 3ffe8938 00000030
3fffeeb0:  401015ea 3ffe88f4 004ae1cb 40233b68
etc etc etc

The code is as follows.
#include <Adafruit_MAX31865.h>

// Use software SPI: CS, DI, DO, CLK
Adafruit_MAX31865 thermo = Adafruit_MAX31865(D4,D1,D2,D3);
//Adafruit_MAX31865 thermo = Adafruit_MAX31865(D4);

#define RREF      430.0
#define RNOMINAL  100.0

void setup() {
  Serial.begin(9600);
  Serial.print("Adafruit MAX31865 PT100 Sensor Test!");
  thermo.begin(MAX31865_3WIRE);  // set to 2WIRE or 4WIRE as necessary
}

void loop() {
  uint16_t rtd = thermo.readRTD();
  Serial.print("RTD value: "); Serial.println(rtd);
  float ratio = rtd;
  ratio /= 32768;
  Serial.print("Ratio = "); Serial.println(ratio,8);
  Serial.print("Resistance = "); Serial.println(RREF*ratio,8);
  Serial.print("Temperature = "); Serial.println(thermo.temperature(RNOMINAL, RREF));

  // Check and print any faults
  uint8_t fault = thermo.readFault();
  if (fault) {
    Serial.print("Fault 0x"); Serial.println(fault, HEX);
    if (fault & MAX31865_FAULT_HIGHTHRESH) {
      Serial.println("RTD High Threshold");
    }
    if (fault & MAX31865_FAULT_LOWTHRESH) {
      Serial.println("RTD Low Threshold");
    }
    if (fault & MAX31865_FAULT_REFINLOW) {
      Serial.println("REFIN- > 0.85 x Bias");
    }
    if (fault & MAX31865_FAULT_REFINHIGH) {
      Serial.println("REFIN- < 0.85 x Bias - FORCE- open");
    }
    if (fault & MAX31865_FAULT_RTDINLOW) {
      Serial.println("RTDIN- < 0.85 x Bias - FORCE- open");
    }
    if (fault & MAX31865_FAULT_OVUV) {
      Serial.println("Under/Over voltage");
    }
    thermo.clearFault();
  }
  Serial.println();
  delay(10000);
}

simulate this circuit – Schematic created using CircuitLab


text:
Various Bluetooth HC-06 modules erratic in different ways
I am trying to make a Bluetooth controlled robot and have troubles with the Bluetooth modules. I used  3 HC-06 Bluetooth module. All of them have different problems.

I could not find the 1st HC-06 under the list of Bluetooth devices in the settings.
The 2nd HC-06 could be paired with the phone but I could not send the message on the Bluetooth terminal app (The error message from the app is below).
The 3rd HC-06 could be paired and I could send a message but the message was not registered on the Arduino nor on serial monitor. On the Bluetooth terminal app, the message was received but not replied.

What could be the problem? I'm pretty sure my connections are correct as I have checked them and they used to work.

Check your power supply for the BT module. Try 1000uF or more decoupling close to the module.

why would putting capacitors around the bluetooth help, is it also subject to EMI?


text:
Resistor - Correct value for optocoupler, but dont have that size
I am making a shutter for my camera using a Arduino and an optocoupler.
I understand most of most parts, but unsure about the resistor because I don't have the correct size. 5V will be coming from the Arduino, and the 4N35 will need 1.3V 10mA. This leads to a 380Ω resistor.
Now I only have 100Ω, 220Ω, 330Ω, and 1kΩ resistors. I have read I shouldn't use anything lower than 380Ω and only use higher but 1kΩ seem a little too high haha.
Just looking for some pointers please.

1kΩ will be just fine. But if you want lower you could take two 1kΩ and place them in parallel - that will give you 500Ω.
BTW - 1kΩ will give you ((5-1.3)/1000=) 3.7mA through the diode of the optocoupler, and 500Ω will give you ((5-1.3)/500=) 7.4mA.

Thank you, works perfectly. Still got a lot of learning to do haha.

And 330 will give you just over 11mA, I'd go with that

Agreed, absolute max current for 4N35 is IF < 50 mA. But if IF= 3.7 mA works reliably, as there's no current required on the output side, I'd take that.


text:
ArduinoJSON define as extern
My sketch contains 2 .h files. one defines
on 1st .h file:
#define JSON_SIZE_IOT 400
#define JSON_SIZE_SKETCH 300
StaticJsonDocument<JSON_SIZE_IOT> paramJSON;
StaticJsonDocument<JSON_SIZE_SKETCH> sketchJSON;

and other need to define paramJSON and sketchJSON as extern
on 2nd .h file:
extern JsonDocument paramJSON;
extern JsonDocument paramJSON;

but I get this error:
error: conflicting declaration 'ArduinoJson6172_91::StaticJsonDocument<400u> paramJSON'
 StaticJsonDocument<JSON_SIZE_IOT> paramJSON;

....
: previous declaration as 'ArduinoJson6172_91::JsonDocument paramJSON'
 extern JsonDocument paramJSON;

please look at the code snippets that you posted ... the problem appears to be obvious ... the copy'n'paste bug strikes again

@jsotola do you mean JsonDocument instead StaticJsonDocument? it does not work either way

no ... you made a duplicate declaration

@jsotola See edit which code snippet belong to which .h file ( unless I don't understand why it is a duplicate )

don't do variable definitions in h file which is included in multiple translation units

@Juraj I understand what you say, it can be done, but it is very not clear way. Does it mean that it is impossible to do so ?

a variable definition should always be in cpp. in h only if you know what you are doing. but in to extern: it must be the same type including the template types.

@Juraj Thank you. My .h file sums each functionality used in sketch. BTW, there is no .cpp in my case, only .ino and .h's. How would you have done it if there was a .cpp file ?

then put it in ino or add a cpp file

For an extern the whole definition has to match the "master" definition.
So if you have:
StaticJsonDocument<JSON_SIZE_IOT> paramJSON;

then you extern has to be:
extern StaticJsonDocument<JSON_SIZE_IOT> paramJSON;

Of course you have to make sure your JSON_SIZE_IOT is the same for both - so it's best if that comes from a common source.
This is known as explicit instantiation declaration and you can read more about it in the Class template C++ reference.

Doesn't StaticJsonDocument a template ? that is why I used JsonDocument . Since JSON_SIZE_IOT defined using #define - how can I use it? ( pre-processor won't pass extern)

@Guy.D You can't extern to a different type. If you want to have something else then give yourself a pointer to it and do a cast to that pre-defined object.


text:
Adding zero padding to decimal values
I want to add zero before the float number like this:
010.0

The code I'm using is this:
if(value < 10){
  lcd.print(F("0"));
}

lcd.print(value);

But when the value is exactly 10, it adds the zero anyway:
0010.0

I tried something like this but haven't had any luck:
if(value < 10 && value != 10){
  lcd.print(F("0"));
}

How can I solve this issue?

- EDIT:
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3B, 16, 2);

#define turnOff 3
#define turnOn 2
#define gateStatus 8
#define btn 4

float ADC0, current, ADC1, voltage, ADC2, temp, watt;
int8_t state, btnState, btnPushed, btnToggle, lcdClear;
uint32_t deBounce = 0;

void setup() {
  analogReference(EXTERNAL);
  pinMode(turnOff, OUTPUT);
  pinMode(turnOn, OUTPUT);
  pinMode(gateStatus, INPUT);
  pinMode(btn, INPUT_PULLUP);
  pinMode(13, OUTPUT);
  lcd.begin();
}

void loop() {
  digitalWrite(13, LOW);
  state = digitalRead(gateStatus);
  btnState = digitalRead(btn);

  if (!btnState) {
    if (millis() - deBounce > 200) {
      btnPushed = 1;
      deBounce = millis();
    }
  }
  if (btnPushed && btnState) {
    btnToggle = 1;
  }
  if (btnToggle && state) {
    digitalWrite(turnOn, HIGH);
    delay(5);
    digitalWrite(turnOn, LOW);
    btnToggle = 0;
    btnPushed = 0;
  }
  if (btnToggle && !state) {
    digitalWrite(turnOff, HIGH);
    delay(5);
    digitalWrite(turnOff, LOW);
    btnToggle = 0;
    btnPushed = 0;
  }

  for (int i = 0; i < 500; ++i) {
    ADC0 += analogRead(A0);
  }
  ADC0 /= 500;
  current = ADC0 * (2.5 / 1023.0);
  current = current / 0.211;

  for (int i = 0; i < 500; ++i) {
    ADC1 += analogRead(A1);
  }
  ADC1 /= 500;
  voltage = ADC1 * (2.5 / 1023.0);
  voltage = voltage * 20.2;

  for (int i = 0; i < 100; ++i) {
    ADC2 += analogRead(A2);
  }
  ADC2 /= 100;
  temp = ADC2 * (2.5 / 1023.0);
  temp = temp * 100.5;

  watt = voltage * current;

  lcd.setCursor(0, 0);
  if(voltage < 10){
    lcd.print(F("0"));
  }
  lcd.print(voltage);
  lcd.setCursor(5, 0);
  lcd.print(F(" V"));

  lcd.setCursor(9, 0);
  if(temp < 10){
    lcd.print(F("0"));
  }
  lcd.print(temp, 1);
  lcd.print((char)223);
  lcd.print(F(" C"));

  if (state) {
    lcd.setCursor(0, 1);
    lcd.print(F("   OUTPUT OFF   "));
    lcdClear = 1;
  }

  else {
    if (lcdClear) {
      lcd.clear();
      lcdClear = 0;
    }
    lcd.setCursor(0, 1);
    if (current < 10) {
      lcd.print(F("0"));
    }
    lcd.print(current);
    lcd.setCursor(5, 1);
    lcd.print(F(" A"));

    lcd.setCursor(9, 1);
    if (watt < 10) {
      lcd.print(F("0"));
    }
    if (watt < 100) {
      lcd.print(F("0"));
    }
    lcd.print(watt, 1);
    lcd.setCursor(14, 1);
    lcd.print(F(" W"));
  }
}

Then something else in your code is wrong. The if statement check for value being snaller than 10. If value is exactly 10, it will not execute. Please show a minimal compilable example code, that shows your problem. Then we can try to reproduce and solve your problem

@chrisl the code wasn't too long so I added the whole code to the question.

I currently cannot try that out myself, but you could try writing 10.0 (which is a float) instead of 10 (which is an int). And have you tried also printing the values directly to the serial monitor for debugging? Or inserting serial prints in the if statements, to check, if they get executed?

@chrisl I tried that and also 10.000 and 9.999. still the same! I can't print to serial monitor, it's standalone with no USB interface...

This looks like a rounding problem. If the number you want to print lies
within the open interval (9.95, 10), the condition value < 10 is true,
as the number is strictly less than 10. Obviously, value != 10 is also
true. Yet, lcd.print(x, 1) will round the number to the closest
multiple of 0.1, which in this case is 10.
I see no better solution than handling the rounding yourself. I would
use integers for the comparison, as they avoid all rounding issues:
// Print a float to the LCD in 2.1 format (xx.x), left padded with a
// zero if needed. Assume x < 100.
void printPadded(float x)
{
    // Left pad.
    int i = round(x * 10);
    if (i < 100) lcd.write('0');

    // Print the rounded value.
    lcd.print(i * 0.1, 1);
}


text:
Will the L9823 work at 3.3 V with Wemos boards?
Or is it 5 V only?
https://www.st.com/en/automotive-analog-and-power/l9823.html
I see in the data sheet it says under Absolute Maximum:

Supply Voltage:  VDD -0.3 V to 7 V

Then, under Electrical Characteristics:

4.5 V < VDD < 5.5 V; unless otherwise specified.

Is the Electrical Characteristics section just listing values for an example voltage of 5 V, or does the chip need 5 V to work properly?

the datasheet states that the chip may perform an undervoltage reset when supply voltage drops below 3.95 V ... but the undervoltage reset is not not guaranteed until the voltage drops to 2.5 V ... i assume that it is a manufacturing variation .... you would have to screen devices to find one that allows the voltage to drop below 3 V before resetting ... even then, it is unclear if the device would operate at 3.3 V

No. The undervoltage puts it in reset at 3.95V per the ST data sheet. It is a  5v only part with a wide tolerance on VCC. It was designed many years ago as an automotive part. It is a very nice part and performs well.

The Absolute Maximum section in a datasheet describes what will damage a component, or shorten its life span; it does not state the acceptable range of values that will make the component work as expected. It is not a design guideline.
You can deduce from these Absolute Maximum data that a Vdd of 3.3 V will not damage the IC, but not that it will work well at that voltage.
In this case, the datasheet says that all Electrical Characteristics are specified at a Vdd of about 5 V. This by itself does not necessarily mean the IC won't work at lower voltages, but it is a hint.
But, further on in the Electrical Characteristics, it is stated that the IC could reset at any Vdd between 2.5 V and 3.95 V, so the IC will very probably not work reliably at 3.3V.


text:
Problems with green TWI (I2C) port on Arduino Braccio Shield
Summary: The green TWI/I2C port on my Braccio shield I2C port hasn't worked for me so far. Looking for advice or information please.
Detail:
I'm using the Arduino (Tinkerkit) Braccio robot arm for self education. It comes with a Uno based Braccio Shield. Tinkerkit no longer seems to be in business and documentation is a bit scarce. The shield uses KF2510 style connectors for servos (orange), inputs (white), serial (yellow) and importantly for my question a TWI/I2C port (green).

The green four pin TWI/I2C connector provides GND, +5V, SDA (A4), SCL (A5). However the SDA and SCL connections are reported to not be direct, but that "a very tiny chip (located next to the I4 connector) buffers between the green connector and the Arduino pins SDA and SCL" . A photo of the chip described is below.

Contrary to the reports of a "buffer" studying the schematic shows a level shifter PCA9306TI and two sets of 10K pullup resistors (R7,R8 and R11,R12) on the bus on both sides of the chip. VREF2 on the outboard side of the chip has a R9 220K resistor to +5V.

The other side of my I2C connection was an Arduino Pro-mini 5V. I was never able to get it working using the green port described, but it works fine directly hooked into SCL and SDA bypassing the level shifter.
My questions (sorry for the long lead up) are:

Has the green TWI port been level shifted to expect ~3V? (Only really came to this conclusion writing this all up clearly).
If I want to change the green TWI port to 5V I2C can I replace R9 220K with a zero ohm jumper?
The 10K pullups (R7,R8 and R11,R12) seem larger than anticipated (I had anticipated about 4.7K for 5v or about 2.4 for 3V)? Can they be removed and left open if I have a single set of pullups elsewhere on the bus? Or better suggestions?

Thanks!
Update 2021/01/30
Well my I2C debugging skills are improving researching this! As a test bed I set up a clean working I2C bus with two MCU's running the Arduino Example Master/Writer Slave/Receiver sketches by Nicholas Zambetti. I tested the I2C signal on the oscilloscope to make sure it was clean. All good. To that test bed I connected the Braccio shield (5V, GND, SCL, SDA). Connecting the Braccio shield changes the I2C signal in interesting ways, with partial strength (runt) pulses, and round shoulder slow rises. Connecting via the green TWI port seems to accentuate the runt pulse aspect. Also interesting the oscillscope was still able to decode the signal. Still working on figuring this out.
Pic 1. First test - SCA and SCL connected via pin headers in top left of shield picture above.

Pic 2. Second test - SCA and SCL connected via green TWI port

Pic 3. Clean Signal (no Braccio Shield connection)

is your Uno a R3 with the SDA, SCL header pins?

@Juraj, Yes a genuine Uno R3. The additional SDA and SCL pins are present next to the AREF pin, and it is actually these I'm connecting to directly to achieve the work around.

I fear we have a colloring issue. Your green is my blue ;-).
I have looked into the data sheet of the level shifter IC and TI only describes scenarios with a higher voltage on the right side and a lower voltage on the left side. Also the allowed voltage translations do not contain 5V to 5V. So I would say in equal voltage scenario the Level shifter may not work.
Answers

Q1: The TWI port is always used with 5V (not ~3V). The Arduino that is supposed to use the shield might be a 3.6V version (like a DUE or M0). Perhaps the TWI port is only intended for this use case: A low voltage arduino with a 5V device. I admit: This should be noted in the documentation. So perhaps Braccio shields work outside the specification and may works under normal circumstances. But meanwhile I begin to understand why they are out of busines ;-).

Supplement: the SCL and SCL signals are routed to two pairs of header pins as they are connected to different pins on different Arduinos. On a UNO you can not use A4 and A5 for analog as they are used for I2C for example. Do you use A4 A5 in any way? Or did you connect the second I2C pin pair in the power header when you had used the TWI connector? (rhetoric question ;-) of cause I will change the answer if you give me more information ;-) )

Q2: The 220k resistor is necessary as it limits the current through the chip if VRef1 is lower than VRef2. Removing it with 0 Ohms would be a bad idea. As long as 5V is used on both sides, nothing would happen. But if Vref1 is 3.6Volts, you would waste energy and perhaps the chip would take part at a grill fest.

Q3: Most I2C devices breakout boards already use their own pullup resistors. So lowering the pullups is not the best idea. -> too high current with LOW signals as the devices pull ups and the braccio pull ups are set in parallel.
-- There is a chance, that the resistors are too large for devices that don't use their own pull ups, but at a 100kHz bus speed I don't think, this could cause an issue.

BTW: You do not need to exchange the pull ups, if you insist to try out different values. Just use parallel resistors to lower the resistance (10K || 10K -> 5K) [|| means connected in parallel] (R || Rp -> (R*Rp) / (R+Rp))


text:
Valid options for output port on Mega 2560
I would like to adopt this library on an Arduino Mega2560:
https://github.com/gueei/DShot-Arduino
However, the macro DSHOT_PORT needs defined for the Mega2560 here:
https://github.com/gueei/DShot-Arduino/blob/master/src/DShot.h
So I need to add a #if defined(__AVR_ATmega2560__) macro to that DShot.h header, however, it is not clear to me where to lookup the port mapping on a 2560 mega.  I'm looking directly at the schematic itself here:
https://www.arduino.cc/en/uploads/Main/arduino-mega2560-schematic.pdf
And understand that the 'ports' are groupings of IO where the pins are described as P?#, ? being the port letter and # being 0-7.
So what are my valid options?  It appears that some ports (A,C,L) aren't pinned at all, some (D,J) only a few pins, and just about none of them (except K/F) have all port pins utilized.  Also, I can see most of these pins are reserved for some type of functionality (analog, SPI, etc).  I'm assuming I'm looking for a port with available pins reserved for PWM, such as Port B (pins 10-13 are PWM).  Would this be correct?

According to the PDF you link to, port A is mapped to digital pins 22-29 on the board, port C to 30-37, port C to 42-49.

You don't care about extra functionality of the pin unless you do need that extra functionality. Why would you want PWM?

Thanks for clarification, I did read the drawing right.  I assumed the lines that stopped early where not completed on the drawing (PDF search function failed me).
Also, w/ respect to the additional functionality, I assumed PWM because DShot is often a replacement for PWM (as far ESC's).  Does other functionality prevent me from using the pin (ex - pin 22 is PB3 'MOSI' SPI signal)?

It would seem this library needs a single pin to communicate. So it
doesn't really matter whether the port you choose has only a few pins
available. Also, you do not care that some pins can have extra
functionality, like SPI, I2C, etc, unless you do plan to use that
functionality.
There is one think you should be aware of: the library uses the in and
out assembly instructions to access the port. These instructions can
only access the ports that are mapped in the regular I/O space of the
microcontroller, not those that are in the “extended I/O” space. In the
case of the ATmega2560, this means you can use any of the ports A
through G, but you cannot use H, J, K nor L.

Thank you for feedback!  Sounds like I can likely use most any pin on the board.


text:
IDE compiles incorrect file after renaming them
I am using the stand alone Arduino IDE to build some projects, and I have a few .cpp files now, but during work I renamed them .c and back. When compiling the project now (with Ctrl-R), it is still trying to compile the .c files. But, I don't even see them on disk!
Changing the .cpp makes no difference. I am used to IDEs having some kind of project file, or a "clean project" option, but I cannot find those here.

are the files open in tabs in IDE? IDE takes source code from the editors. a 'sketch' is a folder with source files. all are compiled

The Arduino IDE copies all files to a tmp folder. Try restarting the IDE.

A restart did it.

The Arduino IDE does not monitor changes to open files. So if you rename or change a file externally (i.e. in another editor), the IDE won't update the file contents. Therefore, after such a change, a restart might be necessary.
Note: If you use another editor to change a file but only compile (and upload) in the IDE, this will work, because the compiler correctly reads the updated file. But editing the source in the IDE and an external editor at the same time might overwrite either change!


text:
Run multiple function with different argument/return structure by one function pointer
Edit:
I tried a simple code in Arduino IDE which should've done in the first place instead in doing it in a desktop compiler. Because the results are different by experiment. In the desktop C compiler, it's working and bypassing the code without much problems, just one or two warnings.
But in Arduino IDE, it's not acceptable and gives error.
This is the code:
// functions
void function1(uint8_t x, uint8_t y){
  int z = x + y;
  Serial.println("function1\n");
  Serial.println(z);
}
uint8_t function2(uint8_t x, uint8_t y){
    Serial.println("function2\n");
    return 1;
}

void (*fun_ptr)();

void setup() {
  // put your setup code here, to run once:

  Serial.begin(9600);
  fun_ptr = (void (*)())function2;
  int value;

  value = fun_ptr(1,2);

}

void loop() {
  // put your main code here, to run repeatedly:

}

Of course you get that warning, since fun_ptr is a pointer to a function without any parameters, while fun1() is a function with a uint8_t parameter. Though it is unclear to me, why you are doing this, since you want to implement your FSM with a switch case. What structure do you want to build with the function pointer? Please show it the the context of your FSM, then we can try give you a good answer

I edited the post.

Note that the only place you call fun_ptr(), you do not supply any argument. Thus it wouldn't even make sense for fun_ptr to reference a function that does expect arguments.

OK, I'm trying to fix the code for now and thanks for the note.

I figured that I can redesign the question from all over, is it a good idea or I better start a new question ?

the auto type, templates/macros, and "void pointers" can be your best friends in this case

yeah, the auto is a C++ type, I'm focusing on C, I don't know why I don't want to use C++ right now ! But what I think most the time is that I want to test everything I can do in C. I want to develop a task manager, now I figured out using array of function pointers + array of bool locks to each related number of function pointer. Managed in the task manager function.

I was able to return data from a void function pointer to a function that returns uint8_t, but my problem now is with a function that has multiple arguments.

It looks to me like you are trying to find the right answer to the wrong
question, typical of an XY problem. In the example you provide in
your own answer, you call the function pointer right after having set
its value. In this case, there is no use to the function pointer, as you
could directly call either read_chars() or write_chars().
Obviously, this is just because that example is excessively simplified.
In a more realistic use case, you would set the function pointer in one
part of the code, and call it in a completely different part. Assuming
the functions and the pointer are defined like this:
void (*fun_ptr)();

void read_chars(uint8_t address) {
    printf("address of array is 0x%.2x\n", address);
}

void write_chars(uint8_t row, uint8_t col, const char *str) {
    printf("[%d, %d]: %s\n", row, col, str);
}

One section of the program sets the pointer:
// Here we learn what action should be performed.
if (should_read()) {
    fun_ptr = (void(*)()) read_chars;
} else {  // should write
    fun_ptr = (void(*)()) write_chars;
}

and a different section calls it:
// Here we have to perform the action.
if (fun_ptr == (void(*)()) read_chars) {
    ((void(*)(uint8_t)) fun_ptr)(1);
} else if (fun_ptr == (void(*)()) write_chars) {
    ((void(*)(uint8_t, uint8_t, const char *)) fun_ptr)(
            1, 1, "messaage0");
}

Note that this second section must know what function it is calling
in order to pass the correct arguments. Hence the if...then test. Note
also that, in order to have valid C++, you must explicitly cast the
function pointer before calling it. This gets very clumsy, and it is a
lot more convenient to store this information (what function should be
called) in an enum rather than a function pointer:
enum {
    CALL_NONE, CALL_READ_CHARS, CALL_WRITE_CHARS
} what_to_call = CALL_NONE;

which would be used like this:
// Here we learn what action should be performed.
if (should_read()) {
    what_to_call = CALL_READ_CHARS;
} else {
    what_to_call = CALL_WRITE_CHARS;
}

// ...

// Here we have to perform the action.
if (what_to_call == CALL_READ_CHARS)
    read_chars(1);
else if (what_to_call == CALL_WRITE_CHARS)
    write_chars(1, 1, "messaage1");

That being said, it is often the case that when it is time to perform
the action, the part of the code responsible of doing so does not know
what arguments should be passed, and this information is more readily
available at the time when when learn what action should be performed.
This is a quite common situation, and a standard C idiom in this case is
to give the function a void * parameter that it will cast to the
appropriate type in order to retrieve the data it needs. For instance:
void (*fun_ptr)(void *);
void *fun_ptr_data;

void read_chars(void * data) {
    uint8_t address = * (uint8_t *) data;
    printf("address of array is 0x%.2x\n", address);
}

struct write_chars_data {
    uint8_t row;
    uint8_t col;
    const char *str;
};

void write_chars(void *data) {
    write_chars_data *d = (write_chars_data *) data;
    printf("[%d, %d]: %s\n", d->row, d->col, d->str);
}

Note that, since write_chars() needs to retrieve multiple parameters
from a single pointer, it uses a pointer to a struct.
Now, the part of the code that learns what should be done has the
responsibility of providing the data:
// Here we learn what action should be performed.
if (should_read()) {
    fun_ptr = read_chars;
    uint8_t *p = new uint8_t;
    *p = 1;
    fun_ptr_data = (void *) p;
} else {  // should write
    fun_ptr = write_chars;
    write_chars_data *p = new write_chars_data;
    p->row = 1;
    p->col = 1;
    p->str = "messaage2";
    fun_ptr_data = (void *) p;
}

The part of the code that has to perform the action now is very simple:
// Here we have to perform the action.
if (fun_ptr)
    fun_ptr(fun_ptr_data);

Note that this code snippet doesn't free the allocated memory. You will
have to figure out who will be responsible for that.
This pattern is quite common in libraries, where the client (the user of
the library) wants an action to be performed, but the library is
responsible for performing that action at the right time. The client
would then provide the library a pointer to a function that accomplishes
the action (called a “callback”), together with a generic pointer to the
data needed by the callback. The use of a generic void * pointer makes
sense, because the library cannot know what kind of data the callback
will need.
In your case, since you know what kind of data you may need, you could
use a pointer to an union instead of a generic pointer:
union fun_data {
    uint8_t address;  // for read_chars
    struct {          // for write_chars
        uint8_t row;
        uint8_t col;
        const char *str;
    };
};

void (*fun_ptr)(fun_data *);
fun_data *fun_ptr_data;

A more idiomatic C++ style would be to pack together the callback
function and its data into a “functor”, i.e. an object that can be
called like a function, and can also store the data it needs. You would
then use inheritance in order to create specific functor types while
calling a generic one.

@R1S8K: 1. You can have the callbacks return a number if you want, but that has to be done consistently: all the callbacks should return the same type, and the pointer should be consistent with their signature. You should not need to typecast when assigning or using the function pointer. 2. The issue with your answer is not that it doesn't work. It is that it is fragile and bad practice. Being illegal C++, it can very well work on one platform/compiler combination, and fail on the next one.

I assume, that the fun_ptr points to the different service functions to do some kind of animation other other long running tasks on your display, thus you want to repeatedly call them in a structured way.
What you are currently doing will not really work. When you call a function, you need to provide its arguments. That's the same for a function pointer. You cannot call a function, that demands parameters, without any parameters. While you can still set a function pointer of type (void (*)(void*) to a function of type (void (*)(uint8_t)), the compiler warns so, because you still cannot call the function without any parameter. If you are trying to do so, you will still get an error of too few arguments to function ....
I see 2 ways to go from here:

You could overload your functions, so that a version without any parameters exists. Like this:
  void foo(uint8_t i){Serial.println(i);}
  void foo(){foo(10);}

With 10 being the value, with which the function should be called, when you provide no parameters. You can of course also use variables or function calls here, to actually get that value for the parameter i. Then you can use the pointer to call that function:
  void (* p)(void);
  p = &foo;
  p();

The assignment of the pointer will choose the version of the function without any parameters out of the overloaded pool of this function, since that matches the type of the pointer. Note, that I removed the * from the void parameter definition. I don't understand, what that would mean anyway (pointer to void?). The function pointer p() can now be called without any parameters, since it points to a function without any parameters.

You could ditch the function pointer and use a simple switch case statement with a state variable (which holds some identifier for the corresponding function), to call the correct service function. I won't go into detail here, since that is already basically, how an FSM can be programmed in C++, which is covered on this site and on the web numerous times.

If I were you, I probably would go with the first option, though that might also depend on the overall logic, that I currently don't really understand (too few information).

Re “pointer to void?”: A void * is commonly used as a generic pointer, i.e. a pointer to a data item of unknown type. See for example the interface of qsort().

Here's my latest work around:
I was searching for a work around. I got back to copy a method of casting a function pointer.
And changed my data structure of having 2 nested structs to one that contain everything which should serve my project well.
Here's my work:
task_manager.h
///////////////////////////////////////////////////////////////////////////
// enumerations
typedef enum {NOT_FINISHED,FINISHED,DONE}STATE;
// variables
typedef void (*f_ptr)(void *args);

// structs
typedef struct __attribute__((__packed__)) THREAD{
    uint8_t tsk_cnts, tsk_cntr;     // task information
    STATE   thrd_st;                  // thread flag states
    f_ptr   *tsk_fptr;
}THREAD;

main.c
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "task_manager.h"

const unsigned char PIC[] = {9, 8, 7, 1, 2};

void function1(void){printf("function1\n");}
void function2(uint8_t i){printf("function2\nnumber = %d\n",i);}
void function3(uint8_t a, uint8_t b, const uint8_t *img){
    printf("function3\na#%d b#%d\narray[0] = %d\n",a,b,*(img+0));}
uint8_t function4(uint8_t i){printf("function4# return\n"); return i+=1;}

THREAD thread1;

uint8_t fn4_ret;

int main(){

    // set thread main info
    thread1.thrd_st = 0;
    thread1.tsk_cnts = 4;
    thread1.tsk_cntr = 0;

    // allocating memory for tasks
    thread1.tsk_fptr = malloc(4*sizeof(f_ptr));

    // store tasks addresses
    thread1.tsk_fptr[0] = (void(*)())function1;
    thread1.tsk_fptr[1] = (void(*)())function2;
    thread1.tsk_fptr[2] = (void(*)())function3;
    thread1.tsk_fptr[3] = (void(*)())function4;

    // call the functions
    ((void(*)())thread1.tsk_fptr[1])(9);
    ((void(*)())thread1.tsk_fptr[2])(1,2,PIC);
    fn4_ret = ((uint8_t(*)())thread1.tsk_fptr[3])(1);
    printf("\fn4_ret = %d\n",fn4_ret);

    return 0;
}

It compiled with me fine, passed what I want and returned the required data.

Even though that may work on some compiler/platform, it is illegal in C++. gcc says about the cast: error: invalid conversion from ‘void (*)()’ to ‘uint8_t (*)()’, and about the call through the pointer: error: too many arguments to function.

I edited my answer.
What you think ? It worked with me well. No problems.


text:
Timing push button code
I am trying to time how long button is held for. The code seems to work but with two problems:

the millis values are being read wrongly. If you hold the button for 1 second, it returns holdTime of about 3000 ms. A quick click returns holdTime of about 1000 ms.

Each successive button press adds to the previous millis value so holdTime just gets higher and higher and doesn't measure how long the button has just been pressed for

Any ideas or advice for newbie welcome!
#include <LiquidCrystal.h>

const int button1Pin = 1;  // pushbutton 1 pin
const int ledPin = 13;     // LED pin

int button1State, button2State;  // variables to hold the pushbutton states
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int startPressed = 0;
int endPressed = 0;
int holdTime = 0;

void setup() {
  // Set up the pushbutton pins to be an input:
  pinMode(button1Pin, INPUT);

  // Set up the LED pin to be an output:
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
\
}

void loop() {

  while (digitalRead(button1Pin) == LOW) {}

  button1State = digitalRead(button1Pin);
  startPressed = 0;
  endPressed =0;
  holdTime = 0;

  // if button1 or button 2 are pressed (but not both)
  if (button1State == LOW) {
    digitalWrite(ledPin, LOW);   // turn the LED on
    startPressed = millis();
  } else {
    digitalWrite(ledPin, HIGH);  // turn the LED off
    endPressed = millis();
    holdTime = endPressed - startPressed;
  }
  lcd.print("You pressed for");
  lcd.setCursor(0, 1);
  lcd.print(holdTime);
  lcd.print("ms");
  while (digitalRead(button1Pin) == LOW) {}
  lcd.clear();
  startPressed =0;
  endPressed =0;
  holdTime = 0;
}

use unsigned long to store milliseconds

You may use this library: https://arduinogetstarted.com/tutorials/arduino-button-library, you can count the time that the button is pressed down. Greetings

thank you for your advice - i will check on these things

Your source has several flaws, and one error that generates the output you see. This is the analysis of the error.
In loop() you start by waiting for the button pin to get HIGH, following by another read of the pin's state that will most probably return the same, HIGH. Note: Only if your button bounces with just the right timing, this last read will return LOW.
while (digitalRead(button1Pin) == LOW) {}
button1State = digitalRead(button1Pin);

Next you check the pin's state, and let's assume that it is HIGH. Only the else part is executed, and it calculates the holdtime as the difference of endPressed and startPressed. The former has the current value of millis(), but the latter is 0 as you initialized it.
That's why you're getting always growing values.
How to solve?
Think about the while loops, do you need them? Remember that loop() is already called repeatedly.
You may need a state variable that stores the last pin's state, so you can detect changes.

thank you for your advice - i will check on these things


text:
How do I make my motors speed change?
I'm using an Adafruit V1 Motor Shield for coding two 12 volt DC motors. In my code I'm changing the set speed, but the motors still seem to be going the same speed, which is really fast, and I want them to go slow.  What do I change to make my motors speed run the way I want them to run?
Here's my code below:
#include <AFMotor.h>

AF_DCMotor motor1(1);
AF_DCMotor motor2(2);

void setup() {
  Serial.begin(9600); // set up Serial library at 9600 bps
  Serial.println("Motor test!");
  // turn on motor
  motor1.setSpeed(3);
  motor2.setSpeed(5);
}

void loop() {
  uint8_t i;

  //second motor
  Serial.print("tick");

  motor2.run(FORWARD);

  for (i=0; i<255; i++) {
    motor2.setSpeed(i);
    delay(10);
  }

  for (i=255; i!=0; i--) {
    motor2.setSpeed(i);
    delay(10);
  }

  Serial.print("tick");

  motor2.run(FORWARD);

  for (i=0; i<255; i++) {
    motor2.setSpeed(i);
    delay(10);
  }

  for (i=255; i!=0; i--) {
    motor2.setSpeed(i);
    delay(10);
  }

  Serial.print("tick");

  motor2.run(FORWARD);

  for (i=0; i<255; i++) {
    motor2.setSpeed(i);
    delay(10);
  }

  for (i=255; i!=0; i--) {
    motor2.setSpeed(i);
    delay(10);
  }

  Serial.print("tick");

  motor2.run(FORWARD);

  for (i=0; i<255; i++) {
    motor2.setSpeed(i);
    delay(10);
  }

  for (i=255; i!=0; i--) {
    motor2.setSpeed(i);
    delay(10);
  }

  Serial.print("tick");

  motor2.run(FORWARD);

  for (i=0; i<255; i++) {
    motor2.setSpeed(i);
    delay(10);
  }

  for (i=255; i!=0; i--) {
    motor2.setSpeed(i);
    delay(10);
  }

  //1 motor
  Serial.print("tick");

  motor1.run(FORWARD);

  for (i=0; i<255; i++) {
    motor1.setSpeed(i);
    delay(10);
  }

  for (i=255; i!=0; i--) {
    motor1.setSpeed(i);
    delay(10);
  }

  Serial.print("tick");

  motor2.run(FORWARD);

  for (i=0; i<255; i++) {
    motor2.setSpeed(i);
    delay(10);
  }

  for (i=255; i!=0; i--) {
    motor2.setSpeed(i);
    delay(10);
  }

  Serial.print("tick");

  motor2.run(FORWARD);

  for (i=0; i<255; i++) {
    motor2.setSpeed(i);
    delay(10);
  }

  for (i=255; i!=0; i--) {
    motor2.setSpeed(i);
    delay(10);
  }

  Serial.print("tack");

  motor1.run(BACKWARD);

  for (i=0; i<255; i++) {
    motor1.setSpeed(i);
    delay(10);
  }

  for (i=255; i!=0; i--) {
    motor1.setSpeed(i);
    delay(10);
  }
}

delete all of the code inside loop() ... what happens then?

What do I change to make my motors speed run the way I want them to run? ... how is anyone supposed to guess how you want the motors to run?

@jsotola  I mean by like how do i change the speed?

please read my first comment

@jsotola when I delete all of the code inside void loop(), nothing happens.

please add motor1.run(FORWARD);

@jsotola Its still the same speed. I have the power supply of 12v hooked up to the Arduino mega, which makes the motor sheild turn on, but is there any chance that it could be that there is to much power going to the motor shield which is causing the motors to spin faster?

are you saying that you are connecting 12 V to something that is not rated for such a voltage?

The arduino mega is 12 volts but the motor shield is 5 volts

hey . so if you have multimeter take it and check for the voltage at the terminals for the motor and the voltage should change according to the speed you have set

It looks like that motor shield can control stepper motors, servos, or variable speed DC motors. Are you using variable speed DC motors? (What model of motors are you using?)


text:
trigger a function of a Arduino Uno from signal received by LoRa module
I have two sx1278 Lora transceivers where both are connected to two Arduino Uno boards. I want to trigger a function in the Arduino Uno board where receiver side of LoRa connected using the signal received by Lora receiver.

Do you have a specific question? Have you looked at the examples of whatever LoRa library you’re using?

"LoRa by sandeepmistry" is the library I am using. I was able to send hello packets between two LoRa modules. Now what I want is trigger a function of receiver side of Arduino from a message get from LoRa module

what is preventing you from doing that? ... you still have not asked a question

I suggest writing code for that.

I'm assuming you have read the datasheet for the SX1278.  If not, please refer to it at:
SX1278 Datasheet
On page 69 you will see a couple of tables regarding the functions possible on the digital I/O (i.e. DIO) pins:

I'm not clear what exactly you are looking for or which mode you are operating in (you have provided almost no information about your project) but all the information you might need is available on these DIO pins.
You can connect the appropriate pin or pins to some of the edge sensitive lines on your Arduino and define and enable an INTERRUPT in your code.  So when the event you are waiting for happens, an interrupt will occur, you can go and read the data and do whatever with it.


text:
Code is not running, servo does not even spin
I am trying to run a program which works as follows:
An LDR is integrated in a box. A block is placed on top. This box can be rotated by a servo. The program is supposed to make the box turn until the block slides and lifts off from the LDR.
At that point the servo angle is stored and used to calculate the friction coefficient.
Finally, the answer to this calculation is printed on an LCD and the program repeats by first returning the box to the original state. The entire programs runs on an Arduino and an Arduino Lotus. Why doesn't the servo rotate?
//servo
#include <Servo.h>

Servo myservo;
int previous_angle = 0;
int angle = 0;

//lightsensor
int lightsensor = 0;
int LIGHT = 800;
int DARK = 940;

//LED screen
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);

void setup() {
  Serial.begin(9600);
  myservo.attach(6);

  pinMode(lightsensor, INPUT);

  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);

  delay(100);
}

void loop() {
  int i = previous_angle;
  int lightStatus = analogRead(lightsensor);

  if (lightStatus >= DARK) {
    delay(300);

    while (int i = previous_angle) {
      i<=90;
      i = i+1;
      myservo.write(i);
      delay(45);
    };
  } else if (lightStatus < DARK) {
    for (int i = previous_angle; i>0;) {
      delay(300);
      int angle = tan(i);
      display.clearDisplay();
      display.setTextSize(1.5);
      display.setTextColor(WHITE);
      display.setCursor(0,0);
      display.println(angle);
      display.display();
      delay(300);

      myservo.write(0);
      delay(45);
    };
  }
}

In the future, please format your source code using the {} on this site.  As it was it was very difficult to follow your code.  Also, please include a schematic of how your motor is connected.

Question: Have you been able to make your motor run with just a simple program?  It's often helpful to start out simple and add things one step at a time.

For starters: this bit is a strange mixture of for and while syntax:
while (int i = previous_angle) {
  i <= 90;
  i = i + 1;
  myservo.write(i);
  delay(45);
};

It will compile, but probably not do what you want it to do. It should probably be:
for (int i=previous_angle; i<=90; i=i+1) {
  myservo.write(i);
  delay(45);
}

Also, previous_angle is never changed in your code after initialisation; it is always 0.
That also means that the for loop below will not do what you want (and that loop also doesn't increment i anywhere):
for (int i = previous_angle; i>0;)

There may be more; make the suggested changes first and see what happens.

If I change it I get an error when verifying the code 'expected ')' before ';' token'

I blame coffee underflow 8-). Answer edited.

Changing to a "for" does resolve the error, I will check whether the code also properly as needed thankyou


text:
Stepper not working properly using L298N
If googled and search here but can't find the same issue.
I'm using an Arduino Uno, L298N driver (5v jumper is off - actually just 2 holes where the jumper pins were supposed to be), scavenge stepper motor from a 5 inch drive - TEAC P.no. 14769070-90 (we call it a floppy drive). I used the example from the Arduino IDE that spins the stepper in on direction and then the other.
The stepper motor has a 5 wire ribbon and with an LED test showed that the out side two wires are a pair. I've look at schematics for the 5 wire, I know it's got to do with the uni/bi polar of the motor but I have no idea if I need to connect this middle wire?
I've wired it according to this Maker Guides article
The issue is that in the clockwise direction it is very weak and it just vibrates in the anti-clockwise direction.
How do I go about diagnosing the issue?
(I'm on a beginner level with regards to hw. Sw engineer with a Solder iron - very dangerous)

The motor you got is a unipolar stepper motor. The five wires are one end of the four windings inside the motor, plus a common wire that connects all the other poles together.
Bipolar motor offer more torque than unipolar, at the expense of a more difficult control. 6 wires unipolar stepper motors can be converted to bipolar motors just selecting the correct wires. I am not aware of any method to convert a 5 wires unipolar motor to bipolar that does not imply tearing it apart (which is not really a great idea).
The L298 is not really made to drive this kind of motor, it is best suited to drive bipolar motors (can still drive it tho, please read the next paragraph). Good news, driving unipolar steppers is rather simple. You basically have to connect the common wire to you V+ rail and connect the other wires to GND via BJT/MOS. Don't connect them directly to the Arduino! It's the perfect recipe for fried chips. You can either choose to use discrete transistors or arrays like the ULN2003.
If you still want to use the L298 to drive the motor you can exploit the lower transistors of the H-bridge. Connect Vss and the enable pins to 5V, Vs to your positive rail voltage and pin 1, 8, 15 to GND. Then connect each phase to each output and the input to 4 pins to an Arduino/microcontroller. Leave the pins normally on and turn one off in turn (1->2->3->4->1...) and your stepper should run! This works because when you leave the pins on, the upper side of the H-bridge is powered on, thus shorting the winding. When you turn one pin off the lower part of the bridge will actually turn on and let the current flow to GND, closing the circuit and powering the winding. Using this kind of circuit you could also omit the freewheeling diodes needed to discharge the windings (as said before, you short them, allowing current to freely circulate).
EDIT/TLDR: Connect the windings to the output of the L298 and the common one to the positive rail. Keep the pins high and turn one sequentially off, you should see the motor move.

Take a look at this video - it has a great explanation of using a 5-wire stepper motor with an Arduino


text:
(Arduino Uno) PWM output (and servo plugged on it) becomes unstable if I use 1Wire on another pin
Unnecessary context but hey I'm guessing you might be interested
Hi, I want to build a PID temperature regulator with a servo that presses on a silicon pipe to adjust the flux of liquid passing through. The liquid is hot beer that must be cooled very quickly from 100°C to 25°C, and it passes through a heat exchanger where also passes in the other direction a constant flux of cold water. The lesser the flux of beer, the colder it becomes. But it is cumbersome to regulate it by hand and I'd like to automate it, because I (think I) can.
Overview of the system
My system is mainly composed of an Arduino Uno, a servo motor (PWM on pin 11), a BS18B20 1Wire temperature probe (on pin 2), and a few buttons. In 'manual' mode I can choose the position of the servo with the buttons and it is very stable.
I also have a buzzer on pin 13 and will add an I2C screen when the core works.
My problem
As soon as I start to request the temperature at regular intervals (like every 200 ms), the servo flickers all the time, which is boring, looks bad, and probably will reduce its life expectancy. I think every time I request a temperature something happens on the PWM, like a brief reset or something, and the servo reacts and then gets back to its original position.
The only power I've tested so far is the USB cable from the computer. In case you wonder, the code is here:
#include <AceButton.h> // https://github.com/bxparks/AceButton
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Servo.h>

Servo myservo; // create servo object to control a servo
// twelve servo objects can be created on most boards

#define ONE_WIRE_BUS 2 // pin for thermometer

using namespace ace_button;

// The pin number attached to the button.
const int BUTTON_SET_PIN = 12;
const int BUTTON_MORE_PIN = 4;
const int BUTTON_LESS_PIN = 0;

const int BUTTON_MODE2_PIN = 5;
const int BUTTON_MODE3_PIN = 7;

const int LED_PIN = LED_BUILTIN;
const int SERVO_PIN = 11;

const int MODE_THERMOMETER = 1;
const int MODE_REGULATOR = 2;
const int MODE_MANUAL = 3;
int mode;

// LED states. Some microcontrollers wire their built-in LED the reverse.
const int LED_ON = HIGH;
const int LED_OFF = LOW;

// Both buttons automatically use the default System ButtonConfig. The
// alternative is to call the AceButton::init() method in setup() below.
AceButton buttonSet(BUTTON_SET_PIN);
AceButton buttonMore(BUTTON_MORE_PIN);
AceButton buttonLess(BUTTON_LESS_PIN);

ButtonConfig modeConfig;
AceButton buttonMode2(&modeConfig);
AceButton buttonMode3(&modeConfig);

// Setup a oneWire instance to communicate with any OneWire devices
// (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

// variables for tune
float value = 50;
unsigned long tuneStart;
float max = 175;
float min = 10;

void handleModeEvent(AceButton *, uint8_t, uint8_t);

void handleModeEvent(AceButton *button, uint8_t eventType, uint8_t /* buttonState */) {
  switch (eventType) {
  case AceButton::kEventPressed:
    if (button->getPin() == BUTTON_MODE2_PIN) {
      mode = MODE_REGULATOR;
      printMode();
    }

    if (button->getPin() == BUTTON_MODE3_PIN) {
      mode = MODE_MANUAL;
      printMode();
    }
    break;
  case AceButton::kEventReleased:
    if (button->getPin() == BUTTON_MODE2_PIN) {
      mode = MODE_THERMOMETER;
      printMode();
    }
    if (button->getPin() == BUTTON_MODE3_PIN) {
      mode = MODE_REGULATOR;
      printMode();
    }
    break;
  }
}

void printMode()
{
  Serial.print("Mode ");
  Serial.println(mode);
}

void handleButtonEvent(AceButton *, uint8_t, uint8_t);

void setup() {
  Serial.begin(9600);
  while (!Serial); // Wait until Serial is ready - Leonardo/Micro
  Serial.println(F("Test 3 boutons - la suite en 115200 bps"));
  delay(300);

  // servo
  myservo.attach(11);

  // thermal probe
  sensors.begin();
  sensors.setWaitForConversion(false);
  sensors.setResolution(10);

  Serial.begin(115200);
  while (!Serial); // Wait until Serial is ready - Leonardo/Micro
  Serial.println(F("setup(): begin"));

  // Initialize built-in LED as an output.
  pinMode(LED_PIN, OUTPUT);
  pinMode(SERVO_PIN, OUTPUT);

  // Buttons use the built-in pull up register.
  pinMode(BUTTON_SET_PIN, INPUT_PULLUP);
  pinMode(BUTTON_MORE_PIN, INPUT_PULLUP);
  pinMode(BUTTON_LESS_PIN, INPUT_PULLUP);

  pinMode(BUTTON_MODE2_PIN, INPUT_PULLUP);
  pinMode(BUTTON_MODE3_PIN, INPUT_PULLUP);

  buttonMode2.init(BUTTON_MODE2_PIN);
  buttonMode3.init(BUTTON_MODE3_PIN);

  // Configure the ButtonConfig with the event handler, and enable all higher
  // level events.
  ButtonConfig *buttonConfig = ButtonConfig::getSystemButtonConfig();
  buttonConfig->setEventHandler(handleButtonEvent);
  buttonConfig->setFeature(ButtonConfig::kFeatureClick);
  buttonConfig->setFeature(ButtonConfig::kFeatureLongPress);
  buttonConfig->setFeature(ButtonConfig::kFeatureRepeatPress);

  // Configs for the tune-up and tune-down buttons. Need RepeatPress instead of
  // LongPress.
  modeConfig.setEventHandler(handleModeEvent);
  modeConfig.setFeature(ButtonConfig::kFeatureClick);
  // These suppressions not really necessary but cleaner.
  modeConfig.setFeature(ButtonConfig::kFeatureSuppressAfterClick);

  // Check if the button was pressed while booting
  if (buttonMode3.isPressedRaw()) {
    mode = MODE_MANUAL;
    printMode();
  } else if (buttonMode2.isPressedRaw()) {
    mode = MODE_THERMOMETER;
    printMode();
  } else {
    mode = MODE_REGULATOR;
    printMode();
  }
  Serial.println(F("setup(): ready"));
}

long timer_200 = 0;
long timer_1000 = 0;

void loop() {
  // Should be called every 4-5ms or faster, for the default debouncing time of ~20ms.
  buttonSet.check();
  buttonMore.check();
  buttonLess.check();
  buttonMode2.check();
  buttonMode3.check();

  // every 200 ms
  long now = millis();
  if (now > timer_200 + 200) {
    timer_200 = now; // to reinit timer
    if (mode == MODE_MANUAL) {
      myservo.write(value);
    }
  }

  // every 1s
  if (now > timer_1000 + 1000) {
    timer_1000 = now; // to reinit timer
    // get temperature requested last time
    Serial.print("Temperature for Device is: ");
    Serial.println(sensors.getTempCByIndex(0));
    // and request a new one
    sensors.requestTemperatures(); // Send the command to get temperatures
    if (mode == MODE_THERMOMETER) {}
  }
}

// The event handler for both buttons.
void handleButtonEvent(AceButton *button, uint8_t eventType, uint8_t buttonState) {
  switch (eventType) {

  case AceButton::kEventClicked:
    if (button->getPin() == BUTTON_MORE_PIN) {
      value = value * 1.01;
      if (value > max) {
        value = max;
      }

      Serial.println(value);
    }

    if (button->getPin() == BUTTON_LESS_PIN) {
      value = value * .99;
      if (value < min) {
        value = min;
      }
      Serial.println(value);
    }

    if (button->getPin() == BUTTON_SET_PIN) {
      Serial.println(F("set"));
    }
    break;

  case AceButton::kEventLongPressed:
    if (button->getPin() == BUTTON_SET_PIN) {
      Serial.println(F("set long press"));
    }

    if (button->getPin() == BUTTON_MORE_PIN || button->getPin() == BUTTON_LESS_PIN) {
      tuneStart = millis();
    }
    break;
  case AceButton::kEventRepeatPressed:

    if (button->getPin() == BUTTON_MORE_PIN) {
      tuneUp();
    }

    if (button->getPin() == BUTTON_LESS_PIN) {
      tuneDown();
    }
    break;
  }
}

void tuneUp() {
  unsigned long duration = millis() - tuneStart;
  float ratio = 1 + (0.00001f * 4 * duration);
  value = value * ratio;
  if (value > max) {
    value = max;
  }
  Serial.println(value);
}

void tuneDown() {
  unsigned long duration = millis() - tuneStart;
  float ratio = 1 - (0.00001f * 4 * duration);
  value = value * ratio;
  if (value < min) {
    value = min;
  }
  Serial.println(value);
}

It's still quite a prototype.
What could cause this and how can I prevent it?

What are you using for your controller?  Some devices don't have hardware PWM and even some that do use "bit banging" if you don't choose the correct pin.

I'm sorry, I forgot the main component, the arduino Uno. I've edited my question.

I suspect the 1Wire libary disables (and enables) interrupts when it sees fit. This will cause servo "hickups" because the servo library uses interrupts.
If I'm right then your best bet is using a servo library that doesn't use interrupts. I always use a hardware PWM library for driving servos, so I have no servo library recommendations to make, but maybe somebody else has.
Also: you are doing a Serial.begin() twice, and the variables you use for timing (using millis()) should be unsigned long, not long.

Thanks, this is very interesting ! I really don't need the Servo library, outputting a regular PWM will likely work seamlessly for my application. I'll try that tomorrow and let you know.

Is that a problem to use Serial.begin twice ? I do it on purpose, because I like to know what is currently loaded on a given arduino board, so I start by a message in 9600 bps with the name of the sketch and the speed of the next messages, then I reinit with the said speed. It seems to work :)

It's not necessarily a problem, but why would you, if the receiving application apparently can handle the higher baudrate anyway? If you do it on purpose though, it's fine.

The idea was to always start at 9600 as a standard whichever sketch I upload, and then choose freely the communication speed. Otherwise I may not remember later on what speed I have to set in the console to communicate with it. It's quite a fresh idea I had, I don't know if it's gonna be that useful.

You were very probably right. I made a custom code to output the signal I needed, which is actually not PWM, see https://forum.arduino.cc/index.php?topic=530091.0 and it solved the problem. Thanks a lot !

You are most welcome. A servo signal is PWM, though, usually left-aligned, and with a fixed frequency, but let's not discuss that now.


text:
make servo motor to increase/decrease degree
I'm trying to make servo motor to increase or decrease degrees according to user choice.
I've created an code that get input from the user via Serial and according to the input the motor increase or decrease.
But for some reason, when I call each of one of the function the motor start working without a break.
do I miss something over here?
 #include <Servo.h>

Servo servo1;
int currentAngle = 0;
String readString;
void setup()
{
   servo1.attach(8);
   Serial.begin(9600);
}
void increaseServo(){
  Serial.println('+');
  currentAngle += 5;
  servo1.write(currentAngle);
  delay(15);
}
void decreaseServo(){
  Serial.println('-');
  currentAngle -= 5;
  servo1.write(currentAngle);
  delay(15);
}
void loop()
{
  while(Serial.available()>0) //Allocating the data from Serial Monitor.
  {
    delay(3);
    char c = Serial.read();
    readString += c;
  }
  readString.trim();
  if (readString.length() > 0) {
    if(readString == "+"){ //increase
      increaseServo();
    }else if(readString == "-"){ //decrease
      decreaseServo();
    }
    readString="";
  }
  delay(1000);
}

Thanks for the help.

"But for some reason, when I call each of one of the function the motor start working without a break" - I don't quite understand, what exactly that means. Do you mean, that the motor will continuously move, as soon, as you send either + or - from the Serial Monitor?

Yes, Exactly the servo continue to move without stop

Which servo are you using? Common RC servos cannot run without stop, because they have a range of just about -90° to +90°.

@the_busy bee I am using FT90R


text:
HMC5883L Magnetometer X, Z values constant, only Y value Changes
I have a HMC5883L module connected to an Arduino Mega 2560 via +5, GND, SCL, SDA.  The Arduino code is from the MagMaster-master example, as follows:
#include "Wire.h"
#include "HMC5883L.h"

HMC5883L compass; //Copy the folder "HMC5883L" in the folder "C:\Program Files\Arduino\libraries" and restart the arduino IDE.

float xv, yv, zv;

void setup()
{
  Serial.begin(9600);
  Wire.begin();
  compass = HMC5883L();
  setupHMC5883L();
}

void loop()
{
  getHeading();

  Serial.flush();
  Serial.print(xv);
  Serial.print(",");
  Serial.print(yv);
  Serial.print(",");
  Serial.print(zv);
  Serial.println();

  delay(100);
}

void setupHMC5883L()
{
  compass.SetScale(0.88);
  compass.SetMeasurementMode(Measurement_Continuous);
}

void getHeading()
{
  MagnetometerRaw raw = compass.ReadRawAxis();
  xv = (float)raw.XAxis;
  yv = (float)raw.YAxis;
  zv = (float)raw.ZAxis;
}

When I run the code, I get the following output on the serial monitor
-15872.00,-27601.00,1.00
-15872.00,3264.00,1.00
-15872.00,19536.00,1.00
-15872.00,-18208.00,1.00
-15872.00,12401.00,1.00
-15872.00,-27647.00,1.00
-15872.00,1170.00,1.00
-15872.00,17442.00,1.00
-15872.00,-21326.00,1.00
-15872.00,7235.00,1.00
-15872.00,21715.00,1.00
-15872.00,-15261.00,1.00
-15872.00,15604.00,1.00
-15872.00,-22396.00,1.00
-15872.00,7189.00,1.00
-15872.00,23717.00,1.00
-15872.00,-13259.00,1.00
-15872.00,14534.00,1.00
-15872.00,-24490.00,1.00
-15872.00,3303.00,1.00
-15872.00,17527.00,1.00
-15872.00,-20473.00,1.00
-15872.00,9368.00,1.00
-15872.00,26664.00,1.00
-15872.00,-8008.00,1.00
-15872.00,8265.00,1.00
-15872.00,23769.00,1.00
-15872.00,-14231.00,1.00
-15872.00,13562.00,1.00
-15872.00,-24438.00,1.00
-15872.00,3099.00,1.00
-15872.00,17579.00,1.00
-15872.00,-19397.00,1.00
-15872.00,11468.00,1.00

As can be seen from the above, only the Y (middle column) values change when I move the sensor around.  If I plot these values in Excel, I get a plot that looks like this:

I have looked through the code, and the HMC5883L library code (below) and nothing seems amiss.  I tried a different HMC5883L module and got the same (bad) result.  I know I must be doing something wrong, but I can't for the life of me figure it out. Any hints would be appreciated! ;-)
HMC5883L.cpp:
/*
HMC5883L.cpp - Class file for the HMC5883L Triple Axis Magnetometer Arduino Library.
Copyright (C) 2011 Love Electronics (loveelectronics.co.uk)/ 2012 bildr.org (Arduino 1.0 compatible)

This program is free software: you can redistribute it and/or modify
it under the terms of the version 3 GNU General Public License as
published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

 WARNING: THE HMC5883L IS NOT IDENTICAL TO THE HMC5883!
 Datasheet for HMC5883L:
 http://www51.honeywell.com/aero/common/documents/myaerospacecatalog-documents/Defense_Brochures-documents/HMC5883L_3-Axis_Digital_Compass_IC.pdf

*/

#include <Arduino.h>
#include "HMC5883L.h"

HMC5883L::HMC5883L()
{
  m_Scale = 1;
}

MagnetometerRaw HMC5883L::ReadRawAxis()
{
  uint8_t* buffer = Read(DataRegisterBegin, 6);
  MagnetometerRaw raw = MagnetometerRaw();
  raw.XAxis = (buffer[0] << 8) | buffer[1];
  raw.ZAxis = (buffer[2] << 8) | buffer[3];
  raw.YAxis = (buffer[4] << 8) | buffer[5];
  return raw;
}

MagnetometerScaled HMC5883L::ReadScaledAxis()
{
  MagnetometerRaw raw = ReadRawAxis();
  MagnetometerScaled scaled = MagnetometerScaled();
  scaled.XAxis = raw.XAxis * m_Scale;
  scaled.ZAxis = raw.ZAxis * m_Scale;
  scaled.YAxis = raw.YAxis * m_Scale;
  return scaled;
}

int HMC5883L::SetScale(float gauss)
{
    uint8_t regValue = 0x00;
    if(gauss == 0.88)
    {
        regValue = 0x00;
        m_Scale = 0.73;
    }
    else if(gauss == 1.3)
    {
        regValue = 0x01;
        m_Scale = 0.92;
    }
    else if(gauss == 1.9)
    {
        regValue = 0x02;
        m_Scale = 1.22;
    }
    else if(gauss == 2.5)
    {
        regValue = 0x03;
        m_Scale = 1.52;
    }
    else if(gauss == 4.0)
    {
        regValue = 0x04;
        m_Scale = 2.27;
    }
    else if(gauss == 4.7)
    {
        regValue = 0x05;
        m_Scale = 2.56;
    }
    else if(gauss == 5.6)
    {
        regValue = 0x06;
        m_Scale = 3.03;
    }
    else if(gauss == 8.1)
    {
        regValue = 0x07;
        m_Scale = 4.35;
    }
    else
        return ErrorCode_1_Num;

    // Setting is in the top 3 bits of the register.
    regValue = regValue << 5;
    Write(ConfigurationRegisterB, regValue);
}

int HMC5883L::SetMeasurementMode(uint8_t mode)
{
    Write(ModeRegister, mode);
}

void HMC5883L::Write(int address, int data)
{
  Wire.beginTransmission(HMC5883L_Address);
  Wire.write(address);
  Wire.write(data);
  Wire.endTransmission();
}

uint8_t* HMC5883L::Read(int address, int length)
{
  Wire.beginTransmission(HMC5883L_Address);
  Wire.write(address);
  Wire.endTransmission();

  Wire.beginTransmission(HMC5883L_Address);
  Wire.requestFrom(HMC5883L_Address, length);

  uint8_t buffer[length];
  if(Wire.available() == length)
  {
      for(uint8_t i = 0; i < length; i++)
      {
          buffer[i] = Wire.read();
      }
  }
  Wire.endTransmission();

  return buffer;
}

char* HMC5883L::GetErrorText(int errorCode)
{
    if(ErrorCode_1_Num == 1)
        return ErrorCode_1;

    return "Error not defined.";
}

HMC5883L.h:
/*
HMC5883L.h - Header file for the HMC5883L Triple Axis Magnetometer Arduino Library.
Copyright (C) 2011 Love Electronics (loveelectronics.co.uk) / 2012 bildr.org (Arduino 1.0 compatible)

This program is free software: you can redistribute it and/or modify
it under the terms of the version 3 GNU General Public License as
published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

 WARNING: THE HMC5883L IS NOT IDENTICAL TO THE HMC5883!
 Datasheet for HMC5883L:
 http://www51.honeywell.com/aero/common/documents/myaerospacecatalog-documents/Defense_Brochures-documents/HMC5883L_3-Axis_Digital_Compass_IC.pdf

*/

#ifndef HMC5883L_h
#define HMC5883L_h

#include <Arduino.h>
#include <Wire.h>

#define HMC5883L_Address 0x1E
#define ConfigurationRegisterA 0x00
#define ConfigurationRegisterB 0x01
#define ModeRegister 0x02
#define DataRegisterBegin 0x03

#define Measurement_Continuous 0x00
#define Measurement_SingleShot 0x01
#define Measurement_Idle 0x03

#define ErrorCode_1 "Entered scale was not valid, valid gauss values are: 0.88, 1.3, 1.9, 2.5, 4.0, 4.7, 5.6, 8.1"
#define ErrorCode_1_Num 1

struct MagnetometerScaled
{
    float XAxis;
    float YAxis;
    float ZAxis;
};

struct MagnetometerRaw
{
    int XAxis;
    int YAxis;
    int ZAxis;
};

class HMC5883L
{
    public:
      HMC5883L();

      MagnetometerRaw ReadRawAxis();
      MagnetometerScaled ReadScaledAxis();

      int SetMeasurementMode(uint8_t mode);
      int SetScale(float gauss);

      char* GetErrorText(int errorCode);

    protected:
      void Write(int address, int byte);
      uint8_t* Read(int address, int length);

    private:
      float m_Scale;
};
#endif

Is this the Adafruit module? If so I would follow their tutorial step by step before breaking out on your own. Also, know that magnetometers are more difficult to align and use then, say, an accelerometer or gyroscope.

No, it's not - just a typical GY-273 clone.  I did  look at the Adafruit tutorial, but it just covers the same ground.

If it is not too big of an investment, I would buy the HW so as to be able to use the Adafruit tutorial exactly. Or, if you can, look for a working example that fits your HW situation. I've only worked w/the STMicro magnetometers & IMUs.  Their magnetometers are very sensitive and need to be aligned either by setting registers inside the chip or externally in the SW.  Regardless, there are usually many registers needing configuration before meaningful data is read out.  Meanwhile, in the short term, perhaps someone will spot something missing in your code preventing your HMC5883L from working.

Oh, do make sure that all your libraries are up to date.  I know you may have heard this many times.  But more often than not, code created for the Arduino by other hackers is only truly vetted after many others have tested and improved the code.


text:
Shift between the carrier frequency of the signal transmitted with arduino and my garage door RC (433 mhz)
I have this 433 mhz transmitter and receiver for arduino.

I want to replay my garage door remote control with this transmitter so I reversed the RC (remote control) signal with RTL-SDR/sdrsharp and audacity.
It is not working.

Why is there a shift between the carrier frequency of the signal transmitted with arduino (RH_ASK library) and my garage door RC ?
How can I change this ?

the remote control could be using encrypted communication ... if it does, then replaying the code will not work .... compare multiple recordings before wasting your time trying to retune the transmitter

Yes I checked it, the code is not changing over time.

I'm more worried about difference in duration of the signal than the 0.1Mhz difference in frequency. (Though, if you bought a tree-pack, like in the image, you could try the other two. )

The reason is that your garage door opening is operating on a different carrier frequency than your transmitter module.  The plot you are showing is called a "waterfall" plot and shows the frequency on the "x" axis with time progressing from top-to-bottom.
The garage door remote appears to be centered just above 433.900 MHz while your transmitter is around 434.000 MHz.  While that might not seem like a large difference, these things are designed to be receptive in a very narrow band.
So you need to read the specifications of your transmitter module and see if its frequency is adjustable and, if so, adjust it upward to the correct frequency.

Are you certain about what modulation is used by your garage door?
There are relatively strong side bands on 433.800 MHz. While most of the signal is at 433.900 MHz this might be an FSK variant instead of ASK modulated signal. In that case you will not be able to use this transmitter for your task. Usually taking apart your remote and searching for the IC numbers will give you more insight about what is being used. If you find an FCC-ID on your remote, you can try to find information that way as well.

All the garage door systems I have seen for many years use a KeeLoq encoder to prevent exactly what you are doing from working. The code changes every time it is used. There is a lot of stuff on the internet on KeeLoq that may help you. The Microchip HCS301 was once the most widely used system on garage and gate remote control and receivers. The chip uses the KeeLoq algorithm. The HCS301 KeeLoq system transmits 66 data bits.

The term "433MHz" refers not to a frequency, but to a band. That is, a range of frequencies, officially defined as 433.05MHz to 434.79MHz.  You are free to use any frequency within that range you choose for your carrier frequency. The manufacturers of the garage door opener have chosen one frequency, your TX/RX are tuned to another frequency.
If you want to receive the frequency your opener transmits at then you will need a receiver tuned to that exact frequency. If you want your garage door to receive your signals then you will need a transmitter tuned to the correct exact frequency.
You can think of it as a normal radio. "433MHz" is akin to "The FM band". Within that band are a number of stations, all with their own frequency. Your TX/RX pair are tuned to BBC Radio 2, but the garage door is working on Classic FM (replace with two radio stations that mean something to you...)


text:
Not able to build program with arduino program under clion
I'm pretty new to arduino and I just downloaded clion and installed the arduino plugin so I have an IDE that I'm used to. Here is my code:
#include <Arduino.h>

// Time between a switch indicating not full and the time a valve is opened
#define SWITCH_DELAY 5000

#define PIN_SWITCH 2
#define PIN_GREEN 3
#define PIN_YELLOW 4

#define INT16 int
#define UINT16 unsigned int
#define UINT32 unsigned long

DelayChecker    degassingChecker(PIN_SWITCH, PIN_GREEN);

void setup() {
    pinMode(PIN_SWITCH, INPUT);
    pinMode(PIN_GREEN, OUTPUT);
    pinMode(PIN_YELLOW, OUTPUT);

    Serial.begin(9600);
    Serial.print("UINT16: " + sizeof(UINT16));
    Serial.print("UINT32: " + sizeof(UINT32));
}

void loop() {
    UINT32 now = millis();

    degassingChecker.check(now);
}

public class DelayChecker {
    private:
        UINT32 delayExpires = 0;
        UINT16 switchId = 0;
        UINT16 solenoidId = 0;
        bool solenoidOn = false;

    public:
        DelayChecker(const unsigned int sw, const unsigned int sol) {
            switchId = sw;
            solenoidId = sol;
        }

        void check(const UINT32 now) {
            if (delayExpires == 0) {
                INT16 switchState = digitalRead(switchId);
                if (switchState == LOW) {
                    delayExpires = millis() + SWITCH_DELAY;
                    digitalWrite(PIN_YELLOW, HIGH);
                }
            }
            else {
                if (now >= delayExpires) {
                    INT16 switchState = digitalRead(switchId);
                    if (switchState == LOW) {
                        if (!solenoidOn) {
                            digitalWrite(solenoidId, HIGH);
                            solenoidOn = true;
                        }
                    }
                    else {
                        if (solenoidOn) {
                            digitalWrite(solenoidId, LOW);
                            solenoidOn = false;
                        }
                    }
                }
            }
        }
};

I hit the run button and get the following.
====================[ Build | untitled1 | Debug ]===============================
/opt/clion/bin/cmake/linux/bin/cmake --build /home/thomas/CLionProjects/untitled1/cmake-build-debug --target untitled1 -- -j 12
[  7%] Building C object CMakeFiles/uno_CORE.dir/opt/arduino-1.8.13/hardware/arduino/avr/cores/arduino/wiring_pulse.c.obj
[  7%] Building CXX object CMakeFiles/uno_CORE.dir/opt/arduino-1.8.13/hardware/arduino/avr/cores/arduino/new.cpp.obj
[ 10%] Building C object CMakeFiles/uno_CORE.dir/opt/arduino-1.8.13/hardware/arduino/avr/cores/arduino/wiring_shift.c.obj
/opt/arduino-1.8.13/hardware/arduino/avr/cores/arduino/new.cpp:29:46: error: expected initializer before 'noexcept'
 void * operator new(size_t size, void * ptr) noexcept {
                                              ^~~~~~~~
gmake[3]: *** [CMakeFiles/uno_CORE.dir/build.make:317: CMakeFiles/uno_CORE.dir/opt/arduino-1.8.13/hardware/arduino/avr/cores/arduino/new.cpp.obj] Error 1
gmake[3]: *** Waiting for unfinished jobs....
gmake[2]: *** [CMakeFiles/Makefile2:99: CMakeFiles/uno_CORE.dir/all] Error 2
gmake[1]: *** [CMakeFiles/Makefile2:133: CMakeFiles/untitled1.dir/rule] Error 2
gmake: *** [Makefile:151: untitled1] Error 2

It looks like an error in the libraries. Has anyone seen anything like this?

Could be some incorrect build settings by that plugin.

I found a github issue fixing this error : https://github.com/vsch/CLionArduinoPlugin/issues/36
It worked for me

You're referring to setting the Clion project settings to use language standard to c++17?

Yeah I'm sorry... First time for me ^^ thanks for explaining to me