text:
ESP32 WROOM32E w/ Arduino IDE 2axis joystick - how do I get a good reading?
How do I get the full range of motion from an analog joystick and the ESP32 WROOM32E using the arduino IDE with esp-idf installed?
Using a 2 axis analog joystick, the 5v/3.3v pin, ground pin and the following code I do not get the correct results printed out. I do get the correct range of values to print but when the Jstick is at 50% or greater it's distance away from center it will print out 50 or -50 when it should be closer to 25. I cannot use the full range of motion, I tried it with the 5v pin and did not have better results, I tried a second identical board, I swapped out my playstation style analog jsticks. Why does it do this? Is this a code probelem?
int       test  = 0;
const int pinVar  = 33;

int  read_jstick(int rxy)
{ int JXY = analogRead(rxy);  //int JXYr = map(JXY,0,4095,-50,51);
  return JXY;
}
void  print_jstick(int pjs)
{ Serial.print("Joystick-X:  "); Serial.println(pjs);
}
void setup()
{ Serial.begin(115200); pinMode(pinVar,OUTPUT);
}
void loop()
{ test = read_jstick(pinVar);
  print_jstick(test);
}

Adding:
looking at the profile the joystick motion is like this: L   _\ | / _   R
When the joystick is like this: | print val is: ~2500 at 5v and ~1800 at 3v
When the joystick is like this: _ on the L side the print val is 0
When the joystick is like this: _ on the R side the print val is 4095
Cool, but...
When the joystick is like this: \ at about 50% the range of motion, the value reads 0. It should be closer to 1200.
When the joystick is like this: between \ and | (0 and 50% range of motion) the print values will vary within the range of 0 and the middle value
I would like to be able to read the full range of motion on the joystick and receive a values incrementally over the entirety of that distance, how do I accomplish this? Example: I would like to move in let's say 10 incremental 'steps' with the joystick physically and the printout should be 1 through 10 and that would cover the movement from stationary to full extent of motion.
I have multiple of the same dev board, multiple of the same joystick, I have swapped cables and wires and I don't see how this could be a hardware problem so let's focus on coding unless it's perfect and should work exactly how I want it to because then that means for sure it's hardware and I just wasted a bunch of money buy multiple of everything and it's all broken. Sorry that I am frustrated here.
Update: I believe that a standard analog joystick module cannot be used with the ESP32 properly because the ESP32 cannot read the resistance of the joystick beyond 1.1v which means that it stops reading values in the middle of its range. You cannot get a scaling range of return from the joystick so it's basically a bad analog version of a digital left right up down inputter.
Prove me wrong please. If there is a way to read an analog pin higher than 1.1v or some other way so I could use the joystick for it's full range of motion on an ESP32 please let me know. All I can do is get a scaling range from stationary to a short move in 1 direction and when the stick is pushed passed 50% that direction it's all maxed out read value wise when it should be related to the position along length of travel.

start debugging by printing the value of axisVar

it makes a difference if you define variables as signed or unsigned

thanks, I have it print the value now and that's how I can tell that half way through the joysticks motion it hits the max 50/-50. I will try them as signed/unsigned variables.

I am saying to write the simplest code ... the map function is not simplest code ... print what is actually being read from the joystick without modifying the value

Did that, it sits at around  a val of 1800 with range between 0 and 4095 when I move the joystick. The problem here is that the values of 0 and 4095 are in the middle of the sticks motion from stationary to one extent, eg at half of it's range of motion it maxes at the high or low value. I can only use half of the joysticks range of motion on each axis.

it is probably caused by using a signed integer ... I don't have an ESP32 right now to test your code ... btw  you did not write the simplest code ... don't be calling functions for reading a joystick and for printing the value ... it could be the functions that are messing up the values

That sounds to me like your joystick is the problem. If you have a multimeter you can verify it directly by measuring the voltage at the slider pin. If it doesn't change in the last half of the full side motion, then the joystick itself only supports a smaller range of motion.

@chrisl - The Joystick works with my arduino correctly, I can receive readings along the full motion of the joystick and I have tried multiple joysticks and the full range of motion is not available on the ESP32 for some reason, I also don't know how to do what you said with the multimeter. Powered by either 5v or 3v the print has the same issue, it stops half way through the sticks motion at the max or min value instead of being half way through the range of values. I also tried this on multiple dev boards, the same type of board. Is this and ADC software issue that can be coded to solve?

@jsotola - I don't understand your simple code thing because I will need functions down the line to handle the joystick values and I don't understand how what I wrote wasn't simple. So then Signed v unsigned seems to have no effect whatsoever that I noticed. If you don't know how to use the ESP32 then you might not be helping and could be leading me down the wrong rabbit hole. If this is a print issue then no one could use a joystick and pass its values, I think it's something internal to with the ADC that needs to be modified but I don't know what or how. Thanks for your time.

yes, you will need functions, but how do you know if the function call somehow changes the reading? ... at this point, you do not know what value is actually returned by the analogRead(rxy) function ... that is why I suggested that you simply get the value and print it inside loop()

@jsotola
"const int pinVar  = 33;
void setup(){ Serial.begin(115200); pinMode(pinVar,INPUT); }
void loop(){ int J = analogRead(pinVar);  Serial.println(J); }"
That gave me the same results... when the joystick is at 50% it's range (~25% the total range from max - to max + along the same axis) it prints out the max value and will do that for any position above it. I don't think you understand the problem. There is some ADC (analog to digital conversion) coding that neither of us know how to do.

you may be right that I do not understand the problem ... try an unsigned integer unsigned int J = analogRead(pinVar);

@jsotola I have already said that I tried that and that it did not change anything, I did the whole gamut of combos signed v unsigned and it was a waste of time. I'm almost 100% certain that the ESP32 cannot use a standard analog  joystick correctly because it can only read up to 1.1v so no once you pass that 1.1v range on the stick it maxes out and that is at a point less than 50% the distance of travel in 1 direction on the axis.

Same issue here. Did you get any answer?


text:
Is I2C a good option for transmitting data over 200 meters by cable?
Is I2C a good option for such application or are there other protocols? I know that modules like these exists to extend I2C range, and I'm planning to use this one (P82B96).
I'd like to use a frequency of 100kHz for I2C and use DMX cables of 20m connected in series.
So, is there any alternative that is more adapted for Arduino to Arduino data transmission over a cable?
EDIT : The solution here is CAN because it allows to have multiple devices on the bus. But if it is a simple communication between two arduinos, then go for the RS-232.
Solution mentionned by @Dmitry Grigoryev and @Joe S
Thanks in advance.

I2C is intended fo very short ranges. The capacitance of long cables makes the signal unusable. There are other communication standards designed for long distances that mostly use differential signals. You won't get such a signal out of the Arduino itself but need some peripherals that do that.

And some of those peripherals can be controlled with I2C,

@Kwasmich So what are the "other communication standards designed for long distances" ? :)

something like RS-485 might be an overkill. But RS-232 (the 12V variant) is also rated for longer distances than I2C.

Also 1Wire was designed for long distances.

RS-485 or CAN is the way to go here.

With I2C, you're unlikely to get reliable communication on a cable longer than 1m. For your reference, here's a table showing what you can achieve with regular RS-232:
Length (m)  Maximum Baud Rate
1600        600
800         1200
400         2400
200         4800
100         9600
50          19,200
25          38,400
16          57,600
8           115,200

So, if you don't really need 100 kHz data rate, you could use regular RS-232 (which is cheap). If RS-232 is not fast enough for you, consider more complex solutions. RS-485 is one possiblility. Another one is CAN, which supports topologies up to 500m at 100kHz. The key difference of CAN is that it's a bus, meaning that all devices will share the same pair of wires.

It should be noted that regular RS-232 uses +/-12V signals not 5V signals like arduino serial interfaces.

The problem is that I control multiple devices on a bus and they have to be able to send data back to "master", and RS-232 is not adapted for this usage but CAN seems to have that functionnality.

@Storca CAN is more complex (you have to deal with message priority, bus arbitration, etc), but it's totally worth learning if your project is complex enough. BTW, this is how typical CAN transcievers look like.

I2C is perhaps the worst possible choice for this type of communication. Instead you should be using something like RS-485 (which is incidentally what DMX uses) with differential signalling.

source: Stack Exchange

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

sort: votes


text:
8Ω speaker, what resistor values to use?
I want to connect 2 speakers of 8 ohm to 2 (different) pins of the Arduino.
However, for this example one speaker is enough.
I came across a lot of circuits without or with a single resistor which on other foras was not adviced, where one pin directly controls the speaker. This way (assuming 0,02A is the max recommended output for a pin), the resulting power is like 0.02A * 5V = 0.1W.
My speaker is 0.5W (8 ohm) and I want to hear how hard that is :-)
But it seems I have to use something with a transistor to isolate the path.
I came across this circuit:

However, when I would calculate the values or R1 and R2 myself I would get:

R2: Afaik, the recommended output for a pin is 0.02 A. This means:
V = I * R <=> 5 = 0.02 * R <=> R = 5 / 0.02 = 250Ω -> 270Ω (nearest higher value)
R1: my speaker is 0.5W, 8Ω.
P = V * I <=> 0.5 = 5 * I <=> I = 0.1A
V = I * R <=> 5 = 0.1 * R => R = 50Ω, which is Rtotal below:
Rtotal = Rspeaker + R1 <=> R1 = Rtotal - Rspeaker = 50 - 8 = 42Ω => 47Ω (nearest higher value)

This result in
V = I * R <=> 5 = I * (R1 + Rspeaker) <=> I = 5 / (47 + 8) = 5 / 55 = 0.0909 A
P = V * I = 5 * 0.0909 = 0.4545 W (so I lose 'just' 10%)
Are my calculations correct, and I assume the +5V pin of the Arduino will not have trouble giving 90.9 mA ?
Update:
I have some more questions regarding the accepted answer:

