text:
How to add another time counter to my functioning sketch?
I have a functional sketch that I run on an Arduino Uno, the output controlling a fan module; I need another timer to run a 2nd fan and I would like to use another output on the Uno to do that rather than using another unit.
What my sketch does is as follows:

counts 15 minutes (interval_1)
starts the fan for 1 minute (interval_2)
starts another cycle.

What I need to do is to add another function that will start fan#2 for 15 sec (interval_3) when the cycle starts, using another output (relayPin_1), then stop.
So the flow will be:

counts 15 minutes (interval_1)
starts fan#1 for 60 sec (interval_2)
starts fan#2 for 15 sec (interval_3)
resets and starts another cycle.

Unfortunately, can't figure out how to insert the 2nd timer.
Sketch is below, if you have any ideas that would be much appreciated.
Thanks
const byte relayPin = 4;                           // fan#1 control on pin 4,
const byte relayPin_1 = 7;                         // humidifier fan#2 control on pin 7,
const unsigned long interval_1 = 1000UL * 60,      // RUN timer, msec
                    interval_2 = 1000UL * 60 * 15, // OFF timer, msec
                    interval_3 = 1000UL * 15;      // Humidifier timer
unsigned long currentMillis, previousMillis = 0;

void setup() {
    // put your setup code here, to run once:
    pinMode(relayPin, OUTPUT);   // Output#1
    pinMode(relayPin_1, OUTPUT); //Output#2
    // relayPin_1 controls the humidifier's fan#2
    pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
    // at startup, fan is ON for interval_1 duration
    currentMillis = millis() - previousMillis;
    if (currentMillis <= interval_1) {
        digitalWrite(relayPin, HIGH);    // fan ON
        digitalWrite(LED_BUILTIN, HIGH); // LED ON (blinking)
        delay(333 / 2);
        digitalWrite(LED_BUILTIN, LOW);   // LED Off
        delay(999);
    }

    // when interval_1 is reached, turn fan OFF for the duration of interval_2
    else if (currentMillis <= (interval_1 + interval_2)) {
        digitalWrite(relayPin, LOW);    // fan OFF
        digitalWrite(LED_BUILTIN, LOW); // led OFF
    }
    else {
        // reset the timer
        previousMillis = millis();
    }

}

Okay... I had time to play with it today; what it does:
it starts both fan#1 and fan#2, then stops fan#2 at (interval_1 + interval_2), but fan#1 continues running until the cycle ends.
Therefore: fan#1 runs for 35 sec, fan#2 runs for 15 sec, as it should; and the cycle is stopped for 30 sec as it should.
However, I can't make fan#1 to run for only 20 sec. as it is defined.

const byte relayPin = 4;   // recyrculation fan#1 control on pin 4,
const byte relayPin_1 = 7; // humidifier fan#2 control on pin 7,
const unsigned long interval_1 = 1000UL * 20,    // RUN timer fan#1, msec
                    interval_2 = 1000UL * 15,    // RUN timer fan#2, msec
                    interval_3 = 1000UL * 30;    // OFF timer
unsigned long currentMillis, previousMillis = 0;

void setup() {
   // put your setup code here, to run once:
   pinMode(relayPin, OUTPUT); // Output#1
    pinMode(relayPin_1, OUTPUT); //Output#2
     pinMode(LED_BUILTIN, OUTPUT); }

void loop() {
// at startup, fan#1 & fan#2 are ON
 currentMillis = millis() - previousMillis;
  if (currentMillis < interval_1) {
    digitalWrite(relayPin, HIGH);   // fan#1 ON
    digitalWrite(relayPin_1, HIGH); // fan#2 ON
     digitalWrite(LED_BUILTIN, HIGH); // builtin LED ON

 } else if (currentMillis < (interval_1 + interval_2)) {
    digitalWrite(relayPin_1, LOW); // fan#2 OFF

   // when (interval_1 + interval_2) is reached, turn fans OFF for the duration of interval_3
 } else if (currentMillis < (interval_1 + interval_2 + interval_3)) {
   digitalWrite(relayPin, LOW);      // fan#1 OFF
    digitalWrite(LED_BUILTIN, LOW); // led OFF

 } else {
   // reset the timer
     previousMillis = millis(); }
 }

your description of the fan cycles is unclear .... do both fans start at the same time?

draw a timing chart on paper ... it nay help you to visualize the required code

Your code doesn't match your description. In your description you want the fan off for 15 minutes, then on for 1 minute. You have your fan on for the entire 15 minute interval_1, then off for 1 minute.

The code comments on your intervals suggest that interval_1 is your run (fan 1 on) time and interval_2 is your fan off time. That is what your code does, but not what you say in your description. Which is correct?

I'm not clear on what you want it to do. Please add a clear statement of your goal. For the first interval (20 seconds?) which fans should be on? Then for the 2nd, 15 second interval which fans should be on? And I gather that you want both fans off for interval 3 (30 seconds)?

Assuming you get your logic straightened out, you should be able to add as many cases to your if statement as you want:
  if (currentMillis <= interval_1) {
      // Before end of interval 1, fan off.
  } else if (currentMillis <= (interval_1 + interval_2)) {
      // In interval 2, fan on
  } else if (currentMillis <= (interval_1 + interval_2 + interval_3 )) {
      // In interval 3, fan2 on
  } else {
      // Turn everything off
      // reset the timer
  }

In any case, I showed in my answer how to adjust your code to have 3 different intervals, then turn everything off after the end of the last interval. You can extend that pattern to as many intervals as you want,

If you can't get it to work edit your question and put the new code at the end, along with what it is doing wrong.


text:
Items needed to build an automatic watering system
I would like to build an automatic watering system. So my research brought me to the following items:

Breadboard Solderless Prototype PCB Board – ALLDE BB-007 (3pcs) 400 Pin with 4 power Rails and Double Sided Tape
Capacitive Soil Moisture Sensor (Operating voltage: 3.3 ~ 5.5 VDC, Output voltage: 0 ~ 3.0 VDC, Interface: PH2.54-3P)
1 Channel 5V Relay Module (VCC: Connect 5V Positive Pole Power Supply, GND: Connect 5V Negative Pole Power Supply)
Mini Water Pump (DC Voltage: 3-5 V)
Arduino UNO REV3 [A000066]

