text:
Continous running light with fading trail
In examples of FastLED library, there's the animation of a dot sweeping back and forth, with fading trails (file "DemoReel100", animation "sinelon"). How can I alter the code so instead of moving back, the dot begins at LED #1 again; so when using a LED ring, then the movement is continuous and circular.
Since the code will be part of a more complex project with reading of button states etc, the animation code has to be non-blocking, i.e. delay() is not an option.
void sinelon()
{
fadeToBlackBy( leds, NUM_LEDS, 20);
int pos = beatsin16( 13, 0, NUM_LEDS-1 );
leds[pos] += CHSV( gHue, 255, 192);
}

Can't follow you. I think there's no explicit code for back movement, it's just the natural thing of a sine wave: it has a sign reversal in it.

Oh, missunderstanding, my example animation is called "sinelon" and resides in example file named "DemoReel100".

replace the beatsin16( 13, 0, NUM_LEDS-1 ); with a function that returns a value that increments on successive calls to the function ... starts at 0 and resets to 0 when it reaches NUM_LEDS

If you look at the surrounding methods, you'll see that 'fadeToBlackBy' will give a fading effect on anything you feed in. You'll want to locate method 'beatsin16' and then edit it yourself so that it doesn't bounce back but restarts the counter at the first LED. (hint: phase_offset)
You'll find the code snippet you want to copy in lib8tion.h
/// beatsin16 generates a 16-bit sine wave at a given BPM,
///           that oscillates within a given range.
LIB8STATIC uint16_t beatsin16( accum88 beats_per_minute, uint16_t lowest = 0, uint16_t highest = 65535,
                               uint32_t timebase = 0, uint16_t phase_offset = 0)
{
    uint16_t beat = beat16( beats_per_minute, timebase);
    uint16_t beatsin = (sin16( beat + phase_offset) + 32768);
    uint16_t rangewidth = highest - lowest;
    uint16_t scaledbeat = scale16( beatsin, rangewidth);
    uint16_t result = lowest + scaledbeat;
    return result;
}

Thank you, altering the beatsin16 method is a good idea, but fiddeling with phase didn't work. I am not very savvy concerning the math behind sine function. Could you please give more information?

You shouldn't be altering the function as much as duplicating it and calling it 'beatshoot16' or similar
The sine function is just what gives the light the 'acceleration' and 'deceleration' motion. if you don't need that it might be simpler for you to rewrite the function to just have a light beeping on incrementally through the strip
With regards to phase offset, google images for "sine wave phase offset". Changing the offset value just changes the timing, what you want is to restart the sine wave if the offset is in a certain range (when it is pi to 2pi, change it to zero to pi).


text:
execute if function in a timed loop
I have a school project where I had to make a piece of code work for 1 minute and then return. I first used a RFID reader which didn't work for me so I decided to use the serial monitor. I did this through a switch function and if it was the correct number you had 1 minute to push in the buttons.
But now to the problem for me is that in the timed loop I made it can't look for if functions and because of that I can't look if the buttons are pressed.
I hope it was a
clear explanation and someone can help me.
Thanks in advance.

Pasted code can be formatted correctly by selecting it and clicking the {} button in the question editor (or pressing Control+K).

Your problem is not clear to me. But I think you should actually read the switches via digitalRead() inside the loop.

Why did you again removed your pasted code, that I formatted for you?

Because the code had no spaces or next lines and thus wasn't readable. I also had no idea how to change it to make it look readable. But your comment about digitalRead() was very helpful, I had a digitalRead() for my buttons but I had put it in a different loop but now that I moved the digitalRead() to the Right() it work now. So thank you very much.

Normally, a timed loop is a bad design in Arduino projects. Rather use the given void loop() function and non-blocking functions inside.

As chrisl mentions,  you should use digitalRead.
Assign this to the correct variables:
switchState1 = digitalRead(…) // Fill in the correct pin here
switchState2 = digitalRead(…) // Fill in the correct pin here

Also, you can separate the first part of the if, so you get:
if (switchState1 == HIGH)
{
    if (switchState2 == HIGH)
    {
        digitalWrite(2, HIGH);
        digitalWrite(3, HIGH);
        digitalWrite(4, HIGH);
    }
    else if (switchState2 == LOW)
    {
        digitalWrite(2, LOW);
        digitalWrite(3, LOW);
        digitalWrite(4, LOW);
    }
}

Since the inner condition only depends on switchState2 and the pins are equal, you can write:
if (switchState1 == HIGH)
{
    digitalWrite(2, switchState2 == HIGH);
    digitalWrite(3, switchState2 == HIGH);
    digitalWrite(4, switchState2 == HIGH);
}

And you can use instead of the switchState2 a switchState2High (Boolean), and only check it when switchState 1 == HIGH.
if (switchState1 == HIGH)
{
    switchState2High = (digitalReadState(…) == HIGH);
    digitalWrite(2, switchState2High);
    digitalWrite(3, switchState2High);
    digitalWrite(4, switchState2High);
}

You also could use a for loop for the last part so you get:
if (switchState1 == HIGH)
{
    switchState2High = (digitalReadState(…) == HIGH);
    for (int pin = 2; pin < 5; pin++)
    {
        digitalWrite(pin, switchState2High);
    }
}

The code works now so thank you very much for your time and help

You are welcome / good luck with your project

source: Stack Exchange

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

sort: votes


text:
Print unsigned long long in ESP8266
I need to print an unsigned long long variable:
unsigned long long t = 1559072327000ULL;
I have tried the following:
Serial.println(t); // call of overloaded 'println(uint64_t&)' is ambiguous

char[18] buf;

sprintf(dt, 18, "%lu", t); // Prints 4294165848

snprintf(dt, 18, "%lu", t); // Prints 126

vsnprintf(dt, 18, "%lu", t); // cannot convert 'uint64_t {aka long long unsigned int}' to '__gnuc_va_list {aka __va_list_tag}'

Any suggestion?

char[18] buf; <-- what on earth is this? When you intend to post code in your question, please don't fake the code. Post the real code you actually tried to use.

Okay, I figured out... this two prints the right number:
sprintf(dt,"%llu", t);
snprintf(dt, 18, "%llu", t);

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


text:
Voltage transfer
I'm trying to read the battery voltage using Arduino, using a 9V battery. I keep getting the same voltage (4.99). I connected my Arduino to Matlab so I'm only using the command voltage=readVoltage(a,'pin'). I'm very new to this, so any help would be appreciated.

Analog inputs on the arduino will measure 5v maximum. If you want to mesure higher voltage you will have to use a voltage divisor circuit (resistors).

Also your analog input might now be dead from providing almost twice the voltage it's designed for.

Aren't you getting any Magic smoke ?

Thank you all, somehow I didnt damage the analog input, thank God. But i tried with resistors (10k) and its still measuring the same voltage...

And if you measure with a multi-meter the voltage at the Arduino input ?

@SoundoussSassi could you show/describe how you have connected the resistors (just to make sure it is a proper voltage divider)? I also wonder if it is necessary to select a proper reference (there should be an internal and external reference possible).

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


text:
Float division returns "inf" and 0
I'm new to Arduino and I'm doing an ultrasonic project where I test for the speed of sound. My code is below and for some reason, this is what the serial port returns:
This is the measured speed of sound: inf m/s
This is the measured speed of sound: 0m/s
This is the measured speed of sound: 0m/s
etc...
Here's my code. Any help's massively appreciated:)
int trig = 13;
int echo = 11;
float target_distance = 0.3;
float recieved;
float speed_of_sound;

void setup() {
    Serial.begin(9600);
    pinMode(trig, OUTPUT);
    pinMode(echo, INPUT);
}

void loop() {
    digitalWrite(trig, LOW);
    delayMicroseconds(2000);
    digitalWrite(trig, HIGH);
    delayMicroseconds(10);
    digitalWrite(trig, LOW);

    recieved=pulseIn(echo, HIGH);
    recieved = recieved*1000000.0;
    speed_of_sound = (2*target_distance)/recieved;
    Serial.print("This is the measured speed of sound: ");
    Serial.print (speed_of_sound);

    Serial.println("m/s");
    delay(3000);
}

What do you expect the division of 0.6 with 1000000  * some value?

Assuming the speed of sound is of the order of 330 m/s, you expect
the round-trip to the target and back to last about 1.8 ms. Then
recieved = pulseIn(echo, HIGH);

should give a value close to 1,800, and
recieved = recieved * 1000000.0;

should make received something like 1.8 × 109.
Then
speed_of_sound = (2*target_distance)/recieved;

gives a speed of sound of 3.3 × 10−10. It is the
correct value if you want that speed in meters per picosecond, but this
is inconsistent with your program printing “m/s” after the value.
The Arduino's Serial.print() is quite dumb with floating point
numbers. It defaults to printing two digits after the decimal point,
irrespective of the order of magnitude of the number. Thus, anything
smaller than 0.005 gets printed as “0”.
I don't quite understand why you got ∞ on the first loop. Looks like
pulseIn() missed the pulse and returned zero, in which case the speed
is computed as 0.6 ÷ 0 = ∞.
The solution is to compute received as
recieved = pulseIn(echo, HIGH) * 1e-6;

This can be remembered by thinking that a quantity (round-trip time) is
a numeric value (pulseIn(echo, HIGH)) multiplied by a unit (1e-6,
which stands for “microseconds”).

nice, thorough answer. (voted)

Ah, a maths error... thats embarrasing. I assumed it was my code. Thanks for taking the time to help though! I just changed the faulty line to: recieved = recieved/1000000 and apart from the first line being  "inf", it works well now.

@ThisUsernameHasBeenTaken: Scanning the available datasheets didn't turn up any anomalies related the first measurement. I would take a practical approach to it by triggering the device once during setup() and ignoring that result.


text:
Optical mouse sensor M116504386 arduino libary
I am doing project and I used optical mouse IC sensor M116504386 with 16 pins and I don't know how to get this sensor libraries to interface it with arduino uno.

When I google "M116504386", I get 2 results in Chinese. Is this the sensor you are using? https://www.sparkfun.com/products/retired/12907 Can you tell us which library you're using?

do you still have the mouse? ... if you have it, try to determine the schematic diagram of the mouse


text:
Waking up async the Arduino while it is sleeping periodically
I´m using LowPower.h and PinChangeInt.h libraries to put my Arduino into the sleep mode every 8 seconds and then it wakes up, modifies a counter and it goes to sleep again, but also I need to wake it up when a button is pressed asynchronously.
I´ve reached to wake up the Arduino every 8 seconds using LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF) and, in other code, I´ve also reached to wake it up while it sleeps indefinitely with LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF) but I can´t combine that periodical awakening with the asynchronous awakening.
Here is my code:
void setup(){

    Serial.begin(9600);

    //Pines declaration

    loopsToSend = setTimeToSend();  //

    //The three async buttons
    PCintPort::attachInterrupt(4, readOpinion,RISING);
    PCintPort::attachInterrupt(5, readOpinion,RISING);
    PCintPort::attachInterrupt(6, readOpinion,RISING);
}