Would it mean if I use 7 transistors, all my voltages will be used for transistors and nothing is left (7 times 0.7 V which is approx. 5 V?)
**** Answer = No, a transistor will add Voltage so 7*0.7= 4.9Volt added ***
I assume I can better use as less as possible to 'switch' a transistor? * Answer = No, 0.7-Volt required, 5V is fine depending on the rating of the transducer   (but enough to be able to switch it) ? You say R2 can be smaller, but I can better make it higher not to waist voltage?  Answer = Changing the resistor will change the volume, look at the wattage rating for the speaker *
I already built the circuit below (but with a BC547 transistor) ... using a 0,25W R1 resistor. I guess I was lucky (?) * Answer = No, luck has no part, that transistor would work fine within the parameters used, look at the datasheet *
Regarding the base pin of the transistor ... by making the resistor higher (see item 2 above) ... that would help also not to burn the transistor pin? * Answer = No... please view the datasheet and ratings for the hw *
Again about the transistor, so I should make the resistor R2 in such a way that the gain times the mA is driving the speaker? (need to calculate this again) * Answer No, and I think you are thinking of "Gain" the wrong way, "Gain" is a "DB" measure and is for how well AC is transferred between antenna. *
You say to remove R1 completely ... but than I expect V = I * R <=> 5 = I * 8 => I = 0.625A ... P = V * I = 5 * 0,625 = 3.1W which blows the speaker? * Answer = Wrong way of looking at the 8-Ohm Impedance rating, Impedance is AC *

Also consider using an audio transformer, and see the linked questions.....

I'm voting to close this question as off-topic because it is about electronics and not about Arduino.

Basically you are right and it should work.
But if you want to go to details, it would be better look on AVR328 documentation, as nothing is as easy as it looks in Arduino tutorials.

maximum (really maximum) current on pin is 40mA for one DC pin and 200mA for all pins together (otherwise destruction of the processor is possible - never ever try to reach it), also  datasheet states:

Although each I/O port can source more than the test conditions (20mA
  at V CC = 5V, 10mA at V CC = 3V) under steady state conditions
  (non-transient), the following must be observed:
  ATmega48A/PA/88A/PA/168A/PA/328/P: 1] The sum of all I OH , for ports
  C0 - C5, D0- D4, ADC7, RESET should not exceed 150mA. 2] The sum of
  all I OH , for ports B0 - B5, D5 - D7, ADC6, XTAL1, XTAL2 should not
  exceed 150mA. If II OH exceeds the test condition, V OH may exceed the
  related specification. Pins are not guaranteed to source current
  greater than the listed test condition.

so 20mA is not recomended but is maximum guaranteed to be provided under some more conditions met - if you can, you should use less (also even if it works for one module on one pin, it may fail mysteriously for mor modules on more pins).

Even if 20mA is guaranteed for one pin, the voltage on it would drop more then 0.5V if you drain so much
you cannot draw as much on too many pins together
also the maximum you can draw is less if you want higher frequency (I think the sound is not usually in category, where it matter too much)

In your equation 1 you used 5V/20mA, you should use 4.4V/20mA also keep in mind, that there is usually like 0.7V on base of open transistor (depends of type) - so the R2 can be even smaller, if you use only few pins.
About R1 - if you open the transistor, there can be like 0.2V on the collector, so the current is like 4.8V/6.8Ohm = 0.7A - on UNO board v3.0 is used NCP1117 as stabiliser, which can support even 1A (if powered not from USB, but 7V and higher source (if such source can give as much) so it could work too, but beware as it is about 4.8V*0.7A=3.4W so R1 should be able to stand at least as much if the pin is HIGH for any longer time. If the pin is oscilating, the SPKR adds it current to that, so the value can be even higher (I would not use anything under 5W for R1).
On the other hand - Q1 2N3904 can support Ic max 200mA, so you could burn it by setting the pin for HIGH (or for PWM with more like 20% HIGH or more - switching makes even more heat) so you should use othe transistor here.
And this Q1 have current gain over 30 even for such currents as 100mA, so you need just 1/30 of Ic go thru the base from pin (so you need supply only 3.3mA to have 100mA thru Q1, 6.6mA is able to force 200mA and burn the transistor, if not properly cooled. 20mA is clearly much more than needed anyway.)
I would suggest some darlington transistor here or something like that, if you want manipulate such currents.
If your speaker is 0.5W only, you will burn more power on the R1 than on the speaker - not good result. It would be better just manipulate the speaker directly (put it instead of R1 and leave the R1 and C1 out).
(but on usual Arduino setup the power source and all is usually so underrated, that there is a good chance, that it would not be able to supply enough power to burn your equipement out, just it would drop the voltage and maybe fail randomly. Who knows. Also breadboards and long thin wires with bad connection adds a lot of resistance and voltage drops and manufacturers publish as maximal rating what the product should survive, which is usually a lot les, than is needed to sure destroy it, so many experiments can survive even if they should burn on simple paper calculations - which is part of why Arduino is so popular - is cheap and usually does not burn even if managed out of specs.)

I have to read multiple times to understand everything (which I still don't) ... more questions now than answers :-) But very good points to take care of ... I will think of how to formulate further questions... Thank you for the long and detailed answers what to think more (what I didn't knew about).

Thank you very much for your answers, bfter reading the answer several more times I have 6 additional questions (sorry for my lack of electronic 'practical' knowledge). It seems the ideal world differs a lot from theoretical 'ideal' circuits from high school text books.

Yes, exactly :) Arduino is for easy start on easy tasks, if you need go deeper, a lot can be obtained in Electrical Engineering - even about Arduino (once you start thinking about it little more like microprocessor AVRxxx and some electrical circuits around - change of philosofy or point of view, physically it is exactly the same). Anyway I use Arduino both ways - like simple tool for simple tasks the simple way (sometimes it is much faster than any other setup) and as AVR328  on simple board, which can be used in anything anyway. Also I made my own PCBs and programmed them both ways.

Arduino is really good starting point for many people and even if I changed my point of view on it and do a lot with more sofisticated setups, I still use Arduino platform for a lot of simple projects, as it does not need more. But sometimes you hit the limits of "simple world" and have to learn more. And sometimes you do not hit it and can do a task in simple way and then it is good to return fully to Arduino world. Aech task needs its tools and usually the simples can be used, the faster you get result :) So don't worry, be happy and have a fun any way you enjoy :)

That's why I like Arduino ... it's a quite easy environment (and also it doesn't break down if I make stupid mistakes, so far I only broke a LED, a IR receiver and one LED in an 8x8 matrix). But the best is there is a lot of documentation that can be found (although sometimes contradictory), and help from users here (which is highly valuable).
I will try to answer my own questions (in the near future after reading more about it).

The speaker rating of 8 Ω is AC resistance, speaker impedance. Impedance (AC-Resistance) changes based on the frequency of the signal fed into it.
If you are worried about hurting the speaker and need to calculate power driving that particular "load", look at the speaker Wattage rating.
Say it is 1 W for example, and you are providing 5 V d.c., the amperage required will be: 0.2 A.
V * A = W
0.2 * 5 = 1

So the DC resistance is actually:
V = I * R (0.2 / 5 = 0.04 Ω).

Give it a higher amplitude... say 5.7 V to account for a transistor no resistor, and you get about 0.175 A. and a change in DC resistance again to 0.0301 Ω.
If the power supply is AC, the impedance needs to be matched to the speaker impedance to get best energy efficiency, otherwise the amplifier can be damaged.
For that circuit I suggest you place a variable resistor where the resistor is in your circuit to allow for a volume change. Also a flyback diode maybe a good idea, that will protect the speaker but take down voltage 0.7 V d.c. keep in mind you have that transistor there adding 0.7 V d.c.! so it evens things out too using that diode.
That diode placed on the high (+) side of the circuit, before the speaker and after the variable resistor.

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:
Slow response from ENC28J60
I am making a circuit which turns a LED on and off through internet. I am connecting an Arduino to a LED and to an Ethernet controller(ENC28J60), but when I make a GET request to the device, it takes too long to respond - around 2 minutes - but my internet connection is fast.Before i get ip "ether.begin(sizeof Ethernet::buffer, mymac,8)" command fails it returns zero still i am able to control it.
Code:
#include <EtherCard.h>

#define STATIC 0

// mac address
static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 };
// ethernet interface ip address
static byte myip[] = { 172,26,40,250 };
// gateway ip address
static byte gwip[] = { 172,26,40,1 };

// LED to control output
int ledPin10 = 10;

byte Ethernet::buffer[700];

const char page[] PROGMEM =
"HTTP/1.0 503 Service Unavailable\r\n"
"Content-Type: text/html\r\n"
"Retry-After: 600\r\n"
"\r\n"
""
"<title>"
"Service Temporarily Unavailable"
"</title>"
""
"
This service is currently unavailable
"
"
"
  "The main server is currently off-line.
"
  "Please try again later."
"
"
""
""
;

void setup () {
    pinMode(ledPin10, OUTPUT);

  Serial.begin(9600);
  Serial.println("Trying to get an IP...");

  Serial.print("MAC: ");
  for (byte i = 0; i < 6; ++i) {
    Serial.print(mymac[i], HEX);
    if (i < 5)
      Serial.print(':');
  }

  if (ether.begin(sizeof Ethernet::buffer, mymac,8) == 0)
    Serial.println( "Failed to access Ethernet controller");
  else
    Serial.println("\nEthernet Controller Initialized");

#if STATIC
  Serial.println( "Getting static IP.");
  if (!ether.staticSetup(myip, gwip)){
    Serial.println( "could not get a static IP");

  }
#else

  Serial.println("Setting up DHCP");
  if (!ether.dhcpSetup()){
    Serial.println( "DHCP failed");
  }
#endif

  ether.printIp("My IP: ", ether.myip);
  ether.printIp("GW IP: ", ether.gwip);
  ether.printIp("DNS IP: ", ether.dnsip);
}

void loop () {

  word len = ether.packetReceive();
  word pos = ether.packetLoop(len);

  // IF LED10=ON turn it ON
  if(strstr((char *)Ethernet::buffer + pos, "GET /?LED10=ON") != 0) {
  Serial.println("Received ON command");
  digitalWrite(ledPin10, HIGH);
}

// IF LED10=OFF turn it OFF
if(strstr((char *)Ethernet::buffer + pos, "GET /?LED10=OFF") != 0) {
  Serial.println("Received OFF command");
  digitalWrite(ledPin10, LOW);
}

// show some data to the user
memcpy_P(ether.tcpOffset(), page, sizeof page);
ether.httpServerReply(sizeof page - 1);
}

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


