text:
Some Blocks of Code gets stuck in a loop, I do not know why

The code below Gets stuck at function "Led Off?" & "Check button".
I'm using Blockyduino editor.
The check button code was intended as a toggle switch for the lights. When I deleted "Led Off?" and "Turn off All LED", the code did not get stuck.
int Button_Status;

// Toggle Code for the button.
void Check_Button() {
  Serial.println("Check button Activated");
  if (Button_Status == 1) {
    if (digitalRead(13)) {
      Button_Status = 0;
    }
  }
  if (Button_Status == 0) {
    if (digitalRead(13)) {
      Button_Status = 1;
    }
  }
  LED_OFF_();
}

void Left_Animation() {
  Check_Button();
  digitalWrite(2, HIGH);
  digitalWrite(3, HIGH);
  Check_Button();
  delay(1000);
  digitalWrite(4, HIGH);
  digitalWrite(5, HIGH);
  Check_Button();
  delay(500);
  digitalWrite(2, LOW);
  digitalWrite(3, LOW);
  Check_Button();
  delay(300);
  digitalWrite(4, LOW);
  digitalWrite(5, LOW);
  Serial.println("Finshed Left cycle");
}

void Right_Animation() {
  Check_Button();
  digitalWrite(8, HIGH);
  digitalWrite(9, HIGH);
  Check_Button();
  delay(1000);
  digitalWrite(10, HIGH);
  digitalWrite(11, HIGH);
  Check_Button();
  delay(500);
  digitalWrite(8, LOW);
  digitalWrite(9, LOW);
  Check_Button();
  delay(300);
  digitalWrite(10, LOW);
  digitalWrite(11, LOW);
  Serial.println("Finished Right cycle");
}

// Main Loop Core
void Main_Loop() {
  while (Button_Status == 1) {
    Left_Animation();
    Right_Animation();
    Serial.println("Finshed Main Loop 1111");
  }
  while (Button_Status == 0) {
    Check_Button();
    Serial.println("Finished Main Loop 2222");
  }
}

// Checks if button toggle variable is off.
void LED_OFF_() {
  Serial.println("LED off? Activated");
  if (Button_Status == 0) {
    Turn_Off_All_LED();
  }
  Main_Loop();
}

// Turns off all LED
void Turn_Off_All_LED() {
  Serial.println("LED Turn off Activated");
  digitalWrite(2, LOW);
  digitalWrite(3, LOW);
  digitalWrite(4, LOW);
  digitalWrite(5, LOW);
  digitalWrite(6, LOW);
  digitalWrite(7, LOW);
  digitalWrite(8, LOW);
  digitalWrite(9, LOW);
  digitalWrite(10, LOW);
  digitalWrite(11, LOW);
  Main_Loop();
}

void setup()
{
  Serial.begin(9600);
  pinMode(13, INPUT);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
}

void loop()
{
  // Start
  Button_Status = 1;
  Main_Loop();
}

You have a problem with infinite recursion in this program: loop()
calls Main_Loop(), which calls Left_Animation(), which calls
Check_Button(), which calls LED_OFF_(), which calls Main_Loop(),
which calls Left_Animation(), which calls Check_Button(), which
calls LED_OFF_(), which calls Main_Loop(), which calls... This will
pretty quickly exhaust the memory of your Arduino.
If you only know about graphical programming, this may not make too much
sense to you. So I ask you to imagine that, in your definition of
Main_Loop() (the big structure titled “to Main Loop”) you replace the
smallish box labeled “Left Animation” by its own definition (the big
structure labeled “to Left Animation”). Within this definition, you
replace “Check Button” by its own definition and so on. You will soon
reach a point where you need to embed the definition of Main_Loop()
within itself. It should then look more or less like this:
Main Loop
│ repeat while Button Status = 1
│ do Left animation
│ │  │ Check Button
│ │  │ │ Serial Print “Check button Activated”
│ │  │ │ ...
│ │  │ │ LED OFF?
│ │  │ │ │ Serial Print “LED off? activated”
│ │  │ │ │ if Button Status = 0
│ │  │ │ │ do Turn Off All LED
│ │  │ │ │ Main Loop
│ │  │ │ │ │ repeat while Button Status = 1
│ │  │ │ │ │ do Left animation
│ │  │ │ │ │ │  │ Check Button
│ │  │ │ │ │ │  │ │ Serial Print “Check button Activated”
│ │  │ │ │ │ │  │ │ ...
│ │  │ │ │ │ │  │ │ LED OFF?
│ │  │ │ │ │ │  │ │ │ Serial Print “LED off? activated”
│ │  │ │ │ │ │  │ │ │ if Button Status = 0
│ │  │ │ │ │ │  │ │ │ do Turn Off All LED
│ │  │ │ │ │ │  │ │ │ Main Loop
│ │  │ │ │ │ │  │ │ │ │ repeat while Button Status = 1
│ │  │ │ │ │ │  │ │ │ │ do Left animation
│ │  │ │ │ │ │  │ │ │ │ │  │ Check Button
│ │  │ │ │ │ │  │ │ │ │ │  │ │ Serial Print “Check button Activated”
│ │  │ │ │ │ │  │ │ │ │ │  │ │ ...
│ │  │ │ │ │ │  │ │ │ │ │  │ │ LED OFF?
│ │  │ │ │ │ │  │ │ │ │ │  │ │ │ Serial Print “LED off? activated”
│ │  │ │ │ │ │  │ │ │ │ │  │ │ │ if Button Status = 0
│ │  │ │ │ │ │  │ │ │ │ │  │ │ │ do Turn Off All LED
│ │  │ │ │ │ │  │ │ │ │ │  │ │ │ Main Loop
...etc ad infinitum...

Note that it is possible to write programs using recursion, but:

This is kind of an “advanced topic”, not suitable for someone still
programming at a graphic level.
You have to take precautions in order to avoid the program to
infinitely recurse.
On a microcontroller with little memory, you have to make sure the
recursion is always very shallow. Which is hard, so people writing
embedded code tend to avoid recursion altogether.


text:
Memory usage in AnalogBinLogger of SdFat library
The AnalogBinLogger.ino file of SdFat library says the following:

Each 512 byte data block in the file has a four byte header followed by up to 508 bytes of data. (508 values in 8-bit mode or 254 values in 10-bit mode).
   Each block contains an integral number of samples with unused space at the end of the block.

I was wondering why only 254 values can be stored in 10-bit mode instead of (508*8 bits/ 10 bits ~ 406 values ).

Is this because of the memory being byte-addressable and hence does a 10-bit value take up 2 bytes?
If so, how will a file-reader differentiate between a 10-bit value taking 2 bytes and two 8-bit values?
The AnalogBinLogger.ino says:

The logger will use SdFat's buffer plus BUFFER_BLOCK_COUNT additional buffers.

BUFFER_BLOCK_COUNT is 1 for the Arduino Uno since it has 2KB of SRAM. Each buffer is 512-byte long. Is SdFat's internal buffer also in SRAM? If I am not wrong, the libraries the program uses and the program code reside in the Flash memory, can SdFat write into a buffer in Flash memory?

yes it is because it takes 2 bytes. "10 bit mode" is the 10 bit mode of the ADC, the source of the data, not some 10 bit mode of the file

@Juraj If the ADC converts the analog values to a 10-bit binary value, why does the value take 16 bits when written to the file?

@Harini: Because you cannot store bits in a file. A file is a sequence of bytes.

it is only an example, not an exercise in optimization or compression

@EdgarBonet Sure, in that case, referring to the second part of my question: how does a file-reader differentiate between a 10-bit value and two 8-bit values? You can post it as an answer so that I can mark it accepted for this question.

how will a file-reader differentiate between a 10-bit value taking 2
  bytes and two 8-bit values?

The file AnalogBinLogger.h, which comes with the example sketch you
mentioned, contains the following:
// First block of file.
struct metadata_t {
  unsigned long  adcFrequency;     // ADC clock frequency
  unsigned long  cpuFrequency;     // CPU clock frequency
  unsigned long  sampleInterval;   // Sample interval in CPU cycles.
  unsigned long  recordEightBits;  // Size of ADC values, nonzero for 8-bits.
  unsigned long  pinCount;         // Number of analog pins in a sample.
  unsigned long  pinNumber[123];   // List of pin numbers in a sample.
};

Thus, the file reader just needs to be aware of the format of this first
block, and read the recordEightBits field in order to know whether
this is 8-bit data or not.

Is SdFat's buffer also in SRAM?

Yes, that's the only sensible place you could have a data buffer. It's
allocated on the stack, only during the execution of the
logData() function.

Is this the 'four-byte header' mentioned in AnalogBinLogger.ino which I have quoted in my question? But clearly, this header is 24 bytes.

@Harini: No. This is the first block of the file. It's 512 bytes long, not 24. The four byte header you mention is in every block except the first one.

You're right, pardon me for not accounting for the 123 elements in pinNumber. It would be helpful if you can clarify the third part of the question about SRAM and Flash memory use.

Yes, the line of code highlighted in the link provided is the additional buffer SdFat uses. The sketch mentions the use of SdFat's internal buffer and my question is whether this too resides in the SRAM.

source: Stack Exchange

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

sort: votes


text:
Timestamping AnalogBinLogger data
I would like to timestamp the data collected from AnalogBinLogger.ino on an Arduino Uno. The sketch uses 512-byte buffers, and I have read that writing data in 512-byte chunks is 'better' in terms of write latencies.
The sketch uses this structure for the buffers:
// Data block for 10-bit ADC mode.
const size_t DATA_DIM16 = 254;
struct block16_t {
  unsigned short count;    // count of data values
  unsigned short overrun;  // count of overruns since last block
  unsigned short data[DATA_DIM16];
};

Since I want to add the timestamps which are of unsigned long type, I would have to modify the structure as follows:
// Data block for 10-bit ADC mode.
const size_t DATA_DIM16 = 254;
struct block16_t {
  unsigned short count;    // count of data values
  unsigned short overrun;  // count of overruns since last block
  unsigned short data[DATA_DIM16];
  unsigned long  milli[DATA_DIM16]; // time in milliseconds
};

Now, this structure exceeds 512 bytes and is 1528 bytes. Due to unavailability of enough free stack, my program doesn't run (sketch reports FreeStack to be 1135 bytes). How can I go about this?
PS: My root problem is to achieve time-synchronisation among multiple data-collecting Arduinos which sample at high rates like 8kHz. Due to clock drifts, even if I sync the start times, the timestamps collected afterwards would not be relative to each other. Hence I plan to have a master Arduino send its time to the others in regular intervals.

The straightforward solution:
const size_t DATA_DIM16 = 84;
struct block16_t {
  unsigned short count;    // count of data values
  unsigned short overrun;  // count of overruns since last block
  unsigned short data[DATA_DIM16];
  unsigned long  milli[DATA_DIM16]; // time in milliseconds
  unsigned long padding;   // pad to 512 bytes
};

