text:
Can't stop SG90 spinning
I have a SG90. I just want it to spin 360° and stop, that's about it. This seems impossible.
I have tried the sweep example:
 by BARRAGAN <http://barraganstudio.com>
 This example code is in the public domain.

 modified 8 Nov 2013
 by Scott Fitzgerald
 http://www.arduino.cc/en/Tutorial/Sweep
*/

#include <Servo.h>

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

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

This works fine.
I read somewhere that for 360 motors the variable in myservo.write() is actually just the speed. So I tried:
void loop() {
    myservo.write(0);              // tell servo to go to position in variable 'pos'
    delay(2000);                       // waits 15ms for the servo to reach the position
    myservo.write(180);              // tell servo to go to position in variable 'pos'
    delay(2000);
    myservo.write(0);              // tell servo to go to position in variable 'pos'
}

The motor rotates several times then spins the other direction and repeats doing this.
What do I need to do to make it complete 1 rotation and stop?

TL;DR: Can't be done.
On a servo modified for continuous rotation, the signal you send sets direction and speed, not rotation angle. You can stop it, but you can't set an angle.
The sweep example will turn a continuous rotation servo in both directions, but I doubt it hits the angles you send it; it will just adjust speed and direction.
Without external hardware and feedback, like a limit switch, or a rotary encoder, there is no way of knowing what angle the servo is at, and no way to rotate to exactly 360° other than experimenting and "guessing" based on time and rotation speed.
You can then stop it by setting it to the PWM value for 90° or center position, which should set the rotation speed to 0.
On a servo, you can't have both continuous rotation with a set speed, and a set angle of rotation, without extra hardware.
Maybe a stepper motor would be a better choice for your application, or a "normal" servo with a gear that gives you the required rotation range.

A dc motor might be better. I just need to turn an auger once. I can add a limit switch, not sure how I would implement this to stop the servo?

You would need a pin on the axle that hits a switch. Could be awkward. You could also use a regular servo (non continuous, 0°-180°) with a gear on it to get 360°, or look into sail winch servos. Don't forget to accept the answer (if you accept it).

A value near 90 will make your rotating servo stop. Try 89, 91 etc. until you find it.
If you are running an auger, use a microswitch that pulses once per revolution. Starting at the point where the switch makes contact, run the servo until the switch opens and closes again then stop. You have made one revolution.


text:
Why are transistors necessary before LEDs?
Below is the small RGB LED circuit I'm trying to build. My question is why are the 3 transistors necessary, and can I not link the LEDs directly?

I doubt if the LEDs will ever light up with 4.7k base resistor and 4.7k resistor in series with LEDs

@SBF they will not. They’re NPN transistors on the wrong side of the load. Also, the LEDs will not be driven higher than about 0.5mA each, which might be enough, but will not be very bright.

We don't know what the supply voltage is from that circuit. It's not a good circuit at all.

@StarCat They're not on the "wrong" side of the load. There's no "wrong" side. They're just not on the "traditional" side for simple saturation switching. Instead they (and their resistors) form part of the base current path and severely limit the amount of base current that can flow. Your current of 0.5mA for each LED is bang on though. I make it 594uA per LED. A pitiful current.

@Majenko, agreed, when I said "wrong" I meant this was not the most logical or efficient placement of the switching NPN transistors. Your explanation is correct of course.

@StarCat would you care to explain why it is inefficient and how this circuit could be improved (apart from the way too big resistors)? Thanks.

NPN transistors in this configuration will not fully turn on because the amount of current they can pass between collector and emitter is limited by the current that flows from the base through the emitter (which is limited because of the high base resistance and the small voltage difference between base and emitter). There will be a 0.7V voltage drop between collector and emitter. A better placement of NPN transistors would be between ground (connected to the emitter) and the negative pins of the LEDs (to the collectors). This allows the transistors to turn fully on (more like a switch).

The port pins of your Nano can deliver current in a quite limited range, and six LEDs need a lot more to shine brightly. The transistors are amplifying the available current.
However, 4k7 resistors in series with each LED will not allow enough current to let them shine well. Reduce the resistors by a factor of at least 10. Read the LEDs' data sheet and apply Ohm's law.

The transistors are connected as an emitter follower, not as a switch. The transistors are acting as current amplifiers. The emitter voltage will rise to approximately the voltage on its base - about 0.7V. That places the voltage at about (5 - 0.7 = 4.3V) at the emitter. Since the collectors of transistors are powered by Vin I would guess you have at least 6 volts available assuming a 5V Nano so the extra voltage drop across the transistors will be dissipated as heat. The base resistors are not needed but should not affect performance much. The available current at the emitter would be the Hfe of the transistor times the base current. Each LED will consume about 2 milliamps making the load on each of the transistor around 12 milliamps. It should work fine. You can divide the 12 milliamps of the LEDs by the Hfe of the transistor to get the base load.

Each LED consumes up to 20mA and You are using three LEDs at each I/O port in Arduino Nano. In other word, each part consumes 120mA.
The important thing is Arduino Nano I/O provides 20mA at maximum. So if you want to control 120mA by I/O ports, you must use transistor to support huge current.
Transistor can afford current up to 500mA.

I see 6 LEDs controlled by one pin

How do you know how much current the transistor can handle? The OP did not specify the transistor used...

He said "Why transistors are necessary" not "Why this transistors are necssary"

@Juraj I see 12 LEDs controlled by pins 6/10

3 transistors on pins D2, D6 and D10 and 18 LEDs

The emitors of the transistors to D6/D10 are connected ;-)

yes I see, but I guess that is only an error on the schematics and not on the real circuit

source: Stack Exchange

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

sort: votes


text:
How to make motors start when pressing a button, and then go through a cycle with a specific motor order?
I'm very new to arduino and have to work on a project for school. We have connected 3 motors (Servo, Stepper (180 degrees) and a DC motor) to an Arduino Uno, Adafruit motorshield and a pcb. With the pcb we were able to record values of the motors individually and use these values to create a playback motion. The code which we got for the playback motion is below (I've already filled in my values for the 3 motors).
This is what I want to do with the motors:
When I press a button I want to 'start' the cycle of motor motions

first the dc motor starts doing the motion based on the chosen values
When this stops after 5 seconds I want the servo motor to do it's motion
When the servo motor is done, I want the stepper motor to start doing the motion based on the chosen values for 5 seconds and then stop.

We were told not to use a delay and someone suggested to use millis() instead of delay() but since I am a beginner I have no idea where to start.
This is the code:
// With this code it is possible to play back recorded motion paths for for motors connected to the Adafruit motorshield

#include <AccelStepper.h>
#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include <Servo.h> // this is a library that allows you to drive servo's.

// variables
int modeChoice = 0;

int buttons = A2;  // the three buttons share an analog pin, resitors provide different levels that point to which button is pressed
int slide = A1;    // the slide is read through one analog pin, resitors provide different levels that point to which slide position is current
int rotation = A0; // the pin for the potentiometer

int buttonPressed = 0; // a variable to remember which button is pressed, it is used to control leds and motion memory position management

int buttonValRaw = 0; // a variable to store the raw analog reading of the buttons pin
int slideValRaw = 0;  // a variable to sore the raw analog reading of the slide pin
int valButton = 0;    // a variable to store the interpreted value, the exact pointer to a button
int valSlide = 0;     // a variable to store the interpreted value, the exact pointer to a slide position
int idleState = 0;    // a variable to toggle the servo idle behavior
int resetMotion = 0;  // a variable to return the arrayPosition to 0 if a button is pushed so that the behaviour starts at the beginning
int motionVar1;       // a variable to hold a motion position
int motionVar2;       // another variable to hold a motion position

int mySensorArray[20];  // an array with 20 slots to store raw potentiometer readings (for filtering)
int sensorArrayPos = 0; // the array position of interest.

//////////////////////////////////////