void loop(){

    if(loops < loopsToSend ){

        byte opinionValue = readOpinion(); //This method must awake the Arduino ASYNC to give a value to the opinionValue var, write the result in the file and go to sleep

        if(opinionValue != 0){
            Serial.println("Button pressed!");

            //Writing result in a file
            opiniones++;
            delay(500);
        }
        //Go to sleep 8 seconds
        LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
        opinionValue = 0;
    }
    else {
        wdt_disable();

        if(opiniones > 0){
            //Send file using GSM module
        }
        else{
            loops = 0;
        }
    }
    loops++;
}

Can anyone help me? Thanks

Which Arduino is it? Please post a Minimal, Complete, and Verifiable example. I don't see readOpinion declared anywhere.

It's an encouraged practice to answer your own question if you've solved your problem.

My aim was to attach multiple interrupts to my Arduino but my problem was that I didn´t know if when the board changed to sleep mode using LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF) then it could be awake using another interrupt instead of the timer.
The void loop() method must sleep the board every 8 seconds if no button is pressed. Aside there is a method that is called when a button is pressed, that´s because in the void setup () I´ve attached an interrupt using PCintPort::attachInterrupt(PIN_NUMBER, METHOD_TO_CALL,MODE);

OP (PinaGamer) posted this answer inside the question, hence the community wiki answer.

authors: Дмитрий Дымов

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


text:
Waking up async the Arduino while it's sleeping periodically
I´m using LowPower.h and PinChangeInt.h libraries to put my Arduino into the sleep mode every 8 seconds and then it wakes up, modifies a counter and it goes to sleep again, but also I need to wake it up when a button is pressed asynchronously.
I´ve reached to wake up the Arduino every 8 seconds using LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF) and, in other code, I´ve also reached to wake it up while it sleeps indefinitely with LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF) but I can´t combine that periodical awakening with the asynchronous awakening.
Here is my code:
void setup(){

    Serial.begin(9600);

    //Pines declaration

    loopsToSend = setTimeToSend();  //

    //The three async buttons
    PCintPort::attachInterrupt(4, readOpinion,RISING);
    PCintPort::attachInterrupt(5, readOpinion,RISING);
    PCintPort::attachInterrupt(6, readOpinion,RISING);
}

void loop(){

    if(loops < loopsToSend ){

        byte opinionValue = readOpinion(); //This method must awake the Arduino ASYNC to give a value to the opinionValue var, write the result in the file and go to sleep

        if(opinionValue != 0){
            Serial.println("Button pressed!");

            //Writing result in a file
            opiniones++;
            delay(500);
        }
        //Go to sleep 8 seconds
        LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
        opinionValue = 0;
    }
    else {
        wdt_disable();

        if(opiniones > 0){
            //Send file using GSM module
        }
        else{
            loops = 0;
        }
    }
    loops++;
}

Can anyone help me? Thanks

Only the INT0 (pin2) and INT1 (pin3) pins can wake the arduino from SLEEP_MODE_PWR_DOWN. So I don't know how the buttons could have worked in the first place. Are you sure the uC was really sleeping?

But I´m using the PinChangeInt.h to use any pin to generate the interrupt and it works.

@Gerben According to Nick Gammons How do interrupts work on the Arduino Uno and similar boards? refference Q/A and the comments bellow, it woks (I've tested it). The External Interrupts in all modes and PinChange interrupts too.

This is an exact duplicate of https://arduino.stackexchange.com/q/31659/17196

This one works for me:
#include <PinChangeInterrupt.h>
#include <LowPower.h>

// I want to know when it was interrupted by PCINT:
volatile byte flag = 0;
void handler() {
    flag = 1;
}

void setup() {
  Serial.begin(115200);
  pinMode(A0, INPUT_PULLUP);
  attachPCINT(digitalPinToPCINT(A0), handler, CHANGE);
}

void loop() {
  Serial.println("entering powerDown sleep mode");
  Serial.flush(); // wait for sending all data

  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);

  if (flag == 1) {
    flag = 0;
    Serial.println("Pin change interrupt");
  } else {
    Serial.println("Timeout");
  }
}

However if you use RISING (or FALLING), it also wakes up from the sleep when pin changes back to the oposite state (and it'll be reported as Timeout).

authors: Олександр Пасенко


text:
What is the theory behind the Arduino UNO being able to create AM waves at 800 kHz
I am doing a school project and saw someone use an Arduino and a piece of wire as an antenna here: https://forum.arduino.cc/index.php?topic=88422.0
I've tested this experiment and it works, but I have searched the internet for some time now for some background knowledge or theory on why this works, and how does it?
If anyone knows anything about the arduino creating simple AM waves, could you please let me know about it or redirect me to another source.
For some context, in this school project I've got to explain the theory behind creating basic AM waves and amplitude modulation in general, then prove the theory by conducting this experiment which I prove it correct.

That code just generates a 800kHz PWM signal, that is then turned on and of to greater the clicking sound you get.

Strictly speaking it's not AM, it's OOK (On-Off Keying) which just turns a carrier frequency (800kHz PWM, 50% duty cycle) on and off.
Many cheap 443MHz (eBay) modules do the same thing - turn the carrier frequency on and off.
The presence of the carrier frequency is seen as a logic 1 and the absence as a logic 0.
The fact that it's using PWM to generate a square wave means that the "cleanliness" of the signal will be incredibly horrible. You really want to get the carrier frequency as close to a pure sine wave as possible. A square wave has lots of harmonics at 3x, 5x, 7x, 9x etc the frequency. So your 800kHz signal will also have a 2.4MHz signal, a 4MHz signal, a 5.6MHz signal and so on, each at a lower level. That causes interference in other signals.
To understand more about why it works you first have to understand radio transmission theory, and that's not something we can cover on an Arduino site (it's an entire college course all by itself).

How do you get 2.4, 4.8, and 7.2 MHz from  6x, 6x, and 9x?

@JamesWaldby-jwpat7 Through the careful use of a typo. Should have been 3x 6x 9x. Actually there should be 5x and 7x in there too. And 6 is wrong.

I thought that might be the technique used!  So useful sometimes :)

It works because everything is wrong. A perfect sine wave of 800 kHz would not transmit very well with such a small wire as antenna.
The output signal is a digital pulse (PWM signal) with very sharp edges. Those edges create many harmonics as Majenko wrote. It is those high harmonic frequencies that can use that small wire as antenna. The receiver might get help of those harmonic frequencies to combine them with the base signal to be able to receive the base signal of 800kHz. The receiver might also receive the electrical field coupling (capacitive coupling) instead of really receiving radio signals. The electrical (capacitive) coupling might even be main part of what is received.
You could add a large antenna or a large open coil or a tuned circuit of a coil with a capacitor. That should increase the range, because that will transmit real radio signals.
The Arduino board with the wire can not be used to explain AM radio signals, because it is not a AM radio signal. You can also not use it to explain AM modulation, because there is no modulation (only on/off).
Do you know someone who has equipment to make modulated AM signals ?
Last but not least: it is illegal to transmit at 800kHz.

authors: Максим Попов


text:
Arduino programming with multiple loops
I was trying to program my Arduino (along with a connected motor controller) to switch from cycle to cycle with this program.  It doesn't seem to work however.  There's still plenty of storage space and dynamic memory, so those aren't the issue.  This is the program:
int EnablePin1 = 8;
int duty;
int period;
int cycle;

int PWMPinA1 = 11;
int PWMPinB1 = 3;
int PWMPinA3 = 6;
int PWMPinB3 = 5;

const byte CPin1 = A0;

int CRaw1;
void setup() {

    Serial.begin(9600);

    pinMode(EnablePin1, OUTPUT);

    pinMode(PWMPinA1, OUTPUT);
    pinMode(PWMPinB1, OUTPUT);
    pinMode(PWMPinA3, OUTPUT);
    pinMode(PWMPinB3, OUTPUT);

}

void loop() {
    digitalWrite(EnablePin1, HIGH); //enable the board
    for (duty = 0; duty <= 255; duty += 15)
    {

        analogWrite(PWMPinB1, 0); //Set pinB to 0, when speed is written to pinA

        analogWrite(PWMPinA1, 255);
        delay(850);
        if (PWMPinA1 == 11)
        {
            PWMPinA1 = 3;
            PWMPinB1 = 11;
        }
        else
        {
            PWMPinA1 = 11;
            PWMPinB1 = 3;
        }
   }
   analogWrite(PWMPinA1,0);//end at max speed
   analogWrite(PWMPinB1,0);
   CRaw1 = analogRead(CPin1);

   Serial.println("Feedback");

   Serial.print(CRaw1);

   delay(2000);
   //analogWrite(PWMPinB3, 0);
   for (duty = 255; duty >= 0; duty -= 51) // ramp down speed
   {
       //analogWrite(PWMPinA1, duty);
       analogWrite(PWMPinB3, 0);
       analogWrite(PWMPinA3, 255);
       delay(period);
       //delay(cycle);
       if(PWMPinA3 == 6)
       {
           PWMPinA3 = 5;
           PWMPinB3 = 6;
           //period = 850;
       }
       else
       {
           PWMPinA3 = 6;
           PWMPinB3 = 5;
          //period = 2500;
       }
   }
   analogWrite(PWMPinA3, 0); //set to 0 speed
   analogWrite(PWMPinB3, 0);
   delay(2000);

   digitalWrite(EnablePin1, LOW);// Toggle enable to reset the power chips           if we have had an overcurrent or overtemp fault

   for (cycle = 1000; cycle < 9000; cycle += 4000)
   {
       //cycle=period;
       period=cycle;
   }

 /*for (cycle = 2000; cycle <= 3000; cycle += 1000)
   {
       //cycle=period;
       period=10000;
   }*/
   for (cycle = 9000; cycle >= 1000; cycle -= 8000)
   {
       period=0;
   }

   //delay(2000);  // Swap pins to make the motor change direction

}//end main loop

I've also tried having the cycle loops be this:
 for (cycle = 0; cycle < 9000; cycle += 3000)
 {
     //cycle=period;
     period=cycle;
 }
 for (cycle = 9000; cycle >= 0; cycle -= 9000)
 {
     //cycle=period/3;
     period=cycle;
 }

But that didn't do anything (I can see what PWM pins are powered through LEDs, and the first attempt, the LEDs only lit up for 1 second and the 2nd, they didn't light up at all.

doesn't seem to work .... this is a very poor description of observed results .... it contains no information that could be used to solve the problem ............ what do you expect to happen? .... what did happen? ....  and what is your question?

Why are you changing the values of the pin numbers? Doesn't seem good. And what should the for loops actually do? Currently they only set the variable period multiple times without doing something with it. The second loop only runs once. The variable period is not used ever again. This code part does absolutely nothing. You need to explain way more, what you want to achieve and what the problems are with this.

duty should be renamed: it's not a duty cycle, and its name is misleading. period should be initialized before use. The loops over cycle should be removed: they serve no useful purpose (and the compiler will remove them anyway). The biggest issue is that, on reading the program, its purpose is not clear at all. And the description in your question (“switch from cycle to cycle”) makes no sense. If you want to have any hope of receiving a useful answer, you should write a clear and complete description of what the program is supposed to do.

First things, try to use multiple function and call it from the loop()
You can use some code magic for dealing with multitasking on Arduino.
It's a bit tricky to understand but it's working.
Here is an example :