I am beginner in electronics so I have some very basic questions. Given the above specifications, and assuming I would like to power this system with battery and not to a power outlet, what battery do I need to power up the Arduino? I would like to have this system running for at most 30 days. The system will be running constantly until the moisture sensor indicates that watering is needed, in which case will run the mini water pump for some time (I don't know how long this will be running).
Could a battery power up this system? I am not sure if I can link products, but this system is based on this system if I forgot to include some critical information about the system.
So to summarize, is is possible to power up this system with a battery pack, if so which battery should I use?

Depending on the actual power needs (mainly of the pump motor), you might get away with a simple USB power bank with enough capacity. Though some power banks cut the power completely, if you don't draw a minimal current from them.

what is your water source and how big a garden bed or pot are you watering? If you are connecting to a tap, why use a pump? If you are not, can you design it to gravity feed the water?

I'd suggest feeding the system with a 12V lead-acid battery and a buck DC/DC converter with 5V output. (Those are more efficient than the regulators in Arduinos.) You could feed the regulated 5V directly into the USB port on your Arduino. You'll probably need a filtering capacitor on the Arduino 5V input to reduce fluctuations in power as the pump turns on and off however.
You'll need to do some back-of-the-envelope calculations on the power consumption of the Arduino, the on current of the water pump, the expected max duty cycle of the pump, and the efficiency of the DC/DC converter. That will let you estimate the power consumption of the whole system in mW/hr. You can then get a battery big enough to power it for your desired run-time. If you add a solar powered charging system you could increase your run-time or even make it run purely on solar power (with a big enough panel and enough bright sunshine.)

For start, I would be seriously supprised if 5 volt pump does much good and vould start from 12VDC (car or campa-van stuff...) I would be supprised if you do not have 12DC supply around (from old router, chinese gimic sliming devices, christmas light box, cable setup-box...)
Don't panic, You may be able to get relay capable of switching higher Voltages.
Second: Newer connect anything that has solenoid directly to arduino. (not even relay). Most IC's or MCU's are only able to handle opening mosfet or a transistor, only some can handle one LED. Although in the moment relay switches off, it (its induced current) will take Arduino with it. if instead you use some common cheap NPN transistor and a diode across(in opposite direction).
I recommend soldering. relays and the things you power from them.
last get an IP55 box from nearest electric shop.

simulate this circuit – Schematic created using CircuitLab
And lastly I would have replaced UNO for NANO here. Its much more compacr and fits easily into IP55 box
 For battery you van use car battery...
I Find since Yuasa started destroying (buying ) competition, the lead-acids lifespan gone far down (on alarms often insufficient in a year)

source: Stack Exchange

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

sort: votes


text:
How do I repeat else if (cmd == '3') until I press another cmd?
This code is for automatically opening and closing a window using a motor with senors such as dust, humidity, temperature, and rain sensor with bluetooth module through phone. With this code if I press 1,2 it would close or open the window and 3 would let the window open or close regarding the measures that the  sensor reads. Right now pressing 3  would only simulate this once and then turn off untill I press it again
So I would want this part
 else if (cmd == '3')
to repeat itself until I press another cmd button so the window keeps opening and closing.
//////////////////////////////////////////////////////////////////////////
#include <SoftwareSerial.h>
#include <Stepper.h>
#include <DHT.h>
#define DHTPIN A1
#define DHTTYPE DHT11
#define D_IN 3
#define A_IN A0

int Txpin = 7;
int Rxpin = 8;
int stepsmotor = 1024;
const int stepsPerRevolution = 64;
SoftwareSerial BTSerial(Txpin, Rxpin);
DHT dht(DHTPIN, DHTTYPE);
int measurePin = 0;          // measurePin을 0으로 설정합니다.
int ledPower = 2; // ledPower를 2로 설정합니다.
int samplingTime = 280;    // samplingTime을 280으로 설정합니다.
int deltaTime = 40;           // deltaTime을 40으로 설정합니다.
int sleepTime = 9680;       // sleepTime을 9690으로 설정합니다.
float voMeasured = 0;      // voMeasured를 0으로 설정합니다.
float calcVoltage = 0;       // calcVoltage를 0으로 설정합니다.
float dustDensity = 0;       // dustDensity를 0으로 설정합니다.

Stepper myStepper(stepsPerRevolution, 8, 10, 9, 11);

void setup()
{
  Serial.begin(9600);
  BTSerial.begin(9600);
  myStepper.setSpeed(550);
  pinMode(ledPower,OUTPUT);
  pinMode(D_IN, INPUT);
}

void loop()
{
 if (BTSerial.available())
  {
    char cmd = (char)BTSerial.read();
    if(cmd == '1'){
      for(int i=0; i<(32*3-6); i++){
    myStepper.step(stepsPerRevolution);
      }}
    else if (cmd == '2')
      for(int i=0; i<(32*3-6); i++){
    myStepper.step(-stepsPerRevolution);
   }
    else if (cmd == '3'){
     int dIn = digitalRead(D_IN);
  double aIn = analogRead(A_IN);
    int h = dht.readHumidity();
    int t = dht.readTemperature();
digitalWrite(ledPower,LOW);
  delayMicroseconds(samplingTime);

  voMeasured = analogRead(measurePin);
  delayMicroseconds(deltaTime);
  digitalWrite(ledPower,HIGH);
  delayMicroseconds(sleepTime);

  calcVoltage = voMeasured * (5.0 / 1024.0);

  dustDensity = (0.17 * calcVoltage - 0.1) * 1000;

    Serial.print(dustDensity);
    Serial.println(" ug/m3");
  Serial.print("Digital Input = "); Serial.println(dIn);
  Serial.print("Analog Input  = "); Serial.println(aIn);
  Serial.println();
    Serial.print("humidity:");
    Serial.println(h);
    Serial.print("temperature:");
    Serial.println(t);
    delay(1000);

    if (t >= 25 or h >= 70 or dustDensity >= 100 or aIn <= 50)
     for(int i=0; i<(32*3-6); i++){
    myStepper.step(stepsPerRevolution);
    }
    else
     for(int i=0; i<(32*3-6); i++){
    myStepper.step(-stepsPerRevolution);
    }

  delay(3000);
    }
    else if (cmd == '4'){

    }
      }
    }

Please no code as image. It is difficult to read and nobody will type the code for testing into their own computer. You already had correctly formatted code. Why did you replace it with an image?

I would suggest to rewrite your program as a Finite State Machine (FSM). It's a simple but powerful concept. You first model your program into multiple states, that are connected through state transitions. It is a good way to first draw this as a graph. You can see one example in my answer to this question.
For your case I would use your "modes" as states for the FSM plus an idle state, where simply nothing happens. You would start in the idle stat and then change to different states depending on the Serial input. In the states/modes 1 and 2, which are only one time actions, you would execute the action in the state and then directly change to the idle state again.
From the programming side a FSM can be implemented in multiple ways. I have seen FSMs using a variable and switch cases, but also FSMs, that use a function pointer. The last is elegant, but not as easy to understand for beginners. So I suggest you use the switch-case variant, as you can see in the answer linked above. Basically you use a variable (something like int or char) to represent the current state. In your loop() function you then build a switch-case statement for different values of your state variable. Often an enum is used as variable type to make the code more readable. In each case statement you write the code for the corresponding state. In your state/mode 3 you would check your sensors and close/open the window as needed, then leaving the case statement. When the next iteration of the loop() function happens, the FSM will still be in this state, checking again the sensors. In your states/modes 1 and 2 you would check, if the window already has the needed state and - if not - drive to motor to close/open the window. Then - still in the case statement - you would set the state variable to the idle state, then leave the case statement. So in the next interation of the loop() function the FSM will be in the idle state, doing nothing, making the states/modes 1 and 2 a one-shot everytime, that you activate them.
In contrast to the code in the linked answer, I would read the Serial data outside of the switch statement, since you will write directly to the state variable in there.
I strongly suggest, that you try to implement this. It is an important principle, that makes your more structural sound and easier to extent. A great learning experience.

Thanks  a bunch!

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


text:
Upload sketch in multiple arduinos
How do I upload sketches in multiple arduinos from one supervisor Arduino using UART , cd4051 for Rx and TX separately and reset pin low

That greatly depends on the actual type of Arduino board. Please describe, which Arduino boards you are trying to program and what you are trying to achieve

@chrisl, tags are Uno, Nano

I am trying to upload program in 3 arduino nanos from 1 Arduino Uno by using cd4051 mux/demux for Rx and TX and setting reset to low when uploading to each one

it is not a trivial task. you have to implement the stk500 protocol or use a library which implements it.


text:
Powering ESP8266 module from arduino nano
I'm just starting up with arduino and i have few simple questions.

Why shouldn't i power ESP8266 WiFi module directly from arduino nano 3.3V rail? There are bunch of tutorials explicitly avoiding this or using resistors and i would like to know why?
Could i use something like a Mean Well Switching Power Supply, 5V 10A to power the Arduino Nano and therefore have stable voltage by avoiding batteries and by doing so, connect ESP8266 directly to arduino without fear of breaking something?
Could Arduino nano be powered through USB? And if yes, would it be then safe to connect ESP module to arduinos' 3.3V rail?

Why shouldn't i power ESP8266 WiFi module directly from arduino nano 3.3V rail?

The 3.3V rail of the Arduino is not meant to provide much current. The onboard regulator is a simple linear voltage regulator, which will dissipate the extra power as heat. As you draw more current through it, it will get hotter and finally get fried, as it cannot dissipate the created heat. The ESP chip needs multiple hundreds of mA, especially, when it is connecting to a wifi network. The onboard voltage regulator of the Arduino cannot handle this much. So you cannot power it over the Arduino.
I don't really know, what you mean with "using resistors".

Could i use something like a Mean Well Switching Power Supply, 5V 10A to power the Arduino Nano [...] connect ESP8266 directly to arduino without fear of breaking something?

Yes, you can power the Arduino with this power supply, but you should power the ESP through the Arduino. Not through the 3.3V, nor through the 5V rail (which will fry the protection diode, I think). Instead you should power the ESP directly from the power supply, in parallel to the Arduino. Often ESP modules have their own voltage regulator, that regulates the voltage from 5V to 3.3V. If that is the case for you, you should use this input of the ESP module with the power supply. If you don't have a 5V capable regulated input on your ESP module, you will have to use a dedicated voltage regulator for that. In that case be sure, that the voltage regulator can provide enough power for the ESP (with some headroom on top).

Could Arduino nano be powered through USB? And if yes, would it be then safe to connect ESP module to arduinos' 3.3V rail?

Yes, the Arduino Nano can be powered over USB. But again you must be sure to not draw too much current from the Arduino. Between USB and the 5V rail is a diode, that will be destroyed, if you draw too much current through it. And the standard USB port can only provide up to 500mA. And regarding the 3.3V rail: All the explanations above about the 3.3V rail apply here again, since the USB voltage (5V) is regulated down to 3.3V by the linear voltage regulator. So: No, you still cannot power the ESP through the Arduino. It's not about the power supply here, but about the electronic parts inbetween.

Thank you, that clears it up a lot !

part. esp8266 has max 170 mA draw. the 3.3 V regulator on standard Uno can supply 150 mA so it usually works. on Nano the 3.3 V si from the FTDI USB chip (50 mA?) 2. dev boards have regulators. modules do not


text:
How to conect multiple output pin from sensors to a single digital pin on a arduino
Hello i have several power management IC that have an active low indicator for a fault, it would be a waste to dedicate a single digital pin for each of them. So i thought of  to interface them to a single digital pin. I do not need to know which of them has a fault, i just need to know that there is a fault.

How do i safely do this? and as a follow up question if the fault voltage is 5v and the arduino pins only take 3.3v how do i shift it down with minimal components. can i just add a resistor in series?

If the ICs output 5V and your Arduino is 3.3V, you can simply use one voltage divider at the Arduinos pin to divide the voltage down to 3.3V.
But there is still one important thing to connect them safely: You have to check, if the outputs of the ICs are driven actively high, when no fault occured, or if they simply use a pullup resistor internally.
A pin, that is actively driven high, does not have an overcurrent protection. So, if one IC would pull it's pin to low and the others are still high, a high current would flow between them, potentially destroying them. In that case you need current limiting resistors in series with the ICs (directly at the ICs, so that the resistors are between them).
On the other side, if the ICs output a high level through a pullup resistor, you are safe to connect them directly, as there can only flow a very little current through the pullup resistors. Often such a situation is called Open-Drain (passive high level through pullup resistors, active low level by driving the pin to low through a MOSFET, like used in a digital output pin). In that case you don't need the current limiting resistors.

EDIT: The datasheet of the ICs, that you linked to states that the fault output is an

Active-low open-drain output

Also the example circuit shows an external pullup resistor. That means, that the fault pin is internally connected to a MOSFET, which will connect the pin to ground in case of a fault. Otherwise the pin is floating. The external pullup resistor will pull the pin state to a high level, when the MOSFET is not activated. This is good for you, since you can now simply use 1 resistor (one resistor is enough for all ICs), to pull the level up to 3.3V. Then you directly have the correct level for your Arduino and you don't need a voltage divider.

according to the datasheet sample circuit fault is pulled up so does this mean that the voltage divider  and a pull up ? is the only thing i have to change in my circuit

Ah, yes. Though, since the IC doesn't use an internal pullup, you can simplify the circuit by directly pulling up to 3.3V with an external resistor instead of to 5V. Then you don't need the voltage divider. The high level will then be 3.3V. I will add this to the answer

oh yes ! thats an amazing trick to do. pulling it up to 3.3 thus reducing the components. Thank you good sir. Additional question good sir, do i have to adjust the pull up resistor so that the line all have 10k resistance equivalent on them , or it does not matter?

Or you can use the Arduino's internal pull-up.

@EdgarBonet or that . but i think its a good design practice to include one anyway :)