int servoMotionArray_B1[50] = {95, 95, 95, 95, 65, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // paste your 50 values in between the brackets

int DCMotionArray_B1[50] = {-85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85, -85};

//recorded motions for position implementation
int StepperMotionArray_B1[50] = {-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200,-200};

//////////////////////////////////////

int arrayPosition = 0;

unsigned long mainTimer = 0; // a variable to time recording and playback
int timeBetweenSamples = 100; // the time between samples.

unsigned long debounceTimer = 0; // a variable to control a timer interval for debouncing of the buttons
int lastValButton = 0; // a variable to help debouncing of the buttons
int debounceFlag = 0; // another variabel to help debouncing of the buttons

// Setup motors
// Create the motor shield object with the default I2C address
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
// Connect a stepper motor with 16 steps per revolution (2048 positions) to motor port #1 (M1 and M2) -- you need to change this if your stepper is on port #2
Adafruit_StepperMotor *myStepper = AFMS.getStepper(16, 1);
// And connect a DC motor to port M3 -- you need to change this if your DC is on a different port
Adafruit_DCMotor *myMotor = AFMS.getMotor(3);

Servo myservo1;   // servo object (employs the servo library that was included above)

// these are dedicated functions to make the steppermotor move
void forwardstep1() {
  myStepper->onestep(FORWARD, SINGLE);
}
void backwardstep1() {
  myStepper->onestep(BACKWARD, SINGLE);
}

//create aStepper object
AccelStepper aStepper(forwardstep1, backwardstep1); // use functions to step

// setup
void setup() {
  Serial.begin(9600); // start serial communication with 9600 baud rate

  AFMS.begin();  // create with the default frequency 1.6KHz
  //AFMS.begin(1000);  // OR with a different frequency, say 1KHz

  myservo1.attach(9); // attach servo object to pin 9

  // turn on motor M3
  myMotor->setSpeed(0);
  myMotor->run(RELEASE);

  // setup the stepper
  aStepper.setSpeed(0); // this is used in the 'speed' implementation

  aStepper.setMaxSpeed(200.0); // these are used in the 'position' implementation
  aStepper.setAcceleration(100.0);
  aStepper.moveTo(0);

  // synchronize the first timer cycle -- because the timer is starting at zero it generates negative values in the first 100 miliseconds after starting up when going through the timer cycle, creating potential erratic bahaviour-- giving it a delay at the end of the setup loop will eradicate this behaviour
  delay(1000);
}

void doButtons() {
  if (buttonPressed != 0) {
    return;
  }
  else {
    buttonValRaw = analogRead(buttons);
    valButton = map (buttonValRaw, 49, 605, 0, 5);
    int localButtonVal = valButton;

    if (valButton > 7) {
      return;
    }

    if (debounceFlag == 0) {
      debounceTimer = millis();
      debounceFlag = 1;
    }

    if (debounceTimer < millis() - 20) {

      buttonValRaw = analogRead(buttons);
      valButton = map (buttonValRaw, 49, 605, 0, 5);

      if (valButton == localButtonVal) {
        debounceFlag = 0;

        switch (valButton) {
          case 1:
            buttonPressed = 1;
            break;
          case 2:
            buttonPressed = 2;
            break;
          case 3:
            buttonPressed = 3;
            break;
          default:
            buttonPressed = 0;
            break;
        }
      }
    }
  }
}

void loop() {
  doButtons(); // this uses the buttons from the PCB, if you use your own implementation you need to reprogram this function

  if (mainTimer < millis() - timeBetweenSamples) { // sampling only once per interval.
    mainTimer = millis(); // time is rewritten to current millis starting a new interval.

    if (buttonPressed == 0) { //'idle play'
      if (idleState == 0) {
        motionVar1 = servoMotionArray_B1[arrayPosition];
      }
      else if (idleState == 1){
        motionVar1 = servoMotionArray_B1[arrayPosition];
      }
      motionVar2 = DCMotionArray_B1[arrayPosition];
      myservo1.write(motionVar1);
      if (motionVar2 < 0) {
        myMotor->run(BACKWARD);
        myMotor->setSpeed(abs(motionVar2));
      }
      else if (motionVar2 >= 0) {
        myMotor->run(FORWARD);
        myMotor->setSpeed(motionVar2);
      }
      arrayPosition++;
      if (arrayPosition > 49) {
        arrayPosition = 0;
        idleState = !idleState;
      }
    }

    if (buttonPressed == 1) { //2nd behaviour
      if (resetMotion == 0) {
        arrayPosition = 0;
        resetMotion = 1;
        myMotor->run(RELEASE); // release the DC motor, otherwise it will continue spinning at the last known RPM
      }
      motionVar1 = servoMotionArray_B3[arrayPosition];
      motionVar2 = StepperMotionArray_B1[arrayPosition];
      myservo1.write(motionVar1);
      aStepper.moveTo(motionVar2);
      arrayPosition++;
      if (arrayPosition > 49) {
        arrayPosition = 0;
        buttonPressed = 0;
        resetMotion = 0;
      }
    }
  }

  // one of these needs to be called to make the stepper motor work, comment out the one you do not need (position or speed)
  //aStepper.run(); //stepper position implementation
  aStepper.runSpeed(); //stepper speed implementation

}

You're almost correct already:
if (millis() - mainTimer >= timeBetweenSamples) {
  mainTimer = millis();
  // executing only once per interval.

  ... the action for current arrayPosition ...

  arrayPosition++;
  if (arrayPosition > 49) {
     arrayPosition = 0;
     buttonPressed = 0; // Show ends
  }
}

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


text:
Can arduino nano drive two circuit
I am building a robot snake with a bunch of servos and ov7670. As I see, ov7670 operate with 3.3v and servos needs 5v. I will use Lipo battery for servos for this I need to connect ground pin of arduino and input of battery. But For ov7670, I already connect the ground pin of arduino. Can I connect ground with a jumper to another breadboard to connect with lipo battery and servos or I need two arduino nanos?

You can use a common ground in fact it's the normal thing to do with external circuits such as relays, servos etc

I am a beginner and do not know much about arduino. Thanks for your answer.


text:
button connection without connection to 5V pin
There are two types of tutorials for buttons:

I don't understand how a button on the first image works. Do we just hope that there is some non zero voltage and hope its enough? I think the first image is really bad, but can't explain why.

There is a pullup resistor you don't see in the diagram because it is internal to the Arduino. I have added it in red. To make pin 7 an input, you can write:
digitalWrite(7, INPUT_PULLUP);

, which not only makes the pin an input but also engages the internal ~20K pullup  resistor.
So, you're right about the first diagram - it looks like the pin is left floating. Without the code, or an explanatory note, the pullup resistor isn't documented. In such a diagram, once you are familiar with the processor and know that there are optional pullups on the pin-drivers, you can assume that the optional pullup will be used.

Update: I drew in the resistor assuming the red rail was connected to 5v - I should have drawn that in, too.

Just note that with the pull-up the signal is inverted from when you use a pull-down. That is; digitalRead will return LOW when the button is pressed, and HIGH when not pressed. For a beginner, this can be a bit counter-intuitive. I guess that's why a lot of tutorials use this method. It also shows the actual resistor, instead of using the internal one you can't see. Once you understand how things work, and how you shouldn't leave pins floating, you'll probably end up using the internal pull-up method, since it's easier to wire up.

Second note; some MCUs also have pull-down resistors. In that case you can use both methods, without having to add a resistor. Though with laying out a PCB, it's often easier to connect the other leg of the button to GND, that to Vcc. So I'd still prefer the pull-up method.

For inverted signals such as this, I remind myself in an end-of-line comment that the signal is active-Low, and often I'll make signal condition name, such as PRESSED in this case, and #define PRESSED LOW. As often as I take advantage of the built-in pullup, guess who still trips over his own code when skimming it quickly!

The digital pins of an Arduino UNO, or rather the AVR microcontroller used in the UNO, have optional internal pull-up resistors that can be enabled with the INPUT_PULLUP option to pinMode.  When you use INPUT_PULLUP (as opposed to INPUT) there is a functional resistor somewhere between 20kOhm and 50kOhm connected between VCC ("5V") and the digital pin.  When you account for this internal resistor enabled, the circuits in your two images are structurally mirror images of one another:

The boxed numbers here are just to clarify what nodes in the wiring diagram correspond to what nodes in the schematic representation.  Don't ask where box number 5 is; it's a mystery.  I chopped part of the original second image so a new GND connection was hand-drawn in.
In your first image (left) the code would have to enable the internal pull-up resistor to establish a default HIGH state on the digital pin.    With INPUT_PULLUP enabled you can imagine that internal resistor there when comparing with your second image (right).  Here I've drawn a resistor symbol over the board to represent the internal one when enabled.  When the button is pushed some current is drawn through that internal pull-up and the voltage at the pin falls to ground.  Note you could just as easily have an external resistor there and use plain INPUT mode.
Your second example image (right) is using an external pull-down resister to establish a default LOW state.  So when you push the button, the signal rises toward 5V/VCC or HIGH, and some current flows through the pull-down resistor. This would be used with INPUT mode rather than INPUT_PULLUP; I have not annotated an internal pull-up on the right to indicate that the pull-up is not enabled in this scenario (plain INPUT mode).  Note that if you were to enable the internal pull-up in this second configuration it would form a voltage divider with external pull-down; for the 10K external pictured this could result default voltage at the pin which is only bordering on being a proper LOW.
Some people find it less confusing to have a HIGH state when the button is pushed and also using an external resistor like this helps to explain the concept having a pull resistor altogether, because you can see it.  In practice though, it's nice to able to use the internal resistors even if they pull in a more confusing direction.  Note there do exist microcontrollers have optional internal pull-down resistors as well, but they're not as common; the UNO in particular does not have these.


text:
7 segment 4 digit not showing numbers 2,3 and 0
https://www.instructables.com/Using-a-4-digit-7-segment-display-with-arduino/
I used this link to make my circuit and I used this code also but some numbers like 2,3 and 0 doesn't display correctly.

So your answer given here is not quite accurate? https://arduino.stackexchange.com/questions/77524/4-digit-7-segment-display-not-showing-value-properly/80525#80525

It looks like you have the center segment and the top left vertical segment reversed. For the image you show, if you switched the on/off states of those 2 segments, you'd see 1230.
I don't know if the problem is in your code or in your wiring. The simplest fix would be to swap the pins for those 2 segments.

Thanks it works.

You should accept my answer if it solved your problem. That is a strong norm on this site. Up-voting helpful answers is optional (once you have enough reputation for that) but also considered good form.


text:
Which Arduino-Board do I need?
I want to use a single Arduino board and link it to both the ANALOG CO2 GAS SENSOR (MG-811 SENSOR) and ANALOG PH SENSOR - METER KIT. I was wondering if the Uno Rev 3 had enough pins or do I have to go with the Mega.

They are hardly going to use 4 pin each . That means u could almost any Arduino u can find.

Nano board has a bunch of analog and digital pins. It does good and cheap. But for convenience UNO board is preferable for its large size easy handling and easy pin and wiring management.

Uno has enough pins. You'll probably need an analog pin for each measured quantity, and you might want a few digital pins to turn them on or off or make mode changes, if any. The next question is: what your project meant to do, and does the Uno have enough memory to accomplish it? You will probably go quite a way with an Uno before your project exceeds its capabilities, unless you have some unusually stringent requirements.

Thank you, I am a beginner to Ardunio and want the CO2 and Ph sensor to collect data for a science experiment over time together. Are there any resources you can direct me to regards attaching 2 sensors to an Arduino or articles to help me better understand arduino.

That's a pretty wide-open question! :-) You'll need to narrow it down some to keep it manageable. Try searching for "Introduction to Arduino" and follow a few of those leads. Try running a few of the the example programs from the Arduino IDE. Make small alterations to the examples to get some some hands-on experience with- and "ownership" of the compile/upload process. Find a few tutorials that demonstrate using a sensor & build them. Even if it's just to measure a resistor. By then you'll have some better-focused questions to search for or to bring back here. Have fun!


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

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

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

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

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

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

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

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

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

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


text:
Attiny : Is it possible to analog read on PB1?
I'm trying to read an analog input on the Attiny85 physical pin 6 (PB1, PWM), but analogRead(PB1) always returns 1023. Is it even possible to use analogRead on this pin?
I'm fairly new to this so sorry if it's an obvious answer.
Thanks!

section 10.3.1 https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf

PB1 has no analog input. So no, you can't read analog with it.
For analog you must use any of PB2 through PB5.

oh shoot... alright, thank you for the quick answer!!


text:
Which Arduino for many analogue sensors (and WiFi)?
For context, I come from a very software-heavy background so I know very little about hardware.
I'm looking to build a system that requires at least 6 sensors (pH, electrical conductivity, humidity, temperature, light intensity, flow rate), and I want to send all of this input over WiFi at ~10 minute intervals. Most of these sensors will be analogue.
I noticed that for example the Arduino Uno only has 6 analogue inputs. Plus from research, I would need to connect a WiFi module to the Uno which seems too much of a hassle and added cost.
I'm looking at the ARDUINO NANO 33 IOT right now. It seems perfect for what I want to do since it's cheap, has 8 analogue pins, and has WiFi out-of-the-box. Is my reasoning correct in choosing this Arduino? I'm wondering why something with WiFi capability and more pins is cheaper than the Uno.
Thanks in advance!

Some of the types of sensors you mention are available with a digital interface (I2C or SPI) and do not require an analog interface. If you need more analog inputs than you have analog pins available, you could also use an external I2C ADC which are available with 8 or more channels and 12 or more bits of resolution.

You can get around a limited number of analog pins by multiplexing sensors on a single one. Power each sensor with a different digital pin, and have all of their outputs go to the same analog pin. On each poll, power up one sensor at a time, read its output on the analog pin, power down the sensor, power up the next one, read etc etc. This is one technique I use in my indoor grow rooms. I use NodeMCU-12e or Wemos D1 minis.

In short, Uno is over-engineered with 20-year old technology. Many of the things needed can be done with a single silicon nowadays. Based on what you want to do, I would say Nano 33 IoT is a good choice.

The ESP32's ADC, while not perfect, is far more capable than the UNO's. No onboard ADC is really worth a darn compared to something cheap and awesome like a $2 ADS1115 4 port 15bit ADC.  I would use a nodeMCU and one of those; $5, done. For the cost of one NANO33, you can get 4 or 5 of that setup. Nobody buys actual Arduino boards, unless they don't know any better.

For short answer: Just use NodeMCU ESP32 or any ESP32 dev board.
TLDR;

ESP32 is actually a wifi module but has very powerful processor (240MHz max), way more faster than Arduino Uno (atmega328 @16MHz). Because of this, wifi comes as natural for ESP32.
You can even buy ESP32 dev board around US$10 (include shipping) while the esp32 module itself costs only $5
Arduino UNO 33 IOT is simply SAMD21 (@48MHz) with external wifi module. This wifi module alone costs about US$10. This configuration is similar to Arduino UNO + wifi shield but of course cheaper because you don't need an extra costly shield for wifi.
The expensive wifi shield is actually HDG204 wifi SIP (system in package) + 32-bit AVR AT32UC3C1512C (66MHz max). Pretty much the wifi shield piggy back on Arduino UNO is 4 times faster than 8-bit micro atmega328 of Arduino UNO. So... it's pricey.
Edit:
ESP32 has 2x 12-bit ADC with 16 channels exposed out to IO pin on most of ESP32 dev board.
If you just read some temperature sensors, range finder sensors, humidity sensors... You are good with most of ADC inside microcontrollers these days. Unless you are building instrumentational device, well, this is a whole different story.

Could you explain how this answers the question?

According to me this almost answers the whole question except why is it   cheaper .

the WiFi module on Nano 33 IoT is an ESP32

One of the issues in the question was the number of analog ports available. You did not mention them in your answer.

OP is looking for interfacing with a lot of analog sensor. ESP-32 won't be a good choice if you want to use ADC, it is noisy, non-linear...

To hcheung, I don't have much experience with ESP32's ADC, but if I want low noise ADC, I rather roll external ADC with it's dedicated low noise PSU. I've been using ADC from a few Arm M0/M0+, not really happy with them.

To StarCat, can you read the pinout picture? OP wants something that doesn't cost much, has plenty of ADC channel and works out of the box without extra addon. Are you trying to say, I have to give answer on strictly arduino board from arduino.cc only? I edit my answer to just answer what OP wants as in the question.

Based on this chart https://github.com/thehookup/ESP32_Ceiling_Light/blob/master/PinModes_ESP32_NodeMCU.jpg , it looks like the NodeMCU ESP32 only has 6 analog input pins. Am I misunderstanding something?

ESP32 D0WD datasheet, page 15 https://www.espressif.com/sites/default/files/documentation/esp32_datasheet_en.pdf , shows the ADC pin matrix. All of those pins are exposed in the pinout picture from TheHookUp's guide. I don't trust 100% those tutorials on the internet. It is good in its own context but sometime wrong in different context.

I have been considering the AdaFruit Huzzah32 Feather ESP32… 16 analog inputs (2 DACs); built-in Wi-Fi, Bluetooth and USB; LiPo battery source/charger built-in; and compatible with Arduino IDE, all for $20. (WipperSnapper IoT compatible.) Seems like this part might satisfy the original question.

Doesn't matter the number of analog pins if you're doing 10 minute polls.
Run the power to each sensor from its own digital pin. Connect the sensor outputs to a single analog pin. Note that any analog pin can be used as a digital pin, but not vice-versa.
Start with all sensors turned off (ie. the individual digital power pins turned LOW). When you poll, turn HIGH a single sensor's digital pin, read the output on the analog pin, and then power back down the sensor. Move on to sensor two, sensor three etc.
This is pretty much multiplexing the analog pin. I do this all the time in my indoor grow room environment automation systems.
Typically I use Wemos D1 minis for the task, or NodeMCU-12e devices. The last batch of D1 minis I paid less than $10 for five of them, shipping and taxes included. Both devices I mentioned have wifi and bluetooth inherent. I even reprogram them over the air (OTA).

:-O how do you turn off power to an analog sensor circuit? for example LDR, CT, temperature sensor circuits would interfere with each other

You do that on your Wemos D1 which has only one mediocre ADC?

For 10K LDR, 10K thermistor or some low power sensors (under 10mA), those can be powered using an IO pin for each sensor without problem. Just turn one on when needed then turn off when done


text:
Connecting MPU6050 to Arduino Due but using Jeff Rowbergs Library
I am working on a personal project in which I need to collect accurate data from the MPU6050 using an Arduino Due.
I can interface and read data from the MPU using the SLC and SDA pins and the "Adafruit Library" or the "MPU6050_Light" library. However I have been told that the Jeff Rowberg library combines both accelerometer data and gyroscope data to get a more accurate measurement of roll, yaw, and pitch. Every time I've tried using the library I get the error below:
Arduino: 1.8.13 (Windows 10), Board: "Arduino Due (Programming Port)"
...
exit status 1
Is there anything I can do to get this to work on the Due's processor (which I know has a different architecture). If not what can I do to get accurate reading on the Due. I should note that the code works perfectly fine on the Uno.

Turn on verbose mode and see if anything more useful shows in the listing.


text:
How to interrupt and direct my program where I want it to in the code by clicking a button?
I want to simulate christmas lights and the different modes of lighting it can produce by pressing a button. I tried to do this by having a button pressed which changes an int variable (1-3) which then corresponds to 1 of 3 of my if statements that each have their own code that lights the leds in a different manner. What I have noticed is that if I were to press the button while my program is in the middle of executing one of these light modes, the operation is NOT interrupted and I'd have to wait for the operation to finish before I could press the button and switch to a different mode. As you know, in actual Christmas lights, this is not the case. One can easily switch between modes with a push of a button with no delays. How can I achieve this through code? P.S. I am a newbie in Arduino. My code is written below

const int buttonPin =2;
int ledPin[5] = {3,5,6,9,10};
int counter = 1;
int brightness = 0;
void setup(){
    Serial.begin(9600);
    pinMode(buttonPin, INPUT);
    for(int i = 0; i<5; i++)
    {
       pinMode(ledPin[i], OUTPUT);
      Serial.println(ledPin[i]);
    }
}
void loop(){

  int reading = digitalRead(buttonPin);
  if (reading != 0){
    counter++;
    if(counter == 4)
    {
      counter = 1;
    }
  }

  if (counter == 1) // mode 1 of the christmas lights (default mode)
  {
    digitalWrite(3, HIGH);
    digitalWrite(6, HIGH);
    digitalWrite(10, HIGH);
    delay(300);
    digitalWrite(3, LOW);
    digitalWrite(6, LOW);
    digitalWrite(10, LOW);
    delay(300);
    digitalWrite(5, HIGH);
    digitalWrite(9, HIGH);
    delay(300);
    digitalWrite(5, LOW);
    digitalWrite(9, LOW);
    delay(300);
  }
  else if (counter == 2)// mode 2 of the christmas lights
  {
      for(brightness =0; brightness <= 255; brightness++)
      {
        analogWrite(3, brightness);
        analogWrite(5, brightness);
        analogWrite(6, brightness);
        analogWrite(9, brightness);
        analogWrite(10, brightness);
        delay(3);
      }
      for(brightness =255; brightness >= 0; brightness--)
      {
        analogWrite(3, brightness);
        analogWrite(5, brightness);
        analogWrite(6, brightness);
        analogWrite(9, brightness);
        analogWrite(10, brightness);
        delay(3);
      }
  }
  else if (counter == 3)// mode 3 of the christmas lights
  {

    for (int i = 0; i < 5; i++)
    {
        digitalWrite(ledPin[i], HIGH);
        delay(150);
        digitalWrite(ledPin[i], LOW);
        delay(150);
    }
    for (int i = 3; i > 0; i--)
    {
        digitalWrite(ledPin[i], HIGH);
        delay(150);
        digitalWrite(ledPin[i], LOW);
        delay(150);
    }
  }
}

Step1: Read Blinking without Delay to replace delay() in your code. This will achieve what you are asking for; Step 2 as a bonus: read Debouncing as you will encounter this once you fix the first problem. Step 3 as another bonus: try to understand statement like digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); to toggle the LED,  and see how to use it to shorten and simply your code. Enjoy your learning.