const int BROCHE_LED_1 = 13;
const int BROCHE_LED_2 = 12;
const int BROCHE_LED_3 = 11;

const unsigned long BLINK_INTERVAL_1 = 1000;
const unsigned long BLINK_INTERVAL_2 = 500;
const unsigned long BLINK_INTERVAL_3 = 2000;

void setup() {

  pinMode(BROCHE_LED_1, OUTPUT);
  pinMode(BROCHE_LED_2, OUTPUT);
  pinMode(BROCHE_LED_3, OUTPUT);

  digitalWrite(BROCHE_LED_1, LOW);
  digitalWrite(BROCHE_LED_2, LOW);
  digitalWrite(BROCHE_LED_3, LOW);
}

void loop() {

  task_led1();
  task_led2();
  task_led3();
}

void task_led1() {
  static unsigned long previousMillisLed1 = 0;
  static byte etatBrocheLed1 = LOW;

  unsigned long currentMillis = millis();

  if(currentMillis - previousMillisLed1 >= BLINK_INTERVAL_1) {

    previousMillisLed1 = currentMillis;

    etatBrocheLed1 = !etatBrocheLed1;
    digitalWrite(BROCHE_LED_1, etatBrocheLed1);
  }
}

void task_led2() {
  static unsigned long previousMillisLed2 = 0;
  static byte etatBrocheLed2 = LOW;

  unsigned long currentMillis = millis();

  if(currentMillis - previousMillisLed2 >= BLINK_INTERVAL_2) {

    previousMillisLed2 = currentMillis;

    etatBrocheLed2 = !etatBrocheLed2;
    digitalWrite(BROCHE_LED_2, etatBrocheLed2);
  }
}

void task_led3() {
  static unsigned long previousMillisLed3 = 0;
  static byte etatBrocheLed3 = LOW;

  unsigned long currentMillis = millis();

  if(currentMillis - previousMillisLed3 >= BLINK_INTERVAL_3) {

    previousMillisLed3 = currentMillis;

    etatBrocheLed3 = !etatBrocheLed3;
    digitalWrite(BROCHE_LED_3, etatBrocheLed3);
  }
}

Second things, Try to use Real time operating system
You can try to use FreeRTOS, it's work with most arduino and you got lot of infos on the web.
It make multi tasking way more easy than the previous example.
Here is the Docs i've found


text:
Uno went in washer and when I shake I hear something shaking around. What do I hear?
My friends Uno went in washer. I gave it a week to dry and when i plug it in, it works. But when I shake I hear something shaking around inside it. What do I hear shaking around?

There is no "inside" to have something shaking around, other than maybe the spaces in the DIP socket. Remove the DIP chip and see if there's something stuck in there.

Unless of course you have it in some form of case, in which case take it out of the case and case the joint. (English is a fun language, isn't it? ;) )

Ok, I will try your suggestion. (Yes English is.)

Just checked the socket. Nothing there. I shook it with the processor removed but I still hear something.

Maybe it’s the crystal? Idk.

Maybe it's in the power jack socket.

Possibly. At least it works.

My guess would be the pushy-part of the reset button. Try putting your finger on different part, then shake, and see if the sound is still there. I don't think it's something to worry about. As for the washing machine part; I wouldn't use that Arduino on something really important. Though it's probably fine.

it is probably the bits in the bit bucket ... lol

But the real question is does the magic smoke come out when you plug it in and turn it on.

Did you examine the board carefully no electronic part is broken or came out of PCB?

your question is not really about an arduino ... the same question could apply to a box of matches

It could be the USB port, barrel jack port, or most likely the pin header. The pin headers are a plastic shell with a two-point prong thing that goes in it. the pin could have desoldered when in the washer. check the pin headers. It might also be the inside of capacitors but that is highly unlikely.


text:
Getting enum name from enum instance
Hello Arduino Stack Exchange,
I have an an enum instance called state:
enum States
{
  SLEEP,
  AWAKE,
  CRAZY
} state;
States state = SLEEP;

I would like to convert the value of state to a String so I can serially print it using Serial.println().
Currently, when I type String(state), I get a value 0, 1, etc.  I suppose this corresponds with the index of the enum's key.
How can I get it to return "SLEEP", "AWAKE", etc.?

your question is unrelated to the Arduino ... it is a C++ question ... please do some research about enums and about arrays

Will do @jsotola, thanks!

the arrays is a hint towards the solution

States state = IDLE; will not compile :)

Ah shoot @DataFiddler thanks for pointing that out.  My actual code has more enum cases, IDLE was one of them.  I updated the question to remove it

and did you read my answer?

Yes I had already read it, finally got around to testing it.  Thank you @Juraj

You can print the value as it is:
Serial.println(state);

This will print the the ordering number of the enum, but you can specify the value as any number or char.
enum States
{
  SLEEP = 'S',
  AWAKE = 'A',
  CRAZY = 'C'
};

Now if you print it with cast to char Serial.println((char) state); it will print a character, which in my opinion is much better then some number.
If you want to convert the enum values identifiers to strings you can do it with a preprocessor macro.
enum States
{
  SLEEP,
  AWAKE,
  CRAZY
} state;

#define IDNAME(name) #name
const char* stateNames[] = {IDNAME(SLEEP), IDNAME(AWAKE), IDNAME(CRAZY)};

I don't think this is better then to print the char values. To do a pretty print it is better to use descriptions.
const char* stateStr[] = {"Sleep", "Awake", "Undefined"};
Serial.println(stateStr[state]);

Love it.  Took me a minute (coming from Python) to realize #name wasn't a comment.  I used the preprocessor macro method, thank you!


text:
Arduino sleep mode problem while sending data with gsm module
i am trying to send gps data via sim800l gsm module. Working fine without the power down code but when i add the power down code it stops working (not sending the gps data. code execution stops in sendGPS() function). Tried different functions but i could not get it work. Thanks.
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
#include <avr/power.h>
#include <avr/sleep.h>
#include <avr/wdt.h>

volatile bool flag_wdt=HIGH;                           // flag of watchdog
ISR(WDT_vect) {                                        // Watchdog Interrupt Service est exécité lors d'un timeout du WDT
  if(flag_wdt == LOW){flag_wdt = HIGH;}                // Reset watchdog flag
}

void setup_my_watchdog(const byte interval) {
  MCUSR = 0;                              // reset various flags
  WDTCSR |= 0b00011000;                   // see docs, set WDCE, WDE
  WDTCSR =  0b01000000 | interval;        // set WDIE, and appropriate delay
  wdt_reset();
}

TinyGPSPlus gps;
int RXPin = 8;
int TXPin = 9;
int GPSBaud = 9600;
SoftwareSerial gpsSerial(RXPin, TXPin);
SoftwareSerial gprsSerial(2, 3); // RX, TX

void enterSleep(int hour_to_sleep) {
  int i=0;                                // Create a counter
  //time_to_sleep = 360*hour_to_sleep;   // how many 10sec i need to sleep ? 6*60*hour(s)

  // ---------------------------- START Save power -------------------
  power_adc_disable();                  // ADC OFF
  power_spi_disable();                  // SPI OFF
  //power_twi_disable();                  // ? OFF
  power_usart0_disable();               // USART et USB COM OFF
  power_timer0_disable();               // Timer 0 OFF (attention timer0 utilisé par millis ou delay)
  //power_timer1_disable();               // Timer 1 OFF
  //power_timer2_disable();               // Timer 2 OFF
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // Configures the Atmega168 for the specified sleep mode

  for(i=0 ; i< hour_to_sleep ; i++){
    setup_my_watchdog(0b100001);          // Set-up first watchdog 8sec
    sleep_enable();                       // Enables the sleep mode to be entered;
    sleep_mode();                         // Entre dans le mode veille choisi
    // -----------------------------------// program restart here after watchdog 8sec timeout
    sleep_disable();                      // First : disable sleep mode
    setup_my_watchdog(0b000111);          // Set-up new watchdog 2sec
    sleep_enable();                       // Enables the sleep mode to be entered;
    sleep_mode();                         // Entre dans le mode veille choisi
    // -----------------------------------// program restart here after watchdog 2sec timeout
  }

  power_adc_enable();                  // ADC ON
  power_timer0_enable();               // Timer 0 ON
  power_usart0_enable();               // USART et USB COM OFF
}

void setup() {
  gpsSerial.begin(GPSBaud);
  gprsSerial.begin(9600);
  delay(10000);
}

void loop() {

    sendGPS();
    enterSleep(30);

}

void sendGPS() {
  gpsSerial.listen();
  while (gpsSerial.available() > 0) {
    if (gps.encode(gpsSerial.read()))
      if (gps.location.isValid())
      {
        gprsSerial.listen();
        String geo;
        geo.concat("field1=" + String(gps.location.lat(), 6));
        geo.concat("&field2=" + String(gps.location.lng(), 6));
        gprsSerial.println("AT");
        delay(1000);
        gprsSerial.println("AT+CGATT?");
        delay(1000);

        gprsSerial.println("AT+CIPSHUT");
        delay(1000);

        gprsSerial.println("AT+CIPSTATUS");
        delay(2000);

        gprsSerial.println("AT+CIPMUX=0");
        delay(2000);
        gprsSerial.println("AT+CSTT=\"internet\"");//start task and setting the APN,
        delay(1000);
        gprsSerial.println("AT+CIICR");//bring up wireless connection
        delay(3000);
        gprsSerial.println("AT+CIFSR");//get local IP adress
        delay(2000);
        gprsSerial.println("AT+CIPSPRT=0");
        delay(3000);
        gprsSerial.println("AT+CIPSTART=\"TCP\",\"api.thingspeak.com\",\"80\"");//start up the connection
        delay(6000);
        gprsSerial.println("AT+CIPSEND");//begin send data to remote server
        delay(4000);
        String str = "GET https://api.thingspeak.com/update?api_key=XXXXXXXXX" + String("&") + geo.c_str();
        String str1 = str + String("&");
        String str2 = str1 + geo.c_str();
        gprsSerial.println(str2);
        delay(4000);
        gprsSerial.println((char)26);//sending
        delay(5000);//waitting for reply, important! the time is base on the condition of internet
        gprsSerial.println();
        gprsSerial.println("AT+CIPSHUT");//close the connection
        delay(2000);
        delay(60000);
      }
  }
}

Define "stops working"...?

i mean not sending the gps data. code execution stops in sendGPS() function.

So... you're waking up, seeing there's no data to read (which there won't be - it's been asleep...), then going back to sleep again? Maybe you should actually wait until some valid data arrives before going back to sleep?


text:
Why is my liquid crystal display not showing any output?
UPDATE:
The LCD will light up only when the all my components are located in the bottom right of the breadboard. Why am I not able to use the entire breadboard for my circuit?
I am trying to display data from a temperature and humidity sensor on the serial monitor and the liquid crystal display.
I am using :

Arduino Uno R3
I2C 16x2 LCD Module
3 pin DHT11 sensor

Here is my code :
#include <dht.h>                // initialize the digital temperature and humidity sensor library ("DHTlib")
#include <LiquidCrystal_I2C.h>  // initialize the liquid crystal display library ("LiquidCrystal I2C")
#include <Wire.h>               // intialize the wire library