text:
Set and extract individual bytes of a number (lowByte() and highByte())
You can extract

the low-order (rightmost) byte of a variable

or

the high-order (leftmost) byte of a word

with the functions lowByte() and highByte() respectively (the quotes are from the Arduino Reference).
Does Arduino provide a way to extract any byte from a number with a similar function?
And does it provide a way to set any individual bytes of a number (which would be the counterparts to these functions, if they exist)?

Any more sophisticated byte exchange can be done with binary operators.
Extracting information
You'll need some constants like
MASK         SHIFT
0xFF000000   24       (first byte, most significant)
0x00FF0000   16       (second byte)
0x0000FF00    8       (third byte)
0x000000FF    0       (last byte, least significant)

You would binary AND the original value with MASK
     0x12345678
AND  0x00FF0000
 =   0x00340000

and then bit shift it left, e.g.
   0x00340000
>> 16
 = 0x00000034

So from the original value 0x12345678 you have gotten 0x34.
Setting information
The opposite direction is also possible with the same constants but opposite operators and in opposite order:
   0x00000034
<< 16
 = 0x00340000

and then
   0x12005678
OR 0x00340000
 = 0x12345678

Note that the OR operation only works reliably if the corresponding positions are 0x00. That's fine with a starting value of 0x00000000.
If you don't know that or you want to process an arbitrary number, you can introduce a step in between
    0x12??5678   (?? could be anything)