text:
random() Function isn't random at all
I'm using the random() to generate random coordinates for coins in a simple game console. The problem here is that the random() function is not generating random numbers, since the coin is at the same coordinates every single time I upload it. I am using the Adafruit GFX library with the Adafruit 1.44" Color TFT LCD Display. Here is my code (sorry, it's kind of long).
//necessary libraries
#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library
#include <SPI.h>

//colors
#define BLACK    0x0000
#define BLUE     0x001F
#define RED      0xF800
#define GREEN    0x07E0
#define CYAN     0x07FF
#define MAGENTA  0xF81F
#define YELLOW   0xFFE0
#define WHITE    0xFFFF

//pins
#define TFT_CS  10
#define TFT_RST  9
#define TFT_DC   8

//joystick variables
const int VRxPin = A1;
const int VRyPin = A0;
const int SWPin  = 7;
bool mov = false;

//data read from joystick pins
int x = 0;
int y = 0;
int SW = 0;

// X and Y coords for entities
int playerx = 50;
int playery = 50;

long coinx;
long coiny;

//game variables
int score = 0;

//defining the tft class
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);

//useful text function
void output(char *text, int x, int y, uint16_t color, bool wrap = 0){
  tft.setCursor(x, y);
  tft.setTextColor(color);
  tft.setTextWrap(wrap);
  tft.print(text);
}

//there is probably a better way to do this but im too lazy to find it
void num_output(int text, int x, int y, uint16_t color, bool wrap = 0){
  tft.setCursor(x, y);
  tft.setTextColor(color);
  tft.setTextWrap(wrap);
  tft.print(text);
}

