text:
Rc receiver giving wrong values when controlling servo
So I'm building a helicopter. That why I need a receiver (tgy 9x) to read the values from my controller. Those values get passed to my Arduino due where some calculation happen and then get sent to the servos.
Now the problem is the moment I move my servo all the value I get from my receiver immediately become gibberish.
The values I should get and get when I am not sending anything to my servos. These values are in microseconds.
Channel1 Channel2 Channel3 Channel4
1486     1484     1482     1472
1486     1484     1482     1472
1486     1484     1482     1472
1486     1484     1482     1472

What I get after moving the servo. These should be between 1000 and 2000.
Channel1 Channel2 Channel3 Channel4
1495     18660    1105     17182
1495     2337     5667     3070
8828     7674     8795     6198
10289    7674     8795     11404

The Arduino gets power from the USB (at the moment) and the servo from the ESC of my motor. All the grounds are connected. There is only one servo hooked up and all wires from the receiver are not anywhere near any power lines or servos.
So the question is why is the receiver giving me gibberish and how do I fix it.
Right now I have commented everything out except this:
RC_controller.h
#ifndef RC_controller
#define RC_controller

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

void RC_init();
void calc_input0();
void calc_input1();
void calc_input2();
void calc_input3();
void calc_input4();
void calc_input5();
#endif

RC_controller.cpp
#define RC_NUM_CHANNELS  8
uint32_t volatile rc_start[RC_NUM_CHANNELS];
uint32_t volatile rc_shared[RC_NUM_CHANNELS];
uint32_t volatile rc_raw[RC_NUM_CHANNELS];

int rc_channels_pin[8] = {2, 3, 4, 5, 6, 7, 8, 9};

void calc_input0() {
 int identifyer = 0;
   if (digitalRead(rc_channels_pin[identifyer]) == HIGH) {
     rc_start[identifyer] = micros();
   } else {
     rc_raw[identifyer] = (uint16_t)(micros() - rc_start[identifyer]);
   }
}

...

void RC_init()
{

 for (byte i = 0; i > RC_NUM_CHANNELS; i++)
   pinMode(rc_channels_pin, INPUT);

 attachInterrupt(digitalPinToInterrupt(rc_channels_pin[0]), calc_input0, CHANGE);
 attachInterrupt(digitalPinToInterrupt(rc_channels_pin[1]), calc_input1, CHANGE);
 attachInterrupt(digitalPinToInterrupt(rc_channels_pin[2]), calc_input2, CHANGE);
 attachInterrupt(digitalPinToInterrupt(rc_channels_pin[3]), calc_input3, CHANGE);
 attachInterrupt(digitalPinToInterrupt(rc_channels_pin[4]), calc_input4, CHANGE);
 attachInterrupt(digitalPinToInterrupt(rc_channels_pin[5]), calc_input5, CHANGE);
}

main.cpp
...
void setup()
{
Serial.begin(115200);
  Wire.begin();
#if I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
    Fastwire::setup(400, true);
#endif
for (int a = 0; a < 3; a++)
  swashplate[a].attach(10+a, 1200, 1800);
RC_init();
}

void loop()
{
if (rc_raw[0] < 2000)
  {
    swasplate[0].write(rc_raw[0]);
  }

  Serial.print(rc_raw[0]);
  Serial.print("    ");
  Serial.print(rc_raw[1]);
  Serial.print("    ");
  Serial.print(rc_raw[2]);
  Serial.print("    ");
  Serial.print(rc_raw[3]);
  Serial.print("    ");
  Serial.print(rc_raw[4]);
  Serial.print("    ");
  Serial.print(rc_raw[5]);
  Serial.print("    ");
  Serial.println();
}

You could well have a problem with the servo introducing power supply noise.  A literal Arduino is a very poor fit in this application - too big, too high a supply voltage, too unreliable in physical implementation.  Typical solutions are more integrated with a lot more attention to the engineering of how the parts work together and avoid interfering with each other - the flight control projects that used Arduino back in their early era have long since moved on to more suitable custom boards.

Can you name an example of these "more suitable custom boards"? Do you mean preprogrammed flight controllers? The thing is I still want to program it myself ...

Any relevant search engine or ecommerce site will be full of boards for the well known open source flight control projects; of course you need to pay attention to details and look at other's experience.  I've always made my own, so no help there.  At this point having a distinct radio receiver connected via PWM seems a bit antiquated compared to an onboard radio as well - part of the problem with stringing modules together is that it means a larger, heavier, more hazardous test aircraft, while compact solutions mean featherweight things you can fly off the lab bench.

So when you make your own, you place the receiver and CPU on the same board?

Yes, like most now do.  It's not only more compact but a more natural interface, without going through the legacy PWM or even still-multiplexed PPM.

I found the problem. The problem was with the interrupts when the program was running and doing calculations at that moment the Arduino would be interrupted and stop in the middle of it, and change the value it was doing calculations with. This somehow caused the Arduino to sent interference over the signal wires. Reading the signals with a reading guard fixed the problem.
void read_inputs()
{
  noInterrupts();

  byte identifyer = 0;
  rc_shared[identifyer] = rc_raw[identifyer];

  ...

  interrupts();
}


text:
Do I need to power off the Arduino board before doing something?
Is it safe to build a circuit while the Arduino board is powered?
Should I power the board only when I have to upload the program?

which switch are you talking about?

Don't be like me, but I keep my Arduino (made in china) connected via USB to my laptop when prototyping. Many times I short pins to ground accidentally, but fortunately my laptop has builtin overcurrent protection on USBs to 500mA. If it didn't the ports (or arduino pins) would be fried long time ago. To break the board all it takes is to connect arduino pin physically to ground, and then accidentally in code assign it as output (instead of input) and set to 5V.

@FilipFranik Even if Arduino boards are inexpensive (like the clone you mention sourced from China), it's no excuse for poor practice.

It is not safe, as you may accidentally connect some points, which should not be connected and destroy Arduino and/or any other part of circuit. typically legs of resistors/LEDs tends to touch other legs near them, when you are putting it in - and if it is powered, magical smoke can happened easily.
Even if you do not this kind of mistake, not everything can be put in random order without risc of damage.
So everytime you change something with circuit, disconnect power source/USB first. And if you have big capacitors anywhere, you better make sure, they are discharged too.
You switch on the board, when the building is done and you want to program it, or use the already present program.

It can be dangerous, not only to the Arduino, but to whatever you are connecting, if you do so with the power applied.
Current can end up flowing where it shouldn't, and components can become damaged.
However if it's something as simple as an LED then it really doesn't matter.

source: Stack Exchange

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

sort: votes


text:
FIS1100 (IMU)/ I2C/ Arduino
I am a student and currently doing a semester project. The first goal is to get accelerometer and gyroscope data from FIS1100 using the Arduino (Uno). I've got the FIS1100 Evaluation Kit user guide from my supervisor. I've simply separated the sensor PCB from the MCU and connected this sensor to an Arduino Uno as shown on this photo:

The connections are as following:

SCL (on the header of FIS) - A5 (Arduino)
SDA (on the header of FIS) - A4 (Arduino)
GND (on the header of FIS) - GND (Arduino)
3V3-to VIOREF (on the header of FIS) - 3V3 (Arduino)

I wrote this simple code, which I uploaded to the Arduino board. Unfortunately as a result, I got zeros as output.
#include <Wire.h>
const int I2C_address = 0b1101010;
long a_X, a_Y, a_Z;
float g_X, g_Y, g_Z;

long gyro_X, gyro_Y, gyro_Z;
float rot_X, rot_Y, rot_Z;

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

}

void loop() {
  recordAccelRegisters();
  recordGyroRegisters();
  printData();
  delay(800);

}

void setupFIS(){
  Wire.beginTransmission(I2C_address);
  Wire.write(0x02);
  Wire.write(0b00000000);
  Wire.endTransmission(true);

  Wire.beginTransmission(I2C_address);
  Wire.write(0x08);
  Wire.write(0b10000011);
  Wire.endTransmission(true);

  Wire.beginTransmission(I2C_address);
  Wire.write(0x04);
  Wire.write(0b00000000);
  Wire.endTransmission(true);

  Wire.beginTransmission(I2C_address);
  Wire.write(0x03);
  Wire.write(0b00000000);
  Wire.endTransmission(true);

  Wire.beginTransmission(I2C_address);
  Wire.write(0x05);
  Wire.write(0b00000000);
  Wire.endTransmission(true);

  Wire.beginTransmission(I2C_address);
  Wire.write(0x06);
  Wire.write(0b00000000);
  Wire.endTransmission(true);

  Wire.beginTransmission(I2C_address);
  Wire.write(0x07);
  Wire.write(0b00000000);
  Wire.endTransmission(true);
}

void recordAccelRegisters(){
  Wire.beginTransmission(I2C_address);
  Wire.write(0x19);
  Wire.endTransmission(false);
  Wire.requestFrom(I2C_address,6,true);
  //while(Wire.available()<6);
  a_X = Wire.read()<<8|Wire.read();
  a_Y = Wire.read()<<8|Wire.read();
  a_Z = Wire.read()<<8|Wire.read();
  processAccelData();
}

void processAccelData(){
  g_X = a_X/16384.0;
  g_Y = a_Y/16384.0;
  g_Z= a_Z/16384.0;
}

void recordGyroRegisters(){
  Wire.beginTransmission(I2C_address);
  Wire.write(0x1F);
  Wire.endTransmission(false);
  Wire.requestFrom(I2C_address,6,true);
  //while(Wire.available()<6);
  gyro_X = Wire.read()<<8|Wire.read();
  gyro_Y = Wire.read()<<8|Wire.read();
  gyro_Z = Wire.read()<<8|Wire.read();
  processGyroData();
}

void processGyroData(){
  rot_X = gyro_X/1024.0;
  rot_Y = gyro_Y/1024.0;
  rot_Z= gyro_Z/1024.0;
}

void printData(){
  Serial.print("Gyro(deg)");
  Serial.print(" X=");
  Serial.print(rot_X);
  Serial.print(" Y=");
  Serial.print(rot_Y);
  Serial.print(" Z=");
  Serial.print(rot_Z);

  Serial.print("   Accel(g)");
  Serial.print(" X=");
  Serial.print(g_X);
  Serial.print(" Y=");
  Serial.print(g_Y);
  Serial.print(" Z=");
  Serial.println(g_Z);
}