/*   the first parameter is the I2C address
 *   the second parameter is how many columns are on your screen
 *   the third parameter is how many rows are on your screen
*/
LiquidCrystal_I2C lcd(0x27, 16, 2);

dht DHT;              // create a handle to call functions from the sensor library
#define DHT11_PIN 7   // assign a digital pin number to the sensor
float TempC;          // create a variable to store temperature in celsius
float TempF;          // create a variable to store temperature in fahrenheit
float Humi;           // create a variable to store humidity

void setup()
{
  lcd.init();                // initialize liquid crystal display
  lcd.backlight();           // turn on the backlight of the lcd
  pinMode(DHT11_PIN,INPUT);  // configure the pin for the sensor as an input for reading the data
  Serial.begin(9600);        // set data rate in bits per second for serial data transmission
}

void loop()
{
  // collect sensor data
  int chk = DHT.read11(DHT11_PIN);  // store sensor data in a variable
  TempC = DHT.temperature;          // store temperature in Celsius
  TempF = 9 / 5 * TempC + 32;       // store temperature in Fahrenheit
  Humi = DHT.humidity;              // store relative humidity as a percentage

  // display sensor data on LCD
  lcd.setCursor(0,0);    //tell the screen to write on the top row
  lcd.print("T: ");
  lcd.print(TempC);    // print the temperature in Celsius
//  lcd.print(TempF);    // print the temperature in Fahrenheit
  lcd.print((char)223);  // print the degree symbol
  lcd.print(" C");
//  lcd.print(" F");
  lcd.setCursor(0,1);    // tell the screen to write on the bottom row
  lcd.print("H: ");
  lcd.print(Humi);       // print the humidity
  lcd.print(" %");

  // display sensor data on the serial monitor
  Serial.print("Temperature = ");
  Serial.print(TempC);     // print the temperature in Celsius
//  Serial.print(TempF);     // print the temperature in Fahrenheit
  Serial.print("\xc2\xb0");  // print the degree symbol
  Serial.println(" C");
//  Serial.println(" F");
  Serial.print("Humidity = ");
  Serial.print(Humi);        // print the humidity
  Serial.println(" %");

  delay(2000);  //delay fetching the next sensor values for 2 seconds
}

My jumper wires are connected as follows:

DHT plus → red plus row
DHT middle → digital pin 7
DHT minus → blue minus row
LCD GND → blue minus row
LCD VCC → red plus row
LCD SDA → analog pin A4
LCD SCL → analog pin A5
Red plus row → 5V pin
Blue minus row → GND pin

Do you not see a breadboard, an arduino board, a liquid crystal display, a sensor, and jumper wires all hooked up?

The picture is unusable, dark and low resolution. Pin names and wire paths are not clearly visible. These allow others to try to identify your problem and it would be a good idea to put some more effort into getting them across clearly. It might also be a good idea to describe your setup in text (such as which pins are connected to which other pins).

Btw, it looks like there’s nothing connected to the (I2C) SDA and SCL pins on your Arduino, but it’s hard to make out. There’s also no way to see if the power pins of your LCD are properly connected.

All right, I put a new picture, and I explained the setup. Is there an error in my code or in my circuit?

Did you try moving the knob on the I2C 16x2 LCD Module for changing the contrast?

@MichelKeijzers I was finally able to get the LCD to light up and show sensor data. The breadboard I have is divided roughly into 4 sections. The circuit works only if all of my components are contained in one quadrant.

@MichelKeijzers I have not tried turning the knob. I do have a contrast issue and it is too bright to see anything properly. Do you know what type of screwdriver will fit?

A small screwdriver, simple one, they are called precision screwdrivers sometimes. You also could try it with your finger nail or something small.

Your breadboard is one of those which have the power/GND lines interrupted between columns 31 and 33. I also once fell into this trap. If you look closely, you see that the blue and red lines are interrupted in the middle of the board. Just put wires between these pins to bridge the gap.

Thanks! I never realized my problem was so trivial!

Glad I could help. If this answer helped you, please don't forget to accept it.


text:
Displaying when Button has been pressed for LED and returning 1
I've just started using Arduino and I'm having trouble getting my code right.
Here is the task I need to do.
"Create a button read function
  Hint: the function header should be int checkbutton ( void )
in the loop function, add code such that if the button has been pressed (i.e. the checkbutton function
returns 1), a message is sent to the serial monitor with your username."
There are no errors in the code but nothing happens in the serial monitor when I press the LED button and it does not return 0 when i don't press the LED button.
Any sort of help would be appreciated!
Thanks!
int Button = 15; //LED and output are on the same pin

int last = 0;

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

int button() {
  pinMode(Button, INPUT);

  int current = digitalRead(Button);

  if (current and not last) {
    delay(5);

    pinMode(Button, OUTPUT);

    Serial.print("Hey");
    return 1;
  }

  else {
    pinMode(Button, OUTPUT);

    current == last;

    return 0;
  }
}

void loop() {
  if (button >=0)
  {
    button();
  }

  else
  {
    ;
  }
}

Look up the StateChangeDetection example that is provided within the Arduino IDE, as well as https://www.arduino.cc/en/Tutorial/Button

Also, it depends on the microcontroller, but on most arduino products the LED is on pin 13 not 15

is this a school assignment?