//clears screen
void clear() {
  tft.fillScreen(BLACK);
}

//setup (lcd init & startup screen)
void setup() {
  Serial.begin(9600);
  pinMode(SWPin,INPUT_PULLUP);
  tft.initR(INITR_GREENTAB);

  long coinx = random(20, 100);
  long coiny = random(20, 100);

  clear();
  output("RAMBUTAN", 40, 60, RED);
  delay(1000);
  clear();
  tft.fillRect(playerx, playery, 5, 5, WHITE);
  tft.fillCircle(coinx, coiny, 5, YELLOW);
}

void loop() {
  //reads data from joystick pins every single tick
  int VRx = analogRead(VRxPin);
  int VRy = analogRead(VRyPin);
  int SW = digitalRead(SWPin);

  //converts joystick pin data into directions
  if (VRx > 250 && VRx < 750 && VRy > 250 && VRy < 750) {
    // middle
  } else if (VRx > 511.5 && VRy < 750 && VRy > 240) {
    // right
    playery -= 5;
    mov = true;
  } else if (VRx < 511.5 && VRy < 750 && VRy > 240) {
    // left
    playery += 5;
    mov = true;
  } else if (VRy > 511.5 && VRx < 750 && VRx > 240) {
    // up
    playerx += 5;
    mov = true;
  } else if (VRy < 511.5 && VRx < 750 && VRx > 240) {
    // down
    playerx -= 5;
    mov = true;
  } else {
    mov = false;
  }

  if (mov == true) {
    clear();
    tft.fillRect(playerx, playery, 5, 5, WHITE);
    num_output(score, 10, 10, WHITE);
    tft.fillCircle(coinx, coiny, 5, YELLOW);
    mov = false;
  }
  delay(100);
}

Have you read the documentation to the Arduino random() function? Especially the section "Notes and Warnings"? A microcontroller cannot easily generate random numbers without a good source of randomness.

Most pseudo-random libraries (like the one in python) at least seems to be random, so I thought I could just use this :/

The random libraries on a PC will also pull randomness/entropy from some sure. On a PC there are many factors, which could be used for that. On a microcontroller the resources are much more limited. Here you need to dedicate an analog input for that (which might or might not be acceptable for you).

Does this answer your question? Getting a truly random number in Arduino

You are correct, random() isn't random - it's pseudo random. It returns successive results from a mathematical formula which, to all intents and purposes, is random. It's also predictable, as you have seen.
The formula has a starting value, called the seed, which you can choose your self. Changing that seed gives you a different sequence of random-like numbers.
So the trick is to set the seed to something that is truly random. One common source of randomness, or entropy, is an unconnected ADC input:
randomSeed(analogRead(A3));

You can read more about the randomSeed() function here.

This seems to work better, but when I move, it automatically goes to the corner like it did before... I'm not sure what's happening.

@jort57 You aren't calling randomSeed() over and over again are you? You only want to call it once in setup().

randomSeed(analogRead(A3)); is better than nothing but, in my experience, it has very little entropy (a couple of bits or so). Unless of course you connect a hardware entropy source to A3.

A trick that has worked for many of my projects requiring randomness is to include some sort of a "start" trigger. This could be a network communication response, a push button (e.g, a "go" button), or some other event that will occur at a random point in time. After observing the "start" trigger, call millis() and use the return value as the random seed. You could probably also use micros() in place of millis() if the start trigger may occur quickly (e.g. a local network communication).

.... or perform analogRead() a few times in sequence and join the last few bits of each call.

a floating pin will usually hover within a few levels read after read, so more of the same isn't really a big help with randomness. Having a few set patterns is better than 1, but not much. In contrast to @Majenko advice, calling randomSeed() at additional indeterminate points (ex if(analogRead(A0)%2)) throughout the sketch would remedy the "Hey I know this pattern" problem that a PRNG poses. Only calling it once means that there could be 4 or 8 or 13 or so persistent and predictable patterns, re-seeding makes it more like a CSPRNG where past result don't imply future results.

If you have input from a human, network or other non-MCU source, reseed with micros() when said input happens, like a button press of wifi connection establishment; since those happen at unpredictable times, they are ideal for PRNG seeding.

As an alternative to Majenko's answer, this is how I generate random n-bit-numbers: for each of the n bits I read the chip temperature (which is pretty noisy), take the least significant bit of the reading and assign it to the corresponding bit in the number. The results are sufficiently random for my purpose at least.


text:
Adafruit CCS811 Air Quality Sensor
in my arduino project I use the Adafruit CCS811 Air Quality Sensor Breakout - VOC and eCO2, I need the references and sizes of these components, knowing that I have found the electrical diagram but the values and references are not clear as you see in the photo.
Link to the sensor: https://learn.adafruit.com/adafruit-ccs811-air-quality-sensor/overview
Thank you in advance for your help.

What exactly is not clear? Do you need to know the physical size of each component? You can look at the PCB layout and then lookup the components with the corresponding packages. Their datasheets also include their size. Or do you want to know something different?

And wouldn't a question about an adafruit sensor be better suited for the Adafruit forum?


text:
Stepper Motor Inconsistent Jittering
I am trying to run a stepper motor using an Arduino stepper motor shield like the Adafruit V1 motor shield. In my code I am just trying to get the motor to rotate forwards and backwards. When I first try uploading and running the code I can get a forward and reverse rotation, but then the motor begins jittering inconsistently. I have tried changing my wiring setup but generally get the same results. Here is the data sheet for the motor I am using. I have the board it connected to a 12v battery. I also got the same problem when trying to drive the motor using just an H-drive chip. I have included my code below as well as a picture of my wiring. Here is a video of the jitter.
#include <AFMotor.h>
AF_Stepper motor(200, 1);
void setup() {
Serial.begin(9600);           // set up Serial library at 9600 bps
Serial.println("Stepper test!");

motor.setSpeed(120);  // 10 rpm

motor.step(100, FORWARD, SINGLE);
motor.release();
delay(1000);
}

void loop() {
motor.step(200, FORWARD, DOUBLE);

delay(1000);
motor.step(200, BACKWARD, DOUBLE);
delay(1000);
}

please run the example code that is included with the library


text:
DHT-sensor-library-master
I only uploaded the library to check whether it has installed correctly. It's installed and i am having this error. Using library DHT-sensor-library-master at version 1.4.1 in folder: C:\Users\Mcniven\Documents\Arduino\libraries\DHT-sensor-library-master\DHT_U.h:36:29: fatal error: Adafruit_Sensor.h: No such file or directory
#include <Adafruit_Sensor.h>
exit status 1
Error compiling for board Arduino/Genuino Uno.

Did you install the Adafruit_Sensor.h library?

Did you install the library by just copying it to the “libraries” folder without checking dependencies (looks like it) or did you install it from the Arduino IDE?


text:
Having trouble compiling in VsCode when including arduino libraries. (Win10)
I recently switched over to Visual studio code and away from the arduino IDE though I am a novice at both. When using VSC and the neopixel library and sample code(strandtest) containing animations such as color wipe, I run into declaration errors. I have insalled the library to the project im working on, it is declared by default in the platformio.ini file as expected. The animation function is in the code as well and the same code works just fine in the Arduino IDE as stated. The standard example files (ie ones other than strand test with no declared function animations) work just fine no declaration issues. When I compile in the arduino ide it works as expected can use the example and immediately upload it no problem.
#include <Arduino.h>

// A basic everyday NeoPixel strip test program.

// NEOPIXEL BEST PRACTICES for most reliable operation:
// - Add 1000 uF CAPACITOR between NeoPixel strip's + and - connections.
// - MINIMIZE WIRING LENGTH between microcontroller board and first pixel.
// - NeoPixel strip's DATA-IN should pass through a 300-500 OHM RESISTOR.
// - AVOID connecting NeoPixels on a LIVE CIRCUIT. If you must, ALWAYS
//   connect GROUND (-) first, then +, then data.
// - When using a 3.3V microcontroller with a 5V-powered NeoPixel strip,
//   a LOGIC-LEVEL CONVERTER on the data line is STRONGLY RECOMMENDED.
// (Skipping these may work OK on your workbench but can fail in the field)

#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
 #include <avr/power.h> // Required for 16 MHz Adafruit Trinket
#endif

// Which pin on the Arduino is connected to the NeoPixels?
// On a Trinket or Gemma we suggest changing this to 1:
#define LED_PIN    3

// How many NeoPixels are attached to the Arduino?
#define LED_COUNT 4

// Declare our NeoPixel strip object:
Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);
// Argument 1 = Number of pixels in NeoPixel strip
// Argument 2 = Arduino pin number (most are valid)
// Argument 3 = Pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
//   NEO_RGBW    Pixels are wired for RGBW bitstream (NeoPixel RGBW products)

// setup() function -- runs once at startup --------------------------------

void setup() {
  // These lines are specifically to support the Adafruit Trinket 5V 16 MHz.
  // Any other board, you can remove this part (but no harm leaving it):
#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
  clock_prescale_set(clock_div_1);
#endif
  // END of Trinket-specific code.

  strip.begin();           // INITIALIZE NeoPixel strip object (REQUIRED)
  strip.show();            // Turn OFF all pixels ASAP
  strip.setBrightness(50); // Set BRIGHTNESS to about 1/5 (max = 255)
}

// loop() function -- runs repeatedly as long as board is on ---------------

void loop() {
  // Fill along the length of the strip in various colors...
  colorWipe(strip.Color(255,   0,   0), 50); // Red
  colorWipe(strip.Color(  0, 255,   0), 50); // Green
  colorWipe(strip.Color(  0,   0, 255), 50); // Blue

  // Do a theater marquee effect in various colors...
  theaterChase(strip.Color(127, 127, 127), 50); // White, half brightness
  theaterChase(strip.Color(127,   0,   0), 50); // Red, half brightness
  theaterChase(strip.Color(  0,   0, 127), 50); // Blue, half brightness

  rainbow(10);             // Flowing rainbow cycle along the whole strip
  theaterChaseRainbow(50); // Rainbow-enhanced theaterChase variant
}

// Some functions of our own for creating animated effects -----------------

// Fill strip pixels one after another with a color. Strip is NOT cleared
// first; anything there will be covered pixel by pixel. Pass in color
// (as a single 'packed' 32-bit value, which you can get by calling
// strip.Color(red, green, blue) as shown in the loop() function above),
// and a delay time (in milliseconds) between pixels.
void colorWipe(uint32_t color, int wait) {
  for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
    strip.setPixelColor(i, color);         //  Set pixel's color (in RAM)
    strip.show();                          //  Update strip to match
    delay(wait);                           //  Pause for a moment
  }
}