So, I really need help to get some relevant data.
And also I have doubts concerning the I2C-address of the FIS1100. In the datasheet of the FIS1100 on page 50 it is said:

the address is 0b1101010 in case when pin SA0 is left unconnected, internally there is a weak pull-down of 200k; the address is 0b1101011 in case when pin SA0 is pulled-up externally.

Now lets go again to user guide and on page 25 (schematic of pull-up/down resistors) we see that SA0 is externally pulled-down.
Question: which I2C-address should I use?

Use a i2c scanner https://playground.arduino.cc/Main/I2cScanner That is the i2c address that you should use. Try to read a status register. According to the datasheet, at startup the sensors are turned off and they will return zero.

Thanks for feedback! I've read the STATUS0 and it gives me 255

Reading STATUS0 seems to start something. What happens when you read the WHO_AM_I register ? How do you read it ? Perhaps a Wire.read() into a byte ? The Wire.read() returns -1 if there is no communication with the sensor, that -1 might turn into 255. Did you run the i2c scanner ?

I think you'll find you need to add some pull up resistors to both connections on the I2C (SDA and SCL).
Also I'm not sure what you should be pulling them up to 3.3v or 5v.  You should check if you need a level shifter or if the device you are connecting is 5v tolerant.
According to you question you should be using the address 0x6A.  0x6B is when you have an external pull up resistor, which I don't think you do have.  So your code is correct.

First, thanks a lot for feedback! Actually if to refer to the user guide (hyperlink in my post) on the page 24 you can see level-shifters. And yes, all the interface pins (SDA, SCL) are pulled properly. Even I used address 0x6A nothing - just zeros. LED on Arduino, which indicates transmission is blinking. Seems like I need to enable I2C or what.... like to give logic 1 maybe somewhere. But it is guessing

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


text:
This is a flood sensor. Moisture sensor and servo working together but it shows different errors
Sometimes the servo moves unnecessarily without moisture sensor giving out any readings.
Another problem is that the servo moves very slowly. Is there a way to counter this problem?
const int VAL_PROBE = 0; // Analog pin 0
const int MOISTURE_LEVEL = 250; // the value after the LED goes ON
#include <Servo.h>
Servo myservo;

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

void Servo(int state) {
  digitalWrite(13, state);
}

void loop() {
  int moisture = analogRead(VAL_PROBE);

  Serial.println(moisture);

  if(moisture > MOISTURE_LEVEL) {
    myservo.write(90);
  } else {
    myservo.write(0);
  }
  delay(1);
}

Try giving external power supply to Servo( not from Arduino )

@LookAlterno please elaborate

The only pin that could possibly need a pinMode is in a function that is never called.

What do you mean by that

One complete year and no answer??

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

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


text:
How to filter data of ultrasonic sensor using arduino
I am working on a project that uses ultrasonic HC-SR04 sensor to measure distance. I've connected the sensor to the Arduino Uno board, I am also using Arduino IDE to program the Arduino. The problem is that I am not getting stable readings, there is the presence of some noise in the readings. How should I filter out this noise.
Circuit connections are as follows:
Ultrasonic sensor | Arduino
VCC                 5V
GND                 GND
Trigger             12 (digital)
Echo                11 (digital)

I am using new ping to measure distance.

Having noise in the sensor data is common and normal, especially on low end sensor.
As you can imagine there is a "data science" to clean up the values, mostly based on statistic.
One of the easiest trick is to remove all values that have a difference > Xt from previous value; as you can imagine the tolerance Xt is calculated by a factor X, let's say a bit more the maximum speed you think the system will operate in time multiplies by the time since the last valid measure.
For example you expect a max distance chance of 10m in one second, so we use as tolerance 15m/s. If we don't read valid value, after 6 seconds our tolerance is 15m/s * 6s = 90m
Of course after much time maybe you just want to accept the first reading that seems valid, so you analyze 10, 100, 1000 value and see if they seems correct.
Then for a quick and dirty smoothing and cleaning if the remaining data, you can run a average on the value, there are different forms, and more value you use more stable are your output, but also less fast to follow changes.
A kallmann filter is the most common but also complex way to clean the data, but I guess in most hobbyist application is just overkill.

First off, Start a time counter. You can get the current time instant by using:
unsigned long StartTime = millis();

After that, keep counting time by using the following block:
 unsigned long elapsedTime = currentTime - StartTime;

With this you can know how much time (in ms) has passed since StartTime. In this time loop, keep reading data from the Ultrasonic sensor. As the sensor may need some time to get each reading, take a conservative delay (e.g. 100 ms). You can again increment the timer by using a goto statement. Note that you must also maintain a counter for later. In this time loop, keep adding the readings from the sensor to itself. Finally when the stipulated time is over, you can take the average by dividing the final sum of the sensor values with the counter maintained earlier.


text:
Problem with a DHT11 Temperature & Humidity sensor
I'm new in the Arduino world and today i was trying to make a simple program to show the temparature an humidity with this sensor. I made a circuit following one tutorial and nothing happend, the result was Temperature: 0 Humidity: 0.
My question is, what is wrong? Probably the sensor is broken or the code is wrong.
I also need to say that i use a 5K1 resistor in exchange of the 4.7K resistor and accidentally I connected the sensor without the resistance for a few seconds.
This is the code:
#include <DHT.h>
#include <DHT_U.h>

int SENSOR = 2;
int TEMPERATURE;
int HUMIDITY;

DHT dht(SENSOR, DHT11);

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

void loop() {
TEMPERATURE = dht.readTemperature();
HUMIDITY = dht.readHumidity();
Serial.print("Temperature: ");
Serial.print(TEMPERATURE);
Serial.print(" Humidity: ");
Serial.println(HUMIDITY);
delay(1000);
}

This is the circuit scheme:

This is a photo of the circuit and the sensor (probably damaged):

Thanks for your time and sorry for my bad english.

Caution! Always inspect components before hooking up! I got a DHT11 sensor in a Kuman kit. I hooked it up per standard and ran the sketch. Getting 0s reported back I grabbed the sensor to check it was in the board properly and it was burning hot. On closer inspection the were marked ground-data-VCC. Sensor is pooched.

Finally I was able to solve the problem by not using the resistor and connecting it directly, I also had a problem with the sensor pins since some were badly connected, but it was also solved. Now both sensors are working well including the melted one. Thanks!.


text:
Read time digits from DS1307 and run code based on return
I am currently reading a DS1307 adafruit breakout board and I need to drive two nixie tubes from a shift register. The shift register is running two 74141 IC chips. I have code that loops through all the nixie digits one at a time with a delay of 1 second between each. Now I need to write some code to pull min, hour, and second and change the shift register low/high outputs to display the correct nixie digit. I have the DS1307 returning the correct time on my com by using
 Serial.print(now.hour(), DEC);
 Serial.print(now.minute(), DEC);
 Serial.print(now.second(), DEC);

However, I am not sure how to dimension a string, set that string equal to the two digits on the hour, minute, or time, and then divide the two digits and write if statements to correctly display the tubes. I am used to VB.NET and now C coding.
=======================UPDATE=======================
I am using this code to set any individual digit of the nixie tube to on.
       //Turn on 0
 sr.set(4, LOW);
 sr.set(5, LOW);
 sr.set(6, LOW);
 sr.set(7, LOW);

The sr is the shift register and each number is which leg of the shift register I am turning low or high. This specific piece turns on the digit 0.

There's no reason at all to develop strings if what you need are digits.  What bit patterns do you need to output to turn on different digits?  Ie, what is the interface to the nixies?

The nixies have an anode positive leg and then a cathode leg for each digit. The 74141 just swaps out which cathode to run to gnd. I will update some code that shows how I turn a number on or off.

@jwpat7 All i need is to read the minute and say if the minute time is 12 then change one tube to a HIGH/LOW pattern to display 1 and the other for 2.

You can set up an array containing the bit patterns to turn on different digits, and then use code that sends the bits for the high digit of now.hour()/12 and the bits for the low digit of now.hour()%12.  For example:
const byte digiBits[] = { B0000, B0001,
// and so forth for all the digits ...
};

void send1Digit(byte digiVal, byte whichDigit) {
  // somehow use whichDigit to direct the bits someplace...

  // To send the bits:
  byte bits = digiBits[digiVal];
  for (byte i=4; i<8; ++i) {
    sr.set(i, bits & 1);  // Set a bit in SR to 0 or 1
    bits >>= 1; // shift out the used bit
  }
}

void send2Digits(byte numVal, byte whichDigit) {
  send1Digit(numVal/10, whichDigit);
  send1Digit(numVal%10, whichDigit+1);
}

void loop() {
  // other stuff, then:
  send2Digits(now.hour(), HourSpot);
  send2Digits(now.minute(), MinuteSpot);
  send2Digits(now.second(), SecondSpot);
  // other stuff ...
}

Note 1:  If your sr.set() routine is doing any complicated masking or shifting, you may be able to avoid some of that by ORing digiBits[digiVal] with whatever number sr.set() might be building up to shift out.
Note 2:  If the numerical value of digiBits[digiVal] is equal to digiVal, then don't bother defining digiBits[], but instead in send1Digit() just say byte bits = digiVal, or use digiVal directly in place of bits.

After days of trying i got it to work. This way probs works but my way is how i had to end up doing it.

@Cheddar, ok, good you got it to work

Yea, a noob question though, I want to upload my code to show how i got it. Instead of doing indentations can I use come kind of bracket. I am having a hard time putting arduino code into the textboxes on this site.

@Cheddar, copy & paste your code into the question edit box, then select it and press Ctrl-K.  That is, highlight the code with mouse (or by placing cursor at start of code, and holding down shift while moving cursor to end of code); then press ctrl-K or click the {} icon in edit tools bar. This marks the code as code.  ¶ Note, you can make the edit box bigger by dragging the bottom bar of it downward.  Makes code easier to see while editing.  ¶ If your code is indented ok as you wrote it, it should be ok as pasted, except that tabs don't expand, so select 'tabs as spaces' in your editor