text:
VSCode vs. Arduino IDE - same program, different behavior
I've got this simple program for testing DS18B20 temperature sensors.
#include "OneWire.h"
#include "DallasTemperature.h"

#define ONE_WIRE_BUS D3

// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

void setup()
{
  Serial.begin(19200);
  sensors.begin();
  delay(1000);  //time for serial to connect
  Serial.print(sensors.getDeviceCount());
  Serial.println(" sensors found");
  Serial.print(sensors.getDS18Count());
  Serial.println(" DS18 sensors found");
}

void loop()
{
  sensors.requestTemperatures(); // Send the command to get temperatures

  Serial.print("Temperature for Device 1 is: ");
  Serial.println(sensors.getTempFByIndex(0));

  Serial.print("Temperature for Device 2 is: ");
  Serial.println(sensors.getTempFByIndex(1));

  delay(5000);

}

I'm compiling for the Wemos D1 mini.
When I compile on the Arduino IDE, the code runs as expected. It reports two devices, then gives the temperature reading from each device.
When I compile using VSCode and the Arduino extension, the code compiles and uploads successfully, the program reports 2 devices, just like the Arduino IDE compilation does, but then it prints -196.60 for the temperature reading, which is the "no device" value.
Same breadboard, same host computer - the only difference is the IDE. I'd much prefer to stick with VSCode, but if the resulting executable is wrong, then it's a non-starter.
Why the different results? More importantly, how do I get the VSCode to produce the same (correct) output as the Arduino IDE?
UPDATE:
Apparently the issue has something to do with the serial monitor. The project I'm actually trying to build has an OLED display for the temperature. The temperature is correct if the VSCode serial monitor is closed. Open the monitor and the incorrect values appears. Close the monitor and the correct values appear again.
UPDATE 2:
The problem remains over a range of serial port speeds, from 19200 to 115200. I didn't try outside that range.
UPDATE 3:
Code compiled using VSCode but run observing through the Arduino IDE serial monitor has the correct behavior - ie, shows the correct temperatures.

what is your question?

What do you want to know? -- "Why is this?" can be quite difficult to answer, while "How to avoid?" is already answered by yourself. -- Since you have not shown the source with the display code, we cannot say anything on that case. Please [edit] your question.

Looks like an issue worth reporting to whoever maintains the Arduino extension for VSCode.

Originally developed by Microsoft, the Arduino extension for vscode reportedly went open source circa 2017. It looks like the repository on GitHub takes bug reports https://github.com/Microsoft/vscode-arduino/issues

There is discussion in some of the error reports at the GitHub repository regarding ongoing instability with the VSCode serial monitor and some ‘fairly significant’ code changes they’re working through.

@EdgarBonet - I've submitted an issue to the github repo for the project.

@RowanP - I've submitted an issue to the github repo for the project

Further testing by OP isolated a bug in the Arduino Extension for VSCode which was logged as an issue at https://github.com/microsoft/vscode-arduino/issues/1467


text:
Arduino randomly freezes during runtime?
I'm currently trying to create a traffic simulation project on Arduino, where it can change lights, open a gate, and turn on street lamps based on light. If anybody could help me diagnose why my arduino is behaving this way, that'd be extremely appreciated. Here is my code, if it helps you understand.
//Libraries Used
#include<Servo.h>

//Variable Declaration
int red1 = 10;
int yellow1 = 9;
int green1 = 8;
int red2 = 13;
int yellow2 = 12;
int green2 = 11;
int debug = 3;
int PIR = 5;

int button1 = 2;
int buttonState = 0;

int light = 0;

unsigned long previousTime = 0;
unsigned long currentTime = 0;
int currentState = 0;

int currentPIR = 0;
int pirState = LOW;

Servo servo;

void setup()
{
  pinMode(red1, OUTPUT);
  pinMode(yellow1, OUTPUT);
  pinMode(green1, OUTPUT);
  pinMode(red2, OUTPUT);
  pinMode(yellow2, OUTPUT);
  pinMode(green2, OUTPUT);
  pinMode(debug, OUTPUT);

  pinMode(PIR, INPUT);

  pinMode(button1, INPUT);

  servo.attach(4);
  servo.write(90);
}

void loop()
{

  currentPIR = digitalRead(PIR);
  if(currentPIR == 1){
    servo.write(180);
  }else{
    servo.write(90);
  }

  buttonState = digitalRead(2);
  light = analogRead(A0);

  if(light > 100){
    digitalWrite(debug, HIGH);
  }else{
    digitalWrite(debug, LOW);
  }

  if(buttonState == HIGH){
    if(currentState == 3){
      digitalWrite(debug, HIGH);
      currentState++;
    }
  }
  //Using millis() instead of delay(), so program doesn't pause completely.
  currentTime = millis();
  changeLights();
}

void changeLights(){
  if(currentState == 0){
    //Red, Green
    digitalWrite(red2, LOW);
    digitalWrite(red1, HIGH);
    digitalWrite(green2, HIGH);
    asyncDelay(4000);
  }
  else if(currentState == 1){
    //Red, Yellow
    digitalWrite(green2, LOW);
    digitalWrite(yellow2, HIGH);
    asyncDelay(2000);
  }
  else if(currentState == 2){
    //Red, Red
    digitalWrite(yellow2, LOW);
    digitalWrite(red2, HIGH);
    asyncDelay(750);
  }
  else if(currentState == 3){
    //Green, Red
    digitalWrite(red1, LOW);
    digitalWrite(green1, HIGH);
    asyncDelay(4000);
  }
  else if(currentState == 4){
    //Yellow, Red
    digitalWrite(green1, LOW);
    digitalWrite(yellow1, HIGH);
    asyncDelay(2000);
  }
  else if(currentState == 5){
    //Red, Red
    digitalWrite(yellow1, LOW);
    digitalWrite(red2, HIGH);
    asyncDelay(750);
  }
}

void asyncDelay(int delayTime){
  if(currentTime - previousTime == delayTime){
    currentState++;
    previousTime = currentTime;
    if(currentState == 6){
      currentState = 0;
    }
  }
}

add debugging code to your sketch

You should replace:
if(currentTime - previousTime == delayTime){

with
if(currentTime - previousTime >= delayTime){

There is always a chance that, since you are using a servo which is quite intensive with interrupts, that millis() may skip a beat and that statement can never be true.

Thank you! I don't know why I hadn't thought of this before, but thank you for such a simple fix! I will accept your answer as solved in a few minutes when it allows me to, but thank you so much, I've been so confused over this the whole day.

@BillBai You should confirm it fixes it - it's only a suggestion...

yup, I confirmed it worked, and it's been working for a few minutes already - rather than the 20 seconds max as before.


text:
Photoresistor Matrix has the same values
I'm a second-year System Engineer student who needs to make a project for class.
I have a 4x4 matrix of photoresistors that goes to an analog digital multiplexer connected to an Arduino Uno. This setup is put in a box with a lid. The lid has a hole in the middle of the matrix. I want to calculate the angle of a light source depending on the photoresistors' readings. Basically, I want to recreate a Sattelite Sun Sensor.
I have the following problem: all the photoresistors from a row have the same reading, even if I try to isolate one of them and shine a light on it. In the column, everything works well.
This is my circuit on a 2 layers PCB:
(C0-C15, SIG, S0-S3, EN are the pins of the CD74HC4067 Multiplexer)

Also, this is my code:
//Mux control pins
int s0 = 11;
int s1 = 10;
int s2 = 9;
int s3 = 8;

//Mux in "SIG" pin
int SIG_pin = 0;
float values[4][4] = {0.0};

void setup(){
  pinMode(s0, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);
  pinMode(s3, OUTPUT);

  digitalWrite(s0, LOW);
  digitalWrite(s1, LOW);
  digitalWrite(s2, LOW);
  digitalWrite(s3, LOW);

  Serial.begin(9600);
}

void loop(){

  //Loop through and read all 16 values
  for(int i = 0; i < 4; ++i)
      for(int j = 0; j < 4; ++j){
        values[i][j] = readMux(i);
        delay(500);
      }

  Serial.println("-----Matrix-----");
  for(int i = 0; i < 4; ++i){
      for(int j = 0; j < 4; ++j){
        Serial.print(values[i][j]);
        Serial.print(" ");
        delay(100);
    }
    Serial.println();
  }
  Serial.println();
  Serial.print(calculateAngle());
  Serial.println();
  delay(1000);
}

float calculateAngle(){
  const int dx[] = {-2, -1, 1, 2, -2, -1, 1, 2, -2, -1, 1, 2, -2, -1, 1, 2};
  const int dy[] = {-2, -2, -2, -2, -1, -1, -1, -1, 1, 1, 1, 1, 2, 2, 2, 2};
  float x = 0, y = 0;

  for(int i = 0; i < 16; ++i){
    x += dx[15 - i] * values[i / 4][i % 4];
    y += dy[15 - i] * values[i / 4][i % 4];
  }
  Serial.print(x);
  Serial.print(" ");
  Serial.print(y);
  Serial.print(" ");
  return atan2(y, x) * 180 / 3.14;
}

float readMux(int channel){
  int controlPin[] = {s0, s1, s2, s3};

  int muxChannel[16][4]={
    {0,0,0,0}, //channel 0
    {1,0,0,0}, //channel 1
    {0,1,0,0}, //channel 2
    {1,1,0,0}, //channel 3
    {0,0,1,0}, //channel 4
    {1,0,1,0}, //channel 5
    {0,1,1,0}, //channel 6
    {1,1,1,0}, //channel 7
    {0,0,0,1}, //channel 8
    {1,0,0,1}, //channel 9
    {0,1,0,1}, //channel 10
    {1,1,0,1}, //channel 11
    {0,0,1,1}, //channel 12
    {1,0,1,1}, //channel 13
    {0,1,1,1}, //channel 14
    {1,1,1,1}  //channel 15
  };
  DDRB = 0;
  //loop through the 4 sig
  for(int i = 0; i < 4; i ++)
    DDRB |= (1 << i) & muxChannel[channel][i]; //faster than digitalWrite(controlPin[i], muxChannel[channel][i]);
  delay(100);
  //read the value at the SIG pin
  int val = analogRead(SIG_pin);
  //convert the value in voltage
  float voltage = (val * 5.0) / 1024.0;
  //return the voltage
  return voltage;
}

Example of a bogus reading:
-----Matrix-----
0.13 0.14 0.13 0.12
3.14 3.17 3.12 2.96
0.12 0.12 0.11 0.12
2.77 2.81 2.83 2.77

What am I doing wrong? Did I make a mistake in my code or connecting everything together? Thank you for any help!

This is probably, because you don't actually set the MUX pins. The DDRx registers set the Data Direction of the port pins. A 1 in there means, that the pin corresponding to that bit is set as output. A zero means, it is set as input. The output state of a pin is controlled by the PORTx registers. If the DDRx bits are set to input and the PORTx bits are set to 1, then the internal pullup resistor is activated.
In setup you set all the MUX pins to OUTPUT and LOW, so DDRB with 1s and PORTB with zeros. Then in readMux() you are just setting bits in DDRB via the (overcomplicated) line:
DDRB |= (1 << i) & muxChannel[channel][i];

So you are switching the pins between OUTPUT+LOW and INPUT+NO_PULLUP. Instead you should write to the PORTB register, which controls the output state of the port B pins.
Also writing the mux channel can be done way easier. When you look at your array in readMux() you might notice, that the channel patters are just a binary number. So you have the following channel number to pattern relationship:
channel  0 --> binary 0000 --> decimal 0
channel  1 --> binary 0001 --> decimal 1
channel  2 --> binary 0010 --> decimal 2
channel  3 --> binary 0011 --> decimal 3
...
channel 10 --> binary 1010 --> decimal 10
...

So instead of using the above overcomplicated line, you can just write the channel number to the 4 target bits of PORTB:
PORTB |= channel & 0b00001111;

You don't even need to for loop for that. The & 0b00001111 part is only for cutting the channel number to only ever use the first 4 bits of the register (keeping it down between 0 and 15).

So this solved one of the problems. The main one was that I was reading just 4 channels 4 times instead of all different 16, thus why the values were similar. Thank you so much for helping me and for the code optimization!


text:
SHT30 giving wrong humidity
I have an SHT30 sensor which is feeding to my Arduino via an RS485 connection. The readings are coming in as they should be for both temperature and humidity. The problem, however, is that the relative humidity I get from the SHT30 sensor is currently 45%, whereas the calculation of humidity from dry and wet bulb readings in the same conditions is 75%.
How can it be that my SHT30 reading differs by 30% from the actual calculated reading?
I confirm that all of the charts I have looked at place my relative humidity (given dry and wet bulb readings that I know are accurate) to be in the region of 75%. I know for certain, therefore, that it is my humidity sensor that is wrong.
Have you experienced this issue and, if so, how have you fixed it?
Many thanks in advance!

There's really nothing here to go on. The performance of an SHT30 over time depends on several factors. I've never had one go too far out of its published specs except when damaged (too-high humidity for too long) but even then it wasn't that far off. You'll likely need to supply details beyond "it's wrong" though :)


text:
Powering an rc car motor with arduino
I have a weird problem. When I power an rc car motor through the 5v or the 3.3V arduino's outputs everything goes fine, while powering it through digitalPins does not work.
I'm testing digitalPins with a simple led Blink example. Leds work, the motor does not move. Shouldn't digitalWrite(pinNumber, HIGH) output 5volts? What is the difference between digitalWrite voltage and 5v board output voltage? It seems crazy to me that leds light up without problems but the motor remains motionless...

Do you know how much current a digital pin can provide? Do you know how much current the motor draws? Please update your question with those details.

I deserve these answers ;)