// Theater-marquee-style chasing lights. Pass in a color (32-bit value,
// a la strip.Color(r,g,b) as mentioned above), and a delay time (in ms)
// between frames.
void theaterChase(uint32_t color, int wait) {
  for(int a=0; a<10; a++) {  // Repeat 10 times...
    for(int b=0; b<3; b++) { //  'b' counts from 0 to 2...
      strip.clear();         //   Set all pixels in RAM to 0 (off)
      // 'c' counts up from 'b' to end of strip in steps of 3...
      for(int c=b; c<strip.numPixels(); c += 3) {
        strip.setPixelColor(c, color); // Set pixel 'c' to value 'color'
      }
      strip.show(); // Update strip with new contents
      delay(wait);  // Pause for a moment
    }
  }
}

// Rainbow cycle along whole strip. Pass delay time (in ms) between frames.
void rainbow(int wait) {
  // Hue of first pixel runs 5 complete loops through the color wheel.
  // Color wheel has a range of 65536 but it's OK if we roll over, so
  // just count from 0 to 5*65536. Adding 256 to firstPixelHue each time
  // means we'll make 5*65536/256 = 1280 passes through this outer loop:
  for(long firstPixelHue = 0; firstPixelHue < 5*65536; firstPixelHue += 256) {
    for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
      // Offset pixel hue by an amount to make one full revolution of the
      // color wheel (range of 65536) along the length of the strip
      // (strip.numPixels() steps):
      int pixelHue = firstPixelHue + (i * 65536L / strip.numPixels());
      // strip.ColorHSV() can take 1 or 3 arguments: a hue (0 to 65535) or
      // optionally add saturation and value (brightness) (each 0 to 255).
      // Here we're using just the single-argument hue variant. The result
      // is passed through strip.gamma32() to provide 'truer' colors
      // before assigning to each pixel:
      strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue)));
    }
    strip.show(); // Update strip with new contents
    delay(wait);  // Pause for a moment
  }
}

// Rainbow-enhanced theater marquee. Pass delay time (in ms) between frames.
void theaterChaseRainbow(int wait) {
  int firstPixelHue = 0;     // First pixel starts at red (hue 0)
  for(int a=0; a<30; a++) {  // Repeat 30 times...
    for(int b=0; b<3; b++) { //  'b' counts from 0 to 2...
      strip.clear();         //   Set all pixels in RAM to 0 (off)
      // 'c' counts up from 'b' to end of strip in increments of 3...
      for(int c=b; c<strip.numPixels(); c += 3) {
        // hue of pixel 'c' is offset by an amount to make one full
        // revolution of the color wheel (range 65536) along the length
        // of the strip (strip.numPixels() steps):
        int      hue   = firstPixelHue + c * 65536L / strip.numPixels();
        uint32_t color = strip.gamma32(strip.ColorHSV(hue)); // hue -> RGB
        strip.setPixelColor(c, color); // Set pixel 'c' to value 'color'
      }
      strip.show();                // Update strip with new contents
      delay(wait);                 // Pause for a moment
      firstPixelHue += 65536 / 90; // One cycle of color wheel over 90 frames
    }
  }
}

The error I run into when compiling is as follows.
> Executing task in folder led pir: C:\Users\Yeee\.platformio\penv\Scripts\pio.exe run --target upload <

Processing nanoatmega328new (platform: atmelavr; board: nanoatmega328new; framework: arduino)
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Verbose mode can be enabled via `-v, --verbose` option
CONFIGURATION: https://docs.platformio.org/page/boards/atmelavr/nanoatmega328new.html
PLATFORM: Atmel AVR (3.1.0) > Arduino Nano ATmega328 (New Bootloader)
HARDWARE: ATMEGA328P 16MHz, 2KB RAM, 30KB Flash
DEBUG: Current (avr-stub) On-board (avr-stub, simavr)
PACKAGES:
 - framework-arduino-avr 5.1.0
 - tool-avrdude 1.60300.200527 (6.3.0)
 - toolchain-atmelavr 1.50400.190710 (5.4.0)
LDF: Library Dependency Finder -> https://docs.platformio.org/en/latest/librarymanager/ldf.html
LDF Modes: Finder ~ chain, Compatibility ~ soft
Found 7 compatible libraries
Scanning dependencies...
Dependency Graph
|-- <Adafruit NeoPixel> 1.7.0
Building in release mode
Compiling .pio\build\nanoatmega328new\src\main.cpp.o
src\main.cpp: In function 'void loop()':
src\main.cpp:59:43: error: 'colorWipe' was not declared in this scope
   colorWipe(strip.Color(255,   0,   0), 50); // Red
                                           ^
src\main.cpp:64:46: error: 'theaterChase' was not declared in this scope
   theaterChase(strip.Color(127, 127, 127), 50); // White, half brightness
                                              ^
src\main.cpp:68:13: error: 'rainbow' was not declared in this scope
   rainbow(10);             // Flowing rainbow cycle along the whole strip
             ^
src\main.cpp:69:25: error: 'theaterChaseRainbow' was not declared in this scope
   theaterChaseRainbow(50); // Rainbow-enhanced theaterChase variant
                         ^
src\main.cpp: In function 'void colorWipe(uint32_t, int)':
src\main.cpp:81:17: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
   for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
                 ^