text:
How to fix 12V RGB LED Strip connection to NodeMCU?
I am trying to hook 12V RGB Led Strip (LTROP SMD 5050 RGB LED Light Strip) to a NodeMCU unit. I know there are many different tutorials on this and I am very new to wiring and electric circuits.
I used BUZ91A n-MOSFETs and 150 Ohm resistors for each of the RGB channels, and the board is using it's own power supply via usb.

I use very simple code to check if the setup works:
#define REDPIN D3
#define GREENPIN D1
#define BLUEPIN D2

#define FADESPEED 5     // make this higher to slow down

void setup() {
  pinMode(REDPIN, OUTPUT);
  pinMode(GREENPIN, OUTPUT);
  pinMode(BLUEPIN, OUTPUT);
  Serial.begin(115200);
  Serial.println("Finished setup");
}

void loop() {
    analogWrite(REDPIN, 800);
    analogWrite(BLUEPIN, 1020);
    analogWrite(GREENPIN, 400);
    delay(100);

  Serial.println("Finished loop");
}

I suspect nothing works because NodeMCU and the LED are using different power sources and the fact they have common ground doesn't seem to be everything required.

What happens when you try to PWM the built-in LED? BTW, you don't have to execute analogWrite() again and again in the loop, it is enough to do that only once in setup() but that isn't the problem.

It works fine with D0 - it changes the brightness based on value in analogWrite()

The connection is OK. Which NodeMCU board/version do you have? The pin mapping may be different from the Arduino defines. For example my NodeMCU (LoLin) has built-in LED on pin 2 which is D4. D0 is pin 16 so the other pins might differ too on your board.

Looks like version 1.0 to me. The Arduino IDE "Get Board Info" does not tell much: VID: 10C4, PID: EA60

I would first try to blink a LED using digitalWrite() on D1, D2 and D3 (one by one) to see if these outputs are really associated with the pins where you connected the PWM outputs (just don't forget the current limiting resistor, max source current is 12 mA and max sink current is 20 mA). And you might first try to change the PWM frequency, for example try with analogWriteFreq(200);. The default PWM frequency is 1 kHz and that should work but nothing to loose if you try.

I connected a 3V LEd to D1 (used for G channel in my setup) pin and ground and it stays led all the time. Changing the analogWriteFreq() did not help, but the onboard led changes it's brightness with either.

If I just try to digitalWrite(pin, HIGH);, the 3V led works fine while the RGB leds on the strip are not reacting

Did you use PWM to light the LED on D1 or did you toggle the output with some delay to confirm that really is D1 pin? Next I would try to connect a jumper wire from one of the 3.3 V pins on NodeMCU board to the resistor connected to MOSFET's gate to see if that will trigger the transistor and light up the corresponding LED strip channel.

I am sure it's the right pin. I think it's something about the wiring or maybe the mostef is not the right type or something.

The MOSFET should be OK, I checked the datasheet. Try to trigger the MOSFET by connecting NodeMCU 3.3 V pin directly to the resistor at the transistor's gate, as I suggested in the last comment. Or try to trigger it with external 3.3 or 5 V. Double check if the strip is connected correctly - remove the MOSFET and use a jumper wire to short the breadboard contacts where source and drain were before you removed the transistor.

I haven't figured it out but I noticed that sometimes when I unhook the nodeMCU from the ground, the leds on the strip go bright.

Wow, I think I got it now - when I swap the D0 pin to Vin (5V in my case since I am using USB power), the leds on the strips work. Does it mean that the D* pins aren't giving the MOSTEF enough current?

No, MOSFET's (not MOSTEF, I can see you are repeating the same 'typing' mistake) gate current draw is near zero. The problem could be the voltage but I still can't tell because you still didn't try what I suggested already twice :-) To say one more time: There are a few pins on NodeMCU board marked with 3 or with 3V3. Connect one of these pins to the resistor in transistor's gate to see if 3.3 V from NodeMCU can trigger the transistor. Only then we could know what's going on.

Nope, the 3v3 does not trigger it - only the 5v does

So now we finally know the reason is MOSFET's threshold voltage is too high. The solution is to drive the gate with NPN transistor (you can use BC547 or 2N5551 or similar). You have to connect it's collector to 5 V and it's emitter to GND. Put 10k or 100k resistor between 5 V and the collector, connect the collector to MOSFET's gate and GPIO to the base of NPN transistor. Put some resistor between GPIO and the base of the transistor, maybe 4k7 or similar.
Note:
HIGH from GPIO will switch off the LED strip and LOW will switch it on.
Another solution is to use MOSFET with lower threshold voltage.
EDIT:
If you want to avoid adding NPN transistor you can use NTD5867NL MOSFET which has max threshold voltage 2.5 V so it will for sure work with 3.3 V at the gate but is rather expensive (about $4). Much better solution is adding cheap NPN transistor.
EDIT:
Here is the schematic:

simulate this circuit – Schematic created using CircuitLab
EDIT:
Here is the correct wiring:

Can you please advise on a fitting MOSFET model to use?

I'll take a look through some other MOSFETs and write you a note if I find the one which might work.

I've edited the answer and added the data about MOSFET which will for sure work with 3.3 V.

Thank you so much for following through on this problem with me. I wanted to ask one last question. Are there any sort of Led Strip Driver Boards I could just purchase and wire to my nodeMCU? I suck at all this wiring and circuits (you can tell) and the further I go the better I understand I'd rather stick to the programming side of things. Also, I am trying to finish by project on time for someone's Christmas gift. Again, thanks a lot for your kind help.

I'm not aware of such driver board. What I've found is only this and this RGB LED strip controller, but that is another way of controlling the strip. It has the onboard IC for PWM and you have to send the data using clock&data signals. This is the IC's datasheet. But you really don't have to run from adding just one more transistor, you can do that in a minute. BTW, you may accept the answer if you liked it :-)

I will try to connect the transistor - haven't figured the wiring yet. Base, collector, all that - have to do some reading first :)

Here you are the schematic. NPN transistor is just like MOSFET except instead of G, S and D you have B, E and C. Emitter is marked with an arrow and base is where you connect the signal from GPIO. Resistor values are not critical but if the values are to high you might need to lower the PWM frequency.

I guess I failed to wire these correctly. I did the wiring and the led does not work BUT if I unplug the wire from transistor base and grab it with my bare hand, the led will shine :)

I tried without resistors - didn't work
I tried to check the voltage on the 5V pin - it's 4.6V
I also checked continuity between different wires on the board (just to make sure everything is connected) and it appears so, I am now out of options :)

I also tried a different power supply for the nodeMCU, this one gives 4.9V and 3A - hasn't helped; I also tried hooking up a different LED strip (regular one color) - hasn't helped either.

You didn't wire the circuit correctly. You connected the base of NPN transistor directly to the MOSFET's gate (the result is as if there isn't NPN transistor), one resistor is missing and you connected the collector of NPN transistor to 3.3 V instead to 5 V. If that even is the collector. Which NPN transistor did you use?

Here you are the wiring diagram. You can use the same 12 V which you are using to power the LED strip instead of 5 V to avoid using 3 different voltages. But, as you are probably getting 3.3 V from 5 V then it isn't a problem if you use 5 V. Of course, a MOSFET must be n-channel and not as in the picture.

BTW, why would you unaccept the correct answer just because you did not wire the circuit according to the schematic I gave you? :-)

I only unticked it because people normally ignored answered questions and since I hasn't gotten it resolved yet, I wanted to sort of let others tip in seeing an answered question, that's all. It actually works now. Thanks a bunch. I now realize I need to stick with programming and get OTB hardware as much as possible :) Again, many thanks!

One thing I noticed is that it works in inverted mode - like when I plug it in, without even getting the nodemcu powered up, the leds are led. And then when the nodemcu commands HIGH to the pin, the led turns off. And if I remove the connection between the third leg of 2N5551 and the +12V, it keeps working the same way without any difference. I know I most likely messed up the wiring and I can't stop laughing at how much time I spent with this and all the trouble I cause people with my stupid questions but I just had to share this :)

You did not mess the wiring this time :-) Take a look at the note I wrote in my answer already before I gave you the schematic where I said: 'HIGH from GPIO will switch off the LED strip and LOW will switch it on'. That is because NPN transistor works as inverter. As for avoiding hardware - do not avoid it!! Being a programmer means you learn fast and your SO reputation confirms you have that ability. So, instead of avoiding - learn it, it's as much fun as programming. I am glad your circuit finally works and hope you'll finish the gift on time, before Christmas! :-)

On the above circuit mosfet switching will depend on collector current as I have 24v/5A source connected to the drain, for switching I am give 5v on gate


text:
compilation terminated. exit status 1 error compiling for board arduino/genuino uno
hi i have done this code for my uno R3 and i cant upload it
any suggestions
#include"DHT.h"
#define DHTPIN 8
#define DHTTYPE DHT11
DHT dht( DHTPIN,DHTTYPE);
const int ledPin=13
int piesoPin=9
void setup(){
  serial.begin(9600);
  pinMode(ledPin,OUTPUT);
  pinMode(piezoPin,OUTPUT);
  delay(5000);
}
void loop(){
  int t=dht.readTemperature();
  int h=dht.readHumidity();
  Serial.print(t);
  if(t>26){
    digitalWrite(ledPin,HIGH);
    digitalWrite(piezopin,HIGH);
    {TONE(9,3047,400);
    delay(1000);
    noTone(8);
    delay(100);
    }
    delay(1000);
    Serial.print("ON T=");
  }
  else(digitalWrite(piezoPin,LOW);
  digitalWrite(LEDpIN,LOW);
  Serial.print("OFF,T=");
  }}

Michel Keijzers gave the answer, but I noticed a few others things. The dht.readTemperature returns a float, you convert it to an integer. The adafruit dht library makes a shortcut in the signal: https://github.com/adafruit/DHT-sensor-library/issues/48

I am pretty sure the compile told you more than that.

Two errors I see is a typo and missing semicolons.
const int ledPin=13
int piesoPin=9

Should be
const int ledPin=13;
int piezoPin=9;