Never ever power a motor or anything, that needs that much power, through a digital output pin. The maximum rating is 40mA, though you should not draw more than 20mA continuously from it. Also there is an overall limit of 100mA over all digital pins together. If you are drawing more from the pins, first the voltage will drop immediately, since the pin cannot provide what you ask for. Then you can easily destroy the pins output hardware or the whole Arduino. For an LED you normally use a current limiting resistor, so that it does not draw too much current from the pin.
For anything with more current demands, you need some kind of driver, which will take the big current load of the microcontroller. The easiest driver is a transistor or MOSFET (to switch the motor on and off or to have different speeds). If you want the motor to spin in both directions, you need an H-bridge driver (effectively 4 transistors/MOSFETs).
Note: I'm talking about simple DC motors here. Other types of motors need other types of drivers.

Good answer. Note that you probably also need a flyback diode to protect the transistor from the inductive motor coils

It's also not a great idea to drive anything but the smallest motors from the 3.3V or 5V outputs on the Arduino board. Those have very modest current output, and the noisy load of a motor will likely cause the power to everything else to bobble, even if it doesn't exceed the low current limits of those supply lines


text:
Daisy chaining of multiple blocs of 4x(8x8) MAX7219 matrix
Thanks for your presentation https://arduino.stackexchange.com/tags/max7219/info.
You say that multiple MAX7219 8x8 blocs can easily be daisy-chained and you show an example of at least 12 blocs displaying "Testing12345".
Trying several programs I found for Arduino, I never succeeded to chain more than 8 blocs with 8x8 matrix (either 8 individual blocs or 2 groups of 4 as on your image).
So I'ld be very happy if you send me examples of programs managing more than 8 blocs for fixed or scrolling displays.
Many thanks in advance.