Now, I suggest to think again about your requirements. Do you really
need a 32-bit timestamp for every data point? If they are closely spaced
in time, a 16-bit, or even 8-bit timestamp should be enough. You could
put a full 32-bit timestamp at the beginning of each block, then only
8-bit timestamps for every data point. This would allow you to store
168 samples per block. You could even pack a 6-bit timestamp with
the data sample into an uint16_t, and have 252 samples per block.

Writing in 512 byte chunks is done by SD libraries, so you could rely on that layer and simply write and store single events
struct block_t {
  uint32_t  milli; // time in milliseconds
  uint16_t data;
  uint8_t  overrun;  // overrun status since last block
};

I do not know your AnalogBinLogger.ino. In other circumstances there's no such 512 byte limit, but a general and strict RAM limit. (You could decrease your DATA_DIM to make it fit safely)

My understanding is that a 512-byte buffer was chosen for its efficiency, which is an important consideration when you try to log data at a high rate.

https://github.com/greiman/SdFat/blob/master/examples/AnalogBinLogger/AnalogBinLogger.ino is an interesting example. Thanks @Edgar and Harini

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


text:
Connecting Function Generator to Arduino
I want to send a function generator's signal to an Arduino UNO Analog pin. Can I use an Oscilloscope probe connected to the function generator output BNC, set to 1x to connect to the Arduino headers using jumper wires? I did read through the manuals of the function generator, but couldn't find a solution.
The function generator available is Tenma 72-14110.

Sure, you can connect the function generator to an analog pin of the Arduino. The probe and the jumper wires are just wires here, nothing special. You should also connect the function generators ground to the Arduinos ground (!).
But: Be sure to stay in the Arduinos voltage range (0 to 5V) with the function generators signal. If you apply a higher or negative voltage, you can destroy the Arduino. As long, as you stay inside that range, nothing bad will happen.

Thanks, I read that the probes are used for 'probe compensation' in oscilloscopes and that they have resistors in them - hence was not sure if I could use them.

As a complement to chrisl's answer, I would recommend putting a
10 kΩ series resistor in series between the function generator and
the Arduino.
This is just for safety: if the function generator accidentally goes out
of the  Arduino's safe voltage range, the resistor will limit the
current that flows through the input pin's protection diodes. These
diodes are rated to only 1 mA, and a 10 kΩ resistor should
greatly expand the range of voltages you can send without frying them.


text:
How do you determine Lead Screw position using Absolute Encoder?
I need to control the position of a lead Screw Stepper motor using EMS22A Absolute Encoder? I've seen James Bruton do this in his video. can anyone help me?
James Bruton Video: https://www.youtube.com/watch?v=ngazw18f6zw
edit: What i did was to determine the "Largest Change" to count the number of cycle that has occurred. However, with fast rotation the program was not able to detect the change.
void loop(){

unsigned long currentMillis = millis();
pos = encoder.ReadAngle();

  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    pos2 = encoder.ReadAngle();
    }
int change = pos2-pos;
if (change > 200){
  cycle--;
}
if (change < -200){
  cycle++;
}
if(change > 1){
  motor.Forward();
}
if(change < -1){
  motor.Reverse();
}
if(change <= 1 && change >= -1){
  motor.Stop();
}
Serial.print(pos);
Serial.print(" ");
Serial.println(cycle);
}

I've offered some general How-To, but you'll get better answers, and more to the point, if you can be specific about what kind of help you need, where you're stuck, etc.

What exactly is your problem in doing so?

What library do you use for the encoder? Please provide a link.

The encoder attaches to the motor (or other) shaft and sends a 10-bit rotational position for a precision of 0.35 deg, and a claimed accuracy of +/- 0.7 degrees. It will be up to the application to keep track of number of rotations, detecting when the shaft has completed a rotation in either direction.
In a lead-screw application there will always be a little bit of backlash or "play". The leadscrew and nut cannot be perfect and must have a little bit of slop (technical term!) to keep the rotational friction low. This means that the nut will have some linear play, leaving that much uncertainty in the linear postion, even if the leadscrew angular position is perfectly known. Most applications manage this by turning the leadscrew back, to behind the target position, and then approaching the target in the forward direction. The leadscrew and nut position will have been calibrated for this direction. Of course it could be calibrated separately for each direction. The key is that the nut must be driven "behind" (for the particular direction) the target by more than the known linear play, to be sure the play will be entirely taken up during the approach to the target.


text:
Slave to Send Data after Receiving Command using I2C
I want to have my Slave Arduino to send signal to Master after the command was made. But the Slave Arduino does not proceeds to sending the signal after doing the command. What is wrong with my code?
Slave

void receiveEvent(int bytes) {
  dir = Wire.read();    // direction
  dis = Wire.read();    // distance
  spe = Wire.read();    // speed
  eStop = Wire.read();    // 1 or 0
  Serial.println(dir);
  Serial.println(dis);
  Serial.println(spe);
  mov = true;
}
void loop() {
    Wire.onReceive(receiveEvent);
  if (dir == 1 && mov == true && eStop == false){
      motor.Distance(dis);
      motor.Speed(spe);
      motor.Forward();
       Wire.onRequest(requestEvent);
      mov = false;
      fin = true;
    }
  if (dir == 2 && mov == true && eStop == false){
    motor.Distance(dis);
    motor.Speed(spe);
    motor.Reverse();
      Wire.onRequest(requestEvent);
    mov = false;
    fin = true;
  }

  else{
    motor.Stop();
  }
}
void requestEvent(){
    Wire.write(1);
    fin = false;
    Serial.println("sent");
}

Master

#include <Wire.h>

const byte interruptPin = 2;
byte dir = 0;
byte dis;
byte spe;
bool upd;

bool state= false;

void setup() {

  Wire.begin();
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), emergencyStop, CHANGE);
  Serial.begin(9600);

}
void loop() {
       if( state == false ){
       dir = 1;
       dis = 30;
       spe = 2;
       Wire.beginTransmission(9); // transmit to device #9
       Wire.write(dir);
       Wire.write(dis);
       Wire.write(spe);
       Wire.write(0);
       Wire.endTransmission();    // stop transmitting
       state = true;
       }
       if (state == true){
        if(Wire.available() > 0){
       Wire.requestFrom(9,2);   //6bytes from slave 9
          bool upd = Wire.read();
          Serial.println(upd);
        }
      }
}
void emergencyStop(){ // not working
  Wire.beginTransmission(9); // transmit to device #9
       Wire.write(0);
       Wire.write(0);
       Wire.write(0);
       Wire.write(1);
       Wire.endTransmission();    // stop transmitting

}

Please wdit your question to include the full sketch

Typically Wire.onReceive(callbackFunction) is called once in the setup().

Serial print in the callback function can cause issues.

found my solution for this. although not verified yet, but i removed Serial print and moved the Wire.onRequest outside of the if loop. and uses a ledPin for checkups
void loop() {

        Wire.onReceive(receiveEvent);
        Wire.onRequest(requestEvent);
  if (dir == 1 && mov == true && eStop == false){
      motor.Distance(dis);
      motor.Speed(spe);
      motor.Forward();
      mov = false;
      fin = true;
    }
  if (dir == 2 && mov == true && eStop == false){
    motor.Distance(dis);
    motor.Speed(spe);
    motor.Reverse();
    mov = false;
    fin = true;
  }

  else{
    motor.Stop();
  }
}

void requestEvent(){
    if ( fin == true){
      Wire.write(1);
     fin = false;
    digitalWrite(ledPin, HIGH);
    }

}

Yes, you should not do serial prints inside an interrupt service routine.


text:
Hardware/Software Serial communication abruptly stops (HC - 05 bluetooth module)
I'm trying to send the readings of 3 sensors simultaneously to my Android phone on an app I made using MIT App Inventor 2 via the HC-05 bluetooth module.
For this, I'm sending a string like "20.067, 58.234, 12 |" where the "," allows the splitting of the text and "|" acts as a delimiter to tell the app that the whole string has reached it.
The problem I'm facing is that after a while(which varies from 2 seconds to a few minutes), the readings just stop and the app stops responding (ie; touching any butons on the app does nothing). However, this is a non-issue when I'm not using Bluetooth at all and just printing to the Serial Monitor.
To find the cause, I tried the following things:

Sent text to the module via the normal Serial.print() function so that I can see it on my PC and my app at the same time. Strangely, after the readings stopped (on the serial monitor as well), as soon as I closed the Serial Monitor and opened it again, the readings were back and again stopped after a while.
I used the SoftwareSerial.h library to define a different pair of RX/TX pins to send the text to the module and the serial monitor separately. This time, when the readings stopped, restarting the serial monitor had no effect.

I'm not exactly sure how to interpret these outcomes but it leads me to believe the problem lies in the serial communication.
Additional information:

The baud rate is set to 115200
I'm sending a string every 500ms and the app clock fires every 100ms

This is a screenshot of the codeblock on MIA 2:

This is the relevant portion of the Arduino sketch. The rest of it just calculates the variables being printed
  if(millis()-looper>500){
  // Sensor 1 data
  Serial.print(" X = ");
  Serial.print(x1);
  Serial.print(" Y = ");
  Serial.print(y1);
  Serial.print(" Z = ");
  Serial.print(z1);
  Serial.print(",");

  // Sensor 2 data
  Serial.print(" X = ");
  Serial.print(x2);
  Serial.print(" Y = ");
  Serial.print(y2);
  Serial.print(" Z = ");
  Serial.print(z2);
  Serial.print(",");

  // Sensor 3 data
  Serial.print(angle);
  Serial.println("|");
  looper = millis();
  }

opening Serial Monitor resets the Arduino. do you use String class? show the Arduino sketch

Thanks, I didn't know that. That explains why it starts working again, but I still need to know why it stops in the first place. I've included the sketch as you said.

the problem is not in this part of the sketch

The rest of it is just maths, I don't know where else the problem could be

you need to determine the location of the failure .... reduce your arduino loop()  code to a single  line that sends  a fixed string like "20.067, 58.234, 12 |" and pauses 500ms ..... do not do any sensor reading, no interrupt handling, nothing more than minimal code that communicates with the android device


text:
How to keep the regulator cool while battery powering the arduino and accessories?
I'm trying to build a battery operated hand lantern. It has the Arduino, an MPU6050 accelerometer, and 4 APA106 (WS2812B-like) LEDs.
If everything's powered through the Arduino's 5V pins, that's 80mA for the Arduino, 240mA for the 4 LEDs, and let's round up to 5 mA for the MPU6050.
If I'm using 5x AA batteries for 7.5V (at full charge) that should be 2.5V * 325mA of power wasted or just under a watt that'll be heating up the regulator? I'm not sure if that's huge or tiny or in between or what.
What's the most sane way to power this device for an absolute newbie?

1W is near the limit of what a small LDO can handle. It will get considerably hot.
I would use 4 batteries instead of 5, and a 3.3V Arduino clone instead of the UNO, and power the LEDs directly from the batteries. You could also use your original UNO, feeding it with 6V on a 5V pin through a simple diode, which would drop it to something like 5.4..5.3V.