Also I see a unnecessary { and } but this cannot cause a compilation error.
Check the delays, when the temperature is higher than 26 degrees you have more delay than when not, maybe this is intended, maybe not.
However, you probably typed over the code, so maybe there are more errors, please add the exact error text and line in your question.


text:
How to prevent interference between dc motor and arduino?
It may be already asked question in somewhere but I am struggling!
I have a four wheel robot which I want to drive it to perform 90-degree left/right turn, I am using the MPU6050 3dof to get angles, however everything is ok when the DC motors are off and the readings from the MPU6050 are pretty good.
But when the DC motors are on, the readings start to be increase randomly. I tried to use a different power supply to the DC motors and the Arduino, but with no solution. At the end when I reset the Arduino everything was back to be normal even if the DC motors are on!

Any help will be appreciated and I am open for any suggestion.

You said " I tried to use different power supply to dc motors" -- please provide details. Your diagram shows a 9V battery, which can hardly supply enough current to operate two motors and an Arduino. Be sure that you include all relevant details in your question.

@josecanuc , thank you for your reply and I'm sorry I wasn't accurate in my question, however, for now, I am using an 11.3v battery for the dc motors and 7.3v for the Arduino , the rest of the image is the connections for my setup as well as I connected the GND of the motor with the GND of the Arduino

There are two basic things you need to do:

Use proper pullup resistors on your I2C lines (2.2kΩ) instead of relying on the (terrible) internal pullups of the ATMega
Add capacitors to the motors.

For point 2 you need two or three small ceramic capacitors (10nF to 100nF) per motor.

Connect one from each terminal to the motor's body
Optionally connect a third between the two terminals of the motor

This will reduce the EMI produced by the motor, and the improved pullups should reject EMI easier.
(Even if this doesn't entirely fix your underlying issue, it's certainly something that you should do regardless.)

well, thank you for the suggestions, is it ok if I do both points?

Yes. You should do both points.

I have a question if you could answer it, why when I press the reset button on the Arduino everything is normal and the readings from MPU6050 back to be normal?

No idea. EMI causes strange things.

it didn't work!
i added the capacitors as you said and pullup resistors but nothing changed!
the problem still only with first power when reset the arduino from the RESET button everything back to be normal

You can just change ground port for your MPU6050 or for your motors(experiment with different choices). You have another ground port near pin13. As far as I know some of them are for analog devices and some of them are for digital (to avoid interference).
Adding capacitors may not help.
If none of the methods will help, try to add an inductor to your circuit.
Please, try that and write here if these were helpful or not.
Update: As per this site the problem is caused by data cables.

Thank you a lot !
Didn't have to change frequency. I just eliminated SDA and SCL wires
  and plugged a chip with MPU-6050 directly into Arduino and it works
  without any problems. Thanks to you this issue is solved :)

In addition, I would like to mention that Arduino standard pin cables are very noisy, so all connected modules which use high data rates or which are very sensitive to data errors (for example, nRF24L01+) will have strange behavior.
Temporary and harsh workaround: You could reset your Arduino after first initialization process (at the end of setup) then, save a flag("1") to EEPROM so it will not reset each time you start Arduino (warning: EEPROM cells can be rewritten only 10000 times).
if(EEPROM.read(0))
{
  EEPROM.write(0,1);
  //put your reset code here
}

if(EEPROM.read(1))
{
  EEPROM.write(0,0); //make it back "0" for next start
}

Comments are not for extended discussion; this conversation has been moved to chat.


text:
Read the image value pixel by pixel
I need your help in SD card and image. It's been a week since I have involved with this problem, So I wish you can help me.
Here is the problem:
I saved a photo to the SD card and now I want to read the color information of each pixel and put the servo in a definite position based of the pixel color.
I want to read pixel by pixel information in a row and after completing a row reed the next row.
The image has 2000*2000 pixels in BMP format, but I can change the format if it is necessary and the picture consist 100 colors, so it means the servo should have 100 different position.
I can also take photo information as a CSV file with 2000 rows and 2000 columns as int values and save the .csv file to the SD card.
it would be grate if someone can help me.

Please add any code/sketch that you have already written. Also add more details with what specifically you need help with. This is very unclear right now.

https://en.wikipedia.org/wiki/BMP_file_format

are you saying that you would like the servo to be positioned 4 million times?


text:
Arduino Uno keeps looping on setup() everytime I press a specific button on the remote
I'm trying to decode my Panasonic television remote using the IR_RECEIVE sketch below.
When I press the remote's buttons it works fine and Iget the values, except from when I press the power button - the setup() function executes.
This is the code:
/* Raw IR decoder sketch!

This sketch/program uses the Arduno and a PNA4602 to
decode IR received. This can be used to make a IR receiver
(by looking for a particular code)
or transmitter (by pulsing an IR LED at ~38KHz for the
durations detected

Code is public domain, check out www.ladyada.net and adafruit.com
for more tutorials!
*/

#define IRpin_PIN      PIND
#define IRpin          2
#define MAXPULSE 65000
#define RESOLUTION 20

uint16_t pulses[100][2];  // pair is high and low pulse
uint8_t currentpulse = 0; // index for pulses we're storing

void setup(void) {
    Serial.begin(9600);
    Serial.println("Ready to decode IR!");
}

void loop(void) {
    uint16_t highpulse, lowpulse;  // temporary storage timing
    highpulse = lowpulse = 0; // start out with no pulse length

    while (IRpin_PIN & (1 << IRpin)) {
        highpulse++;
        delayMicroseconds(RESOLUTION);

        if ((highpulse >= MAXPULSE) && (currentpulse != 0)) {
            printpulses();
            currentpulse = 0;
            return;
        }
    }
    pulses[currentpulse][0] = highpulse;

    while (!(IRpin_PIN & _BV(IRpin))) {
        lowpulse++;
        delayMicroseconds(RESOLUTION);
        if ((lowpulse >= MAXPULSE) && (currentpulse != 0)) {
            printpulses();
            currentpulse = 0;
            return;
        }
    }
    pulses[currentpulse][1] = lowpulse;

    currentpulse++;
}

void printpulses(void) {
    Serial.println("\n\r\n\rReceived: \n\rOFF \tON");
    for (uint8_t i = 0; i < currentpulse; i++) {
        Serial.print("delayMicroseconds(");
        Serial.print(pulses[i][0] * RESOLUTION, DEC);
        Serial.println(");");

        Serial.print("pulseIR(");
        Serial.print(pulses[i][1] * RESOLUTION, DEC);
        Serial.println(");");
    }
}

This is the output:

Ready to decode IR!
Received:
OFF   ON
  delayMicroseconds(34724);
  pulseIR(3600);
  delayMicroseconds(1800);
  ......
  delayMicroseconds(1340);
  pulseIR(460);
  delayMicroseconds(1360);
  pulseIR(460);
  Ready to decode IR!
  Ready to decode IR!

The last 2 rows appeared when I pressed the power button (twice).
The rows above appears when I press any other button.
I played around with the Arduino and the remote, I might have done something to cause this. The first time I tried it - it worked fine.
I tried resetting and re-uploading.
Sorry if the post is too long or not informative enough - I'm new to this and not really sure what kind of information to provide.

the chip resets on some error

try larger array uint16_t pulses[150][2];

How high can currentpulse get before it is reset to zero? It is used an array index and if it gets larger than the (number of array elements-1), your code will write outside of the array.
Can the array be so far over-written that it grows into the stack area? That could definitely cause a reset, or reset-like behavior.


text:
Use IR remote with arduino
I would like to use the IR remote with Arduino to turn on a LED and turn off the same LED when I push on the remote.
That is to say :

If I push on 1 I would like the LED turn on
If I push on 2 I would like the LED turn off

Here is my code :
#include <IRremote.h>

const int RECV_PIN = 7;
IRrecv irrecv(RECV_PIN);
decode_results results;

const int L1 = 13;

void setup(){
  Serial.begin(9600);
  irrecv.enableIRIn();
  irrecv.blink13(true);
  pinMode(L1, OUTPUT);
}

void loop(){
  if (irrecv.decode(&results)){
        unsigned int value = results.value;
        Serial.println(value);
        irrecv.resume();
        if(value == 12495){
        digitalWrite(L1, HIGH);
        delay(1000);
        }
        else if(value == 6375){
        digitalWrite(L1, LOW);
        delay(1000);
      }

  }
}

But the problem is when I push on 1 I just see the LED turn on but very quickly the LED turns off then whereas I don't push on the button 2.
Could you help me please?

Unrelated; there is no need to add the delay(1000); after turning the led on/off.

This line of your sketch irrecv.blink13(true); tells the IRrecv object to flash the LED on and off when an IR signal is received. boarddefs.h in the IRremote folder has pin number 13 defined as the default BLINKLED. The code you have written in loop() is trying to do something different with the same LED. I would remove this line irrecv.blink13(true); then try your sketch again. Once the LED is working correctly, try removing both of these lines delay(1000);.


text:
Confusion on array definition at Arduino website
See the below explanation about Arrays from Arduino's official site:

Creating (Declaring) an Array
All of the methods below are valid ways to create (declare) an array.
  int myInts[6];
  int myPins[] = {2, 4, 8, 3, 6};
  int mySensVals[6] = {2, 4, -8, 3, 2};
  char message[6] = "hello";

You can declare an array without initializing it as in myInts.
In myPins we declare an array without explicitly choosing a size. The
  compiler counts the elements and creates an array of the appropriate
  size.
Finally you can both initialize and size your array, as in mySensVals.
  Note that when declaring an array of type char, one more element than
  your initialization is required, to hold the required null character.

I have the following problems to understand:

Isn't int mySensVals[6] = {2, 4, -8, 3, 2}; wrong? I count 5 elements.
Isn't char message[6] = "hello"; is wrong as well? I count 5 elements.

The last sentence answers your second question.

1-) Isn't int mySensVals[6] = {2, 4, -8, 3, 2}; wrong? I count 5 elements.

No, not wrong at all. There are 6 elements (as the definition says), and the first five are set to 2, 4, -8, 3 and 2. The sixth is undefined.

2-) Isn't char message[6] = "hello"; is wrong as well? I count 5 elements.

No. There are 6 there. To quote your quote:

Note that when declaring an array of type char, one more element than your initialization is required, to hold the required null character.

So "hello" is actually "hello\0".

You wrote "So "hello" is actually "hello\0". This \0 also is required in C or only in Arduino?

It's standard C. The only thing that Arduino provides is advanced helper functions and macros such as digitalWrite(). EVERYTHING else is either C or C++. Arduino does not have its own language. It is merely a library.

So you mean in plain C if I declare: char message[5] = "hello";  Is this wrong? since there is \0 at the end? If so strange that I never noticed this before.

Yes, that is wrong. That would end up with functions like Serial.print() failing and printing lots of junk.

By convention, in C, character strings (not "String" objects) are terminate with a \0. \0 is not otherwise a valid character, so it is used to mark the end of the text. The alternative is that you'd always have to pass not only the string, but it's length as well, which gets cumbersome and is an opportunity to make errors.

To be clear, it's a convention that is imposed by the standard C library (in that all functions that work with strings expect it), and is supported by the compiler (in that it will terminate string literals with NULL while compiling for you).


text:
LCD Identification FPC-JG00467-01B SR36
I salvaged an old LCD from a calculator (Texas Instruments) and I want to interface it with a microcontroller (preferably an Arduino). I‘ve searched the whole internet but I simply can‘t find any information about this display and its driver. I am looking for a specialist who can identify this:

It's most likely a custom part for which there is no public data sheet. LCDs are almost always custom-designed, and require special driver circuitry. This is especially true for such mass-produced items as calculators.
Edit:
There is code to screen capture using an ESP32.
https://github.com/marcrobm/TTRX_Remote/blob/master/main/drivers/TTRX_T30X.cpp
The Protocol is a relatively simple parallel interface with some data pins and a clock pin. To implement a Driver, one could implement the above linked code "in reverse".


text:
Why do we declare constant lat and lon value
static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;
What does this mean?
https://github.com/mikalhart/TinyGPSPlus/blob/master/examples/FullExample/FullExample.ino
The above link contains the full example program of that line.
This line is from tinygps++ library for extracting the coordinates and displaying in a table format. I'm using arduino uno, GSM module and GPS module to extract the coordinates and transmit it as message. Can anyone explain what dies this constant value mean and why do we use this?

Unlike in movies, I hardly think London will ever move.

This constant value is there at tinygps++ full example program and I don't know about this constant value? Do you know any exact answer? Also what type of algorithm is used here for the entire program. I'm new to arduino and so I just wish to have a knowledge of it. Is there any specific algorithm being used to extract the exact gps coordinates using gps module and arduino?

These are the GPS coordinates of London. If you want to know the exact location google the coordinates. In your comment you have more questions about an example program, but you never included the program in your question, nor did you link to it. How should we answer your question? We don't know, what sketch you are talking about, so we cannot know, how this one line ties into the rest of the program

We declare those because the program in which they are declared wants to use that information in some way. Without knowing what the program is we can't say why it might want to know that information. Maybe it wants to work out how far from London you are.

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

This link contains the full program. Sorry to attach the link, since the program to too lengthy.

I'm currently working on a project, where the my location coordinates is to be sended as message using GSM module. The GPS coordinates are extracted using gps module. These are connected to arduino uno board. Tinygps and tinygps++ library is being used for this project. This program is an full example program which is default in tinygps++ library

Please add all this information and questions to the text of your original question, not in the comments. They are temporary and please should not need to read the full comment stream to get the needed information.

If you want us to give you a detailed explanation of every single line of code of the program you are linking to, you are in the wrong place. This site is for specific, well-targeted questions. If you do did study that program and have a specific question, then ask, and include the relevant bits in the question itself. See How do I ask a good question?.

I was actually asking for a particular line, which was mentioned 1st. static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;

@Kwasmich lol ... that is example code ... it is written using proper programming convention... it needs to be clear so that most people would immediately know what to do to modify the code for their needs ... using descriptive names of variables makes the code easier to read, and the code requires less comments ... if the constants were used directly then the OP would probably be asking what is this 51.508131?

@tharrunkumar imagine that you are writing a program that calculates the circumference and the area of a circle from an input of a radius parameter .... which would be clearer to read? ... c = r * 2 * 3.14159 a = r ^ 2 * 3.1459 ... or ... pi = 3.14159 circ = 2 * radius * pi area = radius ^ 2 * pi

Static variables are allocated storage only once in a program lifetime
The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it and you can't change const variable's value
and i guess you know double is a data type that can save floating point numbers
that line declare two variables with names LONDON_LAT and LONDON_LON and both of them are in one line
and because london's latitiude and longtitude doesn't change the const keyword is used
also i guess because those variables are constants you can use #define visit https://www.arduino.cc/reference/en/language/structure/further-syntax/define/

It's a good idea to declare variables the strictest possible way. So if you don't intend to change the value of LONDON_LAT at runtime, declare it as const.
This allows the compiler to alert you if your code tries to modify it, and it often allows the compiler to optimize the code.


text:
Noise in Analog Read Serial from an instrumentation amplifier(ina122p)
I am trying to read the values from a simple EMG circuit (with an INA122P) using the analogRead() and plotting in the plotter using an Arduino nano v3. I am powering the ina1222p from the 5v pin of the Arduino. But no matter what I do, the signal comes out very noisy most of the time(i can rarely make out the EMG). The bandpass filter is also not really helping. I am using regular solid core wire and alligator clips to connect to the electrodes.
Can someone please tell me what I am doing wrong? or tell me how to make a simple EMG circuit that uses the Arduino's analogRead().
I am also getting ac sine waves when my laptop is plugged to power, so I tried removing the power. The distinguishable sine wave wasn't really showing up, but it was still just as noisy...
I am a beginner to both Arduinos and designing Analog circuits.

I found this design from here: https://greenhecktech.wordpress.com/2016/09/19/improving-the-emg-amplifier/

If you could provide a schematic that would really help! One thing you might quickly be able to try is running from a powerbank. You also want to make sure you decouple the power rails of the INA122P with (preferably both) a 10nF and a 100nF capacitor.

@Ananas_hoi a powerbank could have an electrically noisy buck converter ... try to run from a battery directly

You are right. Furthermore, soldering the connections would be desirable over a using a breadboard. It might also help to keep the connections short and isolate wires from noise with some simple aluminium foil shielding.
Since it's a dual input amp, consider looking at this: https://toshiba.semicon-storage.com/us/semiconductor/knowledge/faq/linear_opamp/what-is-the-purpose-of-using-a-differential-amplifier.html
Without schematics I cannot help any further.

"noisy most of the time" - good news: if it's not all the time, that's a sign it can be fixed.
"bandpass filter is also not really helping" - INA122P circuit likely has something wrong.  check any resistors involved. Edit: if this was about U2.2, see below as that doesn't look like a band pass...
"regular solid core wire and alligator clips to connect to the electrodes" -
basically 0 shielding with mini-rabbit ears at each end and a big loop area between the wires.
Eventually you will want something better than gator clips.
My main recommendation is that as far as wire goes, if you form twisted pairs they tend to be pretty darn good at rejecting noise at least for that part of the wire.  You will want to twist a signal along with its reference (such as a +V and a ground).
Some explanation of the circuit:
U2.1 is creating a 2.5V source that it uses as the reference 'ground' for U1.  Reason for this is to treat 0 as "-2.5" and 5 as "2.5" as op amp math is generally done on a +V, -V basis.  (Personally, I prefer to use voltage regulators to make power buses instead of this. As a result, I give a stink eye to circuits that use the op amp method and claim something about reducing part count.)
U2.2 is a capacitor shy of an active band pass.  It's a high pass filter that is helping preserve and even promote some of the high frequency noise you are picking up. So yes, you may wish to modify or even ditch it until you have high frequency noise under control.
If possible, you may also wish to look into operating at a higher voltage.  This can help improve your signal to noise ratio.  If your signal is essentially +/-2.5V, 250mV of noise would be 10:1, but if you can run at +/-5 V, that same 250mV noise contribution gets dwarfed 20:1.

i'll try using a higher voltage as you suggested. I have a question...why does this circuit use an opamp to provide a reference voltage?, i've seen other circuits use just the resistor network(r2, r3) to do that... what benifits does the opamp provide?

op amp or voltage regulator can provide current without voltage drop.  The resistor voltage divider voltage changes as you draw current because another "resistor" path is added to ground, making the equivalent resistance change.

Ah, I got it, thanks~


text:
4WD Robot keeps freezing
I have been working on a 4WD robot for a while now. The parts I'm using are Arduino v4 shield, l298N driver motor, Hc 05 ultrasonic sensor, DHT 11, mq2, Bluetooth module, servo motor, ir transmitter and receiver module and an uno all powered by 2 18650 Li ion batteries and a power bank. when i tried using the Ir sensors only, ultrasonic only or both for obstacle detection and avoidance the code freezes and nothing works anymore until i move the obstacle away then the robot makes the decision it wanted to make. it also used to reset occasionally while frozen but i fixed that issue by powering the Arduino separately. i noticed this problem mostly occurs when all the IRs give a low signal. i think the problem is with my code but i don't really see what i typed wrong.
#include <dht.h>
#include <Servo.h>

#define servoPin 11

// Create a servo object
Servo Servo1;

//Ultrasonic Sensor
#define trigPin 9
#define echoPin 10
// defines variables
long duration;
int distance;

//sensor pins
#define gasSens A4
dht DHT;

#define DHT11_PIN 2

//motor driver pins
#define in1 8
#define in2 7
#define in3 6
#define in4 5

//infared pins
#define lftIr 12
#define ctrIr 4
#define rghIr 3

#define buzzer 13

int dist=1000;
int lastVal=0;
int degVal;
int leftDist;
int rightDist;
int gasVal;
int logicVal=49;
int buzzerTrig=0;
unsigned long curTime;