src\main.cpp: In function 'void theaterChase(uint32_t, int)':
src\main.cpp:96:21: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
       for(int c=b; c<strip.numPixels(); c += 3) {
                     ^
src\main.cpp: In function 'void rainbow(int)':
src\main.cpp:112:19: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
     for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
                   ^
src\main.cpp: In function 'void theaterChaseRainbow(int)':
src\main.cpp:136:21: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
       for(int c=b; c<strip.numPixels(); c += 3) {
                     ^
*** [.pio\build\nanoatmega328new\src\main.cpp.o] Error 1
================================================================================== [FAILED] Took 1.30 seconds ==================================================================================
The terminal process "C:\Users\Yeee\.platformio\penv\Scripts\pio.exe 'run', '--target', 'upload'" terminated with exit code: 1.

Terminal will be reused by tasks, press any key to close it.

add forward declarations of functions. in Arduino IDE the builder does it for you at ino to cpp conversion

@Juraj, if you make that an answer, I'll vote it up, because it points out something relevant to using the Arduino core and libraries with their build environment.  IMO, to be a valid answer it needn't necessarily explain the required C++ aspects, however helpful that might be.  That this is apparently just part of the trade made in choosing to use platform.io, assuming it isn't also capable of running arduino-cli/arduino-builder.

To the extent possible, you can also just arrange your function definitions to appear before their usages.  The definition will serve as a declaration.  If you don't have any mutually recursive functions this is generally something you can do within the context of a single file.


text:
send command to Slave and receive response over I2c
so I have an Arduino mega as the master and an attiny84 as the slave
the master can send a command S to the slave and the slave should respond with TRUE so here is my code:
master:
bool GetOnline(){
      Serial.println("Sending Status Command ");

      if(Address != NULL){
        String res;
        Wire.beginTransmission(Address);
        Wire.write('S');
        Wire.endTransmission();
        Wire.requestFrom(Address, 4);
        while (Wire.available())
        {
          char inChr = Wire.read();
          res += inChr;
        }

        Serial.print("Device responce: ");
        Serial.println(res);
        if(res == "TRUE"){
          return true;
        } else {
          return false;
        }
      }
    }

Slave:
void normalReceive(uint8_t howMany) {
  while(Wire.available())//if wire is avaliable
  {
    char command=Wire.read();//state read the recived command from master, high or low
    MySerial.print("recived: "); MySerial.println(command);
    switch(command){
      case 'A': digitalWrite(LEDReboot,LOW);
       break;
      case 'B': digitalWrite(LEDReboot,HIGH);
       break;
      case 'S': Wire.write("TRUE");
       break;
      case 'R': resetFunc();
       break;
      default: MySerial.print("recived: "); MySerial.println(command);
       break;
    }
  }
}

void normalRequest() {
  MySerial.println("Request SN");
  Wire.write(sn);
  }

now the issue is when I request from the slave it returns the SN rather than the expected TRUE
I am very new to I2C so any help is appreciated.

Are you really using the Wire library on the Attiny84? That chips doesn't have dedicated I2C hardware, so I thought that the Wire library doesn't work with it.

@chrisl well TinyWireS didn't work with AttinyCore and in the examples, from AttinyCore they used Wire

Ah, it seems, that the Wire library as provided by the ATtinyCore incorporates the other libraries and chooses automatically based on the given hardware.

What is sn in the function normalRequest? I can't see it being declared anywhere in the code. Does the Attiny84 recieve the S, can you see it in the Serial Monitor?

@PythonSchlange sn is a char array. the serial number of the Attiny84 device and yes the Attiny84 does receive the S Command

If I understand correctly you're saying that you're getting a value returned over I2C that only the function normalRequest() can return, without ever calling normalRequest()?


text:
need to use jp2 because need extra pins
i clearly understand jp2 is the extra leftover pins of atmega16u2 . but how to access it ? i find my arduino has less pins and jp2 are the only ones left . but if it is not accessable , why do they have it ?
and also , if it requires seperate programing of the atmega16u2 , i'd like to know how . i completely dunno a thing about atmega16u2 . only thing i understand is that it makes the arduino more compatible with the usb input ...
thanks alot !

What exactly are you trying to achieve? Do you just need more IO pins? Then you should either switch to a bigger Arduino, or use extensions chips or other pin-saving principles.

i just try my best to go on with arduino uno because others are a bit expensive ... i tried to find whether i can make my own ic but a can't .that question's link >>> https://arduino.stackexchange.com/questions/81762/need-a-custom-ic-to-be-paired-with-arduino . (i hope you remember adding a comment)

If cost is the limiting factor, and you cannot use pin-saving principles (like arranging buttons or LEDs in matrixes, or doing some kind of multiplexing otherwise) (that highly depends on your actual circuit and what you are trying to drive, so I cannot go in detail here), you might wanna look at some of the Arduino clones. You can purchase them directly from china (for example at aliexpress) or at amazon from a reseller. They don't have the same quality, but most are very good to use. The original Nano for example costs 20€, while a clone is about 2€.

I indicated this sort of thing in the answer I gave, but I addressed it as a more or less direct answer to the question.  Otherwise, like @chrisl says regarding clones. Dig around for questions on here about getting "more pins", "sharing" pins, etc.

if it requires seperate programing of the atmega16u2,

It does.  Often an ATMega8U2 is used here instead though.

i'd like to know how.

You might start by having a look at HoodLoader2 and NicoHood's related projects.
This involves replacing the normal Xu2 transceiver firmware with HoodLoader.  There are different ways to do that outlined in the installation instructions.  If you don't have an ISP programmer or a second Arduino to behave as one, there's a method that involved burning an installer-sketch to the 328P which turns around and reprograms the Xu2 chip.
Once you have that done you can use their board definitions for put sketches onto the ATMegaXU2 itself.
Apparently, JP2's layout is flipped on some boards. So, beware of that.  In any case, the header it makes the ATMegaXU2's PB4, PB4, PB6, and PB7 available.  Sketches on the XU2 would use the Hoodloader pin mapping of these:

Arduino Pin No.
AVR GPIO PIN

D4
PB4

D5
PB5

D6
PB6

D7
PB7

Or course, now you need to find some way to coordinate what happens on the ATMegaXU2 with the ATMega328P.

i find my arduino has less pins and jp2 are the only ones left.

There are clever ways to reuse pins on microcontrollers.  For example, it is possible to put an LED and a switch on the same GPIO pin.  And there are GPIO expanders, SPI/I2C ADCs, etc.
Messing with JP2 and programming the ATMegaXU2 and having it coordinate with the 328P may be more trouble than you like just to get a couple extra pins.

but if it is not accessable, why do they have it ?

Just added capability.  Usually that header is unpopulated, so there's no part cost there.

and also , i completely dunno a thing about atmega16u2 . only thing i understand is that it makes the arduino more compatible with the usb input ...

It serves the role of a USB to logic-level-serial converter for connecting to the USART of the otherwise non-USB-aware ATMega328P (you have tagged UNO).  But, it can be made to run sketches.  Usually if you're doing this, it's to get native USB support on an UNO (or Mega, or..), e.g. so you can have your board act as a keyboard, like you might with a Leonardo or Micro or any other board that has native-USB in normal use.  And that's a large part of what NicoHood's project is about.

The Nano has two extra A/Ds available, will that do it? Same micro almost the same code.


text:
it just gets too hot . any way of cooling it?
there i just got started with the arduino mega2560 . i tried 8x8 matrix tube and after ~30secs i found the atmega2560 a bit hot that i can melt a small amount wax on it ! is there any sort of heatsink or a better way to use the matrix tube ? what i have done is to turn on a led is to turn on the positive side and turn off the negative side . i just tried that method because in my 1st beginner kit , the manual said this should be done incase of a common anode rgb led .
thanks alot

An Atmega should never get that hot. You are definitely going something wrong. Please provide a schematic or wiring diagram of your project. Are you providing the LEDs with power through the IO ports? Or do you use any kind of driver?

well that is just a phrase . i really don't know if it can melt wax .

Doesn't really matter. An Atmega should never get warm by itself. It doesn't incorporate powerful hardware like the ESP (which geta a bit warm, when using wifi). If it gets warm, you are doing something wrong. For example the outputs are only do provide signal, not power. Each pin can only provide 20mA of current. And as I remember the overall IO current is limited to 100mA. With 8x8=64 LEDs you can easily exceed that

@Raj interesting how different parts of the world have different expressions ... it is you could fry an egg on it here


text:
Hardware interrupt calling two ISRs
I've spent three days on this, and either I'm blind to something, or something just ain't right.
Doorbell. Front door switch and back door switch. Two interrupt service routines, one attached to each pin. Rudimentary debouncing in the ISR seems to work.
But for some reason, both interrupt routines are firing off when either of the switches is pressed. I've tried RISING, FALLING, LOW, CHANGE, and it all works the same. I tried INPUT_PULLUP and INPUT_PULLDOWN and changed the polarity on the switches. No change. I've tried different pins, digital, analog. Nothing seems to keep both ISRs from firing.
Pressing front door button, it should print:
front door high
Releasing front door button
front door low
Pressing back door button
back door high
Releasing back door button
back door low
But for some reason, both interrupt service routines are called when pushing either button. Here's what I actually get:
Pressing front door button:
back door low
front door high
Releasing front door button
front door low
Pressing back door button
front door WTF?
back door high
Releasing back door button
front door WTF?
back door low
Here's the code. I hope someone can see something I can't:
#include <Arduino.h>

#define FRONT_DOOR_SWITCH A2
#define BACK_DOOR_SWITCH A3

volatile int frontDoorStatus = 0;
volatile int backDoorStatus = 0;

void frontDoorIsr()
{
    static unsigned long last_interrupt_time = 0;
    unsigned long interrupt_time = millis();
    // If interrupts come faster than 200ms, assume it's a bounce and ignore
    if (interrupt_time - last_interrupt_time > 200) {
        if (digitalRead(FRONT_DOOR_SWITCH) == HIGH) {
            frontDoorStatus = 1;
        }
        else if (digitalRead(FRONT_DOOR_SWITCH) == LOW) {
            frontDoorStatus = 2;
        }
        else {
            frontDoorStatus = -1;
        }
    }
    last_interrupt_time = interrupt_time;
}

void backDoorIsr()
{
    static unsigned long last_interrupt_time = 0;
    unsigned long interrupt_time = millis();
    // If interrupts come faster than 200ms, assume it's a bounce and ignore
    if (interrupt_time - last_interrupt_time > 200) {
        if (digitalRead(BACK_DOOR_SWITCH) == HIGH) {
            backDoorStatus = 1;
        }
        else if (digitalRead(BACK_DOOR_SWITCH) == LOW) {
            backDoorStatus = 2;
        }
        else {
            backDoorStatus = -1;
        }
    }
    last_interrupt_time = interrupt_time;
}

void setup() {
    pinMode(FRONT_DOOR_SWITCH, INPUT_PULLDOWN);
    pinMode(BACK_DOOR_SWITCH, INPUT_PULLDOWN);

    attachInterrupt(digitalPinToInterrupt(FRONT_DOOR_SWITCH), frontDoorIsr, CHANGE);
    attachInterrupt(digitalPinToInterrupt(BACK_DOOR_SWITCH), backDoorIsr, CHANGE);
}

void loop()
{
    switch (frontDoorStatus) {
        case 0:
            break;
        case -1:
            Serial.println("front door WTF?");
            frontDoorStatus = 0;
            break;
        case 1:
            Serial.println("front door high");
            frontDoorStatus = 0;
            break;
        case 2:
            Serial.println("front door low");
            frontDoorStatus = 0;
            break;
    }

    switch (backDoorStatus) {
        case 0:
            break;
        case -1:
            Serial.println("back door WTF?");
            backDoorStatus = 0;
            break;
        case 1:
            Serial.println("back door high");
            backDoorStatus = 0;
            break;
        case 2:
            Serial.println("back door low");
            backDoorStatus = 0;
            break;
    }
}

Board is Adafruit Feather Express M4 (SAMD51)

So far the only way I can think to explain the interrupts being called the way you describe depends on there being more code than you're showing.  Is this, in fact, the entire sketch being tested?

Yes, that's what I first thought. I reduced it down to see if something else could have been causing it, but what I posted runs and fires off both ISRs.

Unfortunately I have no SAMD51 devices at all.  And I'm not sure I want to put my wild guess as an "answer." without any confidence.  As a diagnostic test, what I've have you try is using your same code with #define FRONT_DOOR_SWITCH 21 and #define BACK_DOOR_SWITCH 22 and hooking your signals to those pins labeled on the board as SCL and SDA.  If this improves things, I'll give you an answer as to why I think it may have.

Sorry to say, no improvement with SCL and SDA. Both ISRs are still being called. What's your theory?

Not sure what I was thinking rises to "theory" level. And what you did sort of disproves it.  Pins don't have dedicated interrupts.  They share the same interrupt with a handful of other pins.  In particular your Arduino pin A3 shares an interrupt with one of the onboard SPI chip lines.  SDA and SCL seem to not be sharing with anything else, at least nothing else broken out on the board, so no other pin can be triggering their external interrupt routine.  So, like I said, not that.

I am using SPI to hook an ESP32 up. I wonder if that's causing interference. To rule out a bad board, I swapped out with a brand new Feather M4 Express. Same exact problem. Now I'll disconnect the SPI and see what up.

Turns out that, in the Cortex Mx processors, interrupts don't work the same way as older 8- and 16-bit Arduino-style chips work.
As far as I can tell, there's only one ISR that's connected to the pins. In that routine, you've gotta check the status of the pins you are monitoring and set a global variable accordingly.
I'm not sure this is the only way to do it (seems kludgy), but it does work and it looks like it can scale to any number of pins. I'm using only two.
Here's my demonstration code if anyone is having the same problem. I put the debouncing code in the ISR. I know that's probably not best practice, but it doesn't take a lot of cycles and it's a lot easier than putting it in the loop.
#include <Arduino.h>

#define FRONT_DOOR_SWITCH A2
#define BACK_DOOR_SWITCH A3

volatile bool frontDoor = LOW;
volatile bool backDoor = LOW;

void isr()
{
    static unsigned long last_interrupt_time = 0;
    unsigned long interrupt_time = millis();
    // If interrupts come faster than 200ms, assume it's a bounce and ignore
    if (interrupt_time - last_interrupt_time > 50)
    {
        int fds = digitalRead(FRONT_DOOR_SWITCH);
        int bds = digitalRead(BACK_DOOR_SWITCH);
        if (fds == HIGH) frontDoor = HIGH;
        if (fds == LOW) frontDoor = LOW;
        if (bds == HIGH) backDoor = HIGH;
        if (bds == LOW) backDoor = LOW;
        last_interrupt_time = interrupt_time;
    }
}

void setup()
{
    Serial.begin(115200);
    while (!Serial);
    Serial.println("in setup...");
    pinMode(FRONT_DOOR_SWITCH, INPUT_PULLDOWN);
    pinMode(BACK_DOOR_SWITCH, INPUT_PULLDOWN);

    attachInterrupt(digitalPinToInterrupt(FRONT_DOOR_SWITCH), isr, CHANGE);
    attachInterrupt(digitalPinToInterrupt(BACK_DOOR_SWITCH), isr, CHANGE);
}

bool lastFrontDoor = LOW;
bool lastBackDoor = LOW;

void loop()
{
    if ((frontDoor == HIGH) && (lastFrontDoor == LOW))
    {
        Serial.print("fd+");
        lastFrontDoor = HIGH;
    }
    if ((frontDoor == LOW) && (lastFrontDoor == HIGH))
    {
        Serial.println("fd-");
        lastFrontDoor = LOW;
    }
    if ((backDoor == HIGH) && (lastBackDoor == LOW))
    {
        Serial.print("bd+");
        lastBackDoor = HIGH;
    }
    if ((backDoor == LOW) && (lastBackDoor == HIGH))
    {
        Serial.println("bd-");
        lastBackDoor = LOW;
    }
}


text:
How can we remove unused feature in Arduino's standard SD library so we can reduce the sketch size?
With the ReadWrite example in Arduino IDE, the sketch size is 10980 bytes (34%) of an Arduino UNO's storage. How can we reduce the sketch size? There isn't any kind of #define to turn on/off features in SD.h. I only need read, write, append and seek features, not anything else.
I have found the PetitFS port for Arduino, but it doesn't support appending to a file. There is also TinySDLogger but I think it's for good for logging rather than normal file writing. I have found SdFat too.
My main work has used 26234+ bytes of flash and I cannot add more 10KB to the sketch!

the Arduino SD library is an old version of SdFat wrapped in arduino style API

The linker automatically removes code that is not used, so you do not have to care about that. If the size is this big that means that so much of the code is used. I assume the largest part of the library is the file system support, and that is required regardless of which functions you actually use


text:
ESP8266 wdt reset
I just bought a KS0354 ESp8266 board to make a remote control for my iot project. Not sure why I keep on getting a wdt error. Even before I can complete my entire code I start getting this error. Below is my code:
int PIN_BUTTON_A = 2;
int PIN_BUTTON_B = 3;
int PIN_BUTTON_C = 4;
int PIN_BUTTON_D = 5;
int PIN_BUTTON_E = 6;
int PIN_BUTTON_F = 7;

void setup() {
  Serial.begin(9600);
  pinMode(PIN_BUTTON_B, INPUT);
  pinMode(PIN_BUTTON_E, INPUT);
  pinMode(PIN_BUTTON_C, INPUT);
  pinMode(PIN_BUTTON_D, INPUT);
  pinMode(PIN_BUTTON_A, INPUT);
}

void loop() {
   Serial.print("Buttons A:");
   delay(5000);

}

This seems to be a very simple code. Not sure what is wrong here. Below is the error I am getting @115200 baud rate:
 ets Jan  8 2013,rst cause:4, boot mode:(3,6)

wdt reset
load 0x4010f000, len 3584, room 16
tail 0
chksum 0xb0
csum 0xb0
v2843a5ac
~ld

Does anyone has any idea what could be wrong?
Thanks

has the module a 40 MHz clock? the bootlog at 115200 indicates that. then you must set it in Tools menu. or you did set 40 MHz and it has a 26MHz clock?


text:
Reproduce simulated temperature data with Arduino
I'm starting a test using Arduino to reproduce a set of temperature values in water each three hours and need some help with it.
I will use two ds18b20 sensors to control two thermostats connected to relays. The idea is that Arduino could access the data from a file in which there are simulated data for each day in the future. Something like this:
Date,Time,Temperature
01/01/2070,00:00:00,27.229211807251
30/12/2070,21:00:00,24.6133060455322
01/01/2070,06:00:00,22.1697025299072
01/01/2070,09:00:00,20.3209171295166
01/01/2070,12:00:00,27.7610721588135
01/01/2070,15:00:00,33.6277084350586
01/01/2070,18:00:00,34.5402450561523
01/01/2070,21:00:00,31.9973392486572
02/01/2070,00:00:00,26.2283573150635
02/01/2070,03:00:00,21.5823612213135
02/01/2070,06:00:00,18.6461429595947
02/01/2070,09:00:00,17.2126712799072
02/01/2070,12:00:00,24.8096561431885
02/01/2070,15:00:00,30.6440677642822
02/01/2070,18:00:00,33.8463973999023
02/01/2070,21:00:00,31.3529300689697
03/01/2070,00:00:00,25.2961673736572
03/01/2070,03:00:00,20.8135623931885

Based on this info the sensor will control the thermostat to decrease or increase the temperature within three hours (8 different temperatures by day). I'm going to start with 1 week (7 day x 8 temperatures = 56 simulations), but want to increment it till 3 months (720 simulations).
Considering the use of if/else if, it seems that would be a massive amount of conditionals.
Does anybody have a good solution to run this temperature simulation based on predefined data?
Thanks in upfront.

It is not clear to me, for what exactly you considered if/else if expressions. You have x data tuples with time and set temperature of the thermostat. So you could put these into an array, saving the current element index in a variable. Then you compare the time of the current element to the current time and set the setpoint of the thermostat accordingly. And you move on to the next element, if the time has come to do so. Is that, what you want?

Thank you for the answer @chrisl. It seems quite reasonable what you suggest and exactly what I'm looking for! I've never worked with this approach so need to find out some documentation and reference about it.

it makes no sense to store temperature using floating point values ... you are using 32 bits to store a 12 bit value

You can use an array to go through the times.
Create a struct with the fields time and temperature (you should think about saving time as unix epoch, meaning seconds since 1970, so that you save memory).
struct SetPoint {
    unsigned long time;
    float temperature;
};

Then you can declare an array of type SetPoint to hold the tubles of time and temperature:
#define DATA_SIZE  720
SetPoint data[DATA_SIZE] = {
    {<time1>, <temp1>},
    {<time2>, <temp2>},
    ...
    };

In the above, you need to replace <timeX> and <tempX> by your data. Then declare a position variable, which the element index, which will be invoked next:
unsigned int pos = 0;

We are starting with the first element (index 0) and compare its time to the current time. If it is equal (or current time is after the elements time), we will set the thermostat to the elements temperature and increment the position variable. Something like this:
if(pos < DATA_SIZE && current_time >= data[pos].time){
    set_thermostat(data[pos].temperature);
    pos++;
}

Note: I used the variable current_time here as standin for your way of getting the current time, and the set_thermostat() function as a standin for your way of setting the thermostat. Also I inserted a check into the if statement, to prevent the code going further, when it reached the data array end.

That said, depending on the used board you can easily get into memory trouble here. An Arduino Uno does not have enough memory to save 720 of the data points above. float and unsigned long both take 4 bytes each, so 8 bytes per element, which makes 8*720 = 5760 bytes. The Uno only has 2048 bytes total in RAM. There are enough boards, which have more RAM. The ESP32 for example would have way enough (though there are many others; the ESP32 is just the first to get into my mind here).
Or you can add an SD card module to your build and save the data points in a file. That would also make it way easier to get the data in your project or change the data. It would just involving writing the corresponding file on your SD card.
Then the workflow would be a bit different. Lets assume you save one data point per line as text:

Open file and read one line. Close file.
Parse read text into 2 variables (time and temperature)
Use these variables for the if statement from above
if the time of the loaded data point was reached, open the file again, read the next line and parse it into the variables
The if statement now uses the next datapoint

and so on. If there is no line left to read, you could go into an infinite loop, stopping the code from running further than your data.
There are ready to use SD card modules to buy out there, and you can find many tutorials about how to use them online.

As Edgar Bonet correct stated in the comments, you can greatly reduce the needed RAM, when assuming regular intervals (3h in your case). Then you don't need to save the time for each data point. You only need the one start time for the series. Also above I used float for the temperature (as I assumed, that at this point it would be the easiest for you). But since temperature settings for thermostats are mostly working only down to the 1 digit after the decimal point, you can save memory space by using a different representation. For example you could save the temperature as a single byte signed integer with the unit of 0.1°C and a reasonable offset (for example 25°C being zero). So some example values would be:
Temp | value
------------
18°C | -70
20°C | -50
22°C | -30
25°C | 0
27°C | 20
35°C | 100

That would give you the precision of one digit after the decimal point and a range from 12.3°C to 37.8°C. When changing the factor of 0.1°C, you can also change the range (and precision with it) as you really need it.
So with the above you would only need 720 byte for the actual data, which is good for the Uno.
BUT: I would still suggest looking into the SD card reader. You will have more work building the project, but you won't have the same hassle with including or updating the data. That can come in especially handy, if you want to use to further use the device after the 3 months. Just loading new data on it (maybe even way more data, like for a full year) is easier with an SD card.

Note that if the times are regularly spaced (one setpoint every 3 hours), they do not need to be stored. The temperatures can be stored in 16-bits with a resolution of 0.001 °C, which is most likely already overkill.

@EdgarBonet Thanks, I added a paragraph about that in my answer.

@s_tatus3 If you are going to connect the ESP32 to your wifi, you could also save the data in SPIFFS and write code, that lets you exchange the data over a website hosted on the ESP32. Might also be interesting for you.

Fantastic! Yes, definitely will replace Arduino with ESP32 and use the data in a SD card. Already set epoch time (way better to work with).
Just added the function set_thermostat() to control the relay and now will see the best way to set time to easily reuse it many times.
void set_thermostat() {   if (temperature < data[pos].temperature) {     digitalWrite (relay, HIGH);   }   else if (temperature > data[pos].temperature) {     digitalWrite (relay, LOW);   } }
Will back here to add whole code once is done.
Thank you all the comments and support

@chrisl just opened this question related to the sd file parsing. If you have some great insight about, they will be welcomed! :)


text:
Set up a motion sensor to turn on lights and record how long the lights are on
I'm doing a school project and I want to measure the difference in time that the lights are on in a classroom with and without a motion sensor controlling them. I haven't really found anything about recording how long sensors act or the time between activations. How could I possibly do this?

For what exactly have you googled? When using the terms "arduino measure time" you get pretty good results.

you don't need an arduino to do this ... get two electrically powered mechanical clocks ... one always runs ... the other is powered by the switched circuit

I would consider placing a light sensor close to one of the lights to signal when the lights are on. Placement is critical as you do not want a signal when the lamp is off. I am assuming they are permanent light fixtures and you are not allowed to tamper with the wiring.  Record the elapsed time when they are on.  Note the start time and then subtract that from the current time based on your watch. For elapsed time and subtract the ontime from that. With the sensor you can also record each time the light is turned on etc. That would all be in your software.


text:
HC-05 bluetooth module short range
I have started learning about arduino and just bought a bluetooth module, HC-05. From where i bought, it says it has range of approx.10 meters. I made hc-05 connection with arduino in below described ways
I am using it as a slave with default configurations, 9600 baud rate and HC-05 name with pin 1234
GND of HC05 -> GND of `arduino`
VCC of HC05 -> 5V of `arduino`
TX of HC05 -> RX of `arduino`
RX of HC05 -> TX of `arduino` via voltage divider network 2k---|---1k

Below is my arduino code
#include <SoftwareSerial.h>
SoftwareSerial BTserial(2, 3); // RX | TX
// Connect the HC-05 TX to Arduino pin 2 RX.
// Connect the HC-05 RX to Arduino pin 3 TX through a voltage divider.

int pin = 13;
char c = ' ';

void setup()
{
 Serial.begin(9600);
 Serial.println("Arduino is ready");
 pinMode(pin,OUTPUT);

 // HC-05 default serial speed for communication mode is 9600
 BTserial.begin(9600);
 Serial.println("BTserial started at 9600");
}

void loop()
{
  if (BTserial.available()>0){
    c = BTserial.read();
    Serial.println(c);
    switch (c){
      case '1' :
        digitalWrite(pin,HIGH);
        break;
      case '2' :
        digitalWrite(pin,LOW);
        break;
      default: break;

    }
  }
}

Following things happening to me:

When I power the module I am able to discover it with my phone but only when I hold my phone very near to the module. If I move away from the HC05 module, for example 3-4 feet, I am not able to discover it.

2.After connecting with it (while holding phone near to the module), I am able to send data to it but again, if I move away , only a few steps, I am unable to send data and I disconnect from it automatically. Also if I change direction of the antenna even then no communication happens.
My purpose is to control my home's lights and TV with the help of this module and Relays. But HC05 is useless so far. I was hoping that I would code it and wire it and hang it on a wall and interact it with and andoird app.
Is it suppose to happen like this? or there's something wrong with my module's antenna
thank you.

What, if anything, is near your HC-05 antenna?

on breadboard, some jumper wires near antenna

but i tried holding it up in the air buy pulling it from breadboard and using female jumpers


text:
Can I use laptop USB port to power Nodemcu if every port used
I wonder if a laptop USB port is enough or I have to use an external power supply if the NodeMCU under heavy load. Here is my list of sensors and port used.
3.3V
3.3V
D1 to D7
A0
GND

Sensors: Turbidity sensor, Flow sensor, Temperature sensor, 4 led

That depends on how much current all that needs. We cannot know that. You didn't give us enough information. USB is limited to 500mA

standard current you can draw from a usb port is 500 mili ampere with 5 volt(you may get even more but it is not recommended) . so if you want to calculate
sensors are very low current about 1~2 mA(but you must check out datasheet)
turbidity for example draws 30 mA
temperature ds1820 is 1 mA
flow is up 2 mA
the LEDs based on resistors series with them you normally up to 3 mA for
each(1k series to 3.3 volt)
if you sum up all of them
30+1+2+4*3=45mA
but you should consider other consumers for example if you need 3.3 V you need a regulator such as ams1117 and it may waste some mili Ampere (not too much) and you certainly have a microprocessor and you should check data sheet but consider 100mA for that in worst case.
to count all of them the answer is YES

Sensors don't usually require that much current and a usb port should be able to handle 4 leds and the MCU without a problem.  If you are using an Apple laptop it will disable the usb port temporarily if you draw too much current from it.  Some PC laptops probably do the same.


text:
Problem with HC-06 receiving data
I have paired 2 BT modules HC-05 and HC-06. When I write something through Serial Monitor and send it from HC-05 to HC-06, everything works well. But when I send continuous data through loop, HC-06 receives only specific amount and then just stops! Is it because of BT module, or there is something else?
My code for HC-05:
#include <SoftwareSerial.h>
SoftwareSerial BTserial(2, 3);
void setup()
{
    Serial.begin(9600);
    BTserial.begin(38400);
}

void loop()
{
        BTserial.write('1');
}

Code for HC-06:
#include <SoftwareSerial.h>
SoftwareSerial BTSerial(2, 3);
void setup()
{
    Serial.begin(9600);
    BTSerial.begin(9600);
}
void loop()
{
if (BTSerial.available())
    Serial.write(BTSerial.read());
}

Baud rates are good.
Thanks!

any chance you're sending more than the receiving end can cope with, given the 4x difference in baud rates?

Well, firstly in HC05 baud rate was 9600, but the data was all corrupt. I changed the baud rate in AT+UART to 38400 and same left in setup, and only after that received data came correct.

I think you have 2 problems:

First about the shown sketch: I don't think, that the Baud rates are good. In your HC-05 code (the sender) you are using BTserial.write('1'); without any delay or other code, thus this will run very fast, so the SoftwareSerial interface is almost completely busy. You sending almost at the maximum speed, that you can get with 38400 baud. On the receiving site you are using 9600 baud, which is significantly slower than 38400 baud. How should the HC-06 transmit all data, that it get's, to the Arduino, when you only use 9600 baud, but the data is coming with 38400 baud? That cannot work. You should configure the HC-05 and HC-06 to use the same baudrate, so that this cannot happen. Or - if you really don't want to - you can restrict the overall speed, that you are sending with, by just sending less data per time unit (sending the data slower, but on the same baudrate as before). This will prevent the HC-06 to get flooded by data. (Also there might be a limit on how fast you can send data over the HC-05, but I haven't tested this). All in all it mostly isn't a good idea, to do communication totally without any speed brake. That can get you into troubles, that you mostly don't want to think of.
Secondly: In your comment you wrote, that you tried to change the baudrate, but that gave you garbled data. Since you didn't describe more, we cannot say much about this. But garbled data is a normal symptom for wrong baudrate. So it seems, that you haven't changed the baudrate successfully. I would suggest, that you again look into this and that you try to change the baudrate successfully. It is possible and there are many tutorials and codes on the web, that show how it is done. (When you again have problems with this, you can ask a question about this specific problem, including all the relevant information)