The person who wrote the presentation will probably not see this... I suggest you make this question more 'generic'  (not using 'you' ), and add a comment in his post to mention yours (since it's a new question).

I never succeeded to chain more than 8 blocs with 8x8 matrix is a useless description of the problem because it contains no information that can be used to resolve the problem .... something like if i chain more than 8 blocs, then XYX happens is way more useful

Try using @Majenko 's MAX libary https://github.com/MajicDesigns/MD_MAX72XX .  It allows you to specify how many modules are to be addressed.

Thanks for your answer. Very intersting library. But, with its examples, there is an addressing issue on my display. For each 8x8 matrix the columns seem to be inverted, displaying first the column #8 instead of column #1. So the global scrolling is OK from right to left (first to last matrix of the daisy-chain), but each matrix is scrolling its columns from left to right with inverted display!

With static display of a text, it's the same: the columns of each 8x8 matrix are inverted.

All is OK changing the proposed statement
define HARDWARE_TYPE MD_MAX72XX::PAROLA_HW
to
define HARDWARE_TYPE MD_MAX72XX::FC16_HW


text:
Using arduino uno and an adafruit shield to control 3 dc motors and a linear stepper motor
Hello I am currently doing a project at my university which requires me to order and program 4 motors using an arduino. I will be using an arduino uno and an adafruit motor shield. 2 of the dc motors will have an encoder for better motor control. While connecting the linear and one of the dc motors shouldn't be difficult, I am wondering how can I connect the two motors with encoders.
I was thinking to connect 1 dc motor and the stepper onto one shield and the encoder motors onto another since the shields can stack. Is this option possible or should I use some other method? I am fairly new to arduino and only had a little bit of experience with coding so any help and suggestions are welcome.

It looks like Adafruit motor shield can control 4 DC motors and 2 stepper motors. So one shield should be enough. https://www.adafruit.com/product/1438

Thanks for the reply. The adafruit motor shield has enough connections for either 4 dc motors or 2 stepper motors therefore the most I could connect would be 2 dc and 1 stepper. So at least 2 shields will be required. What I am unsure of is can I even connect encoded motors to the motor shield or will I need to order another board specifically to run them.

You are right, my bad. Looks like you will need two shields then. But you will need stackable header. The ones that come with the Adafruit Shield is not stackable. Something like this: https://www.amazon.com/Arduino-Stackable-Header-Kit-R3/dp/B00PCCWEJG/ref=dp_ob_title_ce


text:
I think i worn out all of my Arduino Uno memory
Hi my Arduino Uno stacked with a motor driver shield was working perfectly however I am using the same board for a while now and suddenly my board stopped working.
When I upload a code no matter what code is the LED's on the board respond however the code is not executed it does nothing , the board doesn t even beep anymore.
Is there a way to clean the memory or something?
Please help.

To check if you really cannot upload anymore (assuming it's not a software error), try the following sketch
https://www.arduino.cc/en/tutorial/blink
This will blink the BUILTIN led.
There is very low chance to wore out your memory, you can write lots of times to it (like 10,000 times guaranteed, in practice mostly more).
But there can be another hardware problem, but first check if this simple sketch works.
Also (based on jsotola's comment), remove shields/wires.
Especially wires/shields using RX/TX since these pins are (somehow) used for loading a sketch.

@jsotola good point, I will edit my answer

Yes thank all codes that i tried work with just the Arduino Uno however when I stack the motor driver shield l239D i cant upload any code it says that an error has ocurred while uploading the sketch.

That's probably because the shield uses some GPIO pins, especially RX/TX... So that means every time you want to upload a new sketch you have to remove the shield.

Hmm thank you are you saiyng that if i upload a code to Control motors just to the Arduino board without the driver shield atached and the i connect the driver shield it Will work?

Michel keijzers thank you so much man really it worked  just fine!!! Thank you realy you do made Diference.

@Noslen Yes I'm afraid you have to do that … if it is the most helpful answer, please accept it (click on the arrow up next to the answer). Or wait a few days to see if someone else has a better answer. (and accept the one that's best at that time).


text:
Micro servo is not working with Arduino UNO
I am new to Arduino and trying to do some basic tasks. I want a micro servo to rotate but it's not working, only slightly virbating when I launch a sketch. Below on the photos is how it is all assembled: I have a jumpwires connected to GND, 5V and #8 ports just as in the tutorial. I use micro servo SG-90 and Funduino UNO. Does anybody have any ideas what might the problem be? Here is also the sketch.
#include <Servo.h>

Servo servo;

void setup() {
  // put your setup code here, to run once:
servo.attach(8);
}

void loop() {
   // put your main code here, to run repeatedly:
servo.write(0);
delay(2000);
servo.write(90);
delay(2000);
}

USB power is usually way too weak for driving servos or motors

Hm, I didn't think about it. So, should I use batteries or charger instead?

You should not power a servo from a USB port.
However, your most glaring problem is that you have entirely mis-wired the connections, such that no wire is going to the correct place.
Servo connections are in the order of Ground - Power - Signal, usually with a dark color for ground and a redder one for power.  Connector shells aren't standardized between brands, but within one there may be keying to prevent reverse installation.
It would appear that on your servo, ground is brown, power red, and signal orange.
Pull out all three wires and start over; also you'd do well to use a dark color for the ground, as you appear to have mixed up the power and ground as well as the signal.

Yes, I totally messed up with all the wire connections. Now when all of them are in the right places everything is working excellent! Thank you for the explanation, I'm gonna keep it in mind.


text:
Highly sensitive light sensor to calculate number of times each color LED blinks
I am working on a project and got stuck on a point, and I hope somebody will guide me. I have a hardware device which has different color LEDs (green, red and yellow) and I have to calculate how many times each color LED glows for each mode of operation.
The LEDs that are connected to the device are pretty small and will blink only for a couple of seconds, ao I am looking for a very sensitive light sensor.
So what kind of light sensor do I have to use with Arduino UNO to achieve this?
Should I go for BH1750 or do you have any other suggestion?
Thanks in advance.

You don't need something that advanced. Simple LDRs or Phototransistors will do just fine. Just make sure you add some back tape, so no outside light can come into the sensors, as that will make it a lot easier for you. Just attach the sensors to the analog pins, with appropriate resistors.

@Gerben, I think you should add that as an answer. It is what I would use, too.

Thank you so much for your suggestion Garben , I will try to use Simple LDR , will you be able to suggest any specific model name related LDR's, So i that i can go and buy those particularly.

Like the OP wrote, you can use very simple sensors, like a phototransistor.
Even simpler, if you can somehow isolate each pair LED-phototransistor, you don't even need to care about the color of the led, just use some bluetac to stick one phototransistor on top of each LED and only measure the brightness.
edit:
A quick check on ebay shows the 3DU5C as good candidate: it has a metallic container, so it is more directional than one with full plastic body.
3DU5C ebay link  and  datasheet
It is shown to have a peak response at 880nm (red light), so you might not be able to use it directly as digital input for the other 2 colors you want to monitor and instead have to treat it as analog reading.
OTOH if you use them all as analog inputs, you will not have to add the resistor that would be required for binary mode.

Thank you so much for your suggestion Igor , I will try to use Simple LDR , will you be able to suggest any specific model name related LDR's, So i that i can go and buy those particularly.


text:
How to use an external clock with the Due timer?
I want to use an external clock signal as an interrupt for the Due timer. How do I do that? I could not find any info on this on the net.

Everything you need to know is in the SAM3X datasheet:
http://www.atmel.com/Images/Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf
However, as Atmel's datasheets are some of the most cryptic ones around, you'll need to spend quite some time deciphering it.
There's an entire section just on the timers.  It tells you all about how they work, however, relating that to which registers you need to set to get it to do that is not clear (as is normal for Atmel) since the registers are listed elsewhere in that section with no real relationship between them.


text:
Floating pins: digitalRead returns always high or always low
I was trying to see whether my board operates as expected with random readings on floating pins. Oddly it does not. The following code produces all HIGH readings:
#define PIN_MISO 12

void setup() {
  pinMode(PIN_MISO, INPUT);
  Serial.begin(9600);
}

void loop() {
  uint16_t data = 0;
  Serial.print("MISO digitalRead: ");
  data = digitalRead(PIN_MISO);
  Serial.println(data, BIN);
  delay(300);
}

MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1
MISO digitalRead: 1

I tried grounding pin 12 and after a few seconds the readings all came back LOW as expected. However leaving it floating produces all HIGH instead of random readings.
I tried the same program for pins 3 and then A3 with more weird output: all LOW.
What am I missing here?

If it's floating, then anything can influence the reading. Humidity, temperature, nearby pins/traces, a human body nearby (try placing your finger near the pin), manufacturing differences, nearby radio sources (WiFi, BT). But in the end of the day, it doesn't matter, as you should rely on a certain value from floating pins. Just add a pull-up or pull-down resistor.

You are missing longer wires, touch or something noisy nearby (like DC motor)

Why you expect to behave randomly every read?
According to Arduino docs, you should be using the random function to get random numbers, of course this is a pseudo random generator which you have to randomSeed, for this you could use an analogRead to a floating input.

Floating means it would generate any value. This could be a result of innumerable factors and it is HIGH in this case! you cannot expect anything other than a HIGH or LOW.
Think of it this way-
It's fluctuating in a range of about 900-1000 but the range is still very close to 1023 hence it results in a HIGH.
Some other time it may be near the lower values then it would show LOW.

While an intermediate level is possible, it may be more probable that the actual voltage is a definite legal "high" but that there is nothing holding it there with any authority - only the vaguest of leakage current, easily overcome by any other driver or source of charge.

Change:
pinMode(PIN_MISO, INPUT);

to
pinMode(PIN_MISO, INPUT_PULLUP);

This will enable the internal 20k pull-up and you should then always read HIGH is the pin is floating.
Using INPUT does not enable the internal pull-up (Ref: https://www.arduino.cc/en/Reference/pinMode)

This does not answer the original question!

Actually, this answer did work for me, the implication being, "you're doing something that's undefined, so there's no point in speculating on what you might read; instead do something like this if you're going to be reading floating pins."


text:
Issues with analog microphone readings
I'm having issues with sampling audio with a microphone and NodeMCU v3. I realize this is the Arduino section so if NodeMCU running the Arduino IDE is not meant for this forum, let me know.
The problem: I am sampling audio for an sound reactive RGB LED strip with the NodeMCU v3. When I use USB power from my computer, everything works well. If I power the NodeMCU from a 7805 linear regulator (5v) to Vin, it works fine. "Silent" conditions hang around 0 volts and audio levels show up clearly. When I power the NodeMCU with a 3.3v switching regulator (with the microphone grounded on the NodeMCU and VCC coming from the 3v3 pin) this is where the problem starts. If I have the LED strip unconnected, it detects the sound find (although my "silent" conditions hover more around .1 volts but for my purposes that wouldn't be an issue).
The problem is powering the board and subsequent microphone from the switching regulator with the lights connected I get very erratic voltage readings that are all over the place. You might be asking why not just use the linear regulator then? Well, even at 12 volts the (12v-5v)*(a few hundred mA) is a decent amount of heat to dissipate but sure I could get a heat sink and control it, but the end goal for this project is to power my 10m strip, which is 24 volts, and the linear regulator would have to dissipate (24v-5v) * (a few hundred mA). I really do not think this is sustainable, which is why I got the switching regulator in the first place.
I was told that these switching regulators do not play nicely with microphones. Even with the LED strip unconnected it wasn't as consistent as USB or linear regulator power but it still worked perfectly fine.
Could anybody explain why this issue arises and hopefully a way to fix it? Are there tricks I can use to limit whatever interference is occurring? Should I give up on trying to make the switching regulator work? Would capacitors/resistors solve this?
I really would prefer to use the switching regulator for efficiency reasons. My second option wouldn't be the linear regulator, it would be powering the Node from a wall adapter and USB cable to be honest. This is getting quite frustrating. One problem's fix causes another, but I suppose that's how things go sometimes.
I am including a diagram of my setup. Please note the linear regulator should actually be a switching regulator and the board I am using is not the Huzzah, it's the NodeMCU v3.
Components:

NodeMCU v3
Adafruit Electret Mic (won't let me post more links... it's the adj. gain one)
Switching Regulator
N Type Mosfets
RGB LED strip (currently a 5 meter 12 volt 5050 leds, future: 10 meter 24 volt)

If there is something that will solve my issue, I am not worried that it costs $5 versus the linear regulator being

I would really really appreciate any help in solving this issue, this is pretty much the last part of a pretty big and feature-rich controller.
Hopefully I have included as much information as is needed.
Thank you and feel free to ask any questions!

The problems mentioned probably result from electrical interference, and as such might be better addressed in  Electronics Stackexchange.  But here is a quick overview of how to ameliorate the problem: add shielding and filtering.
For shielding, add a housing or braided-wire cable sleeves.  To shield against electrical fields, the housing should be conductive and have no openings larger than the wavelength of the  electrical interference you wish to suppress.  To shield against magnetic fields, it should be made of a ferromagnetic material.  You should have a housing around the switching supply, and can also add housings around any sensitive amplifier circuits.
For filtering, you can add an output filter with a few thousand microfarads of capacitance.  For better filtering, use several large capacitors, with a choke (inductor) to connect each capacitor to the next.  Add ferrite beads on each of the wires out of the power supply.  Besides the large capacitors, add a couple of small ones, eg 0.01 and 0.1 μF before the chain of large filter capacitors, ie, close to the output terminals of the switching supply.  Small capacitors generally have smaller self-inductance and can be more effective than large ones at suppressing high frequency hash.  The big capacitors effectively smooth out lower frequency ripple but if they have much self-inductance may fail to suppress high frequencies.

Thank you for the information! I will try to see if it helps!


text:
DS18B20 temperature sensor not working
I am new to arduino.I try to read temperature using DS18B20 temperature sensor.I connected the pins as bellow.But,When I connected 1-pin to ground and 3-pin to +5V the sensor heated and all the little lights on the UNO board turned off and it stopped working.

When I connected 3-pin to ground and 1-pin to +5V the board worked normally.But,I gives -127 as the temperature when I uploaded the bellow code.
#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is connected to the Arduino digital pin 2
#define ONE_WIRE_BUS 2
// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature sensor
DallasTemperature sensors(&oneWire);

void setup(void)
{
// Start serial communication for debugging purposes
Serial.begin(9600);
// Start up the library
sensors.begin();
}
void loop(void){
// Call sensors.requestTemperatures() to issue a global temperature and Requests to all devices on the bus
sensors.requestTemperatures();
Serial.print("Celsius temperature: ");
// Why "byIndex"? You can have more than one IC on the same bus. 0 refers to the first IC on the wire
Serial.print(sensors.getTempCByIndex(0));
Serial.print(" - Fahrenheit temperature: ");
Serial.println(sensors.getTempFByIndex(0));
delay(1000);
}

I connected with both Normal mode and Parasite mode.But, same results..
I use this:

Help me to solve the problem.
Thank you!

you have to connect the middle pin also

The topmost image shows the correct connection (with the flat side of the package facing you). It should not have heated up so I suspect you made an error. Pin 2 (the data pin) should have a pull up of about 4.7k-10k Ohm to VDD. The -127*C value just indicates that the device is not responding or functioning or you might have destroyed it during your first trial. You can use the "Tester" example that comes with the DallasTemperature library to see if the device is recognized and to print out its unique address.

Thank you for the comments...
Yes,I pulled up of 7.4k Ohm to VDD.

Your setup (as you described it) seams OK. I can not find any errors in your program. I fear the device is broken, or you bought a fake 18B20. Can you trust your seller? The device should not heat up at all, even if you reverse connect the power pins. The -127 is plausible because the device was powered with the wrong polarity and does not operate. If you power it correctly it heats up and draws much more current than it should (<4mA). That's a bad sign. Have you a spare part? Then you can try this. But if you bought fake devices, I fear that one will not work too.

I bought this from a trusted shop in the country.
I tried but I could'nt find the error.


text:
Esp8266 SD card read from inside of class
This is now my 3rd attempt at being able to read this sd card from within the Esp8266webserver.
I have made a class WebServer, and would like my sd card to contain my site.
What throws me off, is I am able to access the SD card everywhere with the exception of inside of the
.on callbacks.
I can read from/write to the sd card from Everywhere except for inside of a call back. What makes things even more odd, if I init my sd card using SD.begin(0) inside of the call back, it ALSO fails, That really is confusing. For somereason I can't get SD access inside of the callback.
Any ideas or suggestions would really really be appreciated.
so:
void WebServer::handlers(){
  // THIS WORKS!!!!!
  File myFile;
  myFile = SD.open("test.htm");
  if (myFile) {
    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      Serial.write(myFile.read());
    }
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
  // END THIS WORKS!!!!

  server.on("/", [this](){ sayHello(); }); // <- HERE IS WHERE THE TROUBLE STARTS!!!

  server.begin();
}

Here is what isn't working, i have removed some code to make it more easy to see:
void WebServer::sayHello() { //<- HERE IS THE CALLBACK, This always fails
  File myFile;
  myFile = SD.open("test.htm");
  if (myFile) {
    while (myFile.available()) {
      Serial.write(myFile.read());
    }
    myFile.close();
  } else {
    Serial.println("error opening test.txt");
  }

  server.send(200, "text/plain", "hello from esp8266!");
}

void WebServer::handlers(){
  server.on("/", [this](){ sayHello(); }); // <- HERE IS THE SETUP FOR THE CALLBACK (TROUBLE HERE)
  server.begin();
}

Here is my full code for reference:
#include <ESP8266WebServer.h>
#include "webserver.h"
#include <SD.h>

WebServer::WebServer(int n) { //, Storage*& storage
  ESP8266WebServer server(n);
  if (!SD.begin(0)) {
      Serial.println("SD initialization failed!");
  } else {
    Serial.println("SD initialization success!");
  }
}

void WebServer::sayHello() {
  File myFile;
  myFile = SD.open("test.htm");
  if (myFile) {
    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      Serial.write(myFile.read());
    }
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }

  server.send(200, "text/plain", "hello from esp8266!");
}

void WebServer::handlers(){
  File myFile;
  myFile = SD.open("/test.htm");
  if (myFile) {
    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      Serial.write(myFile.read());
    }
    myFile.close();
  } else {
    Serial.println("error opening test.txt");
  }

  server.on("/", [this](){ sayHello(); });
  // server.onNotFound(handleNotFound(server));
  server.onNotFound([this, SD]() {
    handleNotFound();
  });
  server.begin();
}

void WebServer::handleClients() {
  server.handleClient();
}

bool WebServer::stream(File dataFile, String dataType) {
  return server.streamFile(dataFile, dataType) != dataFile.size();
}

void WebServer::writeFile(String message) {
  File myFile;
  myFile = SD.open("test.txt", FILE_WRITE);
  if (myFile) {
    myFile.println(message);
    myFile.close();
  }
}

bool WebServer::loadFromSdCard(String path) {
  Serial.print(path);
  String dataType = "text/plain";
  if (path.endsWith("/")) {
    path += "index.htm";
  }
  if (path.endsWith(".src")) {
    path = path.substring(0, path.lastIndexOf("."));
  } else if (path.endsWith(".htm")) {
    dataType = "text/html";
  } else if (path.endsWith(".css")) {
    dataType = "text/css";
  } else if (path.endsWith(".js")) {
    dataType = "application/javascript";
  } else if (path.endsWith(".png")) {
    dataType = "image/png";
  } else if (path.endsWith(".gif")) {
    dataType = "image/gif";
  } else if (path.endsWith(".jpg")) {
    dataType = "image/jpeg";
  } else if (path.endsWith(".ico")) {
    dataType = "image/x-icon";
  } else if (path.endsWith(".xml")) {
    dataType = "text/xml";
  } else if (path.endsWith(".pdf")) {
    dataType = "application/pdf";
  } else if (path.endsWith(".zip")) {
    dataType = "application/zip";
  }
  File dataFile = SD.open(path.c_str());
  if (dataFile.isDirectory()) {
    path += "/index.htm";
    dataType = "text/html";
    dataFile = SD.open(path.c_str());
  }
  if (!dataFile) {
    return false;
  }
  if (server.hasArg("download")) {
    dataType = "application/octet-stream";
  }
  Serial.print(dataFile.size());
  Serial.print("About to send it!");

  while (dataFile.available()) {
      Serial.write(dataFile.read());
    }
  if (server.streamFile(dataFile, dataType) != dataFile.size()) {
    Serial.print("Returned too little data");
  }
  dataFile.close();
  return true;
}

void WebServer::handleNotFound() {
  Serial.print(server.uri());
  if (loadFromSdCard(server.uri())) {
    return;
  }
  String message = "SDCARD Not Detected\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET) ? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i = 0; i < server.args(); i++) {
    message += " NAME:" + server.argName(i) + "\n VALUE:" + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
}

Also, I want to add, I am seeing this message while compiling. Because I can access the files in other places, I have been ignoring it, but I am seeing:
extern SDClass SD;

                ^

C:\Users\kevin\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\SD\src/SD.h:206:16: note: 'SDClass SD' declared here

When you say it "fails" or "doesn't work", what actually happens?  Is it reading gibberish?  Is it printing the error message?  Is it failing to compile?  What's going on?

ahh, sorry, The exact thing that happens is the card initializes i get the "SD initialization success!" message from line 10 of the full code. however, I get the error message from the result of myFile = SD.open("/test.htm"); saying: "error opening test.txt"

Have have SD.open("test.htm") and SD.open("/test.htm"). Don't know if the slash matters...

@simSon, I have, I acutally just changed that as It was something I was testing. By moving the read into ANY part of this other than a callback, then it works.... it is just inside of the call back where it fails, I think it has something to do with the callback and I just don't understand this enough to know what is wrong

You could try to make void WebServer::sayHello() a static member if possible


text:
First time arduino attempt. 4 switch inputs controlling 8 LED outputs
This is my first venture into Arduino. I am unsure which one to use even for this. As this will be a dedicated unit, and size is a small priority, the smaller the better.
Here is more info on the scheme I am looking for.
Switch 1 on turns on LED groups 1 and 2
Switch 2 on turns on LED groups 3, 4, 5, 6, 7 and 8
Switch 3 on turns on 1 for say 500 ms, then turns 1 off, turns on 3 for 500 ms, then turns off 3, then turns on 5 for 500 ms, then turns off 5, turns on 7 for 500 ms, then turns off 7, then loops back and turns on 1 repeating the cycle.
Switch 4 on turns on 2 for say 500 ms, then turns 2 off, turns on 4 for 500 ms, then turns off 4, then turns on 6 for 500 ms, then turns off 6, turns on 8 for 500 ms, then turns off 8, then loops back and turns on 2 repeating the cycle.
Will I need an Arduino uno, nano or micro?
I am hoping this will be an easy to do project in order to learn the world of Arduino

Any Arduino would be able to do this trivially small task.  Any of them are capable of way more if you want it.  If size is your biggest concern then get a small one.

nano and uno use the same atmega328p controller, which is the most common "Arduino" type. Nano is more breadboard-friendly.

Micheal well easy solution is to use arduino nano as its bread board friendly and easy as it comes with the arduino IDE installed, well if size is what you are looking for then digispark attiny 85 can also do the task and its size is almost equal to a coin but for that youll need to install it in the arduino IDE which is a bit difficult.
if you need any help with attiny 85 you can come here

The Nano does not come "with the arduino IDE installed", but the Arduino IDE comes with the Nanos board definition installed. Small but important difference in wording.

Promini is even smaller. Plug an FTDI Basic onto it for loading code, remove it when done.

Won't need any more inputs it this as this is the entire project completely. I just have no idea where you start with the coding. I've made circuit boards from bare copper sheets, but never done any coding. Your help and advice is greatly appreciated.

sorry for my words but i meant arduino IDE comes with arduino nano board definition installed, for size attiny85 is best for this application but code would need to be concise and also youll need to install board definition for the attiny85

First of all, you need to have an overview over the whole project because you need to know what components you are going to use, how many digital/analog pins do you need, then check the official Arduino website to see if the board fulfills your needs.
If there is no special need, like more EEPROM or more analog inputs, almost most of the board will work for you (because most of them have the same microcontroller: ATMEGA328P), so it is up to what form factor you prefer more.
Personally, I would like to go with the Micro board because it has microusb connector, it is breadboard friendly (which is a big plus when you are prototyping) and it can be recognised as a mouse or keyboard.


text:
the boxservo works contrary to the code
i want to make a uselessbox .i connected the circuit correctly,i  checked every thing several times and every thing is in right place[ based on  descriptions and pattern],but when i turn  it on,the box servo closes the door and then handservo starts to turn off the switch ,the code says:[the boxservo opens the door then handservo starts to turn off the switch,when the switch  is off and handservo returned to its place then boxservo closes the door]but my box works like this(the boxservo closes the door then handservo starts to turn off the switch,when the switch  is off and handservo returned to its place,then boxservo opens the door).what should i do to solve this problem?Useless box wiring and code
this is the code that i have uploaded:
#include <Servo.h>

Servo handServo;
Servo boxServo;

int switchStatus=0, action=1, vot, randNumber=0;
const int ledPin = 13;
const int frontSwitchPin = 2;
const int handServoPin = 5;
const int boxServoPin = 6;

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

  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin,HIGH);

  handServo.attach(handServoPin);
  boxServo.attach(boxServoPin);
  handServo.write(180);
  boxServo.write(70);

  //randomSeed(analogRead(0));
}