void setup() {
  // put your setup code here, to run once:
  Servo1.attach(servoPin);
  Servo1.write(100);

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);

  pinMode(lftIr,INPUT);
  pinMode(ctrIr,INPUT);
  pinMode(rghIr,INPUT);

  pinMode(buzzer, OUTPUT);

  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);

  curTime=millis();

  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  if(Serial.available() > 0){ // Checks whether data is comming from the serial port
      logicVal = Serial.read(); // Reads the data from the serial port
   }

 if(millis()-curTime>=10000){
    int chk = DHT.read11(DHT11_PIN);
    gasVal=analogRead(gasSens);
    Serial.print(DHT.temperature);
    Serial.print(" C");
    Serial.print("|");
    Serial.print(DHT.humidity);
    Serial.print("%");
    Serial.print("|");
    Serial.print(gasVal);
    Serial.print("|");
    if(gasVal>500){Serial.println("Dangerous gas levels");buzzerTrig=1;}
    else{Serial.println("normal");buzzerTrig=0;}
    curTime=millis();
  }

 if(buzzerTrig==1){
  buzzerCall();
  logicVal==48;
  }

 if(logicVal=='1'){
      dist=distanceCall();

      int leftIr=digitalRead(lftIr);
      int centerIr=digitalRead(ctrIr);
      int rightIr=digitalRead(rghIr);

      if (leftIr==LOW && rightIr==HIGH){
        stopAll();
        while(leftIr==LOW){
          rightMov();
          leftIr=digitalRead(lftIr);
        }
        stopAll();
       }
       else if (leftIr==HIGH && rightIr==LOW){
        stopAll();
          while(rightIr==LOW){
            leftMov();
            rightIr=digitalRead(rghIr);
          }
        stopAll();
      }
      else if (leftIr==LOW && centerIr==LOW && rightIr==LOW){
          stopAll();
              while(leftIr==LOW || centerIr==LOW || rightIr==LOW){
                backMov;
                leftIr=digitalRead(lftIr);
                centerIr=digitalRead(ctrIr);
                rightIr=digitalRead(rghIr);
                }
                stopAll();
          }

      else if (leftIr==HIGH && centerIr==LOW && rightIr==HIGH){
          stopAll();
          while(centerIr==LOW){
            backMov;
            centerIr=digitalRead(ctrIr);
          }
          stopAll();
          delay(10);
          leftMov();
          delay(500);
          stopAll();
        }
      else{
        fowardMov();
      }
    }
}

int distanceCall(){
  // Clears the trigPin
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    // Sets the trigPin on HIGH state for 10 micro seconds
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    // Reads the echoPin, returns the sound wave travel time in microseconds
    duration = pulseIn(echoPin, HIGH);
    // Calculating the distance
    distance= duration*0.034/2;
    return distance;
}

void fowardMov(){
  digitalWrite(in2,HIGH);
  digitalWrite(in4,HIGH);
  digitalWrite(in1, LOW);
  digitalWrite(in3, LOW);
}

void backMov(){
  digitalWrite(in1,HIGH);
  digitalWrite(in3,HIGH);
  digitalWrite(in2, LOW);
  digitalWrite(in4, LOW);
}

void rightMov(){
  digitalWrite(in1, HIGH);
  digitalWrite(in4, HIGH);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
}

void leftMov(){
  digitalWrite(in2, HIGH);
  digitalWrite(in3, HIGH);
  digitalWrite(in1, LOW);
  digitalWrite(in4, LOW);
}

void stopAll(){
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
}

void buzzerCall(){
    tone(buzzer, 5000);
    delay(500);
    noTone(buzzer);
    tone(buzzer, 1000);
    delay(500);
    noTone(buzzer);
 }

The goal is for the robot to avoid obstacles and move autonomously using only the IR sensors.
I used to power everything with the batteries but sometimes it shakes and moves slowly so i decided to power them seperately.
Do you think the problem is with my code or it's a hardware problem? Thank you

this seems to be an error logicVal==48; ... what is the purpose of logicVal? ... a more descriptive name would be useful ... assigning a numerical value and testing a character value tends to be confusing

i move the obstacle away then the robot makes the decision it wanted to make and, what decision would that be? .. you did not say anything about how you expect the robot to behave, and how it should react ... there is no way to know if parts of code actually are meant to do what they do

Without a bit more information it will be difficult to give you much help.  At a minimum, we need a wiring diagram and some more specifics about the DHT library you are using, as there are several.  Also, it appears you have code for a single ultrasonic sensor  that is not used at all.  I have some fairly extensive experience with the HC-04/05 ultrasonic sensors and may be able to help you sort out the problems, but not if we don't have some idea about what you are trying to accomplish

@jsotola i'm sorry if i confused you but i forgot to mention i made an app with MIT app builder to send data to switch the robot on or off and also to display sensor data. what i expected to happen is depending on which Ir goes on first .the robot should move away until that Ir reads high. it works for the left and right Ir but for the center it freezes. it also freezes when all the sensors read low or when the  center and another read low. when i remove the obstacle in front of it then the robot turns left right or even turns around. Thank you for helping i hope you understand my problem now

@user3765883 i'm sorry i will add my schematic to the post I don't know who the dht library i'm using was created by i just downloaded it from the tutorial by circuit basics on how to use a dht (https://www.circuitbasics.com/how-to-set-up-the-dht11-humidity-sensor-on-an-arduino/) Initially i used an ultrasonic sensor but it didn't really work well especially when it faced fabric so i decided to combine it with Ir but after a test my robot hit something then my servo stopped working it's hard and expensive to get parts in my country so i decided to use only IR thats why the variables are there

I'm not surprised that you are having trouble, as you have a very complicated system.  When troubleshooting complicated systems it is important to break it down into very simple 'chunks' and make sure each simple piece works separately.
I would remove everything but the code for the three IR sensors from your system, and use a random number generator to generate a random number between 0 & 7. Then I would use the binary representation of that number to generate the return values for the digitalRead() calls to the sensors, with appropriate printouts to show you what values were generated and what effect those values produced.  I think you'll find that one or more of the 8 possible values causes problems, as you only have IF clauses for 4 (or 6 if you count the two 2-valued systems twice).

Thank you for helping. I took your advice and removed everything except the code for the IR. i also generated random values between 0 and 1 to see what causes the code to freeze. The code doesn't freeze anymore everything works fine for some reason now. maybe the problem was from another part of my code. What do you think? Thank you.

I decided to modify the robot a bit. i'm now using 3 li ion batteries to power both the Arduino and the motors. I tried the script again with only Ir. instead of generating random numbers i decided to see how it'll work with obstacles.  it didn't work.The robot froze immediately it got to a wall so i used the serial monitor to check it out. The problem is with the center IR anytime it reads low first although on the serial monitor the message prints the robot freezes.  Do you think i should use PWM to make the robot slower? Would that improve obstacle detection or it won't matter

Congratulations on making progress!  I'm not sure that going slower will solve your problem, but I doubt it will.  You probably have an issue with your program logic that, if  left unsolved, will continue to make your robot unreliable.  The good news is, now that  you know you have a problem, you should be able to figure it out.  Maybe some more print statements at different points so that you can build a more complete picture of what is actually happening with your logic?  The Mega is undoubtedly executing the programmed logic correctly, but it's also probably not doing what you think ;-).

Thank you very much for your help i have seen the problem. The issue was when the center IR reads low and it enters the while loop it does not move because i did not call the function properly i typed backMov; instead of backMov(); now it works a lot better but i noticed that the UNO resets every time its faces an obstacle. It still avoids the obstacle despite the reset but i don't know why it resets Could it be because the batteries are low? I don't even get a lot of use time with it and i feel it might be due to the fact that i made my own battery holder with easy materials what do you think

If the Mega is resetting it is almost certain it is due to something drawing more current and causing the Mega's internal voltage to drop below 5V.  If you are using the barrel connector or Vin for supplying  power to the Mega, there is about a 2V drop across the internal voltage regulator.

Thank you for your help. The issue was because my batteries were low although it still hits obstacles before making its decision but it still overall works better. do you have any advice on how to fix this i noticed aside from the couch made of fabric and the curtains the robots hits all obstacles before making its decision i feel my problem is the center IR isn't reading low quick enough what do you think?