Everywhere I changed baud rate to 9600. Swear to God, I tried that previously, it didn’t work :D But now I tried that again, also included delay(10) and everything works like a charm, thank you very much!


text:
Arduino acting strange with photoresistor data
So I stumbled into strange problem. I have this circuit, where I connect 2 photoresistors and bluetooth HC05 to Arduino. When one of the resistors senses bright light bluetooth sends '1' or '3' accordingly to another circuit. When dark is sensed, bluetooth sends '2'or '4'. When dark on both resistors is sensed for more than 1.5 second, then everything goes to while loop and bluetooth sends '1' and '3'. So for example, when left photoresistor senses bright light, and right darkness, then bluetooth sends '1' and '4'. At first for a couple of months everthing worked just perfectly fine and one day it just... stopped. While troubleshooting I found out, that when changing bright light/darkness mode on resistor, data, which is seen on com port, stops for a bit and goes in batches again, it does not flow continously. I changed photoresistors, everything is the same. I even changed Arduino, still nothing. Here is the code:
#include <SoftwareSerial.h>
SoftwareSerial BTserial(2, 3); // RX | TX
int fk = A0; // left photoresistor
int fd = A1; // right photoresistor
int a = 0;
int b = 0;
unsigned long dl; // time
const unsigned long p = 1500; //how many milisecs dark should be sensed