void loop()
{
  switchStatus = digitalRead(frontSwitchPin);
  //action = random(1,16);

  if (switchStatus == LOW){

    if (action == 1)
    {
      Serial.println("Action 1");
      for (int i = 70; i <= 110; i++)
      {
        boxServo.write(i);
        delay(20);
      }
      for (int i = 180; i >= 35; i--)
      {
        handServo.write(i);
        delay(20);
      }
      delay(1000);
      handServo.write(26);
      delay(200);
      for (int i = 26; i <=180; i++)
      {
        handServo.write(i);
        delay(20);
      }
      for (int i = 110; i >= 70; i--)
      {
        boxServo.write(i);
        delay(20);
      }
      action++;
    }

    else if (action == 2)
    {
      Serial.println("Action 2");
      for (int i = 70; i <= 110; i++){
        boxServo.write(i);
        delay(6);
      }
      delay(550);
      handServo.write(26);
      delay(550);
      handServo.write(180);
      delay(550);
      boxServo.write(70);
      delay(1500);
      for (int i = 70; i <= 110; i++){
        boxServo.write(i);
        delay(6);
      }
      delay(3000);
      boxServo.write(70);
      action++;
    }

    else if (action == 3)
    {
      Serial.println("Action 3");
      for (int i = 70; i <= 110; i++){
        boxServo.write(i);
        delay(6);
      }
      delay(1000);
      boxServo.write(70);
      delay(2000);
      for (int i = 70; i <= 110; i++){
        boxServo.write(i);
        delay(6);
      }
      handServo.write(26);
      delay(550);
      handServo.write(180);
      delay(500);
      boxServo.write(70);
      action++;
    }

    else if (action == 4)
    {
      Serial.println("Action 4");
      for (int i = 70; i <= 110; i++)
      {
        boxServo.write(i);
        delay(20);
      }
      for (int i = 180; i >= 35; i--)
      {
        handServo.write(i);
        delay(20);
      }
      delay(2000);
      handServo.write(26);
      delay(200);
      handServo.write(180);
      delay(400);
      boxServo.write(70);
      action++;
    }

    else if (action == 5)
    {
      Serial.println("Action 5");
      for (int i = 70; i <= 110; i++){
        boxServo.write(i);
        delay(6);
      }
      delay(2000);
      handServo.write(65);
      delay(550);
      handServo.write(40);
      delay(200);
      handServo.write(65);
      delay(200);
      handServo.write(40);
      delay(200);
      handServo.write(65);
      delay(200);
      handServo.write(40);
      delay(200);
      handServo.write(65);
      delay(200);
      handServo.write(40);
      delay(200);
      handServo.write(65);
      delay(200);
      handServo.write(40);
      delay(200);
      handServo.write(65);
      delay(2000);
      handServo.write(26);
      delay(400);
      handServo.write(180);
      delay(400);
      boxServo.write(70);
      action++;
    }

    else if (action == 6)
    {
      Serial.println("Action 6");
      for (int i = 70; i <110; i++)
      {
        boxServo.write(i);
        delay(20);
      }
      delay(1000);
      for (int i = 0; i < 12; i++)
      {
        for (int j = 70; j <= 110; j++){
          boxServo.write(j);
          delay(6);
        }
        delay(200);
      }
      for (int i = 180; i >= 35; i--)
      {
        handServo.write(i);
        delay(30);
      }
      handServo.write(26);
      delay(400);
      handServo.write(180);
      delay(400);
      boxServo.write(70);
      delay(1500);
      for (int i = 70; i <= 110; i++){
        boxServo.write(i);
        delay(6);
      }
      delay(3000);
      boxServo.write(80);
      action++;
    }

    else if (action == 7)
    {
      Serial.println("Action 7");
      for (int i = 70; i <= 110; i++){
        boxServo.write(i);
        delay(6);
      }
      delay(400);
      handServo.write(26);
      delay(1000);
      for (int i = 0; i < 6; i++)
      {
        for (int j = 70; j <= 110; j++){
          boxServo.write(j);
          delay(6);
        }
        delay(200);
      }
      delay(500);
      handServo.write(180);
      delay(400);
      boxServo.write(70);
      action++;
    }

    else if (action == 8)
    {
      Serial.println("Action 8");
      for (int i = 70; i <= 110; i++){
        boxServo.write(i);
        delay(6);
      }
      handServo.write(26);
      delay(2000);
      for (int i = 0; i < 7; i++)
      {
        handServo.write(75);
        delay(100);
        handServo.write(40);
        delay(100);
      }
      delay(500);
      handServo.write(180);
      delay(1000);
      boxServo.write(70);
      action++;
    }

    else if (action == 9)
    {
      Serial.println("Action 9");
      for (int i = 70; i <= 105; i++){
        boxServo.write(i);
        delay(6);
      }
      delay(2000);
      boxServo.write(110);
      for (int i = 180; i >=35; i--)
      {
        handServo.write(i);
        delay(40);
      }
      delay(500);
      handServo.write(26);
      delay(200);
      for (int i = 26; i <=180; i++)
      {
        handServo.write(i);
        delay(40);
      }
      boxServo.write(70);
      delay(2000);
      boxServo.write(100);
      delay(3000);
      boxServo.write(70);
      action++;
    }

    else if (action == 10)
    {
      Serial.println("Action 10");
      for (int i = 70; i <= 105; i++)
      {
        boxServo.write(i);
        delay(100);
      }
      delay(1000);
      for (int i = 0; i < 10; i++)
      {
        for (int j = 70; j <= 100; j++){
          boxServo.write(j);
          delay(6);
      }
        delay(100);
      }
      boxServo.write(110);
      delay(100);
      handServo.write(26);
      delay(650);
      handServo.write(180);
      delay(400);
      boxServo.write(70);
      action++;
    }

    else if (action == 11)
    {
      Serial.println("Action 11");
      for (int i = 70; i <= 110; i++){
        boxServo.write(i);
        delay(6);
      }
      handServo.write(26);
      delay(2000);
      for (int i = 0; i < 3; i++)
      {
        handServo.write(65);
        delay(200);
        handServo.write(40);
        delay(200);
      }
      delay(1500);
      handServo.write(180);
      delay(400);
      boxServo.write(70);
      delay(1500);
      for (int i = 70; i <= 110; i++){
        boxServo.write(i);
        delay(6);
      }
      handServo.write(26);
      delay(3000);
      handServo.write(180);
      delay(400);
      boxServo.write(70);
      action++;
    }

    else if (action == 12)
    {
      Serial.println("Action 12");
      for (int i = 70; i <= 110; i++)
      {
        boxServo.write(i);
        delay(50);
      }
      delay(1000);
      for (int i = 180; i >= 26; i--)
      {
        handServo.write(i);
        delay(50);
      }
      delay(2000);
      handServo.write(26);
      delay(200);
      handServo.write(180);
      delay(400);
      boxServo.write(70);
      action++;
    }

    else if (action == 13)
    {
      Serial.println("Action 13");
      for (int i = 70; i <= 110; i++){
        boxServo.write(i);
        delay(6);
      }
      delay(2000);
      for (int i = 180; i >= 60; i--)
      {
        handServo.write(i);
        delay(40);
      }
      for (int i = 0; i < 3; i++)
      {
        handServo.write(60);
        delay(200);
        handServo.write(40);
        delay(800);
      }
      handServo.write(26);
      delay(2000);
      handServo.write(180);
      delay(500);
      boxServo.write(70);
      action++;
    }

    else if (action == 14)
    {
      Serial.println("Action 14");
      for (int i = 70; i <= 105; i++){
        boxServo.write(i);
        delay(6);
      }
      delay(4000);
      boxServo.write(110);
      handServo.write(26);
      delay(650);
      handServo.write(180);
      delay(500);
      boxServo.write(100);
      delay(4000);
      boxServo.write(70);
      action++;
    }

    else if (action == 15)
    {
      Serial.println("Action 15");
      for (int i = 70; i <= 105; i++){
        boxServo.write(i);
        delay(6);
      }
      delay(1000);
      for (int i = 0; i < 3; i++)
      {
        for (int j = 70; j <= 105; j++){
          boxServo.write(j);
          delay(50);
        }
        for (int j = 105; j >= 70; j--)
        {
          boxServo.write(j);
          delay(50);
        }
      }
      for (int j = 70; j <= 110; j++){
        boxServo.write(j);
        delay(50);
      }
      for (int i = 180; i >= 35; i--)
      {
        handServo.write(i);
        delay(40);
      }
      delay(1000);
      handServo.write(26);
      delay(400);
      handServo.write(180);
      delay(400);
      boxServo.write(70);
      action = 1;
    }

  }

}