I am also having problems in getting my two arduinos to communicate using the HC05 Bluetooth module (https://arduino.stackexchange.com/questions/78714/bluetooth-modulehc-05-issues) can you please check it out and tell me what you think? Thank you


text:
Understanding the pin diagram for MPU6050 IMU
I was reading this tutorial about the MPU6050 IMU and I was unable to understand why the pin configurations vary so much when compared to this schematic for EasyEDA.
The tutorial has this pin configuration :

Whereas the EasyEDA schematic looks like this :

I am not sure how to reconcile the two. Why does the schematic have 24 pins while the first diagram has only 8? Also I don't know what all the 24 pins are for.

that looks like a correct schematic diagram of the MPU-6050 module ... at least, the connector pinout is the same ... what problem are you having? ... you did not ask any questions

I see 24 pins in the top diagram ... 6 pins on each of the 4  sides of the square chip ... you don't really need to know what the pins are for ... you only need to concern yourself with the pins in J1

Ah! Thanks! Missed that completely. So if I were building a schematic first, it would work fine if I were to connect the relevant 8 pins to the microcontroller and replicate the rest of the schematic as is (from the second diagram)?

it is unclear what you mean by building a schematic first ... if you were building your own board, then you would probably need most of the support components on that module ... if your project already ran on 3.3 V, then you would not need the regulator or the LED or one of the filter caps ... the MPU-6050 chip requires very minimal set of support components, as you can see in the schematic diagram


text:
Password code using interrupts and timers on Arduino Uno

I have a group project where we are trying to make a user enter a password that we have pre-selected for them. They enter the password using tactile buttons, and they have 5 tries to enter the password correctly. If they enter the password incorrectly, one of 5 LED's will light up to indicate that they have entered it wrong. If they get it right, one LED will light up.
We are using timers to time out the attempt if the users take too long to enter the entire password, or if they take too long between pressing buttons. Also, if they use all 5 tries, we are trying to make the LED's that were on turn off one by one.
Right now the code doesn't get past Serial.print("done").
This is our code:
int input_pin_blue = 5;
int input_pin_yellow = 6;
volatile int state_button_red = LOW;
volatile int state_button_blue = LOW;
volatile int state_button_yellow = LOW;
int num_wrong = 0;
double time_between_buttons = 0;
double time_since_first_button = 0;
const int max_time_between_buttons = 10000;
const int max_time_since_first_button = 30000;
int reset = 4;
void setup() {
    pinMode(input_pin_blue, INPUT);
    pinMode(input_pin_yellow, INPUT);
    pinMode(4, INPUT);
    pinMode(8, OUTPUT);
    pinMode(9, OUTPUT);
    pinMode(10, OUTPUT);
    pinMode(11, OUTPUT);
    pinMode(12, OUTPUT);
    pinMode(13, OUTPUT);
    attachInterrupt(0, handler_red, CHANGE);
    attachInterrupt(1, handler_blue_yellow, CHANGE);
    Serial.begin(9600);
}
void loop() {
    Serial.print("bhi"); //wait for button press

    for (num_wrong = 0; num_wrong < 5; num_wrong++) {
        Serial.print("blah"); //wait for button press

        while (state_button_red == LOW && state_button_blue == LOW && state_button_yellow == LOW) {
            Serial.print("waiting"); //wait for button press
        }

        Serial.print("DOne");

        if (state_button_red == LOW) {                  //check if first button pressed is incorrect
            digitalWrite(num_wrong + 8, HIGH);
        } else if (state_button_red == HIGH) {
            time_between_buttons = millis();
            time_since_first_button = millis();

            while (state_button_red == LOW && state_button_blue == LOW && state_button_yellow == LOW
                    && time_between_buttons < max_time_between_buttons && time_since_first_button < max_time_since_first_button) {
                //wait for button press
            }

            if (state_button_yellow == LOW || time_between_buttons < max_time_between_buttons || time_since_first_button < max_time_since_first_button)
//check if second button pressed is incorrect or time has run out
            {
                digitalWrite(num_wrong + 8, HIGH);
            } else if (state_button_yellow == HIGH) {
                time_between_buttons = millis();

                while (state_button_red == LOW && state_button_blue == LOW && state_button_yellow == LOW
                        && time_between_buttons < max_time_between_buttons && time_since_first_button < max_time_since_first_button) {
                    //wait for button press
                }

                if (state_button_blue == LOW || time_between_buttons < max_time_between_buttons || time_since_first_button < max_time_since_first_button)
//check if third button pressed is incorrect or time has run out
                {
                    digitalWrite(num_wrong + 8, HIGH);
                } else if (state_button_blue == HIGH) {
                    time_between_buttons = millis();

                    while (state_button_red == LOW && state_button_blue == LOW && state_button_yellow == LOW
                            && time_between_buttons < max_time_between_buttons && time_since_first_button < max_time_since_first_button) {
                        //wait for button press
                    }

                    if (state_button_yellow == LOW || time_between_buttons < max_time_between_buttons || time_since_first_button < max_time_since_first_button)
//check if fourth(last) button pressed is incorrect or time has run out
                    {
                        digitalWrite(num_wrong + 8, HIGH);
                    } else if (state_button_yellow == HIGH) {
                        digitalWrite(13, HIGH);
                        num_wrong = 10;
                    }
                }
            }
        }
    }

    if (num_wrong == 10) {
        while (digitalRead(reset) == LOW) {
            //wait for reset
        }
    } else if (num_wrong == 5) {
        while (digitalRead(reset) == LOW) {
            digitalWrite(8, LOW);
            delay(100);
            digitalWrite(8, HIGH);
            digitalWrite(9, LOW);
            delay(100);
            digitalWrite(9, HIGH);
            digitalWrite(10, LOW);
            delay(100);
            digitalWrite(10, HIGH);
            digitalWrite(11, LOW);
            delay(100);
            digitalWrite(11, HIGH);
            digitalWrite(12, LOW);
            delay(100);
            digitalWrite(12, HIGH);
        }
    }

    if (digitalRead(reset) == HIGH) {
        digitalWrite(13, LOW);
        delay(100);
        digitalWrite(12, LOW);
        delay(100);
        digitalWrite(11, LOW);
        delay(100);
        digitalWrite(10, LOW);
        delay(100);
        digitalWrite(9, LOW);
        delay(100);
        digitalWrite(8, LOW);
    }
}
// interrupt handler function
void handler_red() {
    state_button_red = !state_button_red;
}
void handler_blue_yellow() {
    if (digitalRead(input_pin_blue) == HIGH) {
        state_button_blue = !state_button_blue;
    }

    if (digitalRead(input_pin_yellow) == HIGH) {
        state_button_yellow = !state_button_yellow;
    }
}

Is there any specific reason why you feel you need to use interrupts for the buttons?

@Majenko it's just one of the requirements for the project that we use 3 interrupts and 2 timers

Ok, that's fair enough. So it's for the purpose of learning how they work, which is good.

I understand that you have to use timers, however, just as comment, if you didn't have such constraint, I think it would be far simpler (and efficient) to define a state machine which reacts exclusively to button presses. When a button is pressed, it checks the time elapsed from the previous button event and acts accordingly.

int input_pin_blue = 5;
int input_pin_yellow = 6;
volatile int state_button_red = LOW;
volatile int state_button_blue = LOW;
volatile int state_button_yellow = LOW;
...
pinMode(input_pin_blue, INPUT);
pinMode(input_pin_yellow, INPUT);
...
attachInterrupt(0, handler_red, CHANGE);
attachInterrupt(1, handler_blue_yellow, CHANGE);

// interrupt handler function
void handler_red() {
    state_button_red = !state_button_red;
}
void handler_blue_yellow() {
    if (digitalRead(input_pin_blue) == HIGH) {
        state_button_blue = !state_button_blue;
    }

    if (digitalRead(input_pin_yellow) == HIGH) {
        state_button_yellow = !state_button_yellow;
    }
}

On the Uno external interrupt 0 is pin D2 not D5, and interrupt 1 is pin D3, not D6.
Hence you are not testing the correct pins.
Also I would use INPUT_PULLUP instead of INPUT mode for those pins, unless you have external pull-up or pull-down resistors on them.


text:
clear serial buffer not working
Also asked in forum.arduino.cc
bool receive_command(char answer[]);
void serial_flush(void);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  for(byte i=0;i<3;i++){
if(receive_command("OK")) Serial.println("OK found");
 serial_flush();
  }
}

void loop() {}

void serial_flush(void) {
  while (Serial.available()) Serial.read();
}

bool receive_command(char answer[]) {
 unsigned long _time = 0;
  const int max_time = 10000;
  bool flag = 0;

Serial.print("in Serial buffer=");
  Serial.println(Serial.available());
  if(Serial.available()){
  Serial.write(Serial.read());
  Serial.println(" left in serial buffer");}

  while (Serial.available() < 2) {
if ((millis() - _time) > max_time) {
      Serial.println("waited too long nothing received");
  return flag;
    }
    }
  do {
    if (Serial.findUntil(answer, '\n')) return flag = 1;
  } while (Serial.available());

return flag;

}