How would powering the LEDs from the battery work? They seem pretty demanding of a steady 5v of power, and at least at a full charge 4 of them would be 6V.

@Different55 instead of the positive coming from VCC it comes straight from the + of the battery. The negative of the battery and LED both get connected to arduino ground.

@Different55 APA106 have a working range of 4.5 to 6V.

I suggest using a DC-DC buck/boost voltage regulator. Those can take a wide range of input voltages and put out an adjustable output voltage
This one on Amazon, for example, can take an input of 3-40V and provide an output of 1.5-35V(Adjustable). It is a switching power supply, so it should not produce much waste heat. That one is rated at 2A, or 3A if you add a heat-sink.
You could feed the regulated 5V into the USB connector on your Arduino, and to your other components as well. (Just take a USB cable, cut it, and tie the red and black wires to ground and +5V, respectively.
You might need a filtering capacitor to protect the Arduino from voltage variations as the load on the power supply changes.

Is that a special type of capacitor or just a normal one used for that purpose? Will any capacitor work? Does it just store energy and spit it out to smooth out tiny dips?

You want a decent sized electrolytic, between 5V and ground physically near the input to the Arduino. I'm not an EE - I'd have to do some digging to figure out what rating of capacitor is appropriate. Yes, it acts as a filter, and resists changes in voltage.

Use en external voltage regulator (go switch-mode if you care about battery life) that is adequately cooled.

"Switch mode"? What would I be regulating the voltage down to, since it still has to be fed through the Arduino's linear regulator?

@Different55 Switchmode voltage regulators rapidly switch on and off the current. Together with a capacitor they can provide a stable voltage with a lot less power lost. Regulate to 5V or slightly above that. The arduino can handle a slight undervolt.

@Different55 I dare to assume that the answer suggest feeding 5V from the regulator directly to the 5V pin of Arduino, skipping its weak and inefficient regulator altogether.

Let me know if this is completely stupid, but as I was thinking about regulators and batteries I remembered I have a portable USB power bank. Doesn't the Arduino's USB input also skip the regulator?


text:
Sound sensor dont work in whole project
When I put this code only on arduino, sound sensor works:
int soundSensor=A1;
int LED=5;

boolean LEDStatus=false;

void setup() {

Serial.begin(9600);

  pinMode(soundSensor,INPUT);
  pinMode(LED,OUTPUT);

}

void loop() {

  int SensorData=analogRead(soundSensor);

  if(SensorData>600){

    if(LEDStatus==false){
        LEDStatus=true;
        digitalWrite(LED,HIGH);
    }
    else{
        LEDStatus=false;
        digitalWrite(LED,LOW);
    }

    delay(50);
  }

 }

When I upload same code in big project, even when I upload little part of project on arduino, sound sensor doesnt work.. whats happening?
I checked soundsensor with everything.
I leave whole code till void loop ()  and sound sensor works.
But if I put even delay(1000) in void loop after, sound sensor doesnt work.
Also, if I put every other thing : servo, dht, lighting in code with sound sensor.. with or without delay... sound sensor doesnt work!
Thanks
Whole code:
#include <Servo.h>
#include "DHT.h"
#include <SPI.h>
#include <MFRC522.h>
#include <Wire.h>

#define SERVO_PIN 8
#define SS_PIN 10
#define RST_PIN 9
#define lightingOutput A2
#define ldrPin A0
#define PIR 7
#define ledGrn 6
#define heatingOutput A3
#define coolingOutput A4
#define DHTPIN 2
#define DHTTYPE DHT11

MFRC522 mfrc522(SS_PIN, RST_PIN); // Create instance of our reader
Servo myservo; // Create instance of our motor /// create servo object to control a servo
DHT dht(DHTPIN, DHTTYPE);     //// Initialize DHT sensor for normal 16mhz Arduino

int pos;
int light;
float h, t;
int soundSensor=A1;
int LED=5;
boolean LEDStatus=false;
const int buzzer = 4;
long zadnje_ocitanje=0;

void setup()
{

  Serial.begin(9600);
  dht.begin();
  SPI.begin();
  mfrc522.PCD_Init();
  myservo.attach(SERVO_PIN);
  myservo.write(0);

  pinMode(heatingOutput, OUTPUT);
  pinMode(coolingOutput, OUTPUT);
  pinMode(ledGrn, OUTPUT);
  pinMode(soundSensor,INPUT);
  pinMode(LED,OUTPUT);
  pinMode(lightingOutput, OUTPUT);

  zadnje_ocitanje=millis();
}
void loop() {

  Serial.println("\nHOME AUTOMATION\n");

  readSOUND();
  readRFID();
  readDHT();
  readLIGHT();

delay(1000);

}

////////////////////////////////////////////
void readRFID()

{
  //Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent() ) {
    return;
  }
  if ( ! mfrc522.PICC_ReadCardSerial() ) {
    return;
  }
  // If a card is detected, execute the following:
  Serial.println("Time to open");
  // Print the card's ID
  String content = "";
  byte letter;
  for ( byte i = 0; i < mfrc522.uid.size; i++ ) {
    content.concat(String(mfrc522.uid.uidByte[i], HEX));
    if ( i < mfrc522.uid.size - 1 ) content += "-";
  }
  content.toUpperCase();
  Serial.println();
  Serial.println("UID tag :'" + content + "'");

  if (content == "C0-E5-86-25") {

    Serial.println("Authorized access");
     digitalWrite(ledGrn, HIGH);

    for (pos = 0; pos <= 90; pos += 1) {
      myservo.write(pos);
      delay(25);
    }
    for (pos = 90; pos >= 0; pos -= 1) {
      myservo.write(pos);
      delay(70);
      digitalWrite(ledGrn, LOW);
    }
  }
  else {
    Serial.println("Access Denied");
      tone(buzzer, 1000, 6000);
  }
}

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

void readDHT()
{

  h = dht.readHumidity();
  t = dht.readTemperature();
  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.println();

  if (t < 18) //if temperature is less than 18 celcius
  {
    digitalWrite(heatingOutput, HIGH);
    Serial.print("Heating activated\n");
  }
  else
  {
    digitalWrite(heatingOutput, LOW);
  }

  if (t > 22) //if temperature is more than 22 celcius
  {
    digitalWrite(coolingOutput, HIGH);
    Serial.print("Cooling activated\n");
  }
  else
  {
    digitalWrite(coolingOutput, LOW);
  }
}

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

void readLIGHT()
{

 int value_pir = digitalRead(PIR);
 light = map(analogRead(ldrPin) , 0 , 1024 , 1 , 100);

  Serial.print("Lighting percentage: ");
  Serial.print(light);
  Serial.print("\nMotion detector: ");
  Serial.print(digitalRead(PIR));

if ((millis()-zadnje_ocitanje)>6000)
  {

  if ((light < 50) && ( value_pir == HIGH) )
  {
    digitalWrite(lightingOutput, HIGH);
    Serial.println("\nLighting ON");
  }
  else
  {
    digitalWrite(lightingOutput, LOW);
    Serial.println("\nLighting OFF");
  }
    zadnje_ocitanje=millis();
  }
}

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

void readSOUND()
{
  int SensorData=analogRead(soundSensor);

  if(SensorData>600){

    if(LEDStatus==false){
        LEDStatus=true;
        digitalWrite(LED,HIGH);
    }
    else{
        LEDStatus=false;
        digitalWrite(LED,LOW);
    }

    delay(50);
  }

}

See his post on Arduino.cc for additional information before you go too far.  https://forum.arduino.cc/index.php?topic=626641.0

You found on that thread that your sound sensor does indeed work.  It's just that you have your threshold set wrong?  Put a line there to print the reading from the sensor.  Does it every go over 600?  We just found out on Arduino.cc that it doesn't.


text:
Ethernet Shield Issue
I just bought a Ethernet Shield for my Arduino UNO. I connected it to my arduino and flashed the Example code for Ethernet Shield, but the code didn't work. The COLL LED on ethernet shield is glowing and I checked with my router, it has not assigned any IP to my ethernet shield. I tried all of the examples given, but none of them worked. Help me in understanding wrong I am doing here?
Ethernet Shield(W5100) Link: https://www.banggood.in/Ethernet-Shield-Module-W5100-Micro-SD-Card-Slot-For-Arduino-UNO-MEGA-p-908461.html?rmmds=search&cur_warehouse=CN
Exampled code given in Arduino (DhcpAddressPrinter):
#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {
  0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02
};

void setup() {
  // You can use Ethernet.init(pin) to configure the CS pin
  //Ethernet.init(10);  // Most Arduino shields
  //Ethernet.init(5);   // MKR ETH shield
  //Ethernet.init(0);   // Teensy 2.0
  //Ethernet.init(20);  // Teensy++ 2.0
  //Ethernet.init(15);  // ESP8266 with Adafruit Featherwing Ethernet
  //Ethernet.init(33);  // ESP32 with Adafruit Featherwing Ethernet

  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // start the Ethernet connection:
  Serial.println("Initialize Ethernet with DHCP:");
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    if (Ethernet.hardwareStatus() == EthernetNoHardware) {
      Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
    } else if (Ethernet.linkStatus() == LinkOFF) {
      Serial.println("Ethernet cable is not connected.");
    }
    // no point in carrying on, so do nothing forevermore:
    while (true) {
      delay(1);
    }
  }
  // print your local IP address:
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  switch (Ethernet.maintain()) {
    case 1:
      //renewed fail
      Serial.println("Error: renewed fail");
      break;

    case 2:
      //renewed success
      Serial.println("Renewed success");
      //print your local IP address:
      Serial.print("My IP address: ");
      Serial.println(Ethernet.localIP());
      break;

    case 3:
      //rebind fail
      Serial.println("Error: rebind fail");
      break;

    case 4:
      //rebind success
      Serial.println("Rebind success");
      //print your local IP address:
      Serial.print("My IP address: ");
      Serial.println(Ethernet.localIP());
      break;

    default:
      //nothing happened
      break;
  }
}

Output
Initialize Ethernet with DHCP:

Code I wrote for Webserver:
#include<SPI.h>
#include<Ethernet.h>

int led = 8;
byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xEF, 0xED};
EthernetServer server(80);
String readString;

void setup() {
  Serial.begin(9600);
  pinMode(led, OUTPUT);
  Ethernet.begin(mac);
  Serial.print("Server is at ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  EthernetClient client = server.available();

  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.print(c);

        if (readString.length() < 100) {
          readString += c;
        }

        if (c = '\n') {
          Serial.print(readString);
          client.println("<HTTP/1.1 200 0K>");
          client.print("<Connection-Type: text/html>");
          client.println("<Connection: close>");
          client.println("");

          client.println("<!DOCTYPE html>");
          client.println("");
          client.println("");
          client.println("<title>Webserver</title>");
          client.println("");
          client.println("");
          client.println("<button>LED ON</button>");
          client.println("<button>LED OFF</button>");
          client.println("");

          delay(1);
          client.stop();

          if (readString.indexOf("?button1on") > 0) {
            digitalWrite(led, HIGH);
          }

          if (readString.indexOf("?button2off") > 0) {
            digitalWrite(led, LOW);
          }
          readString = "";
        }
      }
    }
  }
}