please edit your post ... convert the wall of words into clear sentences  .....what is the actual problem that the program is exhibiting?

And please point us to the action, that is doing problematic, so that we know, where to search in your long code

you are mistaken about this the boxservo works contrary to the code ...... it should say the boxservo works exactly as programmed

when the switch is off boxservo opens the door and when the switch is on boxservo closes the door that is the problem.it's supposed to open the door when the switch is on and close the door when the switch is off.

If the switch is mounted upside down, then pushing the switch up would close the box; but you need it to open the box instead. In that case, turn the switch so that pushing it up would open the box.

no i didn't mount the switch

and my problem isn;t the switch,my problem is that when the switch is on , boxservo closes the door then handservo comes out to turn off the switch and when the handservo turns the switch off and returns to it's place,boxservo opens the door but it's supposed to boxservo opens the door when the switch is on and then handservo comes out to turn it off and after that handservo turns it off and returns back ,boxservo closes the door

You have probably installed the box servo backwards so that when it tries to open it actually closes and vice versa.

no im sure that it is not bacward

Then you probably have a servo that is wired in reverse. You need to change the code to reverse the door movement servo.

i don't know exactly how to change the code.can you help me to change it?please


text:
how do i know what battery(how much ampere and voltage) my circuit needs to work perfectly?
i really love to make a lot of things  but i always have this problem that i don't know how can i determine what battery(with how much voltage and amp)my circuit must have to work perfectly! please help me:( for example i have two circuits.circuit 1  includes:arduino uno ,2 servo motors and a DFplayer module and an led but i don't know is a 7.4 voltage Lipo battery with 1500mAh suitable for it or not???
and circuit 2 includes:arduino uno,L298 driver & 2 dc motors & 2 ultrasonics sensor but i don't know what battery does it need?
i really love to learn it (determine the battery  my self)