AND 0xFF00FFFF   (which is the inverse of 0x00FF0000 and can be expressed as ~0x00FF0000)
 =  0x12005678   (whatever ?? was, it'll be cleared out)

Actual Code
Tested on Arduino Uno. The long data type is 32 bits or 4 bytes.
The code here may not be the most efficient. Advanced developers would likely not use MASK and SHIFT as arrays like this. This answer focuses more on the educational point.
long MASK[]  = {0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF};
byte SHIFT[] = {24        , 16        , 8         , 0};

// Extracts a byte from a larger data type
// value: larger data type to extract a byte from
// position: 0 based number, 0 = MSB, 3 = LSB
byte getByteAt(long value, byte position)
{
  long result = value & MASK[position];  // binary AND
  result = result >> SHIFT[position];    // Shift right, moving all bits
  byte resultAsByte = (byte) result;     // Convert to an actual byte
  return resultAsByte;
}

// Sets a byte in a larger data type
// value: larger data type where to set the byte
// position: 0 based number, 0 = MSB, 3 = LSB
// newPartialValue: the byte to be inserted
long setByteAt(long value, byte position, byte newPartialValue)
{
  long result = value & ~MASK[position];                       // clear the affected byte so that it is 0x00
  long valueToSet = (long) newPartialValue << SHIFT[position]; // Shift left, moving all bits
  result = result | valueToSet;                                // binary OR
  return result;
}

void setup() {
  Serial.begin(9600);
  Serial.println(getByteAt(0x12345678, 1));       // Prints 52, which is 0x34
  Serial.println(setByteAt(0x87654321, 1, 0xBB)); // Prints -2017770719 which is 0x87BB4321
}

void loop() {

}

Worth mentioning that the value you AND the number with to clear the bits prior to OR-ing is the inverse of the mask. You can use ~MASK to create it.

@Majenko: used and added in the example

Thanks for the extensive explanation, but I already knew about this possibility. So there is no inherent way to do this with built in functions?

You don't need to load MASK and SHIFT from an array!  shift = position * 8 = position << 3 (convert a bit offset to a byte offset.  Also, mask after shifting so it's just return (uint8_t)(value >> shift);.  e.g. on Godbolt for AVR and ARM cortex-M0 get and set byte functions: https://godbolt.org/z/2uFXN5  Also included are versions that store/reload and use a byte index, avoiding shift loops on AVR which can only shift 1 byte at a time.  (Will post an answer if I get back to this.)

@PeterCordes: my primary concern was to explain it thoroughly and in an understandable, visible way. I am also participating in code golf, so yeah, it's definitely not the shortest form :-) In general I am not optimizing for speed as long as there is no speed requirement.

Yeah, it's a good explanation, but writing over-complicated code makes it harder for future readers of the code.  Also, I just noticed a flaw: your arrays are backwards!  Most people would consider "byte 0" of an integer to be the least-significant byte.  Your code gives the most significant, opposite of value >> bitpos.  (And opposite of memory order: AVR and ARM are little-endian).  I think the code in my Godbolt link is very readable, like bitpos = position * 8.

And as far as efficiency, sure small differences usually don't matter, but for a compile-time-constant position your GetByteAt version still compiles to ~50 AVR instructions instead of 1 because you forgot to make your arrays const and/or static.  So the compiler can't do constant-propagation through the array indexing.  (see the test_... callers: https://godbolt.org/z/chtKzJ)  That's a pretty significant difference in static code footprint for something you'd expect to be cheap.

The header Arduino.h defines the macro word(high_byte, low_byte). The
resulting value is an uint16_t.

Thank you, that answers the question about the counterpart of lowByte() and highByte(). Are there any functions for the rest of my question though?

@LukasFun: I couldn't find any. But note that on the AVR-based Arduinos an int is only two bytes.

You should simply treat those definitions as samples, learn enough C/C++ to understand them, and extend them to whatever you need. If uint16_t is not what you need, why should exactly uint32_t be your solution?

There are two alternative methods, and they can both be easily used "in reverse" as well:
Unions
union byte_extract {
    uint32_t ival;
    struct {
        uint8_t byte_0; // least significant byte
        uint8_t byte_1;
        uint8_t byte_2;
        uint8_t byte_3; // most significant byte
    } bval;
};

... later ...

union byte_extract x;

x.ival = 65536 * 99; // change to whatever you want
Serial.println(x.bval.byte_2); //3rd byte

Unions are a way to define multiple possible ways to interpret a piece of memory, usually to save memory when you know something can't be 2 things at once. Strictly speaking it is not recommended to use them in this way but it works.
Pointer arithmetic
uint32_t *xaddr;
uint8_t *xbyteaddr;

uint32_t x = 65536 * 99; // change to whatever you want
xaddr = &x;
xbyteaddr = (uint8_t *) xaddr;

Serial.println(xbyteaddr[2]); //3rd byte

Memory addresses (on Arduino as well as on PCs) refer to the first byte of a variable.  If you have an (uint32_t *) you will read 4 bytes starting at that address. But if you have a (uint8_t *) or a (char *) you will only read 1 byte. You can shift this pointer-to-uint8_t forwards by as many bytes as you want.
Apologies if this doesn't quite work on Arduino, I have only tested it on PC.

This use of unions is well-defined by C99.  An array of uint8_t bytes[4] would be more readable and allow runtime indexing, though.  Your pointer-arithmetic version is only safe because uint8_t is going to be unsigned char, and unsigned char* is allowed to alias anything without violating strict-aliasing.  Note that both of these are endianness-dependent.


text:
ESP32-CAM not reading BME680
I am trying to read BME680 on ESP32-CAM with following code :
(Before trying BME680, I have suscessfully connected BME280 to ESP32-CAM over S/W SPI)
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include "Adafruit_BME680.h"

#define SEALEVELPRESSURE_HPA (1013.25)

#define BME_SCK 12 //Connected SCL to IO12
#define BME_MISO 15 //Connected SDO to IO15
#define BME_MOSI 13 //Connected SDA to IO13
#define BME_CS 14 //Connected CS to IO14

//Adafruit_BME280 bme; // I2C
Adafruit_BME680 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI
//float temperature = 0;
//float humidity = 0;
//float pressure = 0;

void setup() {
  Serial.begin(115200);
  while (!Serial);
  Serial.println(F("BME680 test"));

  if (!bme.begin(0x76))
  {
    Serial.println("Could not find a valid BME680 sensor, check wiring!");
    while (1);
  }

  // Set up oversampling and filter initialization
  bme.setTemperatureOversampling(BME680_OS_8X);
  bme.setHumidityOversampling(BME680_OS_2X);
  bme.setPressureOversampling(BME680_OS_4X);
  bme.setIIRFilterSize(BME680_FILTER_SIZE_3);
  bme.setGasHeater(320, 150); // 320*C for 150 ms
}

void loop()
{
  if (! bme.performReading())
  {
    Serial.println("Failed to perform reading :(");
    return;
  }
  Serial.print("Temperature = ");
  Serial.print(bme.temperature);
  Serial.println(" *C");

  Serial.print("Pressure = ");
  Serial.print(bme.pressure / 100.0);
  Serial.println(" hPa");

  Serial.print("Humidity = ");
  Serial.print(bme.humidity);
  Serial.println(" %");

  Serial.print("Gas = ");
  Serial.print(bme.gas_resistance / 1000.0);
  Serial.println(" KOhms");

  Serial.print("Approx. Altitude = ");
  Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
  Serial.println(" m");

  Serial.println();
  delay(2000);
}

When I try to upload the code to ESP32-CAM while BME680 is connected I get following error
esptool.py v2.6
Serial port /dev/ttyUSB0
Connecting....
Chip is ESP32D0WDQ6 (revision 1)
Features: WiFi, BT, Dual Core, 240MHz, VRef calibration in efuse, Coding Scheme None
MAC: a4:cf:12:99:b5:70
Uploading stub...
Running stub...
Stub running...
Configuring flash size...
Warning: Could not auto-detect Flash size (FlashID=0xffffff, SizeID=0xff), defaulting to 4MB
Compressed 8192 bytes to 47...

A fatal error occurred: Timed out waiting for packet content
A fatal error occurred: Timed out waiting for packet content

Then I tried to disconnect BME680 and uploaded the code to ESP32-CAM which worked, then connected BME680 back to ESP32-CAM.
But now I see following error in Serial Monitor :
ets Jun  8 2016 00:22:57

rst:0x1 (POWERON_RESET),boot:0x33 (SPI_FAST_FLASH_BOOT)
flash read err, 1000
ets_main.c 371
ets Jn  8 2016 00:22:57

rst:0x10 (RTCWDT_RTC_RESET),boot:0x33 (SPI_FAST_FLASH_BOOT)
flash read err, 1000
ets_main.c 371
ets Jun  8 2016 00:22:57

rst:0x10 (RTCWDT_RTC_RESET),boot0x33 SPI_FAST_FLASH_BOT)
lash read err, 1000
et_main.c 371
ets Jun  8 2016 00:22:57

rst:0x10 (RTCWDT_RTC_RESET),boot:0x33 (SPI_FAST_FLASH_BOOT)
flash read err, 1000
ets_main.c 371
ets Jun  8 2016 00:22:57

rst:0x10 (RTCWDT_RTC_RESET),boot:0x33 (SPI_FAST_FLASH_BOOT)
flash read err, 1000
ets_main.c 371
ets Jun  8 2016 00:22:57

Any idea what is wrong here ?
Update :
I switched #define BME_SCK 12 to #define BME_SCK 16, now getting following message
ts Jun  8 2016 00:2:57

rst:0x1 (POWEON_REST),boot:0x13 (PI_FAT_FLASH_BOOT)
cnfigsi: 0, SPIWP:0xee
clk_dv:0x00,q_drv:0x0,d_drv0x00,cs0_drv:0x00,d_drv0x00,wp_drv:0x0
mod:DIO, clock div:
loa:0x3fff0018,len:4
load0x3fff001c,len:1216
ho 0 tail 12 room 4
lod:0x40078000,len:9720
h 0 tail 12 room 4
load0x40080400,len:6352
etry 0x400806b8
[D][esp32-hal-psram.c:47] psramInit(): PSRAM enabled

If you read the schematic of ESP32_cam, you will noticed that both GPIO12 and GPIO16 are used by the microSD.

@hcheung, SPI is a bus, but yes if a card would be inserted the SPI wiring must match the wiring of the card

I am not using SD Card. Also BME280 worked perfectly using BME_SCK=14, BME_MISO=12, BME_MOSI=13, BME_CS=15.

GPIO12 must not be pulled high during boot. It's possible there's a pull-up resistor on the BME680 breakout board you're using that's pulling SCK high and interfering with the boot process. I would avoid using GPIO12 here.
If you're out of pins on the ESP32 you can connect the BME680 via I2C rather than SPI. I2C only needs SDA and SCK (and power and ground, of course). The Adafruit library for the BME680 has an example of how to call the constructor for an I2C connection.

I am using ESP32-CAM, not all IO pins are available also I2C not available, so only software SPI is option. I switched BME_SCK fro 12 to 16, getting new error.

You use pins
#define BME_SCK 12 //Connected SCL to IO12
#define BME_MISO 15 //Connected SDO to IO15
#define BME_MOSI 13 //Connected SDA to IO13
#define BME_CS 14 //Connected CS to IO14

for software SPI, but the esp32 can use any set of pins for hardware SPI.
And your set of pins are even the dedicated mux pins for SPI2 (they have the direct connection without mux). But they are in different mapping then your software SPI.
SPI2:
SCLK    14
MISO    12
MOSI    13
SS      15

Source: https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/peripherals/spi_master.html
SPI2 is the default SPI used by the ESP32 Arduino SPI library, so the Adafruit library should have no problem to use hardware SPI with the SPI library.
Adafruit_BME680 bme(BME_CS); // use hardware SPI

and wire the sensor to SPI2 pins according to their function

@roy, I enhanced the answer

With this suggested change I get the last error message mentioned in my question.

try to connect the wire to pin 12 only after the esp32 powerup. it could be the problem in answer by John

Tried this as well, still same error

as next I would try the sensor with some simple board like Uno or Nano


text:
Arduino Nano IoT Power Consumption
I am trying to reduce the power of my Arduino Nano IoT. I would like to run it using a battery over a longer time period. I thought this would be possible when putting it to sleep most of the time. However, at the moment I can only reduce the power consumption to 10mA by

disabling wifi using the WiFiNINA library
putting the arduino to sleep using the ArduinoLowPower library
removing both LEDs
powering it through a 4,5V battery

Is there anything else I can do to further reduce power consumption? If not, is there another, more suitable device I can use instead for this project? It has to support wifi and use very low power during sleep.

use an ESP32 only

The power consumption can also be reduced by increasing the voltage input, see this link in the "How to power the Arduino Nano 33 IoT" section: https://github.com/ostaquet/Arduino-Nano-33-IoT-Ultimate-Guide This may or may not be possible for your project.

Two of those 10mA come from the ATECC608 crypto chip which idles at 2mA.  That leaves 8mA for you to track down.
The WiFi-NINA module has multiple "sleep" modes that range from 30mA down to 4.5µA. Since you can't be in the 30mA "modem sleep" mode (it's too high for your measurements) I suspect it enables "light sleep" at 800µA.
The switching regulator uses 200µA.  So those two together probably account for 1mA in total, leaving you 7mA more to find.
The accelerometer can be up to 1.25mA. I'll assume that since you don't mention it, you haven't set that to "power down" mode.  5.75mA left.
The main MCU is actually quite hungry for power, even when sleeping. Looking at the datasheet it can be between 1.3mA and 2.4mA for the different "idle" modes. Only "standby" mode (where clocks are switched off, etc) drops it below 1mA. With it running a simple program you are looking at 4-6mA.
So it could be that the MCU isn't actually sleeping properly, or that other modules that you think are in low power aren't.
I would suggest manually disabling chips completely (pull their respective RESET pins if available LOW if available) to see how that affects the current.