Output
Server is at 0.0.0.0

Thank You

Also what ethernet shield?

what do the examples print to Serial Monitor?

I have added the code in my question. The ethernet shield I am using is W5100

try this code  https://github.com/esp8266/Arduino/blob/master/libraries/Ethernet/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino

Try disabling the SD. Add pinMode(4, OUTPUT); digitalWrite(4, HIGH); to the setup().

@jsotola Thanks for helping. I tried that code, but the serial monitor prints "Failed to configure Ethernet using DHCP"

@MikaelPatel After adding those lines in setup(), the output in Serial monitor is same, "Server is at 0.0.0.0"

do you have the router set up with a whitelist of MAC addresses? .... also, you could try using a static IP

@darkpanda Did you put the code first in setup()?

@MikaelPatel yes


text:
IsTimeSet library - Assign variables
i get the current time with the example code istimneforset, everything works fine.
now i want to get the current time from the function "Serial.println(timeClient.getFormattedTime());" and i am trying to cache the first character of the array.
code:
#include <NTPClient.h>
// Change the next line to use with a different map/shield
#include <ESP8266WiFi.h>
//#include <WiFi.h> // for WiFi shield
//#include <WiFi101.h> // for WiFi 101 shield or MKR1000
#include <WiFiUdp.h>

const char *ssid =" *";
const char *password = "*";

WiFiUDP ntpUDP;
// initialized to a time offset of 10 hours
NTPClient timeClient(ntpUDP, "pool.ntp.org", 36000, 60000);
// HH:MM:SS
// timeClient is initialized to 10:00:00 if it does not receive an NTP packet
// before the timeout of 100ms is received.
// Without isTimeSet(), the LED would be lit even though the time was
// was not yet set correctly.

const int hour = 10;
const int minute = 0;

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

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay (500);
    Serial.print(".");
  }

  timeClient.begin();
}

void loop() {
  timeClient.update();

 //Serial.println(timeClient.getFormattedTime());

 int stund2  = (timeClient.getFormattedTime()[0]);

Serial.println(stund2);

}

unfortunately it always gives me a wrong value. my goal is to have the current hour in a variable. can someone help me? thanks!

What value do you get? Why is it wrong?

Serial.println(timeClient.getFormattedTime()); -> 01:41:58
Serial.println (stund2); -> 48

There are a number of post in threads here and here that suggest using the NTPClient here.
Also, if we inspect that GIT repository's copy of NTPClient.cpp starting a line 155 we see the function for getFormattedTime():
String NTPClient::getFormattedTime(unsigned long secs) {
  unsigned long rawTime = secs ? secs : this->getEpochTime();
  unsigned long hours = (rawTime % 86400L) / 3600;
  String hoursStr = hours < 10 ? "0" + String(hours) : String(hours);

  unsigned long minutes = (rawTime % 3600) / 60;
  String minuteStr = minutes < 10 ? "0" + String(minutes) : String(minutes);

  unsigned long seconds = rawTime % 60;
  String secondStr = seconds < 10 ? "0" + String(seconds) : String(seconds);

  return hoursStr + ":" + minuteStr + ":" + secondStr;
}

...we see that this function returns a String resembling "hh:mm:ss" where hh is hours, mm is minutes and ss is seconds.
To extract only hours we would have to "cut" the string or parse the string using the ":" character, use only the "hh" portion of the string and convert that back into a number.
This is complex.  Instead, consider using the function getHours():
int NTPClient::getHours() {
  return ((this->getEpochTime()  % 86400L) / 3600);
}

... this uses the epoch time after taking off the date (modulo 86400) and taking off the minutes and seconds (divide by 3600) leaving only the hours.

While st2000 gave a good answer about how to do it instead, I wanted to explain what actually went wrong with your first solution.
You are seeing the difference between binary and ASCII encoded data. Using timeClient.getFormattedTime() will give you an ASCII encoded string. Such a string is an array of chars, each one representing one character (according to the ASCII table) until the string gets terminated with the null character \0.
You are taking the first character and assign it to an integer variable. The value will be directly copied into that variable. But the first element in that char array is the ASCII digit 0, which is the equivalent of decimal 48. And that is what you get from your code. Also the hour field of that string is 2 characters wide, so you need to read both of them, not just the first character.
If you want to extract numbers from a string, you cannot just assign them. You need to parse the data correctly. For that you would tokenize the string (split it in individual parts with data) (for example with strtok()) and then parse each token with a corresponding function. To parse an integer value from a string you can use atoi(). This function will read the string, until a non-digit character appears, and convert that to an integer.
So - since we are only interested into the first number/token in that string, you can leave out the tokenizing and just parse that string (since after the number of hours there is always the : character, which is a non-digit character):
int stund2 = atoi(timeClient.getFormattedTime());

I have not tested this, but it should also work, though not that efficient as the solution of st2000, since parsing string data is commonly more complex than working directly with integer numbers.


text:
How do I send multiple variables via stream to Unity?
So I currently have this for arduino.ino:
Serial.println(Variable1);

that does this in Unity:
string variable1 = stream.ReadLine();
float x = float.Parse(variable1);
transform.Rotate (0, -x/1000, 0);

My question is; How would I send 3 variables from the Arduino to Unity so I can put each value into the transform.Rotate function at once?
For example in pseudocode:
Arduino.ino
send(Variable1, Variable2, Variable3);

Unity
transform.Rotate(Variable1,Variable2,Variable3);

I hope this makes sense.
Thank you.

What you need to do is define a communication scheme/protocol. You appear to be using the Serial UART via USB.
Your first example has a simple scheme its simply the ASCII representation of the variable followed by a newline. i.e. :
float x = 123.45;
Serial.println(x);

this simply outputs
"123.45\n"

you could continue this pattern
float x, y, z,
... // assume x, y and z have values in them
Serial.print(x);
Serial.print(' ');
Serial.print(y);
Serial.print(' ');
Serial.println(z);

this outputs something like:
"123.43 23.34, 42.24\n"

then your receiving code will do do something like
string line = stream.ReadLine();
string[] parts = line.Split(' ', StringSplitOptions.RemoveEmptyEntries)
float x = float.Parse(parts[0]);
float y = float.Parse(parts[1]);
float z = float.Parse(parts[2]);

but this is very inefficient, since the arduino needs to convert the float to an ASCII string, then transmit that over the serial port, where its read on the other side, then parsed back into a float. One doesn't need to do this, you can do in binary, it won't be human readable, but it will use much less transmission space.
float x, y, z; // assume these are valid
Serial.write(&x, sizeof(float));
Serial.write(&y, sizeof(float));
Serial.write(&z, sizeof(float));
// n.b. one should write an end of message here or something else to frame the data

and on the other side
byte[] data = new byte[12];
stream.Read(data, 0, 12);

float x = BitConverter.ToSingle(data, 0);
float y = BitConverter.ToSingle(data, 4);
float z = BitConverter.ToSingle(data, 8);

You will generally also want some way to frame the data, so you might want to start with a simple message header, i.e.:
struct head
{
  int length;
  int code;
};

and you write it like:
head header; //assume this is valid
Serial.write(&header, sizeof(header));

then you can write you message.
You might also want to implement some sort of checksum, so you can verify that you got the data correctly.
You can create multiple message structures this way, i.e.
struct vect3d
{
  head header;
  float x;
  float y;
  float z;
}

just fill and send
vect3d v3;
v3.head.length = sizeof(vect3d); // one could subtract sizeof(head) off so the reader can always read the first 8 bytes and read the rest of the message from there
v3.head.code = VECT3D; // assume this is defined somewhere
v3.x = 123.5;
v3.y = 23.4;
v3.z = 42.24;

Serial.write(&v3, sizeof(v3));

On the other side one would read in the first 8 bytes, then read in the rest of the message based on the length, and parse it based on the code.


text:
SparkFun BasicAHRS_I2C giving unstable readings
SparkFun BasicAHRS_I2C giving unstable readings.
I am using the SparkFun Arduino Sketch from here.
It is giving me these results:
X-acceleration: 91.43 mg Y-acceleration: 249.51 mg Z-acceleration: 1042.05 mg
X-gyro rate: -0.549 degrees/sec Y-gyro rate: 0.557 degrees/sec Z-gyro rate: 1.595 degrees/sec
X-mag field: -164.35 mG Y-mag field: -240.16 mG Z-mag field: -20.73 mG
Temperature is 27.9 degrees C

and then the next result (when MPU9250 is still) is:
X-acceleration: 91.49 mg Y-acceleration: 252.75 mg Z-acceleration: 1039.49 mg
X-gyro rate: -0.076 degrees/sec Y-gyro rate: -0.130 degrees/sec Z-gyro rate: -0.008 degrees/sec
X-mag field: -175.07 mG Y-mag field: -222.24 mG Z-mag field: -27.64 mG
Temperature is 27.9 degrees C

Notice how the temperature has remained constant, acceleration has remained constant (although im not why there is a reading if the MPU9250 is stationary) and the mag field is fairly close. However, the Gyro values are not close.
Could I have a bad MPU9250?
I am using the Mega.
Edit: Added a complementary filter from here, however they have not added a comp filter for the z value as can be seen from my screenshot of the serial monitor:

I think this is because they have the MPU6050 and not the MPU9250. I believe the MPU9250 has the magnetometer which can be used to 'help' the drift?
How could I use the magnetometer to help counter the drift?
End goal: rotate a gameobject in unity with the MPU9250 with minimal drift and maximum accuracy.

Have you tried posting a question to SparkFun's customer service department?

If you haven’t noticed the difference in the two is minuscule.
For example, the change in degree is <1. Also the acceleration is measured in g’s which is acceleration due to gravity. The data says the measures are in mg which is 0.01g.
This is normal with accelerometers and all sensors when they pick up residual voltage from random vibrations or other sources of noise. It also could be with the error margin within SparkFun’s product since the product is more on the lower end of quality which once again is normal.
TLDR: everything is working fine.

When I use them values in Unity, the object rotates fast almost as if its random.

The values seem fine to me. Generally these MPU chips are really noisy, that is totally normal. Ti really use the data to the the current orientation, you have to use a filter to combine the data from accelerometer and gyroscope.
There are multiple possible filters, that can help. The easiest one to implement is a Complementary filter. It gives you pretty good results. You should be able to find corresponding tutorials on the web.

The code from your link does not use a complementary filter for the z axis. In the comment it says, that the accelerometer doesn't provide z angle data, and that is correct. Since gravity always goes down, you cannot distinguish the angles around that axis.
But - as you already stated - you can use the magnetometers data for this. But you will need the inclination angle of the earths magnetic field (the angle between ground and field vector).  You can google the inclination angle for your place and use it as constant. But most likely you will want to use the device inside of buildings. The magnetic field can be very disturbed there due to much steel nearby. Thus it is better to do a calibration step before use, while the device lies flat on the ground.
When you have calculated the angle around the z axis from the magnetometer data, you can use it in a complementary filter, like it was done in the linked code with the accelerometer data.
Note: Due to all the steel, the inclination angle does not have to be constant, when moving around in a building. So this is better for use inside a small space range.