You can guess/calculate/measure the current being used. With that you can calculate how long the project can run on the battery you want to use. You then have the choose if that's a reasonable runtime. Thought there are a lot of tricks to reduce the current being used. For example putting the Arduino in sleep mode. Using an Arduino Pro Mini instead of and UNO, so you don't have the USB chip using up power. etc.

thank youuu, but is there any faster and easier way?it's too time consuming:(

Even 7.4v looks okay for powering the Arduino, it is not a straight answer whether 1500mAh is enough, it also depends on how long you want the battery to last.

@amir this calculator might help. You don't have to be very precise. You just want to get a rough runtime calculation. Like, does is run for hours, days, or months. I often do the first rough extimate this in my head. Then I might do some measurements, or look at the current consumption specified in the datasheet of the different components. Shouldn't take too long.

@hcheung thank you

@Gerben thank youuu.you have no idea how much you helped:)

TL;DR: You really need to know what components you have and you need to find datasheets. In the datasheet, you find what voltage the component requires.
Don't care too much about amperes in the beginning. If you get the voltage right, each component will just draw as much current as it needs.
An Arduino Uno operates from 7 to 12 Volts, so 7.4 V is ok.
"Servo motor" is simply not enough information. There are servo motors for 4.8 V, some for 6 V and others for 12 V. There are even AC servo motors for 240 V~.
DFPlayer is for 3.2 V to 5 V, so it shouldn't be powered directly off the 7.4 V battery. Maybe it can be powered from a 5 V pin of the Arduino. Since they power it from the 5 V pin, it seems to be possible.
Also "LED" is not a term that is good enough. Is it Infrared, Red, Yellow, Green, Violet, UV or white? Depending on the color, it needs something between 1.6 and 3.0 V. Therefore, you need a resistor. What's the use of the LED? Do you need to turn it on and off by Arduino, or can it just be always on from the Lipo battery?
The L298N has a supply voltage from 2.5 V to 46 V, so 7.4 V is fine.
Next, "DC motor" is not specific enough. I have seen 3 V, 5 V, 6 V, 12 V, 24 V.
Also, for ultrasonic, there are SR04 and SRF05. These two operate at 5 V. But if you have a different one, that may not be the case.

it seems that you are a professional teacher and i think you can help me for this question too:i can't understand how much this lipo battery(7.4v) is charged.is there a way i can find out what percentage is charged?or can i make something for it with arduino or anything else that shows what percentage of the it's charge?

thank you so much sir for your help , my servo is MG995(4.8V-7.2V). my led is full color and i turn it on and off by arduino.im not sure but i think my dc motor's voltage is 3volt.my ultrasonics are srf 05.i wanna make a circuit that it works like this:when i turn on the switch servos and DFplayer(circuit1) start working but circuit 2 is off and when i turn the switch off, the circuit 1 will also turn off then dc motors,L298 and ultrasonics(circuit2) start working .is that possible mix two circuit with one arduino? do you think my lipo battry (7.4v)is enough for all of these?


text:
595 Shift Register Not Working Properly
I followed the tutorial on controlling 8 LEDs using a SIPO SN74HC595N shift register on both Adafruit and Last Minute Engineer. I used a Sparkfun Pro Micro (Arduino Leonardo equivalent).
The problem is the LEDs are not lighting up in the way that I'm expecting it do it. Both guides said each LED will light up one after another. After all 8 are lit, all of them will turn off. Here is my result. Other LEDs will either dim up or down as the target LED turn on. I used the code provided from the guide and only changed the pinout number. The resistor values are the same for each color so it can't be the resistor. Anyone have any idea what's going on here?
/*
Test code for 74HC595N SIPO shift register. Used with Pro Micro
*/

int latchPin = 16;
int clockPin = 15;
int dataPin = 14;
int outputEnablePin = 10;

byte leds = 0;    // Variable to hold the pattern of which LEDs are currently turned on or off

void setup()
{
  // Set all the pins of 74HC595 as OUTPUT
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(outputEnablePin, OUTPUT);
  outputEnablePin = LOW;
}

/*
 * loop() - this function runs over and over again
 */
void loop()
{
  leds = 0; // Initially turns all the LEDs off, by giving the variable 'leds' the value 0
  updateShiftRegister();
  delay(500);
  for (int i = 0; i < 8; i++) // Turn all the LEDs ON one by one.
  {
    bitSet(leds, i);    // Set the bit that controls that LED in the variable 'leds'
    updateShiftRegister();
    delay(500);
  }
}

/*
 * updateShiftRegister() - This function sets the latchPin to low, then calls the Arduino function 'shiftOut' to shift out contents of variable 'leds' in the shift register before putting the 'latchPin' high again.
 */
void updateShiftRegister()
{
   digitalWrite(latchPin, LOW);
   shiftOut(dataPin, clockPin, LSBFIRST, leds);
   digitalWrite(latchPin, HIGH);
}

Schematics:

The resistor values are the same for each color so it can't be the resistor. What makes you think that? The current through the LED is dictated by the resistor value and the LED's forward voltage. The LED's forward voltage is dictated by the colour. Thus you need to size the resistor correctly for each colour of LED.

That said, the fact that some turn part way on when they shouldn't really is a concern.

Is your pro micro a 3.3V or a 5V one?

The Pro Micro is 5V. What I meant by the resistors is there is two led of the same color and there is 4 different colors. I calculate the resistors value based on their given forward voltage and current for each color. The resistor value is the same for the pair of leds with the same color.

It would really help if you add a schematic of how you actually built the circuit, instead of me trying to debug your circuit from a low resolution, animated GIF. Your code looks fine at first glance, btw.

The GND of the 74HC595 is connected to the right power rail (blue line) on your breadboard. But this rail isn't connect to the GND of the Arduino.

I was making the schematic for StarCat and just found that GND error! Stupid me! I connected it to ground and now the dimming LEDs are gone! However, I still have problems with the LED. The LEDs are not lighting up in the pattern that the code designed them to.

@Agriculex, Glad to be of help ;-) You could write an answer to your own question.

I just found out solution to the pattern issue. The guides didn't say it (at least not clearly enough) that pin 10 (SRCLR with the line/bar on top) needs to be connected to 5V.

@Agriculex - Please answer your own question then accept that answer in 48 hours.

StackExchange is not a forum. You don't edit the question's title with "Solved" if you have an answer. Instead you write an answer and (later, when you're allowed to) you mark it. Please correct that. People coming here don't look for "Solved", they look for marked answers.

Did that just now. I'm still new to how StackExchange works opps.

The dimming problem was found to be the shift register IC not connected to Ground (dumb me).
However, there is still problem with LED's on and off pattern. Sometimes two LEDs turn on at the same time and all previous LEDS turning off before the last or second last LED is turned on. It turns out Pin 10 (SRCLR Bar) needs to be pulled to high to solve that pattern discrepancy.

Yes. You can't leave important pins, like SRCLR, floating. Signals that matter must be intentionally set. True with any chip.


text:
Arduino HX711 load cell lots of drift
I am trying to make this 50kg load cell work with this HX711 chip. I currently have the following connections :

Load cell red -> E+
Load cell black -> E-
Load cell white -> A-
Load cell green -> A+

I am using this library and this code :
#include "HX711.h"

#define calibration_factor -7050

HX711 scale;

void setup()
{
  Serial.begin(9600);
  scale.begin(2, 3);
  scale.set_scale(calibration_factor);
  scale.tare();
}

void loop()
{
  Serial.println(scale.get_units(1));
  delay(100);
}

The load cell appears to register load changes but the value is constantly going up (or down if the calibration_factor is positive). The value change rate is very high (from 0 to 300 in a couple of seconds).
Edit : I have 2 load cells and both of them do the same thing (with different HX711 chips).
Edit 2 : My question is : has anyone experienced this ? Or does anyone have an idea as to why this is happening ?

what is your specific question?

Oups ! I edited the question @jsotola

The solution was to solder all the wires, now the drift seems to be very minimal or non existant.

Hey Antoine, can you elaborate a little on your solution? What did you use before soldering? Did you just solder all wires and it just worked?

Hey @Motine, This was a while ago, but IIRC I simply soldered the wires from the load cell to the HX711. Previously I was using a breadboard I think.

alright. i will try that too. thanks!


text:
Wired Teensy 3.5 AudioShield and RFID RC-522
I received a set of wired Teensy 3.5 AudioShield and RFID RC-522.
The audio shield is mounted on the Teensy but I cannot connect the MFRC522
Using MFR222 library. Pins are set to 0 and 31:
#define RST_PIN         0          // Configurable, see typical pin layout above
#define SS_PIN          31         // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

Getting:
Firmware Version: 0x0 = (unknown)
WARNING: Communication failure, is the MFRC522 properly connected?
Scan PICC to see UID, SAK, type, and data blocks..

Tried any other combination I can think of.
Checked all soldered points.
I did not find any guide on how to connect teensy 3.5 with RC522. only older versions.
Do I need to tell the library where to find the other pins (MISO, MOSI...)
Any help will be appreciated.
Thanks
Yehuda

the wiring diagram does not show a ground connection to the teensy

The teensy is mounted to audio, wired to RFID, and connected via USB to PC. Do I need to add another wire?

The answer is (as far as I understand) that when both audio shield and rfid are mounted, they have protocol collision  (same protocol for both). So if you want them to work. You need to wire rfid to different pins.