text:
ESP32 doesnt save every string to SD Card
My code initializes, the header (the ID; Value string) for the .csv file gets saved, but the dataString which is the most important part doesnt save to the .csv file.
I get an arraypointer to the start of the array. I dont have much experience with pointers but i dont get any errors.
The best solution would be if i could put everything into the "write matrix to SD"-function. Anyone has an idea? I am just dumbfounded because everything works perfectly without the arraypointer and i dont know what to try.
My setup()
  Serial.begin(115200);

  p_EKG_state_1 = &EKG_state_1;

  pinMode(CS_Pin, OUTPUT);
  if(!SD.begin(CS_Pin))
    {
      Serial.println("Card failed or not present");
    }

  EKG_data_transmision.matrixData = SD.open("/data.csv", FILE_APPEND);  //erstelle data.csv datei

  if(EKG_data_transmision.matrixData)
    {
    String header = "ID; Value;";
    EKG_data_transmision.matrixData.println(header);
    EKG_data_transmision.matrixData.close();
    Serial.println(header);
    Serial.println("card init sucess");
    }
  else
    {
    Serial.println("Couldnt open vector data file");
    }

  //Serial.println(ESP.getFreeHeap());
  pinMode(LED_BUILTIN, OUTPUT); // TEST OUTPUT LED PIN

  pinMode(btn_modus.PIN, INPUT_PULLUP); // MODUSAUSWAHL TASTER
  attachInterrupt(btn_modus.PIN, isr, FALLING); // MODUS TASTER hört auf fallende Flanke und führt dann Funktion isr aus
  WiFi.begin(ssid, password); // Verbinde mit WLAN

  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer); // initialisiere Zeit variablen
  EKG_state_1.set_state(1);

}

My function that writes the matrix/arraypointer to the SD
bool  EKG_data_transmision::write_matrix_to_SD(unsigned short *array_pointer) // Übertrage , unsigned short id
{

   if(!SD.begin(CS_Pin))
  {
    Serial.println("Card failed or not present");
    return 1;
  }
  matrixData = SD.open("/data.csv", FILE_APPEND);  //erstelle data.csv datei

  if(matrixData)
  {
    //look if data.csv exists

    while(matrix_coloum < 3071)
    {
      if(matrix_coloum == 1024 || matrix_coloum == 2048)
      {
          header = "ID; Value;\n";
          matrixData.println(header);
      }
      dataString = String(matrix_coloum) + ";" + String(*array_pointer) + "\n";
      matrixData.println(dataString);
      Serial.println("This is datastring:");
      Serial.println(dataString);
      array_pointer++;
      matrix_coloum++;
    }

  }

  else{
    Serial.println("Error writing to file !");
}
  matrixData.close(); // close the file

  return 0;
}

My class with all the inits

class EKG_data_transmision
{
  private:

    String dataString;
    String header;
    unsigned short matrix_coloum = 0;

  public:
    EKG_data_transmision();

    File matrixData;

    //Definiere Funktionen:
    bool write_matrix_to_SD(unsigned short *array_pointer);
    bool delete_matrix_from_SD(unsigned int record);

How is write_matrix_to_SD() called? From the string String(matrix_coloum) + ";" + String(*array_pointer) + "\n"; you do see the matrix column number but not the value? Is it an empty value or some random invalid value?

the write matrix to SD is called from the loop. Like this EKG_data_transmision.write_matrix_to_SD(EKG_recording.array_pointer);
If i serial.print the strings i can see them. They just dont get saved to the .csv file like the header with "ID; Value"


text:
Arduino transmitter and receiver
hi I am using Arduino transmitter and receiver it works properly with sending and receiving username and password but I would include to check the username if its true open the led , I added this in the code but it seems that the code ignoring it ( the last part) as well as I want it to take the password and username at the same time
this is the recover code
#include <RH_ASK.h>//include radioHead ASK library
#include <SPI.h> // include dependant SPI libray