When I use them gyro values to rate an object in Unity it moves so much as if it is random.

Then you are doing something wrong in your unity game. With that rate from the gyro a full rotation would need about 360 seconds (well over 5min). At least not so fast, that is is random. Please don't use the unity game to test the accelerometer. Instead you should watch the values directy on the serial monitor, to see, how they behave. With a complementary filter you get the absolute orientation. Do this on the arduino, output the calculated orientation, and check, this these values are good over th serial monitor

The above values are from the serial monitor however I haven’t calculated the absolute orientation with the serial monitor.

The above values don't correspond with rapid movement. Try the complementary filter

@Jordan Savage  I added a small explanation about using the magnetometer.

Thank you for the informative edit. My inclination angle constant is 66.31 deg, on this website here: http://autoquad.org/wiki/wiki/configuring-autoquad-flightcontroller/autoquad-calibrations/calibration-faq/magnetic-declination-and-inclination/ it states to make a sign change. From your edit: "calculated the angle around the z axis from the magnetometer data", is this angle the 66.31 deg that the website above is telling me for my location?

"You can use it in a complementary filter" how could I do this? I have the Z mag value (with calibration) and I have my local magnetic inclination angle. How would I use these values in the complementary filter as it is now the magnetometer and not the accelerometer?

@Jordan Savage I think you need to calculate the angle around the gravity angle by taking the magnetic field vector, using only the components perpendicular to the gravity direction and calculating the difference between this vector and the standard/calibration angle. I've not really wrapped my head around the exact calculations. Maybe it will help, when you draw the geometrical setup. I currently don't have time to do so. When you have the angle, you can simply use it instead of the accelerometer angle, like in the calculations for the other components.


text:
Is the code correct? Nrf24l01
I'm am a beginner, so I'm sorry I have written this wrong.
Is this piece of code correct? If not where?
Transmitter:
#include <SPI.h>
#include "RF24.h"

int* Msg, mSg, msG;

RF24 radio(9, 10);
const uint8_t pipe = 1;

void setup() {
  // put your setup code here, to run once:
  radio.begin();
  radio.setPALevel(RF24_PA_LOW);
  radio.openWritingPipe(pipe);
}

void loop() {
  // put your main code here, to run repeatedly:
  Msg = analogRead(A1);
  radio.write(Msg, sizeof(Msg));
  mSg = analogRead(A2);
  radio.write(mSg, sizeof(mSg));
  msG = analogRead(A3);
  radio.write(msG, sizeof(msG));
  delay(100);
}

Receiver:
#include <SPI.h>
#include "RF24.h"

#define in1 2
#define in2 3
#define in3 4
#define in4 5

#define in5 A2
#define in6 A3
#define in7 A4
#define in8 A5

const int maxMsgLength = 64;
char Msg[maxMsgLength];
const int maxmSgLength = 64;
char mSg[maxmSgLength];
const int maxmsGLength = 64;
char msG[maxmsGLength];

RF24 radio(9, 10);
const uint8_t pipe = 1;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  radio.begin();
  radio.setPALevel(RF24_PA_LOW);
  radio.openReadingPipe(1, pipe);
  radio.startListening();
}

void loop() {
  // put your main code here, to run repeatedly:
  if (radio.available()) {
    radio.read(Msg, maxMsgLength - 1);
    radio.read(mSg, maxmSgLength - 1);
    radio.read(msG, maxmsGLength - 1);
  }

  int xAxis = Msg;
  int yAxis = mSg;
  int YAxis = msG;

  if (xAxis < 450) {
    // Forward
    digitalWrite(in1, 1);
    digitalWrite(in2, 0);
    digitalWrite(in3, 1);
    digitalWrite(in4, 0);
    Serial.println("Forward");
  }
  else if (xAxis > 550) {
    // Backward
    digitalWrite(in1, 0);
    digitalWrite(in2, 1);
    digitalWrite(in3, 0);
    digitalWrite(in4, 1);
    Serial.println("Backward");
  }
  else {
    // Stop
    digitalWrite(in1, 0);
    digitalWrite(in2, 0);
    digitalWrite(in3, 0);
    digitalWrite(in4, 0);
    Serial.println("Stop");
  }

  if (yAxis < 450) {
    // Left
    digitalWrite(in5, 1);
    digitalWrite(in6, 0);
    Serial.println("Left");
  }
  else if (yAxis > 550) {
    // Right
    digitalWrite(in5, 0);
    digitalWrite(in6, 1);
    Serial.println("Right");
  }
  else {
    // Stop
    digitalWrite(in5, 0);
    digitalWrite(in6, 0);
    Serial.println("Stop");
  }

  if (yAxis < 450) {
    // Flipper Up
    digitalWrite(in7, 1);
    digitalWrite(in8, 0);
    Serial.println("Up");
  }
  else if (yAxis > 550) {
    // Flipper Down
    digitalWrite(in7, 0);
    digitalWrite(in8, 1);
    Serial.println("Down");
  }
  else {
    // Stop
    digitalWrite(in7, 0);
    digitalWrite(in8, 0);
    Serial.println("Mid");
  }
  delay(250);
}

Edit:
Transmitter:
#include <SPI.h>
#include "RF24.h"

int x, y, f;

RF24 radio(9, 10);
const uint8_t pipe = 1;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  radio.begin();
  radio.setPALevel(RF24_PA_LOW);
  radio.openWritingPipe(pipe);
}

void loop() {
  // put your main code here, to run repeatedly:
  x = analogRead(A1);
  radio.write(x, sizeof(x));
  y = analogRead(A2);
  radio.write(y, sizeof(y));
  f = analogRead(A3);
  radio.write(f, sizeof(f));
  delay(100);
}

Receiver:
#include <SPI.h>
#include "RF24.h"

#define in1 2
#define in2 3
#define in3 4
#define in4 5

#define in5 A2
#define in6 A3
#define in7 A4
#define in8 A5

int x;
int y;
int f;

RF24 radio(9, 10);
const uint8_t pipe = 1;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  radio.begin();
  radio.setPALevel(RF24_PA_LOW);
  radio.openReadingPipe(1, pipe);
  radio.startListening();
}

void loop() {
  // put your main code here, to run repeatedly:
  if (radio.available()) {
    radio.read(&x, sizeof(x));
    radio.read(&y, sizeof(y));
    radio.read(&f, sizeof(f));
  }

  if (x < 450) {
    // Forward
    digitalWrite(in1, 1);
    digitalWrite(in2, 0);
    digitalWrite(in3, 1);
    digitalWrite(in4, 0);
    Serial.println("Forward");
  }
  else if (x > 550) {
    // Backward
    digitalWrite(in1, 0);
    digitalWrite(in2, 1);
    digitalWrite(in3, 0);
    digitalWrite(in4, 1);
    Serial.println("Backward");
  }
  else {
    // Stop
    digitalWrite(in1, 0);
    digitalWrite(in2, 0);
    digitalWrite(in3, 0);
    digitalWrite(in4, 0);
    Serial.println("Stop");
  }
  if(x > 1023)x = 1023;
  if(x < 0)x = 0;

  if (y < 450) {
    // Left
    digitalWrite(in5, 1);
    digitalWrite(in6, 0);
    Serial.println("Left");
  }
  else if (y > 550) {
    // Right
    digitalWrite(in5, 0);
    digitalWrite(in6, 1);
    Serial.println("Right");
  }
  else {
    // Stop
    digitalWrite(in5, 0);
    digitalWrite(in6, 0);
    Serial.println("Stop");
  }
  if(y > 1023)y = 1023;
  if(y < 0)y = 0;

  if (f < 450) {
    // Flipper Up
    digitalWrite(in7, 1);
    digitalWrite(in8, 0);
    Serial.println("Up");
  }
  else if (f > 550) {
    // Flipper Down
    digitalWrite(in7, 0);
    digitalWrite(in8, 1);
    Serial.println("Down");
  }
  else {
    // Stop
    digitalWrite(in7, 0);
    digitalWrite(in8, 0);
    Serial.println("Mid");
  }
  if(f > 1023)f = 1023;
  if(f < 0)f = 0;

  Serial.println(x);
  Serial.println(y);
  Serial.println(f);
  delay(250);
}

Thank you for your time.

Does it behave not the way you want? Because we don't know that. And if it does not behave like you want, describe exactly what you expect, and what you notice.

So, I want it to take the values from the joysticks and send it to the receiver side. There the joystick values must be taken and l298n must behave accordingly. If the joystick is pulled upward then the motors should go forward and vice versa. Same with the x-axis, if the joystick is pulled on the left side the motor must rotate to the left-hand side.

Ok ... and does your program behave like that? If yes, why ask the question? If not, describe what you see and what you expect.

So the program does not behave like that.

The joystick values do not get transmitted and on the receiver, the values are displayed as 0.

Did you try a default RF24 example?

Yes, the default example is working fine.

Try removing the pointer () in int Msg, mSg, msG;. In general, use print to print out all variables to pinpoint problems

Do you mean * <- this symbol.

Yes: remove that *

Still doesn't work

Then try print statements.

According to the code, the Serial monitor of the receiver shows Stop, Left, and Up.

Can you please explain the transmission of integers with the rf24.

The error came that print is not member of the RF24 library.