via serial monitor with CR+LF line ending I`m sending this string:
abcdefghijklmnopqrstuvwxyzOKabcdefghijklmnopqrstuvwxyz
26chars+OK+26chars+CR+LF=56 chars
Output:
in Serial buffer=0
OK found
in Serial buffer=1
b left in serial buffer
in Serial buffer=0
waited too long nothing received

after OK is found serial_flush() is executed but after second run there serial.available() shows there is something in serial buffer. right at that moment it was char 'b' but it also can show char 'd'  and 'c' depending how long it will run.
why serial_flush() is not clearing the buffer?
Thanks.

your serial_flush() code does not wait for CRLF .... once the "OK found" is printed, the input buffer is probably receiving the b or c or d ...  serial_flush() exits before e is received, since the buffer is empty ( e has not yet arrived) ................ imagine that you are the Arduino and you receive one character every hour ... what do you do after you have received the O K ?

The processor is somewhat faster than serial input. If you really want to wait for nothing more to arrive you should probably add a short delay (although jsotola's suggestion of looking for a newline is sensible). Something like:
void serial_flush(void) {
 while (true)
   {
   delay (20);  // give data a chance to arrive
   if (Serial.available ())
     {
     // we received something, get all of it and discard it
     while (Serial.available ())
       Serial.read ();
     continue;  // stay in the main loop
     }
  else
    break;  // nothing arrived for 20 ms
   }
}

the second parameter of findUntil(target, terminator) is of type char* not char
your Serial.findUntil(answer, '\n') doesn't work and you patched it with do while.
use Serial.findUntil(answer, "\n")
'a' is read by readUntil, then it returns  because  of wrong parameter. serial_flush sees no new character. and next you read 'b' from buffer. the sketch runs fast compared to Serial speed. it sees always no or one new character in buffer if the previous was removed


text:
My code isn't adjusting the speed of one of the motors and i'm not sure why
I'm trying to change the speed of motors depending on the amount of light hitting the LDRs. Here i'm trying to make it so that if the LDR has a high value than another, then the motor associated with that LDR slows down so it turns towards the light.
const int motorDirectionA = 9;
const int motorEnableA = 10;
const int motorDirectionB = 5;
const int motorEnableB = 6;

const int leftLDR = A0;
const int rightLDR = A1;

int motorSpeedA = 250;
int motorSpeedB = 250;

void setup()
{
  Serial.begin(9600);
  pinMode(motorDirectionA,OUTPUT);
  pinMode(motorEnableA, OUTPUT);
  pinMode(motorDirectionB,OUTPUT);
  pinMode(motorEnableB, OUTPUT);

  pinMode(leftLDR, INPUT);
  pinMode(rightLDR, INPUT);

}

void loop()
{
  int ldrReadL = analogRead(leftLDR);
  int ldrReadR = analogRead(rightLDR);
  int leftLDRread = ldrReadL;
  int rightLDRread = ldrReadR;

  digitalWrite(motorDirectionA, LOW);
  analogWrite(motorEnableA, motorSpeedA);
  digitalWrite(motorDirectionB, HIGH);
  analogWrite(motorEnableB, motorSpeedB);

  Serial.print("Left LDR reading: ");
  Serial.println(ldrReadL);
  Serial.print("Right LDR reading: ");
  Serial.println(ldrReadR);

  if (leftLDRread > rightLDRread)
  {
    motorSpeedA = 80;
    motorSpeedB = 210;
  }
     else
     {
        motorSpeedA = 210;
        motorSpeedB = 210;
     }

  if (leftLDRread < rightLDRread)
  {
    motorSpeedB = 80;
    motorSpeedA = 210;
  }
      else
     {
       motorSpeedA = 210;
       motorSpeedB = 210;
     }
}

@Maximillian Gerhardt If the left LDR is picking up more light than the right LDR, the left motor should be assigned a 'speed' of 80 whilst the right motor has a speed of 210. If the right one has more intensity, then the right motor should be assigned a speed of 80 and the left motor assigned a speed of 210.
If they're both equal each motor should have a speed of 210 (although I dont have that included in the code).

Let leftLDRread = a and rightLDRread = b.
The two ifs don't make logical sense -- you are already covering the case a > b and in the else case a <= b.
If a > b it will go into the code of the first if clause and in the else clause of the second if, causing both motors to have equal speed, which is probably what you see. Can you describe more clearly to what value the motor speeds should be set if leftLDRRead is greater or smaller than rightLDRread?

You can always edit your question to include clarifications and delete that 'answer'. Again, try to write down your wanted logic more clearly. If the light intensity on the left sensor is greater than that one of the left, what motor speeds should be assigned? What if the right one has a bigger intensity? What if they're both of equal? If you edit your question to include that wanted behaviour, you'll probably see what code you need to write.

If the left LDR is picking up more light than the right LDR, the left motor should be assigned a 'speed' of 80 whilst the right motor has a speed of 210. If the right one has more intensity, then the right motor should be assigned a speed of 80 and the left motor assigned a speed of 210.
If they're both equal each motor should have a speed of 210 (although I dont have that included in the code).

In code you would express this as
void loop()
{
    int ldrReadL = analogRead(leftLDR);
    int ldrReadR = analogRead(rightLDR);
    int leftLDRread = ldrReadL;
    int rightLDRread = ldrReadR;

    digitalWrite(motorDirectionA, LOW);
    analogWrite(motorEnableA, motorSpeedA);
    digitalWrite(motorDirectionB, HIGH);
    analogWrite(motorEnableB, motorSpeedB);

    Serial.print("Left LDR reading: ");
    Serial.println(ldrReadL);
    Serial.print("Right LDR reading: ");
    Serial.println(ldrReadR);

    //assuming motorSpeedA is the left motor
    // left > right
    if (leftLDRread > rightLDRread) {
        motorSpeedA = 80;
        motorSpeedB = 210;
    } else if( leftLDRread < rightLDRread ) {
        //left < right
        motorSpeedA = 210;
        motorSpeedB = 80;
    } else {
        // left == right
        motorSpeedA = 210;
        motorSpeedB = 210;
    }
}

Also note that this is a quite primitive form of a PID controller. You want to respond to environmental influences in some kind of way, for which a PID is for.
You might find these videos interesting:

https://www.youtube.com/watch?v=1pKJ-KcHZ8g
https://www.youtube.com/watch?v=VVOi2dbtxC0

Edit: The code was fixed, a wrong variable was used (the pin number vs the read value)

@mymotordude Retry again. Edit your question if you'd like to comment (or register an account?)


text:
Can you use a 128 pin LCD on an atMega?
I found a couple old calculators and their LCD's have about 130 pins.
I was wondering if I can build an LCD driver to reduce the number of I/O pins, because I don't want to use like 14 I/O extenders; or can I make 1 huge extender?

Shift registers might be easier and cheaper as you don't need input capability like with IO extenders

What kind of LCD is this? Is each pin connected to one segment/pixel, and all of them share the same backplane? Or is this a row-column-matrix? Please keep in mind that you need to apply alternating voltage to LCD because DC will be bad for it.

It is a 32x96 dotmatrix the entire thing running on 1 1.5v lr44

This answer assumes that each LCD segment is controlled by a separate pin (see comment of Juraj).
With a 74HC595 (shift register) you can use SPI to control 8 outputs.
You can daisy chain 4 of them to get 32 outputs with just the SPI pins, to get 128 pins. I assume two pins are for GND and VCC. If you need more than 128 GPIO output pins, than use 5 or more sets of daisy chained shift registers.
Now, since these shift registers use SPI, you can use the slave select to use multiple sets of daisy chained shift registers. I never tried this myself though.
The pins (except GND/VCC) you use is:

3 SPI pins (MISO, MOSI, CLK)
4 SS pins (one for each set of 4 daisy chained shift registers)

The idea is:

Set SS pin to the first set of 4 shift registers
Write 32 outputs for the first 32 segment output pins (using the 4 shift registers of the first set)
Set SS pin to the next set of 4 shift registers
Write 32 outputs for the next set
Continue with the next 2 sets (so you can use 32 * 4 = 128 pins)
In the next cycle, start with step 1 again

this assumes that one pin controls one segment on a LCD with digit segments

@Juraj True, I added it in the answer, thanks. I would think it's otherwise anyway, why would you create a nontrivial protocol and still using 130 pins. And thanks for improving my answer.

it could be a matrix, but now as I think about it, it doesn't change the answer

@Juraj That would make a lot of segments possible (having an X-Y matrix). But indeed only the algorithm to fill the pins is more complicated. I expect like e.g. 10 digits * 8 segments = 80 pins, and some extra for the items/words around (since it's an old calculator).

I see i was thinking of using 8 mcp23017 chips from 2 pins to get to 128 and use 15 for matrix buttons which leaves me 36 pins

That might also be possible, I don't have used MCP23017s so far. In principle the 74HC595 are typically for adding outputs, however, I found out the 74HC595's can only source 70 mA, so in case of 8 segments you could use e.g. an ULN2803. However, as the busybee has written, you might not be able to use these at all, but a specific LCD IC/driver, since LCD uses AC.


text:
Pulse generator with varying width
I am trying to generate a square pulse with a fixed delay of 5 second between pulses and varying width of the pulse. The code I wrote so far generates a sequence of pulses every 5 seconds. Is it possible to generate one pulse (with varying width) every 5 seconds instead? Could you please help me with it?
const int pin =  11;

int i  = 0;

void setup() {
    Serial.begin(9600);
    pinMode(pin, OUTPUT);
}

void loop() {
    i = random(0 , 255);
    analogWrite(pin, i); // turn on LED
    delay(5000);
}

use digitalWrite and set the pin HIGH for desired duration

AnalogWrite generates a series of pulses with a varying duty cycle. If you only want a single pulse, you should probably write the code manually.
What range of pulse widths do you want, and with what precision and accuracy?

As others have said, you could use digitalWrite() and the millis() function to get decent precision and accuracy. If you need higher precision and accuracy though you may want to switch to using port registers to manipulate the pin directly. That is significantly faster to respond than the digitalWrite() function, so you can make your timing more exact. And if you need sub-millisecond precision you could use the micros() function for your timing.

Thank you for your replies and suggestions. I am trying to synchronize two neural recording systems. Therefore I am trying to generate those pulses with varying width and fixed time so I can align them later on offline, to set a proper off set time in data analysis. I was thinking of pulse widths (5-500)ms.

Simple but not fully accurate:

Turn on LED
Delay for the amount of pulse width (e.g. 20)
Turn off LED
Delay 5000 ms - pulse width (20) thus 4980 in this example

However, since turn on/off a LED will also take some time, this will take slightly more than 20 + 4980 = 5000 ms.
Thus better is:

Set time to a variable (use millis function).
Turn on LED
Wait until time >= pulse width
Turn off LED
Wait until time >= 5000

I wonder why OP used analogWrite.

@Juraj I assume he wants a 'random'  pulse width (PWM) generated. so the pulse width I use in my example is some random time the OP should use.


text:
Expected unqualified-id before 'public'
I'm making an arduino program for a buzzer that you can record notes and song for and then play them back. I have 2 arrays that hold both pitch and if a note is being played. I continue to get errors that say expected unqualified-id before 'public'.
Does anybody know how to fix this?
void setup()
{
 Serial.begin(9600);
 pinMode(5, INPUT_PULLUP);
 pinMode(14, INPUT_PULLUP);
 pinMode(12, INPUT_PULLUP);
}

void freePlayMode()
{
    int readP = analogRead(0);
  int readB = digitalRead(5);
  readP = map(readP, 0, 1023, 300, 2000);
  Serial.println(readP);
  if (readB == LOW)
  {
  tone(4, readP);
  }
  else
  {
    noTone(4);
  }
}

void recordMode()
{
 int readS2 = digitalRead(12);
 if (readS2 == LOW)
 {
  rec();
 }
 else
 {
  if (readS2 == HIGH)
  {
    playBack();
  }
 }
}

void rec()
{

static public int recordings[99999999] = {NULL};
static public int notes[99999999] = {NULL};
int state;
static unsigned long i = 0;
int readP = analogRead(0);
  int readB = digitalRead(5);
  readP = map(readP, 0, 1023, 300, 2000);
  Serial.println(readP);
  if (readB == LOW)
  {
  tone(4, readP);
  }
  else
  {
    noTone(4);
  }

  if (i < 99999999)
 {
  if (readB == HIGH)
  {
    state == 0;
  }
  else
  {
    state == 1;
  }
  recordings[i] = state;
  notes[i] = readP;
  i++;

 }
}

void playBack()
{

}

void loop()
{
int readS1 = digitalRead(14);
if (readS1 == LOW)
{
  freePlayMode();
}
else
{
  if (readS1 == HIGH)
  {
    recordMode();
  }
}

}

static public int recordings[99999999] = {NULL}

This is not valid C code. Remove the word public.
Also you cannot create such a big array. The Arduino has only 2 KB (SRAM) memory and also since it is static you have to fill it with values directly, like:
static int recordings[5] = { 0, 1, 2, 3, 4 };

How many values you want to store?
In case you need quite a lot (like hundreds), I would use a different solution for the state array as it only stores values 0 or 1. For example, you can use arrays of uint8_t which cost only 1 byte per element, but even better would be to store 8 0 or 1 (boolean) values in one byte each, but that means you have to get/set the values in the correct indices yourself.

Thanks. Yeah, the arrays used up way to much memory. I appreciate the help.

You're welcome.