 RH_ASK rf_driver; // create ASK object
int ledon = 13;
String userid;
String password;
 //RH_ASK ID1; // create ASK object
//RH_ASK pass1; // create ASK object

void setup() {

  rf_driver.init(); //initialize ASK object

  Serial.begin(9600); //setup serial monitor to 9600

  //if(!rf_driver.init())
       //Serial.print("init failed");
}

void loop() {

  // set buffer to size of expected message
  uint8_t buf[9];
  uint8_t buflen =sizeof(buf);

  //check if recevied packet is correct size
  if (rf_driver.recv(buf,&buflen))
  {
    int i;
    // message received with valid checksum
    Serial.print("id: ");
    Serial.println((char*)buf);
      userid =(char*)buf;
        Serial.println(userid);

  }

delay(5000);

   uint8_t buf2[8];
  uint8_t buflen2 = sizeof(buf2);

   if (rf_driver.recv(buf,&buflen))

  {

    int i;
    // message received with valid checksum
    Serial.print("password: ");
    Serial.println((char*)buf);
      password = (char*)buf;
      Serial.println(password);

  }
  delay(5000);

while ( userid =="A00034732" && password == "123456789"){
digitalWrite(ledon, HIGH);
delay(2000);
digitalWrite(ledon, LOW);

}
}

transmitter code ----
//Include RadioHead Amplitidue shift keying library
#include <RH_ASK.h>
// Include dependatnt ISP library
#include <SPI.h>

//create Ampitude shift keying object
RH_ASK rf_driver;

void setup() {
 // intialize ASK objct
rf_driver.init();

Serial.begin(9600);

  //if(!rf_driver.init())
      //Serial.print("init failed");

}

void loop()
{

  const char *pass= "123456789";
rf_driver.send((uint8_t *)pass, strlen(pass));
rf_driver.waitPacketSent();
delay(5000);

const char *ID= "A00034732";

rf_driver.send((uint8_t *)ID, strlen(ID));
rf_driver.waitPacketSent();
delay(5000);

//const char *pass= "12345678";
//rf_driver.send((uint8_t *)pass, strlen(pass));
//rf_driver.waitPacketSent();
//delay(5000);

}

You're not comparing strings - you're comparing addresses of strings.  Use strcmp().
while (
    (strcmp(userid, "A00034732") == 0) &&
    (strcmp(password, "123456789") == 0)
) {

I want to convert it to integer


text:
TimerOne Hanging
For the following program. Compiles and runs. I start the Serial Monitor (shown following code) and it asks me to input the Blink Rate. This runs in setup. Then it enters the loop and prints to the serial monitor the rate and starts the >Serial.println("the bl    And it hangs! I can exit the serial monitor and restart it and it does the same thing. So the program/sketch seems to be running fine but somehow the serial communication hangs?  Others have tried it and it works for them?  Using an Alien Aurora R5 running Win10 64bit Home.  Added some delays after another person tried it and it hung on them before adding delay and then ran for them.  They are using Win10 32bit and when tried on their 64bit laptop it hangs.
//Testing the Serial Port

#include <TimerOne.h>

int state = 0;
int value;
long int newtime;

void setup() {
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  digitalWrite(13, state);
  Serial.println("Enter the Blink Rate: ");
}

void loop() {
  if (Serial.available()) {
    value = Serial.parseInt();
    delay(100);
    Serial.print("the blink rate is: ");
    Serial.println(value);
    Serial.println("Enter a new blink rate: ");
    newtime = value * 1000000;
    Timer1.initialize(newtime);
    Timer1.attachInterrupt(blinkme);
    delay(500);
  }
}

void blinkme() {
  state = !state;
  digitalWrite(13, state);
  delay(100);
}

Why delay(100); when you already initialize the Timer1 with the right blink time? Delaying in ISRs should be avoided at all costs.

Delays were added after in attempt to get it to run.  Was advised by another that it hung for them UNTIL they added the delay at end of loop function.

Never ever use a delay in an interrupt

It hangs without any interrupts.

Please change int state = 0; to volatile int state = 0; and remove all delay() calls. Before Timer1.initialize(...), add the line Serial.flush();. Does it work once now but not repeatedly?

If it is the case then the ISR crashes the board. digitalWrite() may disable interrupts.. better use direct port manipulation. Exchange the digitalWrite call with DDRB ^= B00100000;

Did the first comment and got a couple more lines in the monitor before it returned a 0 and hung.  DDRB ^= B00100000;  compiled but did nothing different.

Try using unsigned long as the type for both value and newtime (instead of int and long int). And use 1000000UL instead of 1000000.

Do you have anything connected to D13 that could cause a momentary fault like a short-circuit? If you have an external LED connected you also have the current limiting resistor right?

No change...  still hangs

I have tried it with both an LED and current limiting resistor on D13 and with nothing attached to D13 other than the onboard internal LED.

I have tried multiple versions of UNO and MEGA boards.  I don't think it is board related.  I have also tried a new TimerOne library from GitHub with the same results.

test value for 0 and don't set the timer with 0

Use 1000000L instead of 1000000

0 hangs after the 3rd line on the monitor so it really doesn't like 0 for an input.

No Joy w/ 1000000L

If you enter 1 in Serial Monitor and you have line ends selected, the Serial Monitor sends "1\r\n". parseInt() reads 1 and in next loop \r or \n is available and parses as 0. You then set the Timer to 0. The Serial can't finish printing because the Timer fires without a pause.

BINGO!  Changed the monitor to no line end and now works fine!  Thanks!

@SamR, accept he answer to mark it solved

@SamR, Changed the monitor to no line end ... that is not the way to correct the problem ... instead, insert code that prevents newtime from being zero

Change io 13 to (suggestion) 10 and attach led + 1k resister to io 10.
13 seems to be in use. Also No line end in Serial.


text:
I am using Arduino stepper motor and pir sensor
my project about automated system I am using stepper motor to open and close the gate but my point is I want my code be like when the gate opened it stays 5 seconds then check the sensor if there is a motion the gate should not close and stay open when there is no motion the gate should close and if the gate is closing and there is a motion , motion should interrupt closing the gate and reopening the gate I am using Arduino uno
the code is :

#include <RH_ASK.h>//include radioHead ASK library
#include <SPI.h> // include dependant SPI libray
#include <Stepper.h> // Include the Arduino Stepper.h library:
// Define number of steps per rotation:

RH_ASK rf_driver; // create ASK object
int ledon = 13;
int ledoff = 5;
int sensor = 3;

const int stepsPerRevolution = 2048;// Define number of steps per rotation:

// Wiring:
// Pin 8 to IN1 on the ULN2003 driver
// Pin 9 to IN2 on the ULN2003 driver
// Pin 10 to IN3 on the ULN2003 driver
// Pin 11 to IN4 on the ULN2003 driver
// Create stepper object called 'myStepper', note the pin order:
Stepper myStepper = Stepper(stepsPerRevolution, 8, 10, 9, 11);

void setup() {

  rf_driver.init(); //initialize ASK object

  // Begin Serial communication at a baud rate of 9600:
  Serial.begin(9600);

  // Set the speed to 5 rpm:
  myStepper.setSpeed(5);
  pinMode(ledon, OUTPUT);
  pinMode(ledoff, OUTPUT);

}

void loop() {

  //set buffer to size of expected message
  //uint8_t buf[8];
  // uint8_t buflen =sizeof(buf);

  //check if recevied packet is correct size
  //  if (rf_driver.recv(buf,&buflen))
  //{
  // int i;
  // message received with valid checksum
  // Serial.print("id: ");
  // Serial.println((char*)buf);
  // String userid =(char*)buf;
  // Serial.println(userid);

  // }

  //delay(5000);

  // uint8_t buf2[8];
  // uint8_t buflen2 = sizeof(buf2);

  // if (rf_driver.recv(buf,&buflen))

  // {

  //  int i;
  // message received with valid checksum
  // Serial.print("password: ");
  // Serial.println((char*)buf);
  // String password = (char*)buf;
  //  Serial.println(password);

  // }
  // delay(5000);

  String pass = "1234";
  String id = "A00036757";

  if (pass == "1234" ) {
    Serial.print("car exists");
    digitalWrite(ledon, HIGH);
    delay(300);
    myStepper.step(stepsPerRevolution / 3); //clockwise -OPEN GATE
    delay(10000);

    //if(digitalRead(sensor) == HIGH){
    delay(500);
  }

  if (digitalRead(sensor) == LOW) {

    digitalWrite(ledon, LOW);
    delay(300);

    digitalWrite(ledoff, HIGH);
    delay(300);
    myStepper.step(-stepsPerRevolution / 3); // CLOSE AFTER 5s COUNTERCLOCKWISE -  close gate
    digitalWrite(ledoff, LOW);
  }
  else {
    Serial.print("NO CAR");
  }

And what is your question?

Motion sensor's operation depends on the sensor's setting. See motion sensor setting. Please post your sensor's setting


text:
Protecting variables and functions within a library that has no class
If you want to have functions within a library that only the library itself should be able to use or variables that shouldn't be accessed from outside, you usually make them private by writing this in the header file:
class Lib{
  public:
    // All these can be accessed from outside
    void function1();
    void function2();
    int someNumber;
  private:
    // These two can't be accessed from outside
    void secretFunction();
    int secretNumber;
};

My question is this:
I want to write this library without using classes. How do I protect things from being accessed from anywhere in this case?

If your library is implemented in a single .cpp file, you can define these
variables and functions within that file, and give them the static
qualifier:
static int my_private_variable = 42;

static void my_private_function()
{
    ...
}

Obviously, there should be no mention of them in the .h file.
Note also that we are talking about global variables. Local variables
are already hidden within the defining function.

Exactly what I was looking for. Check out this question: https://stackoverflow.com/questions/17554515/hiding-private-members-of-c-library/59093688#59093688 you basically answered that too!


text:
Arduino uno toggle switch help
I am building a box that will start a genset. It has two buttons, run and stop.
I would like button run to be able to start (and remain constant) until pressed a second time, I have sussed this bit so far, but this is where I get stuck.
I would like the stop button to only stop the the engine (as a single function)
So my question is how do I integrate the second button (stop) to carry out this one task?
int LEDYelState=0;
int LEDRedState=0;
int LEDGrnState=0;
int RELAYRedState=0;
int RELAYYelState=0;
int RELAYGrnState=0;
int LEDRedPin=10;
int LEDYelPin=9;
int LEDGrnPin=8;
int RELAYRedPin=7;
int RELAYYelPin=6;
int RELAYGrnPin=5;
int buttonPin=13;
int buttonNew;
int buttonOld=1;
int dt=100;
int buttonOff;
int buttonPinOff=12;
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
pinMode(LEDRedPin, OUTPUT);
pinMode(buttonPin, INPUT);
pinMode (LEDYelPin,OUTPUT);
pinMode (LEDGrnPin, OUTPUT);
pinMode (RELAYRedPin, OUTPUT);
pinMode (RELAYYelPin, OUTPUT);
pinMode (RELAYGrnPin, OUTPUT);
pinMode (buttonPinOff, INPUT);
}
void loop() {
buttonNew=digitalRead(buttonPin);
buttonOff=digitalRead(buttonPin);
if(buttonOld==0 && buttonNew==1){
  if (LEDRedState==0){
    digitalWrite(LEDRedPin,HIGH);
    LEDRedState=1;
    digitalWrite(RELAYRedPin,LOW);
    RELAYRedState=1;

    digitalWrite(LEDYelPin, HIGH);
    LEDYelState=1;
    digitalWrite(RELAYYelPin, LOW);
    RELAYYelState=1;
    delay (8000);
    digitalWrite(LEDYelPin,LOW);
    digitalWrite(RELAYYelPin,HIGH);

    digitalWrite (LEDGrnPin,HIGH);
    LEDGrnState=1;
    digitalWrite (RELAYGrnPin, LOW);
    RELAYGrnState=1;
    delay(2000);
    digitalWrite  (LEDGrnPin,LOW);
    digitalWrite (RELAYGrnPin,HIGH);
    RELAYGrnState=1;
  }
  else{
    digitalWrite(LEDRedPin, LOW);
    LEDRedState=0;
    digitalWrite(RELAYRedPin, HIGH);
    RELAYRedState=0;
    digitalWrite(LEDYelPin,LOW);
    LEDYelState=0;

  }
}
buttonOld=buttonNew;
delay(dt);

}

separate the motor run function from the button press function .... declare a boolean variable ... name it run for example ... when it is true, then the engine runs ... when it is false, then the engine stops ... if you press start, then make run true ... if you press start again, then make run false .... when you press stop, then make run false

Could you give me some code that I can see for example that might work ?
Cheers Bryan

A general hint first: indent your code correctly. It makes it much easier to read and easier to spot logical errors.
Another improvement would be to name the pins with the same names as you name them when explaining the problem to us. I expected to find a int buttonRunPin and int buttonStopPin.
The first issue I see is:
buttonNew=digitalRead(buttonPin);
buttonOff=digitalRead(buttonPin);

This reads the same button twice. You probably wanted to read two different buttons: the "run" button and the "stop" button.
The next issue I see is:
delay(8000);
delay(2000);

During these 10 seconds, you can press and let go the button many times. But since there is no digitalRead() during that time, the button press will not be recognized.
The same applies to
int dt=100;
delay(dt);

If you press the button within these 100 ms, it will not be noticed.
Unfortunately, to fix that, you need to learn a completely new concept: interrupts. And even worse, not all pins support interrupts. On the Arduino Uno, it's only pin 2 and pin 3, which means you would need to change your hardware setup (because you use pin 12 and 13). Put both buttons from the pin to ground, so that it closes when pushed.
You would then prepare the interrupt in the setup() routine:
pinMode(buttonPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(buttonPin), toggleRun, CHANGE);
pinMode(buttonPinOff, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(buttonPinOff), toggleStopped, CHANGE);

You also define global variables for the state of the buttons:
volatile bool running = false;
volatile bool stopped = false;

volatile is needed here to prevent the compiler from optimizing too much. The compiler does not know about the interrupts and thus can't know when the variable changes.
Next, you need two methods that are being executed whenever an interrupt occurs, i.e. you press a button:
void toggleRun() {
    running = !running;
}
void toggleStopped() {
    stopped = !stopped;
}

Note: the above x = !x; pattern is a short and efficient form of
if (x == false) {
    x = true;
}
else if (x == true) {
   x = false;
}

Once you have all that, you don't need the two digitalRead()s any more.
I'm afraid I haven't understood what your code's supposed to do. You have a lot of state variables that seem to have no use and especially they don't correspond to the motors. E.g. once RELAYGrnState is set to 1, it never changes back to 0.
This is what I have in the end:
int LEDYelState=0;
int LEDRedState=0;
int LEDGrnState=0;
int RELAYRedState=0;
int RELAYYelState=0;
int RELAYGrnState=0;
int LEDRedPin=10;
int LEDYelPin=9;
int LEDGrnPin=8;
int RELAYRedPin=7;
int RELAYYelPin=6;
int RELAYGrnPin=5;
int buttonPin=13;
int buttonNew;
int buttonOld=1;
int dt=100;
int buttonOff;
int buttonPinOff=12;

volatile bool running = false;
void toggleRun() {
    running = !running;
}

volatile bool stopped = false;
void toggleStopped() {
    stopped = !stopped;
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(LEDRedPin, OUTPUT);
  pinMode (LEDYelPin,OUTPUT);
  pinMode (LEDGrnPin, OUTPUT);
  pinMode (RELAYRedPin, OUTPUT);
  pinMode (RELAYYelPin, OUTPUT);
  pinMode (RELAYGrnPin, OUTPUT);

  pinMode(buttonPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(buttonPin), toggleRun, CHANGE);
  pinMode(buttonPinOff, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(buttonPinOff), toggleStopped, CHANGE);
}

void doSomething() {
  digitalWrite(LEDRedPin,HIGH);   // red LED is on
  LEDRedState=1;
  digitalWrite(RELAYRedPin,LOW);  // red motor off? others unclear
  RELAYRedState=1;

  digitalWrite(LEDYelPin, HIGH);  // yellow LED and red LED are on
  LEDYelState=1;
  digitalWrite(RELAYYelPin, LOW);  // yellow motor off?
  RELAYYelState=1;
  delay (8000);
  digitalWrite(LEDYelPin,LOW);     // red LED on
  digitalWrite(RELAYYelPin,HIGH);  // yellow motor on

  digitalWrite (LEDGrnPin,HIGH);  // red and green LED are on
  LEDGrnState=1;
  digitalWrite (RELAYGrnPin, LOW);  // green motor off
  RELAYGrnState=1;
  delay(2000);
  digitalWrite  (LEDGrnPin,LOW);    // red LED on
  digitalWrite (RELAYGrnPin,HIGH);  // green motor on
  RELAYGrnState=1;
}

void doLess() {
  digitalWrite(LEDRedPin, LOW);     // red LED off
  LEDRedState=0;
  digitalWrite(RELAYRedPin, HIGH);  // red motor on
  RELAYRedState=0;
  digitalWrite(LEDYelPin,LOW);      // yellow LED off
  LEDYelState=0;
}

void loop() {
  if(running){
    if (!stopped){
      doSomething();
    }
    else{
      doLess();
    }
  }
  delay(dt);
}

I’ve taken that all on board, thank you, now I’ll try to get to grips with your advise ..... thanks again


text:
Determine what size power supply I need to run stepper motors
I have recently purchased two 7.4V, 1A, Planetary Gear Unipolar Stepper Motors as well as two Cytron 3A 4-16V Dual Channel DC Motor Drivers. I was told that I would need these to run the motors off an Arduino board. The question I forgot to ask was: what size power supply I would need for something like this?
I am just looking to learn how to code these arduino boards. I was hoping to get something that I could plug into a wall to save me from buying multiple batteries.

You can't run these off the Arduino board for several reasons:

the Arduino board does not provide 7.4V on any pin, only 5V (model dependent, but never 7.4 V)
the Arduino board can provide about 20mA per pin, never 1A or higher
even if the board would only need to pass the voltage on, the total current were >2A. This would possibly fry the board.

So, what you need is: a power supply with constant 7.4V or a regulated one where 7.4V is within the range. From this power supply you will power 3 devices only:

one arduino board via the Vin pin (accepts 7 to 12 V, so 7.4V is ok)
two Dual Channel DC Motor Drivers (accepts 4 to 16V, so 7.4V is ok)

From each motor driver, you will power

one Planetary Gear Unipolar Stepper Motors (designed for 7.4V)

Now, let's sum of the currents:

Arduino Uno board without any peripherals: ~45 mA
two Stepper motors: 1000 mA each
two motor drivers: hard to say. In theory, the motor driver would not consume power by itself, just forward it to the motors. In practice, it cannot forward everything. The driver will get hot and thus consume some power itself. The datasheet is not specific about the power consumption. Let's assume a 70% efficiency = 30% loss. 30% of 1000mA is 300mA each.

The total current needed for this setup is 2645mA. Depending on your budget you could buy a 3A or 5A power supply. At constant 7.4V, that's 23W or 37W. For a regulated 0V to 20V power supply, go for 60W or 100W.
A cheap regulated one should be at ~50 USD. Expect those to be loud because of bad cooling / fan noise.


text:
7 segment display with common anode
I am brand new to electronics. I am trying to use a seven segment display breakout module with my arduino uno. My problem is that the display has a common positive instead of negative common. How do I make this work? As far as I am aware, all the arduino pins output positive with the exception of the ground, which is the negative common.

You might want to add what driver you are using...Max7219?

This answer assumes Arduino Uno. For other types, refer to the documentation.
Ardino pins are not positive per se: you can change the voltage with digitalWrite() to either 0V (LOW, equal to the GND pin) or 5V (HIGH, equal to VCC).
The difference between a common cathode or common anode will be the flow of the current. With a common cathode (negative), the pins will need to provide current ("source" current), with a common anode, the pins will need to receive current ("sink" current).
There is a description for the limits of sourcing and sinking:

Pin SOURCE Current Limitations:
20 mA at VCC = 5 V
Pin SINK Current Limitations:
20 mA at VCC = 5 V

Please also read about the maximum total of 150 mA sourcing and 100 mA sinking.
You'll need to compare those current limits with the current requirements of your 7 segment display. My guess is that your a 7 segment display has 1 VCC pin and 7 output pins that you connect to the Arduino. The limiting factor is the total maximum here. The Arduino can handle 100 mA/7 = 14mA in the worst case. If that's enough for your 7 segment, it should work.
For example, this one works with 10 mA, so it would be compatible with Arduino. Make sure you have resistors in place.

Thank you very much for your sagely wisdom! I was so wound up over trying to get an answer to my problem, that I neglected to mention that I am using an Arduino Uno! Again, thank you so much for your time and effort.


text:
Arduino Killing USB-C Mini Dock
I've been having some issues with my Arduino Mega Board. I built a PCB that would sense LM35 reading, low-pass filter it and send it to A0 into the Arduino. This is the input for a PID controller based on Brett Beauregard library. The schematics is really simple, a voltage divider after de PWM output, that polarizes the base of a TIP 122, causing current to close the circuit for a wound wire resistor.
1)
I was feeding the PCB board with 12V 2A switching supply (but not the arduino). On the other side, my PC was connected to a USB-C / USB mini dock to the Arduino, and the Arduino conected to the PCB board ( LM35 Output and PWM Input).
While using it my computer lagged a lot, but I didn't do anything, untill it killed my mini dock's USB port.( the power supply GND was connected to the Arduino's GND)
2) I did a new PCB board, filtering even more the LM35 signal, and doing some extra changes. While doing some examinations for the filter (succesfully) and using a lab's regulated power supply for the PCB (12V), everything went okay...Untill I wanted to examine if the PWM signal was causing any noise into the LM35 reading, so I started apply the PWM signal to a header pin in the PCB. After a while my computer stopped recognizing the Arduino and finally killed a second USB mini dock.
I'm pretty sure there's not a shortcircuit or any stupid mistake... but I cannot find whats going on.

Why is the +12V net connected to the Arduino power plug. And how did you connect your Arduino power plug  to the PCB? I do not say it's an error. I simply do not understand what happens there. ;-)

I think the electrical engineering stackexchange might be a better place for this question.  https://electronics.stackexchange.com/


text:
New OLED seems dead, how can I be sure?
I bought this 2.8" OLED from Aliexpress a few weeks ago: https://www.aliexpress.com/item/32988174566.html?spm=a2g0s.9042311.0.0.72304c4dAWcHG8
And after a ridiculous amount of searching for a datasheet, I came across this one that seems to match the board I bought: https://www.buydisplay.com/download/manual/ER-OLEDM028-1_Series_Datasheet.pdf
Wiring up pins 1 and 2 to ground and 3.3V on a breadboard, I'd expect something to happen with the display, but I get nothing. The display is in 8080 mode, so I wire everything up to a standard UNO board and power everything on. Still nothing. Try changing the power to 5V, no joy.
During my testing, I noticed the back of the display is getting hot. Not sure if that's a good thing or not yet.
So what's the best way to 1) determine if the datasheet I found is correct? 2) check if the OLED is just broken? I don't have a ton of experience with these displays yet, so I'm not sure if just powering the thing on should net some visual response.

What do your expect exactly? How are you driving signal to the screen?

Unlike LCD displays, OLED displays don't have a backlight. You probably won't see ANYTHING unless you send data to it to turn on some pixels. (Disclaimer - I've never tried to interface one, so my comment is based on theory. If I was designing the interface I'd make it do a self-test when it was first powered on, where it cycled all the pixels through red, green, and blue. so you could tell it was working and all the pixels lit up.)

Getting hot is not a good sign for such device!

@LotB I have a simple test I've used on other screens that uses the u8g2 library. I would expect a few sentences to show up. I'm using an UNO but in parallel, which should be fine, but I'm wondering if switching to 4-wire SPI might provide better results.

@SimSon I would agree. I suspect I've gotten something wired wrong, which is why I'm questioning the datasheet I found.

The datasheet is not for the same display. If you check the webpage for the display in the datasheet and look at the back of the PCBs and compare them you will see they are different. Thus you cannot assume that the IO connector is wired the same.

Better to buy from a reputable dealer (I always use buydisplay.com - they are very very good) where you get documentation and support, rather from some unknown junkyard that sells you complete crap with no clue what it is.

@Majenko Oh sure, I never expect much from the things I buy off Aliexpress. But the question remains: even if I did get something from buydisplay, how would I know it was functioning correctly? Do OLEDs light up with power applied? Or do they need data as well? Trying to use this as a learning experience when the next display is not working as expected.

You would only know it was working if you programmed your MCU to actively drive it in some way. You get nothing out of an OLED unless you tell it to display something. There's no glow, no flash, nothing. That's the beauty of OLEDs - black is truly black. Each pixel is an individual LED that is either on or off.

The datasheet you have found is not for the same display. Yes, it's similar, and yes, it has the same actual OLED display unit on the board, but the PCB is different. So you cannot assume that the pinout is the same.
The fact that it's getting hot tells me that you have probably wired something wrong and you are injecting voltage into it somewhere where voltage doesn't want to be injected.
To find if an OLED is working you have to actively wire it up.  With an LCD you can just give it power and you should be able to see some visual indication that it's working (back light, some shadowing of the display matrix, etc). But with an OLED you can't do that.  An OLED is made up of a matrix of LEDs which are either on or off. By default they are off, and when they are off it's no different to there being no power. That's the big benefits of OLED displays - low power consumption and true black.
To get any kind of indication that the display works you both need to wire it 100% correctly and program the Arduino in the right way to actively drive it by displaying something on the screen.  My usual test program when working with a new screen is to simply print millis() in the top left corner.

Thanks for the detailed explanation, Majenko. I've ordered a new display from buydisplay and will try this again in 7-40 business days ;)