I created an answer (doesn't mean all is ok, but should give you some advice and solution)

I see (at least one ) problem.
First remove the * from:
int* Msg, mSg, msG;

Because it should store integers (numbers), not pointers to numbers.
Also, make the variables better. These almost identical names are quite confusing (name them x, y or z or a better name).
What you are doing is sending the 3 integers as integers (meaning that each integer is 2 bytes), so you send 6 bytes.
But in the receiver, you read characters, you have to replace this by:

Changing char  to int  for the 3 variables in the receiver side
Also here, change the names
Remove the constants for the length (64)
Instead read the code as you write it:
int xAxis;
radio.read(&xAxis, sizeof(int));

& means: address, the read function stores the value in xAxis (so you don't have to copy it afterwards).
Also print out the value after the read so you can check it.

Thank you this program does work. But even if the joysticks are in the middle the value shown in the serial monitor is Forward, Left, and Up(the first if statements in each argument). then too, the transmission glitches.

That depends on the values you get (did you check the values of x, y and zAxis?)

The values are coming insanely different

When the joystick is pulled upward the values go like 129, 0, 0 then 0, 129, 0 and then 0, 0, 129. But when it is pulled backward then the values are 16382, 0, -13872 and so.

Added if (x/y/f < 0)x/y/f = 0; and if (x/y/f > 1023)x/y/f = 1023;

Ok, also I think even then the radio communication is ok including parsing the data to variables ... So the only thing left (if not already solved) is the input from the joystick.

I tested the joystick inputs in another program just for printing the values of the joysticks. The default value of the joystick is 500 and the maximum is 1023 and the minimum is 0.

The values of the joystick are alright on the transmitter side. But I'm not sure of the receiver.

Thank you Michel. Now the code works just fine but it does glitch rarely. I forgot to add &x, &y, and &f in the transmitter.


text:
What else is consuming Data Segment reported by avr-size?
I am facing a low memory available problem in arduino. I am compiling a big sketch for arduino mega 2560.
Analysing a .elf file, the avr-size tool gives:
text    data     bss     dec     hex filename
68524   4392    2560   75476   126d4 C:\Users\LEAN...

And the avr-nm (avr-nm doc) shows only variables with t, T, b, d and B. The following is how the command is executed (the output is being saved in a file called test.txt).
   avr-nm -a -td -C -l --size-sort -r x.elf >> test.txt

Then, I perform a sum to confirm the avr-size result using this Python script:
f = open("test.txt", "r")
lines = f.readlines()
f.close()

su = 0
dsum = 0
bsum = 0
tsum = 0
gsum = 0
for line in lines:
    #print(line, end="")
    s = line.split()
    try:
        val = int(s[0])
        su = su + val
        if(s[1].lower() == 'b'):
            bsum = bsum + val
        if(s[1].lower() == 'd'):
            print(line)
            dsum = dsum + val
        if(s[1].lower() == 't'):
            tsum = tsum + val
        if(s[1].lower() == 'g'):
            gsum = gsum + val
    except:
        print("ERR: ",s[0])
print("\n\nSIZE: ", su)
print("SIZE d/D: ", dsum)
print("SIZE b/B: ", bsum)
print("SIZE t/T: ", tsum)
print("SIZE g/G: ", gsum)

and the sum result of each var type is:
SIZE:  71015
SIZE d/D:  135
SIZE b/B:  2560
SIZE t/T:  68320
SIZE g/G:  0

The question: Here d/D sums is 135 bytes. So, why the data segment reported by avr-size is 4392 bytes? how to find out what is occupying this space?
Best Regards.
EDIT
It must be a Joke!
I have a lot of like this in the code:
Serial.print("QTDE REG: ");

Just changing for this:
Serial.print(F("QTDE REG: "));

I have reduced by 10 the .data size!
So, in this way Serial.print("QTDE REG: "); "QTDE REG: " is stored as a global variable?? I thought the compiler would save locally.
EDIT 2
I have an advance running avr-objdump -s -j .data x.elf as suggested by Edgar below. Now I see that all my string literals are in data! For example:
void myFunction(){
    ...
    sprintf(buf, "{\"name\":\"Intervalo de Registros\",\"value\":\"%d\", \"unit\":\"C\"},", (int)settings.treg);
    ...
}

avr-objdump -s -j .data x.elf shows:
 800660 2c007b22 6e616d65 223a2249 6e746572  ,.{"name":"Inter
 800670 76616c6f 20646520 52656769 7374726f  valo de Registro
 800680 73222c22 76616c75 65223a22 2564222c  s","value":"%d",
 800690 2022756e 6974223a 2243227d 2c007b22   "unit":"C"},.{"

EDIT 3
As commented, all string literals are saved in the (SRAM). So, the problem is, I have a lot of strings literals spread across different functions. How to save this amount of SRAM? Note that using F() for sprintf gives compilation error.
Is there any way to put the literal in stack (release memory when function returns) and not in the global area? Is F() the only solution?
============ SOLUTION ============
For now, I have found this solution: use sprintf_P with PSTR(...) in the same way of F(...):
sprintf_P(buf, PSTR("{\"name\":\"Intervalo de Registros\",\"value\":\"%d\", \"unit\":\"C\"},"), (int)settings.treg);

I will test more...
Thanks for all clarification!
Best Regards!

all the string literals are copied to SRAM with older versions of avr gcc. F macro ensures they are read from flash.

@Juraj but when the function returns the space allocated is released? seems that all my literals goes to data segment, which is a place for global vars.

sorry, it should be "all the string literals are copied to SRAM at boot"

https://www.arduino.cc/reference/en/language/variables/utilities/progmem/#_the_f_macro

Most of the missing data section is probably made of string literals.
When you write something like
Serial.println("Hello, World!");

the string "Hello, World!" is implemented by the compiler as an
anonymous array of characters, and the address of this array is
provided to the println() method. Since the array is anonymous, it
doesn't show up in the output of avr-nm. You can check that this is
the case by looking at the actual contents of the section:
avr-objdump -s -j .data x.elf

And you can avoid this by wrapping the strings in the F() macro:
Serial.println(F("Hello, World!"));

This has the effect of keeping the string in flash, and passing the
flash address to the println() method. Note that this is actually a
different, overloaded method, that knows how to retrieve the character
data from flash.

Edit: Adding some clarifications.
All this complexity about flash vs. RAM storage comes from the fact that
the AVR uses a Harvard architecture, where RAM and flash are
in different address spaces, accessed through different memory buses
using different machine instructions. Unlike C, the C++
language has no notion of address spaces, and the compiler simply
assumes that any pointer to function holds a flash address, whereas any
pointer to data holds a RAM address.
Per the rules of the language, a string literal has the type
const char *, and a function that should be able to accept a string
literal should take a const char * parameter. Since these are pointers
to data, when you dereference them the compiler emits the machine
instructions that are appropriate for reading RAM. This is why the
compiler puts all string literals in the .data section of the flash: at
program startup, the C runtime copies them to the .data section of the
RAM, making them accessible to those machine instructions.
The current solution to avoid this useless copy involves a bunch of
preprocessor macros like F(), PSTR(), PROGMEM,
pgm_read_byte()... that expand to compiler extensions or inline
assembly. These allow you to pass around the flash addresses of string
literals disguised as regular data pointers. These pointers should never
be dereferenced with the regular operators of the language (* and
[]), but only through the pgm_read_*() macros. And they should only
be given to functions that do expect these kind of pointers, like
sprintf_P() or Print::println(const __FlashStringHelper *), which is
the println() that gets invoked when using the F() macro.

Is there any way to put the literal in stack

Yes, there is, but it has to be done explicitly:
PROGMEM const char greeting[] = "Hello, World!";

void say_hello() {
    char stack_copy[strlen_P(greeting)+1];
    strcpy_P(stack_copy, greeting);
    Serial.println(stack_copy);
}

As you have already noticed, it is preferable to not put the strings in
RAM at all, and instead use functions like sprintf_P that expect
flash-based strings. However, if you need to use a library function that
expects a RAM-based string, you can use this trick to avoid permanently
committing it to RAM.

Using F() on println saves me about 100bytes. Executing avr-objdump as sugested I see the string of sprintf(buf, "{\"name\":\"Intervalo de Registros\",\"value\":\"%d\", \"unit\":\"C\"},", (int)settings.treg); in it. All strrings are stored in this area?

@LeandroIP: all the string literals, unless using the F() macro or, equivalently, PSTR().

Thanks @Edgar, PSTR() solves the problem with sprintf_P. See SOLUTION in answer for details.


text:
ESP8266 crashing with blue LED always on and without the word "w_flash" on startup
When using Arduino SoftwareSerial with ESP8266, the blue led turns always on every time I reset the circuit by power. The only way to take the ESP working again is reflashing with the SDK 2.2.1, AT Firmware.

Have tested AMS1117 and LM317 as Power supply;
I'm using level converter 3V3 <-> 5V;
Have choosen different pins on Arduino for TX and RX;
No problem when using Hardware Serial pins with no SoftwareSerial;
My application works fine. The problem arises when I power off and power on and using SoftwareSerial.

Have noted a difference on the startup of ESP8266 after it gets stuck.
Here is the original startup (at 74880bps), ESP working normally
 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x40100000, len 2592, room 16
tail 0
chksum 0xf3
load 0x3ffe8000, len 764, room 8
tail 4
chksum 0x92
load 0x3ffe82fc, len 676, room 4
tail 0
chksum 0x22
csum 0x22

2nd boot version : 1.7(5d6f877)
SPI Speed : 40MHz
SPI Mode : QIO
SPI Flash Size & Map: 8Mbit(512KB+512KB)
jump to run user1 @ 1000

rf cal sector: 251
freq trace enable 1
rf[112] : 03
rf[113] : 00
rf[114] : 01
w_flash <-- check the presence of this word

SDK ver: 2.2.1(6ab97e9) compiled @ Jun  7 2018 13:59:14
phy ver: 1136_0, pp ver: 10.2

⸮⸮j⸮l <-- here ESP is ready for AT commands at 115200bps. This is the word "ready" at 115200

Now, when the problem arises
 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x40100000, len 2592, room 16
tail 0
chksum 0xf3
load 0x3ffe8000, len 764, room 8
tail 4
chksum 0x92
load 0x3ffe82fc, len 676, room 4
tail 0
chksum 0x22
csum 0x22

2nd boot version : 1.7(5d6f877)
SPI Speed : 40MHz
SPI Mode : QIO
SPI Flash Size & Map: 8Mbit(512KB+512KB)
jump to run user1 @ 1000

rf cal sector: 251
freq trace enable 1
rf[112] : 03
rf[113] : 00
rf[114] : 01

SDK ver: 2.2.1(6ab97e9) compiled @ Jun  7 2018 13:59:14
phy ver: 1136_0, pp ver: 10.2

Someone knows what w_flash means?
EDIT
I solve the problem by creating my own firmware with arduino IDE for ESP8266. Seens to be some type of bug in AT firmware, maybe! Now I can pass more tasks for ESP8266, saving arduino memory or even removing the need for an arduino board.
Thanks to everyone who helped =]

SoftwareSerial at 115200 baud does not work.

cause: 2 is never good. your esp8266 is underpowered or has to high RF TX power enabled

@Majenko On Arduino, SoftwareSerial sends command to ESP to change to 19200 baud. Then runs SoftSerial.begin(19200)

@LeandroIP - SoftwareSerial won't be able to send the command reliably if it is set to 115200 to start with.  I suspect its your power supply, do your PSUs push out enough amp?  (can't remember what an ESP8266 requires)

Please note: 1. SoftwareSerial will not work at those high frequencies. And, please, be clear about your setup. Are you using SS on the arduino or on the esp? What pins? How are both circuits powered?


text:
Same code working on Arduino IDE but not in PlatformIO IDE
I'm running into this weird problem. My code is working just fine when I upload it to an ESP32 from Arduino IDE. That same code is not working when I upload it using PlatformIO IDE. The same libraries versions are being used on both environments.
I've been reading that in PlatformIO you might have to make use of forward declaration (something that Arduino IDE solves out of the box). I do not know if this is the case. And if it is... I do not know how to apply it.
Can someone help me out with this?
#include <Arduino.h>
#include <DHT.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

#define DHTPIN 23
#define DHTTYPE DHT11

LiquidCrystal_I2C lcd(0x27,16,2);

DHT dht(DHTPIN, DHTTYPE);

void setup() {

  lcd.init();
  lcd.backlight();

  Serial.begin(115200);
  dht.begin();
}

void loop() {
  delay(2000);
  float h = dht.readHumidity();
  float t = dht.readTemperature();

  if (isnan(h) || isnan(t)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }

  Serial.print(F("Humedad: "));
  Serial.print(h);
  Serial.print(F("% Temperatura: "));
  Serial.print(t);
  Serial.println(F("°C "));

  lcd.setCursor(0,0);
  lcd.print("Humedad: ");
  lcd.println(String(h));
  lcd.setCursor(0,1);
  lcd.print("Temp.: ");
  lcd.print(String(t));
}

EDIT:
platformio.ini
[env:fm-devkit]
platform = espressif32
board = fm-devkit
framework = arduino
monitor_speed = 115200
upload_port = COM9
lib_deps =
    adafruit/DHT sensor library@^1.4.3
    adafruit/Adafruit Unified Sensor@^1.1.5
    marcoschwartz/LiquidCrystal_I2C@1.1.2

What exactly does "not working" mean here? Do you get compilation errors? Or uploading errors? Or is the behavior of the code different than expected after successfull compilation and upload?

can you post your platformio.ini file? The problem could be that you are using a different version of the ESP-IDF which is pre-compiled in the arduino environment (which is not neccessarily the case when working with platformio).

@chrisl The code just compiles and runs... but it does not print anything to the display

@SimSon I added the plaformio.ini

hmm, the .ini looks like I'd expect it, except that I don't know that board (I assume that you'd choose the exact same board in the Arduino IDE). Maybe you could try to use board=esp32dev in case the pin mapping is messed up some how for that board (the pin mapping should not depend very much on the actual board as long as it's based on an ESP32. But that's my only idea here and I'm actually not sure if that makes much sense...

does not work either... thanks anyway

Does the code print to the serial monitor as expected? Could you try removing the “°” character in F("°C ")? Could you try removing the casts to String (lcd.println(h); instead of lcd.println(String(h));, same for t)?

And what is on the serial interface? (You can always add more trace messages to figure out how far it gets)

yes it does print to the serial monitor as expected

Verbose compile and link output for both environments might be of some use.


text:
What kind of USB cable do I need for my Arduino NANO 33 BLE W/ HEADERS?
I have recently purchased an Arduino Nano from the main site, but it did not come with a USB cable for programming it. I have also checked out the Arduino site and there was no reference for what type of cable I needed. I saw that there was a USB 2.0 CABLE TYPE A/B on the site but I'm not sure that it is the one that I require.
Does anyone know which cable I should buy? Thank you in advance!
Edit: To clarify, I checked out the Arduino Store https://store.arduino.cc/usa/

what is main site? .... we have no idea what you bought ... please provide a link or a picture ....  check this out https://www.cablestogo.com/learning/connector-guides/usb

On Arduino.cc Store I see a Micro USB port on the image


text:
Advice needed for powering Multiple HX711 with Arduino Mega
I have a project where I need to use multiple load cells (6-8), with individual HX711 for each load cell, which need to be powered simultaneously. I am not sure if I can power all the HX711 with 5V and GND pins of Arduino Mega or I need to use a separate 5V DC power supply and connect the VCC and GND of HX711 pins to it and connect the DT and SCK pins to the digital pins of the Mega. Will such an arrangement work?  Thanks for your time in advance. The link to the HX711 datasheet is here.

How much current does every HX711 need, including the load cell?

Hi Chrisl, as per the HX711 the digital supply current is 100 μA. I have edited my question to add the link to the HX711 datasheet. But the datasheet can also mention that - Digital power supply (DVDD) should be the same power supply as the MCU power supply. So I am unsure if the Mega can directly power 6-8 load cells.

The mega can theoretically power about 5000 HX711s.

And how much current does the load cell draw? You can easily draw 500mA from the 5V supply line on a Mega. (and the 100 μΑ load from a single HX711 is 1/5,000 of that amount.)


text:
Problems integrating Reed Switch and Solenoid Lock in Arduino Code
I am trying to integrate solenoid lock, reed switch in my Arduino Code. The flow that I am trying to achieve is - first, the solenoid lock is set to LOW and then the program checks if reed switch is High or Low. Only if its High I want to proceed further. However, even when the reed switch is HIGH the program is not executing further. Here is my code below:
    #include<HX711_ADC.h>
    #include<math.h>

    //pins for lock
    int solenoidPin = 7;

    //pins for reed switch
    int reedSwitch = 2;
    bool reedSwitchStatus;

    //pin for led
    int led_pin= 9;

    void setup()
    {
      Serial.begin(38400);
      pinMode(solenoidPin, OUTPUT);
      pinMode(reedSwitch, INPUT);

      doorUnlock();
    }

    void loop()
      {}

    void doorUnlock()
    {
      digitalWrite(solenoidPin, LOW);
      delay(5000);
      checkReedSwitchStatus();
    }

    void checkReedSwitchStatus()
    {
      reedSwitchStatus = digitalRead(reedSwitch);

      if(reedSwitchStatus == 1)
      {
        Serial.println("Beginning Transaction");
        beginTransaction();
        }
      if (reedSwitchStatus == 0)
        {
          Serial.println("Ending trasaction");
          endTransaction();
          }
      }
      void beginTransaction()
      {
      digitalWrite(led_pin, HIGH);
      delay(500);
      digitalWrite(led_pin, LOW);
      delay(500);
      }

My issue is the beginTransaction function is never executed. Serial monitor continuously prints 'Beginning Transaction'. Attached the screenshot of the serial monitor. Please suggest me what is the error in my code. Thanks in advance!

How do you know, that the beginTransaction() function is not executed. Please include the full code. Also: Do you have an external pullup or pulldown resistor for the reed switch?

Hi Chrisl, I have used an external pull up resistor for the reed switch. I have also edited my question to add the beginTransaction() function in the code. The function is not getting executed because the LED does not blink.

The problem is, that you don't initiate the LED's pin to an output. On reset the pin is configured as input. Doing a digitalWrite(led_pin, HIGH) in this state just enables the internal pullup resistor. If you measure the voltage without the LED connected, it will be 5V, but since the pin only provides a very small amount of current through the pullup resistor, the LED cannot light up when connected.
You need to configure the LED's pin as an output through
pinMode(led_pin, OUTPUT);

in your setup() function.
So actually the beginTransaction() function was correctly executed. You just couldn't see it.

Thanks!! That corrected the issue.


text:
Put Arduino in DFU mode (no RST pin)
The instructions to put the Arduino into DFU say I should shortcut briefly the 2 leftmost ICSP headers next to the USB port.

But my board does not have them. Does anybody know what are the right headers or if it is at all possible to set my board into DFU mode?

It has a CH340G usb serial adapter, which cannot be reprogrammed and has no DFU mode.
If you are looking for DFU mode because it's not detecting correctly and you think it's because the 16u2 isn't programmed correctly, the problem is probably that you need to install the CH340G drivers, not the normal Arduino drivers.
If you are looking for DFU mode for some project that requires custom firmware on the CH340G, that board is not usable for that project, you will need to get a faithful clone of the Uno, which has the 16u2, not the CH340G based ones
EDIT
If you want to use your Arduino as a HID device you need the DFU mode
If you use this library which supports UNO/MEGA/Leonardo/(Pro)Micro/ any 8u2/16u2/at90usb8/162/32u2/32u4 compatible board and some more BUT you need an 16u2 chip

I guess no HID on than one then. Thanks.

See my edit - NO

This board doesn't use as USB adapter an ATMega16u2 with Arduino firmware. It uses a simple USB chip CH340. So you can't put it in DFU mode to upload a firmware.


text:
Increase or decrease the brightness of Nextion display
I have a nextion display. I want to implement this issue of it. Start the program. If for example I don't touch the display for 15seconds, it should to turn off its brightness. If I touch the screen on any point, it should to increase its brightness.
For this I m build this code:
In PreinitializeEvent of page 0, I have insert this code:
tm0.tim=0
tm0.en=1
dim=30

In Touch Release Event of page 0, I have insert this code:
dims=100

But if I try to start the program, the brightness is always the same. Not increase.
/EDIT
I use Nextion Edito 0.58

PreinitializeEvent is a View of NExtion IDE

@bircastri, in this stackexchange.com space we primarily concern our selves with answering questions about developing using the Arduino IDE.  While the Nextion IDE looks interesting, some may consider it off topic.  Also, consider the Nextion IDE its self may not have the feature you are looking for.

dim sets the brightness for that session
dims sets the default brightness and remains even after reset.
I've found the most effective way is to add the code to the page's preinitialize tab.
Obviously if you use dims on page 0 all the pages will have that brightness

The original question has been improved (which is appreciated) to include the IDE which the poster is using.  In this stackexchange.com space we primarily concern our selves with answering questions about developing using the Arduino IDE. While the Nextion Editor looks interesting, some may consider it off topic.
For those who come here interested in controlling the brightness of their Nextion Display and are using the Arduino IDE, there is this answer:
There appears to be several Nextion Arduino Library efforts to choose from.  If you are using this Nextion Display Library, here is the example code which set the screen brightness.  The part of the code which sets the screen brightness is rather simple and resides in the Arduino loop() function.  In the loop() function the brightness is set repeatedly as the program continues to run:
void loop() {
  int brightness = analogRead(A0);
  int bright = map(brightness, 0, 1024, 0, 100);
  String dim = "dim=" + String(bright);
  myNextion.sendCommand(dim.c_str());

}

For those of you using the Nextion editor and the Nextion Arduino Libraries, there is this github.com Issue which talks about adding multiple missing Nextion features including a screen brightness function. This issues appears to still be OPEN (Bad support? / Bad house-keeping?). But is over a year old so may have be incorporated.  If so, here is the example code from that link:
/**
* Set the brightness of the display.
*
* @param buffer - number (0 - 100).
*/
bool setBrightness(byte buffer);

Since you didn't specify which Nextion Library you are using and since you didn't show us the simplest version of your code which still does not work, we have to guess at the most probable answer.

I have added this information of the first post. I use anyway Nextion Edito 0.58v


text:
How to convert char[12] to byte[6]
I am trying to convert a char[12] array that contains a Mac Address into a byte[6] in order to use within the Ethernet.begin method. I have tried various methods from online, but had little success to date. The char array currently contains "A4BDC334688C" and i would like a byte array containing { A4, BD, C3, etc }.
The following is extremely close to working, with the output of the following
"File Opened.
A4BDC334688C
A4
9D
C3
34
68
6C" With BD incorecctly converting to 9D, and 8C becomming 68.
#include <SPI.h>
#include <SD.h>
#include <ArduinoJson.h>

byte ByteMacAddress[6]; // RESERVED MAC ADDRESS
StaticJsonDocument<200> doc;

int ShotCount = 0;
byte buf[40];

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

  //Initialise SD Card for Config
  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
  }

  // open the file for reading:
  File ConfigFile = SD.open("Config.txt");
  if (ConfigFile) {
    Serial.println("File Opened.");
  } else {
    Serial.println("error opening Config.txt");
  }

  //Deserialize Json Config in File
  delay(5);
  DeserializationError error = deserializeJson(doc, ConfigFile);
  ConfigFile.close();
  // Test if parsing succeeds.
  if (error) {
    Serial.print(F("deserializeJson() failed: "));
    Serial.println(error.c_str());
    return;
  }

  char* SDMacAddress = doc["MacAddress"];
  Serial.println(SDMacAddress);

  char arr[12];
  strcpy(arr, SDMacAddress);

  auto getNum = [](char c){ return c > '9' ? c - 'a' + 10 : c - '0'; };
  byte *ptr = ByteMacAddress;

  for(char *idx = arr ; *idx ; ++idx, ++ptr ){
    *ptr = (getNum( *idx++ ) << 4) + getNum( *idx );
  }

  //Check converted byte values.
  for( byte b : ByteMacAddress )
    Serial.println( b, HEX );
}