void setup()
{
    Serial.begin(9600);
    BTserial.begin(9600);
    pinMode(fk, INPUT);
    pinMode(fd, INPUT);
    dl = millis();
}

void loop()
{
    a = analogRead (fk);
    Serial.println (a);
    b = analogRead (fd);
    Serial.println (b);
    if(a>1000)
    {
    BTserial.write('1'); // left photo senses light
    dl = millis(); // capturing last time light was sensed
    delay(10);
    }
    else
    {
    BTserial.write('2'); // left photo senses dark
    delay(10);
    }
    if (b>1000)
    {
    BTserial.write('3'); // right photo senses light
    dl = millis();
    delay(10);
    }
    else
    {
    BTserial.write('4'); // right photo senses dark
    delay(10);
    }
    while (a<1000 && b<1000)
    {
        if ((millis() - dl) >= p) //if dark is being sensed more than 1.5 sec
        {
        BTserial.write('1');
        BTserial.write('3');
    a = analogRead (fk);
    Serial.println (a);
    b = analogRead (fd);
    Serial.println (b);
    }
}
    }

And when I use only this batch of code without while loop
    a = analogRead (fk);
    Serial.println (a);
    b = analogRead (fd);
    Serial.println (b);
    if(a>1000)
    {
    BTserial.write('1'); // left photo senses light
    dl = millis(); // capturing last time light was sensed
    delay(10);
    }
    else
    {
    BTserial.write('2'); // left photo senses dark
    delay(10);
    }
    if (b>1000)
    {
    BTserial.write('3'); // right photo senses light
    dl = millis();
    delay(10);
    }
    else
    {
    BTserial.write('4'); // right photo senses dark
    delay(10);
    }

Everything works fine, data is flowing continously, even when light states are changing fast.
But also everything works fine, when I use only while loop standalone without previous batch. So in my opinion bad things happen in transitions between these two batches of code? But I completely cannot understand what is wrong, why it suddenly stopped working, maybe time is calculated wrongly? I realized that when I soldered bluetooth to another board, but bluetooth is not the case, as I tried the same code with bluetooth data sending part removed. Data still goes with strange batches.
I am completely lost.

your code is badly formatted ... the indentation of the code needs to be corrected .... without correct indentation, it is difficult to follow the program flow

the while loop is unnecessary ... change your thinking a bit .... your code checks each sensor and remembers the last time it sensed light .... all you have to do, is to remember the last time dark was sensed .... then simply determine the time interval between light and dark (or between light and now)

I do not understand why you need this 1.5 sec rule. If both photo resistors indicate darkness BT already sends 1 and 3 . So what is different if the darkness lasts longer than 1.5 seconds. But, there is one small difference that could explain your observations. In the if/else blocks  you use a delay(10); Perhaps your serial connection/Bluethooth is not quick enough to handle the speed up. 9600 baud is not very fast. ;-)


text:
Swap two arrays (using pointers, not copy)
I've got two arrays, defined as:
uint8_t array1[10];
uint8_t array2[10];

I'd like to swap the arrays (actually the pointers to each array) using code like this:
uint8_t *tmp = array1;
array1 = array2;
array2 = tmp;

However, I keep getting errors like:
invalid array assignment

for the last two lines. I don't recall this being such a problem in traditional C++. I've tried all sorts of casting to no avail. Is there something I'm missing?
I can get the code to run properly if I switch the declarations for the arrays to use new and have them just be more-or-less pointers rather than arrays, but I'd rather not have to do that:
uint8_t *array1 = new uint8_t[10];
uint8_t *array2 = new uint8_t[10];

Code is running on an ARM-based SAMD51 (Cortex M4 processor).
Thanks for any tips!

Figured it out. Though using new works, I wanted to keep the buffers out of the heap. The following declarations work with the swap code:
uint8_t a1[10];
uint8_t a2[10];
uint8_t *array1 = a1;
uint8_t *array2 = a2;

uint8_t *tmp = array1;
array1 = array2;
array2 = tmp;