In your button() function, the line
if (current and not last) {

is less common syntax. The more common equivalent is:
if (current && !last) {

(see https://stackoverflow.com/questions/2376448/the-written-versions-of-the-logical-operators)
This line:
current == last;

Has no effect and is incorrect. This ( “==“ ) is not an assignment but a comparison and does not do what you want it to do.
I also think you have this the wrong way around. You want to save the “last” button state to compare it with the current button state when you call button() the next time. So you would need to set “last” to the current button state, like this:
last = current;

The next time you call button(), “last” contains the previous button state, so your comparison to the current button state will work.
And I think your button detection code would work better if you set last = current each time you call button(), whether a button has been pressed or not. Otherwise your code would repeatedly keep printing “Hey” until you stop pushing the button (unless that’s what you want). Like so:
int button() {
  pinMode(Button, INPUT);

  int current = digitalRead(Button);

  if (current &&  !last) {
    ...
    ...

    Serial.print("Hey");
    last = current; // Insert here
    return 1;
  }

  else {
    pinMode(Button, OUTPUT);
    ...

(This has not been tested but should give you a general idea).

Thank you very much! Fixed my code and helped increase my understanding, much appreciated.

Your problem may only be that you are not calling the button function. Try changing if (button >=0) to if (button() >=0).

Ah yes, you're right. I made the change and now the serial monitor is printing hey but its not returning 1, nor am i getting 0 when i do not press the button. Btw, thanks for the edit! Much appreciated.

If you want to print 0 and 1 to the serial console you'll need to add the Serial.print(...) calls. If I understand what you want correctly, you may be able to replace the entire body of loop() with Serial.println(loop());


text:
Program giving one type of output in arduino ide stm32f1xx board version 2019.10.9 giving different output in board verison 2019.12.31
 void setup() {

      Serial.begin(9600);
      Serial1.begin(9600);
      Serial1.println("HM 10 here");
      Serial.println("STM32 here");

    }

 void loop() {

      char inputdata;
      while (Serial1.available()){
      Serial.println("In loop");
      inputdata = (char)Serial1.read();
      Serial.println(inputdata);

    }

With this code , I was able to send signals to hm10 and was able to see the sent signals in serial monitor of arduino ide in the 2019.10.9 version but not in 2019.12.31.
I am dumping the code on stm32 using ftdi driver.
I am sending the string "hai" from BLE terminal app.
I updated my arduino library board manager and stm32f1xx board version upgraded to version 2019.12.31.
In stm32f1xx board version 2019.10.9 , when i send values from the app to hm10 , i get this output on serial monitor
STM32 here
In loop

In loop
h
In loop
a
In loop
i
In loop

In loop

But in the case of stm32f1xx board version 2019.12.31 , i get this output on serial monitor
HM 10 here
STM32 here

If I have to use any libraries do guide me..

It is not clear, what the problem is. Am I understanding correct, that you have problems with 2 different board definitions? What do you mean by, that you were able to send signals or where not? What is actually happening, when you send data from the HM10? (Sending data from the PC to the Arduino won't do anything, as you don't have code for that).

what is "stm32f1xx board version 2019.x.x"? git master branch commits in rogerclarkmelbourne/Arduino_STM32?

@chrisl , yes i think the different board versions are giving different output

@Juraj , I used http://dan.drown.org/stm32duino/package_STM32duino_index.json

@Juraj , no , I followed from this website - https://circuitdigest.com/microcontroller-projects/getting-started-with-stm32-development-board-stm32f103c8-using-arduino-ide , i found the package in that link

I confirmed it on stm32duino forum. This are builds of Roger Clark's STM32 core. This are not releases, but hourly builds published after every commit to the repository. I recommend https://www.stm32duino.com forum


text:
Blank output in serial monitor
So my SIM900 GSM Shield is working fine with Netlight LED blinking and Status LED solid light, after I upload the code nothing happens about mySerial() in my serial monitor. Can I take your time for you to check this code out? I wonder if the problem lies here.
#include<SoftwareSerial.h>

//Create software serial object to communicate with SIM900
SoftwareSerial mySerial(7, 8); //SIM900 Tx & Rx is connected to Arduino #7 & #8

/*void SIM900power()
{
  pinMode(9, OUTPUT);
  digitalWrite(9,LOW);
  delay(1000);
  digitalWrite(9,HIGH);
  delay(2000);
  digitalWrite(9,LOW);
  delay(3000);
}*/
void setup() {
  // put your setup code here, to run once:
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);
  //Begin serial communication with Arduino and SIM900
  mySerial.begin(9600);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT"); //Handshaking with SIM900
  updateSerial();
  mySerial.println("AT+CSQ"); //Signal quality test, value range is 0-31 , 31 is the best
  updateSerial();
  mySerial.println("AT+CCID"); //Read SIM information to confirm whether the SIM is plugged
  updateSerial();
  mySerial.println("AT+CREG?"); //Check whether it has registered in the network
  updateSerial();
  mySerial.println("AT+COPS?"); // Check that you're connected to the network;
  updateSerial();
}

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

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

Output:

What is the purpose of SIM900power()? You defined it but never used it.

I've just commented it and yet it only outputs "initializing.."

your code contains a command that forces the arduino to stop and do nothing for 500 ms with every iteration of loop()

look at the arduino software serial example code and compare it to your code

This is the site where I copy the code: link. It didnt explain the part about why it was delay(500) so Im not aware of it how works. @jsotola

I will reconsider your suggestion. :)

Are you sure, that you are using the correct baudrate? When the communication does not work, but the module is behaving correctly otherwise, this might be the problem.

I figured it out! Silly me. I just rewired it. Thanks for all of your opinion. :D

@TechHermit Then please either answer your own question or delete the question. The comments are not permanent. If they get deleted others will think, that this problem wasn't solved

Step 1) Check RX TX connections
Step 2) Change your baud rate to 115200. Turn off your arduino. Turn off gsm. Start your gsm first and then your arduino.
or
Step 3) Upload Software Serial code and just send "AT" without quotes using serial monitor. If your connections are correct you should get reply as AT.
Also make sure to set the baud rates to 115200.
Most of the GSM modules have default baud rate at 115200 or have auto baud adjustment enabled but need to be power cycled.


text:
Power Source for Arduino
So I have SIM900 Shield and Arduino Uno and they have both power jack, is it possible to power one of them using one power jack and connect it's power with another? If it is possible, I sincerely need the explanation.
I've research about the VIN pin of Arduino but I didnt quite get it and can't take the risk that I might fry the board since Im new here.

It depends on what voltage the devices run at and what their current draw is from the power supply versus what voltage & current your power supply provides.
If everything runs at 3.3V or 5V and minimal amps then you're good to go.
Read the datasheet for each device and for your power supply.


text:
NEO-6M is working but it doesnt show data
So I'm having a little bit of difficulty here in my NEO-6M. The problem is it doesn't show any data in my serial monitor. My NEO-6M Led is already blinking so its already ok.
RX -> Pin3 , TX -> Pin4 , VCC -> 3.3v , GND -> GND

Serial Monitor:

Code:
https://github.com/mikalhart/TinyGPSPlus/blob/master/examples/FullExample/FullExample.ino

Have you crossed the serial lines? Arduino RX to GPS TX, Arduino TX to GPS RX

I have but I already fix it, does it broke my neo?

What do you mean? The lines need to be crossed. And having them not crossed most likely doesn't break it

Iv'e updated it now. @chrisl

I found a solution to my problem. On my first setup, I separate my GND of NEO-6M to Arduino and put connect it in breadboard that has powerboard on it because I thought it is only for electrical purposes but it doesn't since I encounter it.
Solution:

The GND of every module must still connect on the Arduino.


text:
stepper motor doesn't work but get no error message
So I work for a department that uses arduino to move a stepper motor for a wave machine and I am encountering a issue.  They gave me the code that they used to use but it doesn't move the motor and just makes this intermittent beeping noise.
My code is as follows:
int pulse_delay = 20;
int wave_period = 1000;

void setup() {
pinMode(8,OUTPUT);
pinMode(9,OUTPUT);
digitalWrite(8,LOW);
digitalWrite(9,LOW);
}

void loop() {
digitalWrite(9,HIGH);
delay(10000);
for (int i=0;i<wave_period;i++)
{
  digitalWrite(8,HIGH);
  delayMicroseconds(pulse_delay);
  digitalWrite(8,LOW);
  delayMicroseconds(pulse_delay);
}
digitalWrite(9,LOW);
for (int i=0;i<wave_period;i++)
{
  digitalWrite(8,HIGH);
  delayMicroseconds(pulse_delay);
  digitalWrite(8,LOW);
  delayMicroseconds(pulse_delay);
  }
}

I do not receive any error messages and the IDE just says upload complete.  We use a Arduino Mega board. I am pretty new to Arduino.
Edit:
Someone asked for pictures about how it was connected.  Sorry for the late response, had a family emergency.

The cable coming in from the bottom of first picture is from the stepper motor, as is the cable I'm holding but that is what I was told isn't necessary.

I guess I am asking if there is something missing from the code or if there is something I can add to it to see where the code stops.

motors need quite a bit of current (more than the GPIO pins can handle), can you describe how you connected the stepper?

It has 2.  One is I believe a HX2.54 5 pin cable.  The other I have no idea, it has a black base and 4 long prongs that stick out but I have been told they didn't need to use those.  I will try and ask my supervisor when they come back from teaching.

We also plug that cable into the arduino board and the board is what is plugged into an outlet.

Between the Arduino and the stepper motor there has to be a driver circuit. It controls the phases of the motor according to the pulses and the direction pin and provides the motor with the needed power. Please show an image of the circuit, where we can see how everything is connected

Ok, currently at my other department(I work for 2).  I will go back this afternoon to take a picture of the board and motor to post.

In your images I see more wires running between the Arduino and the (assumed) driver board (the green one at the bottom). As the driver board has good connectors and the connector from the motor seems to fit, I would guess, that the driver is connected correctly, but that the signals from the Arduino aren't what the motor driver expects. Can you tell us, what motor driver this is, so that we could look up a datasheet?

The only identification I can find on the green board is CDV524-K     TV8 1U54101 and what I guess is a date 2016/08 and its from Oriental Motor Co.

Here you can find the manual of your stepper driver.
Look at page in the section "CN3 (I/O signals)". Beside the pulse and directions, that you already set in your code, there are 2 more input signals defined: AWO will turn off the motor completely, if you provide a signal, CS changes the source of the step angle setting. As you don't configure any pins, other than pulse and direction, the other pins on the Arduino are set as input/high impedance. The state of these pins can float wildly depending on what noise is comming by. I don't know, if this really matters for this driver, but you should try to provide a valid state on all the input pins of the driver. For example a floating AWO pin might randomly disable and enable your motor very fast (which would at least fit with the described behavior). Set the corresponding pin on the Arduino as output (via pinMode()) and give them the state, that you want via digitalWrite() (I suggest LOW for AWO to enable the motors and HIGH for CS to get the basic step angle).
I cannot see on your images, if everything is connected to the driver, as it should (here a wiring diagram or a schematic would help). For now I assume, that the signal pins on the Arduino side are connected correctly.
The input signals of the driver are meant to be provided by a pair of twisted wires. This is done to minimize noise on the line. Thus all input signals have 2 pins: "+" and "-". Connect all "-" pins to ground and the "+" pins to the appropriate digital output pin on the Arduino.
If a have a oscilloscope or a logic analyzer, you can also monitor the ALM and TIM outputs of the driver. Maybe they are showing, what is going wrong.
Let us know, if this helps.

What are 8 and 9 plugged into on your stepper?
also define your baud rate based on the motor requirements.

void setup() {
pinMode(8,OUTPUT); < should be PUL
pinMode(9,OUTPUT); < should be ENA(maybe dir)
digitalWrite(8,LOW);
digitalWrite(9,LOW);
Serial.begin(115200);
}

void loop() {
digitalWrite(9,HIGH);
delay(10000);
for (int i=0;i<1000;i++)
{
  digitalWrite(8,HIGH);
  delayMicroseconds(20);
  digitalWrite(8,LOW);
  delayMicroseconds(20);
}
digitalWrite(9,LOW);
for (int i=0;i<1000;i++)
{
  digitalWrite(8,HIGH);
  delayMicroseconds(20);
  digitalWrite(8,LOW);
  delayMicroseconds(20);
  }
}

How does this answer the question? What has Serial and it's baudrate to do with the stepper motors? And the function Serial.begin() is with a lower case b.

You.. I tested this code (corrected the SMALLL typo) on a servo I have here and it worked... So? Did you do anything to try and help this person?

In the 9, LOW for loop I get a wave_period not declared error.

once again not adding value.

OK, then I guess I don't know what you want.  I posted pictures of what is plugged in and I tried your code.  Thanks for your help anyways.

@chas I didn't want to insult you, so if I did, sorry. Your working code is different from the non-working code of the OP only in the Serial.begin() line. Thus you propagate, that this line is the solution to the problem. I don't understand, how it could be, since the state of the Serial(UART) hardware should not effect any other digital outputs. If you know it otherwise, please explain, so that others can learn from it.


text:
Bootloader vs. Programmer
I have just started using Arduino boards and I am not sure what the programmers are. I read that you can use a bootloader or a programmer to run your code on an Arduino board. I also read that running with a programmer does not take up any memory space for the bootloader and does not take any time to go through the bootloader.
My question is then, why should I not upload my code during development using a programmer?

you definitely can do that if you want ... it is unclear why you think otherwise .... also your question is bogus because it is asking for a reason about something that does not exist

The bootloader is a 'program' that resides inside the Atmel IC and makes that IC an 'Arduino'. The bootloader takes care that a sketch can be retrieved by UART (via the USB) and stored inside the Arduino.
The programmer is an external hardware device that can upload a sketch without using the bootloader. Another Arduino can also be used as programmer.
In both cases, when a sketch is loaded, it can be run by the Arduino. The programmer does not need a bootloader, so the memory that normally is taken by the bootloader can be saved.
You could use a programmer, but normally there's plenty space for a sketch. Note, it's not the SRAM memory that is saved, only the Flash memory. And if you are reaching the limit of the Flash memory, you should either optimize it, or move to an Arduino with more Flash memory.
Also, the bootloader is much more easy to use, since you can upload the sketch (to the boatloader) with the Arduino IDE. Programming can be done too by the IDE but is less trivial.


text:
Can I connect an SD card shield to Digispark ATtiny85 board?
I have a Digispark ATtiny85 Arduino board (as shown in the picture). Can I connect a SD card shield to this board as a normal Arduino? How can I do that I'm new to this field?

Just connect the MISO, MOSI, and SCK pins. And use another pin to connect to the Chip Select of the SD card.

By "another pin" we mean "D5", since the other two pins are your USB connection.

So i must use D0, D1, D2, D5, power and ground right?

Yes, and then hope that there is SD software that fits in that rather underpowered chip.

you can get an sdcard module for under $1, might be worth it get rid of the ill-fitting jank...

Did you manage to connect SD card module to digispark?

In short I am going to say NO.
The flash is too small to adequately run the SD library as well as the rest of your Arduino code.
The RAM is also underpowered for what is needed to properly access files on an SD card.
Having said this, I am sure there are some clever software engineers that could write a cut down SD card library to do limited commands. Overall this is too hard for the beginner - Just buy an Arduino Uno/Mega/Due and avoid the unnecessary hassle.

Yes you can connect it: http://elm-chan.org/fsw/ff/00index_p.html
Your happiness depends on what you want to accomplish. Simple streaming, like feeding an FPGA with a bitstream is achievable. Logging an incoming data stream to the SD card filesystem is probably not.

Can I use the digispark as SD reader so when I connected to PC it will work as a flash drive?

#include <SPI.h>
#include <SD.h>

File file;
int const pinCS = 2;

void setup()

{
SD.begin(pinCS);
file = SD.open("Test.txt", FILE_WRITE);
file.println("anything");
file.close();}

void loop()
{}

This Arduino(ATmega) code creates to SD card a file "Test.txt" and records there a text "anything".
Dear Arduino experts, pls kindly, let me ask you, rewrite this code to ATtiny85.
It can helps to many Arduino hobby men.
Josef


text:
Function is executing when I try to store it in an array
I am trying to store a set of functions with different parameter in an array. When the code enters the function songlearn with tune==1 I want the functions with set parameters to be stored in the array without executing. What am I doing wrong? Here's my code:
const int x=100;
int (*SongSeq[x])();
int note[x];
int playNote(int midi, int row, int col, int len, bool short_led = false);
void songlearn(int tune);
int tune;

void songlearn (int tune){
  if (tune==1){
    state=1;
   lcd.clear();
  lcd.setCursor(4,0);
  lcd.print("Learning Song :");// Print a message to the LCD.
  lcd.setCursor(1, 1);
  lcd.print(menuP1);
// if (songpage==1){
// if (BackState==HIGH){//leaving song
//     posP=0;
//     Page=2;
//    Play(posP);
//    }
// }
  //Plays Mary Had a Little Lamb on a loop at 145 BPM
//Bar 1
SongSeq[0]= playNote(0x40, 3, 1, 414); //Quarter note: E
note[0]=0x40;
SongSeq[1]=playNote(0x3e, 2, 4, 414); //Quarter note: D
note[1]=0x3e;
SongSeq[2]=playNote(0x3c, 2, 2, 414); //Quarter note: C
note[2]=0x3c;
SongSeq[3]=playNote(0x3e, 2, 4, 414); //Quarter note: D
note[3]=0x3e;
//Bar 2
SongSeq[4]=playNote(0x40, 3, 1, 414,1); //Quarter note: E
note[4]=0x40;
SongSeq[5]=playNote(0x40, 3, 1, 414,1); //Quarter note: E
note[5]=0x40;
SongSeq[6]=playNote(0x40, 3, 1, 828,1); //Half note: E
note[6]=0x40;
//Bar 3
SongSeq[7]=playNote(0x3e, 2, 4, 414,1); //Quarter note: D
note[7]=0x3e;
SongSeq[8]=playNote(0x3e, 2, 4, 414,1); //Quarter note: D
note[8]=0x3e;
SongSeq[9]=playNote(0x3e, 2, 4, 828,1); //Half note: D
note[9]=0x3e;
//Bar 4
SongSeq[10]=playNote(0x40, 3, 1, 414); //Quarter note: E
note[10]=0x40;
SongSeq[11]=playNote(0x43, 3, 4, 414,1); //Quarter note: G
note[11]=0x43;
SongSeq[12]=playNote(0x43, 3, 4, 828,1); //Half note: G
note[12]=0x43;
//Bar 5
SongSeq[13]=playNote(0x40, 3, 1, 414); //Quarter note: E
note[13]=0x40;
SongSeq[14]=playNote(0x3e, 2, 4, 414); //Quarter note: D
note[14]=0x3e;
SongSeq[15]=playNote(0x3c, 2, 2, 414); //Quarter note: C
note[15]=0x3c;
SongSeq[16]=playNote(0x3e, 2, 4, 414); //Quarter note: D
note[16]=0x3e;
//Bar 6
SongSeq[17]=playNote(0x40, 3, 1, 414,1); //Quarter note: E
note[17]=0x40;
SongSeq[18]=playNote(0x40, 3, 1, 414,1); //Quarter note: E
note[18]=0x40;
SongSeq[19]=playNote(0x40, 3, 1, 414,1); //Quarter note: E
note[19]=0x40;
SongSeq[20]=playNote(0x40, 3, 1, 414,1); //Quarter note: E
note[20]=0x40;
//Bar 7
SongSeq[21]=playNote(0x3e, 2, 4, 414,1); //Quarter note: D
note[21]=0x3e;
SongSeq[22]=playNote(0x3e, 2, 4, 414,1); //Quarter note: D
note[22]=0x3e;
SongSeq[23]=playNote(0x40, 3, 1, 414); //Quarter note: E
note[23]=0x40;
SongSeq[24]=playNote(0x3e, 2, 4, 414); //Quarter note: D
note[24]=0x3e;
//Bar 8
SongSeq[25]=playNote(0x3c, 2, 2, 1656); //Whole note: C
note[25]=0x3c;

//End song
  }
 }
 int playNote(int midi, int row, int col, int len, bool short_led = false)
{
    int len1, len2;
    if (short_led) {
        len1 = len * 3 / 4;
        len2 = len * 1 / 4;
    } else {
        len1 = len;
        len2 = 0;
    }
    noteOn(0x90, midi, 100);
    digitalWrite(LedR[row], HIGH);
    digitalWrite(LedC[col], LOW);
    delay(len1);
    digitalWrite(LedR[row], LOW);
    digitalWrite(LedC[col], HIGH);
    delay(len2);
    noteOff(0x90, midi, 0);
}

You probably want to explain in greater detail what you meant by "storing functions in an array". It may be well understood to you but certainly not to others.

What you have done will certainly call the function. Since it is always the same function, just store the arguments into an array. Something like this:
const int COUNT = 100;

struct
  {
  int midi;
  int row;
  int col; int len;
  bool short_led;
  } notes [COUNT] = {
  { 0x40, 3, 1, 414 },  //Quarter note: E
  { 0x3e, 2, 4, 414 },  //Quarter note: D
  { 0x3c, 2, 2, 414 },  //Quarter note: C

  // and so on
  };

int playNote(int midi, int row, int col, int len, bool short_led = false);

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

void loop()
  {
  for (int i = 0; i < COUNT; i++)
    {
    if (notes [i].midi)
      playNote (notes [i].midi, notes [i].row, notes [i].col,
                notes [i].len, notes [i].short_led);
    }
  }

int playNote(int midi, int row, int col, int len, bool short_led)
{
    int len1, len2;
    if (short_led) {
        len1 = len * 3 / 4;
        len2 = len * 1 / 4;
    } else {
        len1 = len;
        len2 = 0;
    }
    noteOn(0x90, midi, 100);
    digitalWrite(LedR[row], HIGH);
    digitalWrite(LedC[col], LOW);
    delay(len1);
    digitalWrite(LedR[row], LOW);
    digitalWrite(LedC[col], HIGH);
    delay(len2);
    noteOff(0x90, midi, 0);
}

yeah but i want to be able to store the function in an array with the set parameters

Do you? I wonder why.
Anyway, you can do that by making an array of lambda functions like this:
const int COUNT = 100;

int playNote(int midi, int row, int col, int len, bool short_led = false);

void (*SongSeq[COUNT])() =
 {
 [] { playNote(0x40, 3, 1, 414); } ,
 [] { playNote(0x3e, 2, 4, 414); } ,
 [] { playNote(0x3c, 2, 2, 414); } ,
 [] { playNote(0x3e, 2, 4, 414); } ,

 // ... and so on

 };

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

void loop()
  {
  for (int i = 0; i < COUNT; i++)
    {
    if (SongSeq [i])
      SongSeq [i] ();
    }
  }

int playNote(int midi, int row, int col, int len, bool short_led)
{
  Serial.print ("Playing note ");
  Serial.println (midi);
  delay (100);
}

yeah but i want to be able to store the function in an array with the set parameters

i am getting an error: exit status 1
conflicting declaration 'void (* SongSeq [100])()'

The second sketch I posted above compiles without errors for me under IDE 1.6.9. Have you tried that exact code?

i was able to get it to work i had an extra int (*SongSeq [100] ) in the code which i got rid of. thank you for your help and guidance

Leave it to you, @Gammon.  Very clever use of code.

Calling or entering a function means executing it -- that is just how the language is defined. A 'function' is not a construct you can manage, i.e., store or otherwise mess-with (technical term!) in the ways you might do with other kinds of data. But:
You can store a function's address (i.e., a pointer to the function) and use the pointer to call the function, and you can store its parameters just as you would store any data. So, if I understand correctly what you want to do, try something like this crude outline based on my quick read of your code. It uses stored function pointers and song-numbers and shows how to call one of those functions with the associated, stored song number as a parameter:
// Ptr to a function and a song number
typedef struct {
   void (*pfunc)(int tune);
   int tuneNum;
} SONG_T;

#define COUNT 12

void songlearn(int);
void othersongfunc(int);
// void moresongfunctions(int);
// void moresongfunctions(int);

// Table of songs & functions:
SONG_T Songs[COUNT] = {
   {songlearn, 2},
   {othersongfunc, 1},
   {songlearn, 7},
   {othersongfunc, 3},
   // etc
};

void songlearn(int)
{
    ;   // does whatever it does
}

void othersongfunc(int)
{
    ;   // does whatever it does
}

void somefunc(uint8_t whichSong)
{
   if( whichSong < COUNT )
      (*Songs[whichSong].pfunc)(Songs[whichSong].tuneNum);
}

void setup(void)
{
   somefunc(3);
}

void loop(void)
{
   ;
}


text:
Connecting multiple load cells to the same microcontroller
This is my first post and I am a little bit confused about one thing.
I would need to do the following project:
have about 5-6 load cells to be connected to a microcontroller.
I am not sure if there is a way to connect multiple load cells to the same arduino.
I would need each load cell to act individually, so I would need an individual result from all each load cell.
I believe I would need to connect 1 load cell to 1 load cell amp and then connect the load cell amp to the Arduino and repeat this process 5-6 times (for each load cell that I need)
I'm not sure if this is possible using one Arduino or I would need 1 Arduino for each individual load cell.
The main idea of the project is to have a load cell to be placed under different kitchen supplies (1 load cell to continuously check the weight of Flower, another one to check for bread, another to check for paprika, and so on)
After this is read from the sensors, I need to write the weight of each item in a table / DB every 30 minutes.
Also, if this can be done with another board, like a microcontroller (Raspberry Pi) I'm open to that.

All you need is the following :

Arduino (Mega, if you need alot of inputs.)
Load Cell Amplifier
Load Cells (I recommend only using four wire cells)
Resistors (Only if you are connecting one cell to one amplifier)

If you are using only one load cell per "Scale" , you would connect it as you say correctly. One load cell to each load cell amplifier and then to the Arduino.
Yes, a single Arduino can in theory take as many scales as the number of Digital inputs you have can provide. You can use the Analog inputs as well but from my experience I would recommend you only use the Digital inputs. You can just share the power and ground sources.
Usually each Load Cell Amplifier will need to use two(2) Digital inputs.
If you want to use multiple load cells together (to improve accuracy) to act as a single scale, you would connect them together in what they call a Quarter, Half or Full Bridge wiring configuration depending on how many you would like working together.
You can write to a DB if you want sure.
What I personally like to do is send the readings to the cloud using dweet.io or ThingSpeak. ThingSpeak.com would probably be best for you.
I usually use the NodeMCU arduino boards that have WiFi built in. They are cheap and work great.
I hope this helps.

Thanks a lot for your answer, it helps very much. About sharing the same power (5v) and grounding, I just simply connect multiple wires to the same pin on the board? Won't that overload the pin, if for example, I connect 5 "energy draining" load cell amps to the same 5v pin?

Well in general , load cell amplifiers such as HX711 , based on their spec sheets, only draw 1.5ma . On an Arduino board, the maximum current draw per pin is 40ma for I/O pins and 200ma for VCC & GND . If you are using an Arduino UNO or something like that I recommend attaching a Proto shield on top of it which would give you some flexibility for your wiring and vcc / gnd sources.

You can use multiplexers to multiplex the loadcells and you can select the loadcells using only less selector pins


text:
Calculating Amp/Hrs of a solar panel
I am interested in calculating the amp/hour output of a solar panel using an Arduino. I am confident I can get the voltage (with a voltage divider) & the amperage (with an ACS712). My question is about the math of calculating Amp*hour.
Here is my plan:

My plan is to pull the voltage and amperage every second.
I would then add this amp*second value to a variable. I would also increment another variable for each second.
I would then be able to get an average or total of Ampseconds from these 2 variables. I could also divide the ampsecond by 3600 if I wanted Amp*Hour.

Is it too much a stretch to poll the amperage every second and call it amp/second? How can I make this more accurate?

and why do you measure the voltage?

Just one minor comment: It's Amp hours (Ah) and Amp seconds, not Amp/Hours. Otherwise your method for calculation seems correct. I would not  expect very accurate results though. You could use the voltage in the same way to calculate Watt Hours.

I was in the process of editing your answer, then decided against it. I'll just say it here instead: there's no such thing as amp/hour as a useful measurement. What you mean is amps*hours, or Ah (https://en.wikipedia.org/wiki/Ampere_hour). Also, change the word "pull" to poll. Those are two completely different English words, and what you mean is poll, or "ask repeatedly", not "pull", or "exert a force towards something", or "draw or haul towards you".

@Juraj I mentioned I have the voltage if by chance it was needed.

How to make your own coulomb counter (Amp*hours [Ahr] meter, or Watts*hours [Whr] energy meter) with an Arduino
Quick summary:
Jump straight down to the "Full coulomb counter example in code" section if you just want the final answer.
Details
There are a lot of misunderstandings here, but here is the gist of it.
What you want to do is a perfect application of an Arduino. No need to buy a coulomb counter, instead, you should make one with your Arduino.

I would then add this amp/second value to a variable.

First correction, it's an amp*second, NOT an amp/second. You are multiplying amps by the number of seconds that current value existed.
amp*seconds / 3600 = amp*hours. Read about that here: https://en.wikipedia.org/wiki/Ampere_hour. Multiply that by the voltage over that same time period and you've got amps*hours*volts = (amps*volts)*hours = Watts*hours = units of energy! Remember, your house electricity it purchased in units of kilowatt hours, which is kilowatts*hours, or kWhr. And in engineering units a joule is  the standard unit of energy, and it is simply Watts*seconds. So, you can convert kWhr to joules like this, where units are in square brackets [].
Joules = kWhr * 1000 [Whr/kWhr] * 3600 [sec/hr] = [Watts*sec] = [Joules]

So, 1 kWhr x 1000 x 3600 = 3600000 Joules = 3600kJ

I would also increment another variable for each second.

That doesn't make any sense. Don't do that. You've already captured the seconds by adding your new bit of amps*seconds to your old sum of it.
DO account for voltage too! What you're really after is energy, which can be expressed in units of joules or kWhr, as already described above.

Is it too much a stretch to poll the amperage every second and call it amp*second?

(my corrections in bold)
No, absolutely not! That's exactly what an amp*second is! It's the current, amps, times the number of seconds that current existed. That's a coulomb counter!
A. Making the coulomb counter as good as possible

How can I make this more accurate?

This is the part where the engineer and programmer (you) determines the quality of the result.

Don't assume 1 second elapsed because you told it to. Measure it for each and every measurement!
The smaller the time interval, the more accurate, since it allows you to capture the small current fluctuations, so use a smaller time slice than 1 second. I'd start with 10ms.
Measure voltage AND current AND actual time elapsed on this loop as close to the same time as possible.
Do NOT use blocking techniques, such as delay() or delayMicroseconds().
What you're doing when you're multiplying a new amp reading x seconds, and adding it to the previous sum is called numerical integration. You're simply numerically integrating, or summing, the area under the Amp (y-axis)-time (x-axis) curve, or, if you're doing what I'm saying to do intead: the Watt (y-axis)-time (x-axis) curve, where the area under the curve is the total energy collected. Don't do rectangular integration, do trapezoidal integration following the trapezoidal rule! It's more accurate!
Calibrate your clock! An Arduino's clock can be off by a couple percent. Figure out how much it's off by comparing its clock output over, say, 10 minutes, and comparing it to a better clock source, say...an internet time server displaying the atomic clock in Colorado or wherever it is. Then, multiply each measurement by a scaling factor to fix it!
On the same lines as above, ideally you'd also compensate in real-time for temperature, as the clock frequency drifts with temperature.
Calibrate the voltage measurement.
Calibrate the current measurement.

B. Extra: when is trapezoidal integration most beneficial?
You might call the following list my "5 hypotheses about the benefits of trapezoidal integration".
The merits of trapezoidal integration can be argued, and it's probably not as important as I originally made it sound, but it is super easy to implement, so why not!? Also, it is most important when:

The time sampling rate is super low.
The rate of change of readings (ie: their derivative, or slope) is super high.
The readings consistently have a rising slope (rectangular integration _under_estimates the area in this case) OR a consistently falling slope (rectangular integration _over_estimates in this case).
When you care about real-time readings in this instant, not just overall trends or averages. This is because trapezoidal integration instantly removes overestimation and underestimation error which can accumulate over short periods but then "de-accumulates", or is negated, over long periods, when the opposite slope occurs in the data.
[This may apply only when there is jitter in the sample rate--see @Edgar Bonet's comment here] When the readings consistently rise at a different rate than they fall, as this results in asymmetric accumulation of error. This means that the rectangular integration error accumulated by the values rising distance delta_y will NOT be fully negated by error in the opposite direction when the values fall distance delta_y. Therefore, even over long periods, rather than seeing the error negated, it will accumulate more and more over time. [Note: I'd need to analytically/numerically play with this hypothesis for a while to prove it conclusively to myself, but I'm pretty sure it is correct].

Full coulomb counter example in code:
This code is now in my eRCaGuy_hello_world repo here: coulomb_counter_with_cooperative_multitasking_macro.ino.
Here's a full coulomb counter example in code. You just need to implement a few functions to read samples and do calibrations is all.
I'm borrowing the timestamp-based cooperative multitasking part of this code from my answer about cooperative multitasking here, so go check it out for more information on that.
As written, this code compiles, but I haven't wired anything up or tested it. Here's the compilation output:

Sketch uses 3750 bytes (12%) of program storage space. Maximum is 30720 bytes.
Global variables use 262 bytes (12%) of dynamic memory, leaving 1786 bytes for local variables. Maximum is 2048 bytes.

coulomb_counter_with_cooperative_multitasking_macro.ino:
Jump to the bottom for the setup() and loop() functions. They are both really short.
/// Coulomb counter example
/// By Gabriel Staples
/// See: https://arduino.stackexchange.com/questions/75932/calculating-amp-hrs-of-a-solar-panel/75937#75937

/// @brief      A function-like macro to get a certain set of events to run at a desired, fixed
///             interval period or frequency.
/// @details    This is a timestamp-based time polling technique frequently used in bare-metal
///             programming as a basic means of achieving cooperative multi-tasking. Note
///             that getting the timing details right is difficult, hence one reason this macro
///             is so useful. The other reason is that this maro significantly reduces the number of
///             lines of code you need to write to introduce a new timestamp-based cooperative
///             task. The technique used herein achieves a perfect desired period (or freq)
///             on average, as it centers the jitter inherent in any polling technique around
///             the desired time delta set-point, rather than always lagging as many other
///             approaches do.
///
///             USAGE EX:
///             ```
///             // Create a task timer to run at 500 Hz (every 2000 us, or 2 ms; 1/0.002 sec = 500 Hz)
///             const uint32_t PERIOD_US = 2000; // 2000 us pd --> 500 Hz freq
///             bool time_to_run;
///             uint32_t actual_period_us;
///             CREATE_TASK_TIMER(PERIOD_US, time_to_run, actual_period_us);
///             if (time_to_run)
///             {
///                 run_task_2();
///
///                 // OR, if `run_task_2()` needs the actual period that just occurred, for
///                 // whatever reason, you may pass it in to your `run_task_2()` function:
///                 run_task_2(actual_period_us);
///
///                 // OR, just do all your code right here instead of in `run_task_2()`
///             }
///             ```
///
///             Source: Gabriel Staples
///             https://stackoverflow.com/questions/50028821/best-way-to-read-from-a-sensors-that-doesnt-have-interrupt-pin-and-require-some/50032992#50032992
/// @param[in]  period_desired_us  (uint32_t) The desired delta time period, in microseconds;
///                             note: pd = 1/freq; the type must be `uint32_t`.
/// @param[out] time_to_run     (bool) A `bool` whose scope will enter *into* the brace-based scope block
///                             below; used as an *output* flag to the caller: this variable will
///                             be set to true if it is time to run your code, according to the
///                             timestamps, and will be set to false otherwise.
/// @param[out] actual_period_us  (uint32_t) The actual period, in us, since the last time it was
///                             time to run--ie: since the last time `time_to_run` was set to true.
/// @return     NA--this is not a true function
#define CREATE_TASK_TIMER(period_desired_us, time_to_run, actual_period_us)                                            \
{ /* Use scoping braces to allow multiple calls of this macro all in one outer scope while */                          \
  /* allowing each variable created below to be treated as unique to its own scope */                                  \
    time_to_run = false;                                                                                \
                                                                                \
    /* set the desired run pd / freq */                                                                                \
    const uint32_t PERIOD_DESIRED_US = period_desired_us;                                                              \
    static uint32_t t_start_us = micros();                                                                             \
    uint32_t t_now_us = micros();                                                                                \
    uint32_t period_us = t_now_us - t_start_us;                                                                        \
    actual_period_us = period_us;                                                                                \
                                                                                \
    /* See if it's time to run this Task */                                                                            \
    if (period_us >= PERIOD_DESIRED_US)                                                                                \
    {                                                                                \
        /* 1. Add PERIOD_DESIRED_US to t_start_us rather than setting t_start_us to t_now_us (which many */            \
        /* people do) in order to ***avoid introducing artificial jitter into the timing!*** */                        \
        t_start_us += PERIOD_DESIRED_US;                                                                               \
        /* 2. Handle edge case where it's already time to run again because just completing one of the main */         \
        /* "scheduler" loops in the main() function takes longer than PERIOD_DESIRED_US; in other words, here */       \
        /* we are seeing that t_start_us is lagging too far behind (more than one PERIOD_DESIRED_US time width */      \
        /* from t_now_us), so we are "fast-forwarding" t_start_us up to the point where it is exactly */               \
        /* 1 PERIOD_DESIRED_US time width back now, thereby causing this task to instantly run again the */            \
        /* next time it is called (trying as hard as we can to run at the specified frequency) while */                \
        /* at the same time protecting t_start_us from lagging farther and farther behind, as that would */            \
        /* eventually cause buggy and incorrect behavior when the (unsigned) timestamps start to roll over */          \
        /* back to zero. */                                                                                \
        period_us = t_now_us - t_start_us; /* calculate new time delta with newly-updated t_start_us */                \
        if (period_us >= PERIOD_DESIRED_US)                                                                            \
        {                                                                                \
            t_start_us = t_now_us - PERIOD_DESIRED_US;                                                                 \
        }                                                                                \
                                                                                \
        time_to_run = true;                                                                                \
    }                                                                                \
}

// Convert microseconds to seconds
#define US_TO_SEC(us) ((us)/1000000UL)
// Convert Joules to KWh (Kilowatt*hours)
#define JOULES_TO_KWHRS(joules) ((joules)/3600/1000)

/// @brief      Obtain a corrected time measurement from a raw time measurement.
/// @details    Assuming you have done experiments to determine your microcontroller (mcu)
///             clock's error, you can correct for it with this function. Pass in a time
///             measurement the mcu has timed directly, and get back a corrected value.
/// @param[in]  raw_sec     A raw time measurement, in seconds
/// @return     A corrected time measurement, in seconds
float do_time_correction(float raw_sec)
{
    // You determine the correct calibration constant. Perhaps it is 0.9813, or perhaps it is
    // 1.19.... You will need to determine this for each individual mcu.
    constexpr float TIME_CORRECTION_CONST = 1.0; // default: 1.0
    float corrected_sec = raw_sec*TIME_CORRECTION_CONST;
    return corrected_sec;
}

/// @brief      Obtain a new instantaneous (at this moment) current reading, in Amps
/// @param      None
/// @return     Current, in Amps
float get_current()
{
    // you implement this
}

/// @brief      Obtain a new instantaneous (at this moment) voltage reading, in Volts
/// @param      None
/// @return     Voltage, in Volts
float get_voltage()
{
    // you implement this
}

/// @brief      Run the coulomb counter task to sum the total energy received from the solar panels
/// @param[out] total_energy_joules_p  (optional) A pointer to a float to receive back the total
///                         energy value acquired, in Joules (Watts*sec). Pass in `nullptr` to not
///                         receive back this value. Note that the previously-cached value is
///                         passed out in the event it's not time to calculate a new value.
///                         The return value of this function will indicate whether a new value
///                         or cached value is passed out here.
/// @param[in]  reset_sum   (optional) pass in true to reset the internally-stored "total energy
///                         acquired" value during this call (prior to performing the latest
///                         power_watts_avg calculation, if it is time for that).
/// @return     true if a new total_energy_joules value was just calculated and passed back via the
///             pointer above, or false if an old, cached value was passed out instead since it
///             wasn't time to obtain and calculate a new value.
bool run_coulomb_counter(float* total_energy_joules_p = nullptr, bool reset_sum = false)
{
    // Set this task to run at 100 Hz
    constexpr uint32_t PERIOD_DESIRED_US = 10000; // 10000us = 10ms, or 100Hz run freq

    static float total_energy_joules = 0;

    if (reset_sum)
    {
        total_energy_joules = 0;
    }

    bool time_to_run = false;
    uint32_t actual_period_us;
    CREATE_TASK_TIMER(PERIOD_DESIRED_US, time_to_run, actual_period_us);
    if (time_to_run)
    {
        // Time to obtain new samples and perform some numerical integration to obtain the total
        // energy received.

        // the previous power calculation, in watts; required for trapezoidal integration
        static float power_watts_old = 0;

        // take new samples, & calculate power from those samples
        float current_amps = get_current();
        float voltage = get_voltage();
        float power_watts = current_amps*voltage;

        float actual_period_sec = US_TO_SEC((float)actual_period_us);
        actual_period_sec = do_time_correction(actual_period_sec);

        // Perform trapezoidal integration to obtain the "area under the curve", which is equal to
        // the energy in joules. Imagine a plot where the y-axis is power and the x-axis is time. If
        // you split the x-axis up into segments of width PERIOD_DESIRED_US, then the trapezoidal
        // area under the curve, within each of those time segments, is equal to time_delta x
        // (power_old + power)/2. This is the energy (Joules) obtained during that time period.
        float power_watts_avg = (power_watts + power_watts_old)/2;
        power_watts_old = power_watts; // prepare for next iteration
        float energy_joules = actual_period_sec*power_watts_avg;

        total_energy_joules += energy_joules;
    }

    if (total_energy_joules_p != nullptr)
    {
        // output this value back to the user
        *total_energy_joules_p = total_energy_joules;
    }

    return time_to_run;
}

void setup()
{
    // do whatever you need to here
    Serial.begin(115200);
}

void loop()
{
    // Energy, in Joules, or Watt*seconds. To convert to Watt*hours, simply divide by 3600 [sec/hr]
    float total_energy_joules;
    bool new_measurements_made = run_coulomb_counter(&total_energy_joules);

    // Let's do an event-based print where we print the latest total_energy_joules value at a rate
    // of 2 Hz, which is typical for digital displays showing information expected to be read by
    // us slow humans. Since the run_coulomb_counter() task is running at 100 Hz, that means we
    // need to print the latest value every 50 runs.
    if (new_measurements_made)
    {
        static uint16_t run_count = 0;
        run_count++;
        if (run_count % 50 == 0)
        {
            float total_energy_kwh = JOULES_TO_KWHRS(total_energy_joules);
            Serial.print("total energy received (J) = ");
            Serial.print(total_energy_joules);
            Serial.print("; (kWh) = ");
            Serial.println(total_energy_kwh);
        }
    }
}

References:

My own answer about generic, timestamp-based cooperative multitasking: Stack Overflow: How to do high-resolution, timestamp-based, non-blocking, single-threaded cooperative multi-tasking

See also:

[my answer] Numerical derivation and integration in code for physics, robotics, gaming, and controls

So how will the OP measure current? A high current, low value resistor in-line with the current flow, and using the Arduino ot measure the voltage crop over the resistor?

That would work, but he mentioned he had this instead: ACS712.

I'll post sample code for the whole coulomb counter thing later too.

Also, measuring those types of low voltages over a resistor requires either oversampling or an op-amp, so the ACS712 is easier for sure.

Trapezoidal vs. rectangular doesn't make much of a difference: it is only a factor 1/2 on the first and last data points. It would be relevant if the integration interval was known with a precision much better than the sampling period (a common case in some engineering contexts), but it is not relevant for a real-time display, especially if sampling at 10 ms intervals and monitoring the result using human eyes.

The merits of trapezoidal integration can be argued, and it's probably not as important as I originally made it sound, but it is super easy to implement, so why not!? Also, it is most important when: 1) the time sampling rate is super low, 2) the rate of change of readings is super high, 3) the readings consistently have a rising slope (rectangular integration underestimates here) OR a consistent falling slope (rectangular overestimates here), and 4) when you care about real-time readings in this instant, not just overall trends or averages.

Also, I wasn't thinking this data would just be looked at with the human eye: I planned for it to be logged too, so you might as well do it right when doing it right is so easy (trapezoidal integration is super simple).

Code posted. I just did the whole coulomb counter.

With a constant sampling rate, your hypothesis 5 is wrong, as rectangular and trapezoidal only differ by the weights of the first and last samples. However, if the sampling rate is unsteady, and correlated with the signal derivative (e.g. faster sampling when the signal rises), then rectangular integration would indeed accumulate errors. Lacking this correlation, the error introduced by the sampling jitter into the rectangular integrator would “wander” (i.e. random walk) as √t. Trapezoidal definitely copes better with very high-jitter sampling.

I wonder why the downvote just now. If you're the downvoter, I'd like to know how the answer is inadequate and where it goes wrong.

I just UP-voted this answer. No idea why somebody would down-vote it. Very thorough and easy to understand. I’d have to study it a lot harder than I have time now to understand your #5 about trapezoidal integration vs. rectangular. As you say, though, it’s easy, so why not?

You want a device called a "coulomb counter". Such a device measures the total current  that flows through it.
I've seen some for Arduino. I believe SparkFun sells one. From a quick search it looks like theirs might be too low voltage for a large solar panel though.

Would I be able to pull the amperage faster to get an equivalent output or is this a fool's errand? Thanks for the tip of coulomb counter. LTC4150 seems cheap and simple to use.

A coulomb counter measures amp/hours of current directly. What is the max voltage of your solar panel? Assuming it can handle the voltage & amount of current you need to measure, it should be perfect for your needs.

I don't like this answer, because it ignores the fact that an Arduino IS a coulomb counter if used correctly, but I won't downvote it because this answer isn't incorrect per se. @RonSper, an Arduino can act as a coulomb counter just fine. It is not a fool's errand, it is exactly what I'd do.

In case you're interested, as I think it's a pretty cool use-case for Arduino, I just did a full implementation of the coulomb counter algorithm from scratch, in code, in my answer.

There are a number of good choices for a sampling device. Some like the INA2221 can do simultaneous I & V at a higher sample rate sampling and accumulate or average the results to produce a low rate data stream better suited to a processor with limited resources without sacrificing anything.
If the idea is to test the output of a solar panel the terminal voltage isn't entirely irrelevant. Panels aren't always maximally illuminated.
If this concept is tied to battery charging I think there's a dimension missing from the concept guiding the approach - the charge acceptance of a storage cell is not a constant. The implicit use for this is to monitor the battery state of charge in order to either disconnect the charger entirely or change to charge balancing and or float modes.
Simply relying on Amp-hours_out = constant * Amp-Hours_in would need to set the constant at the maximum value to avoid trying to drive current at a high rate into fully charged cells. That charger relies on a long low rate charge completion and balancing phase to avoid gradually walking the state of charge down to a fractional charge with maximum acceptance. The available hours of sunlight tend to limit the time available for charge balancing, and the battery's available capacity is set by the cell with the lowest state of charge, so the idea is to get as close to 100% as possible on the cell with the highest state of charge before the charge rate has to drop to avoid damaging cells.
The details are battery technology dependent, but if the idea is to know the state of charge of a battery, then a more complex formula for charge acceptance may produce a more satisfying result.


text:
Serial.print skips or hangs inside a "if" statement. Trying to call a function VIA serial uart
I have two microcontrollers talking to each other using serial UART pins.
Now for some reason which I can not figure out why... doing a Serial.print() does not work in an "if" statement. And also assigning/declaring/initializing variables and values inside the "if" statement does not work... this is really weird. I can turn on the GPIO pins in the "if" statement but other than that nothing else works.
Microcontrollers are: Arduino Nano and WeMos D1 Mini.
Just want to note that both of the microcontrollers are talking to each other fine and arduino can determine the serial input but it can not "Serial.print" in the "if" statement of "strcmp", it is being skipped.
EDIT: I just woke up this morning, and magically "Serial.print" is working properly inside the "if" statement of "strcmp"... I guess the microcontroller needed some rest, I was testing it for 13+ hours...
Please view the code below:
    void setup()
    {
      Serial.begin(9600);
    }

    void loop()
    {
      char a[5];
      delay(100);
      int i = 0;

      if (Serial.available() > 0)
      {
        while(Serial.available() > 0)
        {
            a[i]=Serial.read();
            i++;
        }

        a[i] = '\0';  //last character inserted with a "null char".
      }

     if(strcmp(a,"RGB_1") == 0)   //<----- "if" statement, comparing the string array buffer
     {
        int m = 1; //<---------------- declaring and initializing a variable
        //Serial.print(m); //<-------- Serial monitor will hang and skip the GPIO pins below to trigger.
        digitalWrite(12, HIGH);
        delay(1000);
        Serial.print(m); //<---------- "if" statement allows the GPIO pins to trigger but skips this serial print.
     }
   }

print the value of i

High likely you are exceeding your character array, see:
char a[5];

Which can hold 5 characters. However, you write:
if(strcmp(a,"RGB_1") == 0)

Which assumes you receive "RGB_1" which is 6 characters, because a string ends with a 0.
What also might happen is that you indeed receive only 5 characters without the ending newline, which means strcmp keeps searching until it finds a string end which may not happen.
So you can increase the array size a few just for testing purposes, and print i as jsotola proposes. Beyond that, also print each character you put into the array so you know how/if to handle a new line.
If you don't receive a string end, then use instead of the strcmp function, then use strncmp, which can search for exactly 5 characters, not checking until the end of the string.

@S-To: No. a[5] holds 5 values, indexed 0 to 4.

@ Michel Keijzers Thank You for quick comment.

@ocrdu Yes you're right, my bad.... just had a brain fart.