void loop(){
  //Maintain DHCP Lease
  //Ethernet.maintain();

  //GetShotCount();
  delay(500);
}

Have you seen the function strtol(buf, &targetvariable, BASE) like it is used in the answer to this question? You could use it do convert each byte (2 characters) individually or even - via using a union - convert the whole string at once.

In getnum you don't consider upper case letters. Are the letters all lower case or all upper case?

usually the binary representation of MAC address is in reverse order then the hex string

@chrisl Thank you also for your answer, I really appreciate everyone who took time to help me.

Please see the comments in the code:
// SDMacAdress is zero terminated
// (it should be because you use strcp not strncp)
// char arr[12]; you need one extra byte for the zero
char arr[13];
strcpy(arr, SDMacAddress);

auto getNum = [](char c)
{
  // you forgot upercase HEX letters (A-F)
  // don't use sophisticated code
  // the best programmers produce understandable code IMHO at least ;-)
  // perhaps you copied it from the internet
  // return c > '9' ? c - 'a' + 10 : c - '0';

  if ( c >= '0' && c <= '9' ) return c - '0';
  if ( c >= 'a' && c <= 'f' ) return 10 + c - 'a';
  if ( c >= 'A' && c <= 'F' ) return 10 + c - 'A';

  return 0;
};

byte *ptr = ByteMacAddress;

for(char *idx = arr ; *idx ; ++idx, ++ptr )
{
  *ptr = (getNum( *idx++ ) << 4) + getNum( *idx );
}

Im kicking myself for that, the uppercase was the issue. And you are correct, that is copied from the internet but I had also made the same silly mistake in my attempt. Thank you very much for your time and help.

I should mention, that @chrisl had had this idea before me. I just gave you an example of how to do it. Please upvote his/her (?) comment above. I did it already. ;-)

I wish I had the rep to upvote you all, alas i am a newbie here.

It is not clear why you are trying to implement it from scratch. If your input is always properly formatted you can perform the conversion in one call to sscanf
char arr[] = "A4BDC334688C";
byte ByteMacAddress[6];

sscanf(arr, "%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx",
  &ByteMacAddress[0],
  &ByteMacAddress[1],
  &ByteMacAddress[2],
  &ByteMacAddress[3],
  &ByteMacAddress[4],
  &ByteMacAddress[5]);

Of course, you can also implement it [more elegantly] through a cycle, i.e. sscanf it one byte at a time.


text:
Ethernet.h Ethernet.Begin(mac) only connects if i have a LiquidCrystal object from LiquidCrystal.H
I have the following code;
#include <Ethernet.h>
#include <SPI.h>
#include <LiquidCrystal.h>

LiquidCrystal lcd(31, 30, 29, 28, 27, 26, 25, 24, 23, 22);
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
EthernetClient client;

void setup()
{
  Serial.begin(9600);
  //client.begin(mac);
  //Init Ethernet Comms
  Serial.println(F("Start."));
  while (!Ethernet.begin(mac) == 0) {
    Serial.println(F("Network Error"));
    delay(200);
  };
  Serial.println(F("Connected"));

}

void loop() {}

As it is above it gets out of the while loop. However, if i remove the line LiquidCrystal lcd(31, 30, 29, 28, 27, 26, 25, 24, 23, 22);It will then fail to connect, and stay in the loop. Im at a complete loss here as the Ethernet shield and 2x16 LCD are unrelated devices, and if anything id expect the addition of used pins to cause issue, not the removal.
Edit: I should note this is occurring on two devices, one Mega one Uno.
2nd Edit: As pointed out by Juraj in the comments, this can be resolved using Ethernet.Init(CS_Pin) where CS_Pin is an unused pin, in my case D9.

do you have SD card inserted? if yes remove it or set the SD CS pin 4 HIGH. And I would add Ethernet.init(10);. What happens if you disconnect the LCD?

You beauty, that was exactly the issue. Oddly i have been using both the SD card and Ethernet port without issue for a while now, but only recently ran into this issue.


text:
How to use the Osepp proximity module with arduino uno
I have recently purchased an Osepp proximity module at Radio Shack and am attempting to use it with my Arduino Uno. How should I connect it to the
Arduino, and what library do I use?

What's an "Osepp proximity module"?  Links please.

https://www.osepp.com/electronic-modules/sensor-modules/75-ir-proximity-sensor-module

Well, it states that it uses a "GP2Y0D805Z0F", so googling for that plus Arduino gives plenty of results, including an Adafuit one, and they are notoriously good with their documentation and example code, so you should check that out first.

That's how to use the "GP2Y0D805Z0F". I'm trying to connect the Osepp board to the arduino, not the raw distance sensor.

With wires. Connect the correct pins on the board (I2C pins...) to the Arduino's I2C pins. The pins are shown in the schematic linked from that page.

Forgive me for being completely new to Arduino, but I have no idea how to follow that diagram.

Looking over your question, @Majenko's answer and the comments - you already have everything you need except for some work on your part.  If you are still lost - I would suggest to put everything you have bought aside, find a posting where someone has done the work, buy exactly the same items and copy the posting step by step.  Like this posting which uses similar parts.

How should I connect it to the Arduino

Refer to the schematic in the page you link to. That shows you which pin is which.  It's I2C, so there's just 2 data pins, power, and ground.

and what library do I use?

The Osepp board is a GP2Y0D805Z0F connected to a PCA9534 IO expander. There is a library here.

I have no idea which pins on the arduino itself besides maybe the 5v and gnd. Is the data cable analog or digital? Is the clock cable even necessary? If so, what pins will work with it?

Look at the pretty pictures of the board and the arduino and match the names. Learn what I2C is. Understanding schematics is absolutely fundamental to working with electronics.


text:
Adafruit Circuit Playground Express fails to upload
When uploading code to the Adafruit Circuit Playground Express, I have found that most of the time it fails to upload saying that the port is busy. There seems to be no logical reason behind this, as it uploads perfectly to an Arduino Uno (Yes, I did switch the board types). What am I doing wrong?
Here is the error:
processing.app.debug.RunnerException
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:152)
    at cc.arduino.UploaderUtils.upload(UploaderUtils.java:77)
    at processing.app.SketchController.upload(SketchController.java:732)
    at processing.app.SketchController.exportApplet(SketchController.java:703)
    at processing.app.Editor$UploadHandler.run(Editor.java:2075)
    at java.lang.Thread.run(Thread.java:748)
Caused by: processing.app.SerialException: Error touching serial port '/dev/ttyACM1'.
    at processing.app.Serial.touchForCDCReset(Serial.java:107)
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:136)
    ... 5 more
Caused by: jssc.SerialPortException: Port name - /dev/ttyACM1; Method name - openPort(); Exception type - Port busy.
    at jssc.SerialPort.openPort(SerialPort.java:164)
    at processing.app.Serial.touchForCDCReset(Serial.java:101)
    ... 6 more

Operating system: kubuntu linux 64 bit
EDIT: Never mind. In the end I used chmod a-x /usr/sbin/ModemManager to remove execute permissions from every user, and that worked without any noticeable repercussions to my system. For anyone who wants to do the same, make note of the original permissions, so you can change it back if you have to.

The actual error part of that stack trace is:
Port name - /dev/ttyACM1; Method name - openPort(); Exception type - Port busy.

You have something else using /dev/ttyACM1.  If you don't yourself have something open, such as a serial terminal or the Arduino serial monitor, then the most likely culpret is modemmanager.

https://majenko.co.uk/blog/diagnosing-arduino-problems-linux


text:
Arduino Core for the Raspberry Pi Pico
I recently bought a Raspberry Pi Pico to play with, and am attempting to upload my first program to it the Arduino way, as my own operating system rather than a c++ program over an existing operating system (meaning to replace the built-in Raspberry Pi Pico operating system which runs MicroPython, not in the sense of running Linux, Windows, Mac, or any derivative or fork). I have not found any record of people hacking it like that - is it possible? If so, how would I go about it? Sorry if this is in the wrong Stack Exchange.

operating system? on a pico? maybe an RTOS, but i doubt an OS.

@dandavis What I mean is that an Arduino program is an operating system, albeit extremely minimal and simplistic. Will edit for clarity.

Technically an OS is just a program which has a lot of functionality including advanced memory management. I have edited for clarity.

@nerdguy, don't have a good answer for you, but maybe phrasing that would help.  What you're looking for is "Arduino Core for the Raspberry Pi Pico." in the sense that the UNO uses the Arduino Core for the AVR.  I see one thing on github, but it's an initial commit, and probably with no substance.

@timemage I wasn't entirely certain how to phrase it - thank you!

I recently saw an announcement that Arduino is going to officially include the Raspberry Pico as target board in their Arduino IDE. But I have not found a repo proofing that.

Official support.
Apparently there's official support for it, now anyway.
I was digging around in the Arduino-mbed core, trying to help someone else, specifically in the boards.txt and spied the line:

pico.name=Raspberry Pi Pico

Unfortunately, I don't have any way to give it a proper test as I don't have one of these.  But I did go so far as to install the core and compile a simple hello world program.
In boards manager
Search for "mbed rp2040"; these names sometimes change, but those terms work well now.  You can see in the lower item, I have version 2.0.0 installed.

Board menu selection
Tools/Board/Arduino Mbed OS RP2040/Raspberry Pi Pico

Seems to work.
As you see it at least builds without error.  As I said, I'm unable to give it a real test.  But that at least looks promising.

It is worth mentioning this excellent alternative to the Arduino one from Earle F. Philhower. It seems well-maintained and doesn't depend on Mbed OS, so it leaves more space (ram and flash) for your application.
Here an informal comparative list.

This alternative doesn't require the Pico to have a serial port (which it won't have when new), but rather can upload to a Pico in bootloader mode. See https://arduino.stackexchange.com/questions/84372/

Here is the library for the Arduino IDE and a Raspberry Pi pico.
https://github.com/lrusak/Arduino-Core-Pico
Just install normally as a .zip.

Thank you! Sorry your original post didn't work out

Yeah, this does look to be more along the lines of what's being asked for.  I dug around that repo a bit and I'm a little skeptical that it actually works though.  Seems to be very early work in progress.

This doesn't seem to be a complete Arduino Core, may files and definition are missing.