text:
Arduino Code for Pulse Skip Modulation (PSM)
I have recently bought this light dimmer, and only when I received it I noticed it works with PSM (Pulse Skip Modulation) and not PWD (Pulse Width Modulation).
Does anyone know how to write Arduino code and do the wiring for this dimmer? I can't seems to find a working example.
Thanks

The module is basically a triac with some support components. So instead of PSM, you could do Phase cutting (leading edge cutting). This is where you turn on the triac somewhere during the sinewave. Once the triac is turned on, it stays on till the next zero crossing. So you use the zero crossing signal to know when the next cycle starts, and you then turn the triac on somewhere in the cycle. Just note that since you are chopping up the sinewave the resulting brightness will not be linearly proportional to the percentage of time it's turned on.

Also, mains led lights that support dimming do so by measuring the waveform that's coming in and calculate the PWM value based on than. Since the main part of an led is a bridge rectifier, and a smoothing capacitor. Using a regular led bulb on a dimmer will have very little effect, right until the dimmer is almost fully off.

I actually also recently bought this same dimmer switch. Is there any way to vary the intensity through more than high and low intensity? Is there a way to have let’s say 25-30 intensities of getting dimmer or brighter? I wanted to set some sort of counter on it so that over a span of like a minute it could decrease from full brightness to completely off. Also does the Z_C pin have to be a PWM pin on the Arduino? Thanks for all the help!

I assume you use this module.
PSM is often used because of it's higher efficiency with light loads. It's also better for AC loads, since they should get a complete AC voltage and not a DC voltage (when you cut half of the wave).
The module you have, is build to support you with implementing PSM correctly. It has a zero-crossing detection, which gives you a signal on the Z-C pin, every time the AC sine wave crosses zero voltage (which is the best time to switch). You can sense the signal with an interrupt in your Arduino. The website does not explain exactly, what is outputted by the Z-C pin on a zero crossing, but you can check this easily yourself, by monitoring both AC and Z-C voltage in operation. Most likely you will have to use either a FALLING or a CHANGE interrupt.
PSM works with modulating the number of pulses (in this case full sine wave periods) are transmitted to the load. Imagine you want to dim the light in 10 distinct values.

For full power you always set the pin marked with PWM to high, when a full sine wave is starting (this is at every second zero crossing). This means the PWM pin is always high.
For half power you turn the PWM pin high for 5 full periods and then turning it off for further 5 periods.
For 10% (a value of 1) you turn the PWM pin high for 1 full period and then off for 9 periods.

The downside of this method is, that you might see the light flickering when having low values.
When implementing this, you can use the attachInterrupt() function with the Z-C pin. In the callback function you toggle a global (volatile!) boolean variable, to indicate, if a new full period is starting, or if the zero crossing signal is only indicating the start of the negative part of the sine wave. Also use a global (volatile!) counter variable, that counts (increments every full period) to the value, you preset (Here something between 0 and 10). When the counter variable is 0 (and the desired value is greater than 0) you write HIGH to the PWM pin of your module. When the counter reaches the desired value, you write LOW to the PWM pin. When the counter reaches the maximum value, you have reset it to 0.
In code something like this:
volatile byte counter=0;
volatile boolean new_period = true;
volatile byte value=5;
#define MAX_VALUE 10

void setup(){
  // set pinModes for the correct pins

  // active interrupt. Note, that you may have to change FALLING to a value fitting the output of the module (see explanation above)
  attachInterrupt(digitalPinToInterrupt(Z_C_pin), zero_crossing, FALLING);
}

void zero_crossing(){
  if(new_period){
    if(counter==0 && value>0) digitalWrite(PWM_pin,HIGH);
    if(counter==value) digitalWrite(PWM_pin,LOW);
    counter++;
    if(counter > MAX_VALUE) counter=0;
  }
  new_period=!new_period;
}

Note: Especially when having a great range of possible values, some of the values can be exchanged by a better behavior, that would prevent a bit of the flickering. For example, when using 100 distinct dimming stages and wanting to dim to 50%, you can either (as depicted above) turn the light on for 50 periods and then turning it of for another 50 periods. Or you can turn on during every second period. Though this will not help you with really small values. So I left it out for simplicity.

Amazing answer. Works perfectly...

@chrisl Hi while I try on Mega 2560 with attachInterrupt(0, zero_crosss_int, RISING); or attachInterrupt(digitalPinToInterrupt(interruptPin), zero_crosss_int, RISING); I am getting
exit status 1
Error compiling for board Arduino/Genuino Mega or Mega 2560.
error. How to solve it?

The full error code is;
WInterrupts.c.o (symbol from plugin): In function `attachInterrupt':
(.text+0x0): multiple definition of `__vector_5'
libraries\RBDdimmer\RBDdimmer.cpp.o (symbol from plugin):(.text+0x0): first defined here
c:/program files (x86)/arduino/hardware/tools/avr/bin/../lib/gcc/avr/5.4.0/../../../../avr/bin/ld.exe: Disabling relaxation: it will not work with multiple definitions
collect2.exe: error: ld returned 1 exit status
exit status 1
Error compiling for board Arduino/Genuino Mega or Mega 2560.

The RBDdimmer library seems to also define the corresponding ISR, which cannot be done twice. Have you tried other pins? The Mega 2560 seems to have 8 external interrupts and the RBDdimmer library is locked to D2 as of the github page.

All ports (2, 3, 18, 19, 20, 21) results with the same error..

Mhh, maybe you should ask a new question with this and refer to this question in it

Just adding to chrisl's answer since I bought this module, too.
There is a simple example on the manufacturers website of this module which does not seem to implement PSM the obvious way:

/*
Connect RobotDyn AC Light Dimmer as follows:
Dimmer pin  --  Arduino pin
    VCC     --    5V
    GND     --    GND
    Z-C     --    D2
    PWM     --    D3

Glow sketch for AC Voltage dimmer with Zero cross detection
Based on the sketch by Charith Fernanado
Adapted by RobotDyn: http://www.robotdyn.com
License: Creative Commons Attribution Share-Alike 3.0 License.
Attach the Zero cross pin of the module to Arduino External Interrupt pin
Select the correct Interrupt # from the below table (the Pin numbers are digital pins, NOT physical pins: digital pin 2 [INT0]=physical pin 4 and digital pin 3 [INT1]= physical pin 5)

Pin    |  Interrrupt # | Arduino Platform
---------------------------------------
2      |  0            |  All
3      |  1            |  All
18     |  5            |  Arduino Mega Only
19     |  4            |  Arduino Mega Only
20     |  3            |  Arduino Mega Only
21     |  2            |  Arduino Mega Only

In the program pin 2 is chosen
*/
int AC_LOAD = 3;    // Output to Opto Triac pin
int dimming = 128;  // Dimming level (0-128)  0 = ON, 128 = OFF

void setup()
{
  pinMode(AC_LOAD, OUTPUT);// Set AC Load pin as output
  attachInterrupt(0, zero_crosss_int, RISING);  // Choose the zero cross interrupt # from the table above
}

// the interrupt function must take no parameters and return nothing
void zero_crosss_int()  // function to be fired at the zero crossing to dim the light
{
  // Firing angle calculation : 1 full 50Hz wave =1/50=20ms
  // Every zerocrossing thus: (50Hz)-> 10ms (1/2 Cycle) For 60Hz => 8.33ms (10.000/120)
  // 10ms=10000us
  // (10000us - 10us) / 128 = 75 (Approx) For 60Hz =>65

  int dimtime = (75*dimming);    // For 60Hz =>65
  delayMicroseconds(dimtime);    // Off cycle
  digitalWrite(AC_LOAD, HIGH);   // triac firing
  delayMicroseconds(10);         // triac On propogation delay (for 60Hz use 8.33)
  digitalWrite(AC_LOAD, LOW);    // triac Off
}

void loop()  {
  for (int i=5; i <= 120; i++){  // We use 120 as the lowest and 5 as the highest brightness setting. May be adjusted depending on the lamp used.
    dimming=i;
    delay(20);
   }
  for (int i=120; i >= 5; i--){  // Same as above
    dimming=i;
    delay(20);
   }
}

They are using an interrupt as suggested by chrisl.
There is no flickering present with low dim values (using an incandescent bulb).
See this video for a similar board with the original version of the above sketch.
Note: If you want to integrate your own code into this example, it will likely not work as intended because the Arduino is busy with delayMicroseconds() most of the time

EDIT: The manufacturer of this module just released a library. Check it out on their github

This module allows you to implement pulse skipping modulation but also phase angle control. The code that reins.ch posted is actually the latter.


text:
USB Device not recognized (error 43, arduino uno)
I know that there's already post about this, but mine is different. Instead of not recognized, it gets recognized, and I can upload codes, but after a while, windows starts to not recognize it. And there is a temporary fix for this for my laptop, I need to restart. And even after restarting, it still becomes not recognized after a while
Edit : forgot to mention, even if it is not recognized, it still sends power to the arduino

Genuine Arduino board, or a cheap Chinese knock-off?

I am pretty sure it is a genuine arduino board. Also, this just happened recently, I had this board for over 5 months now, and this just happened

It sounds like the USB chip is dying. I would expect that from a Chinese clone, but not a genuine Arduino.

Does the USB chip get hot?

The USB Chip does not get hot

Are you using a USB hub, or plugging it in direct to the laptop?

I plug it in directly to the laptop without any other external stuff...Still, I guess I should try other cable first and then I'll see

"both of them has the same problem." sounds like it's a problem with your computer, USB cable, or with something you're connecting to the Arduinos.

The USB microcontroller Atmega16U2/Atmega8U2 on the Ardunio UNO board might be corrupted. Try uploading the USB to Serial HEX file with boot-loader found in C:\ProgramFiles\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\firmwares\atmegaxxu2\Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex
using Flip OR any other other ardunio (as an ISP programmer). for doing this you have to first enter BOOT-LOADER by shorting the Reset Pin of the USB controller to GND  both pins can be found on ICSP2 of the UNO.
This will surely solve the issue.
But,
if the problem still persists then your USB controller is damaged and have to replace the controller and again upload the USB to serial firmware, the process is same as mentioned above, but you don't need to short reset and GND as you don't have an boot loader installed in the new controller.

I can confirm that this cannot be the case. As I have two arduino boards lying around and both of them has the same problem. I don't think both of them could get damaged at the same time. But I might try this option

source: Stack Exchange

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

sort: votes


text:
Use ESP8266 GPIOs after Flash Startup
I'm a bit confused about the ESP8266 launching and GPIO behaviour.

When I'm programming the ESP8266 I have to set GPIO2 high and GPIO0 low.
But when I want to use the ESP8266 in my project I have to set GPIO2 and GPIO0 to HIGH, but if they are both high I can't use them as inputs or outputs. So my question is how can I use atleast of the GPIO as an output and starting the ESP8266 without reprogramming it.

but if they are both high I can't use them as inputs or outputs - the state of those pins are important at powerup/reset, not all the time - you can definitely use them as outputs withut any worry, and "carefully" as inputs (i.e. usually as simple as having a pullup resistor connected to each of those pins) - note: GPIO15 also has to be LOW on boot/reset - but I guess you have an ESP01 if you failed to worry about that

they only need the special state for about 50ms at power-on, then it doesn't matter.

Do you know a way how to set it high at the beginning, and then use it as output, without a complicated circuit around it?

you can use pin 2 as output, only don't connect it direct or indirect to ground at startup. it is good for output that is normally HIGH

ESP8266 was developed for 'Serial over WiFi' as system-on-chip based on the Tensilica processor. The GPIO pins of Tensilica where used for different purposes of the system, like antena, flash memory connection, boot setup etc.
The more general use of the ep8266 as micro-controller with WiFi has evolved, but needs to accept the legacy of the original concept. Smart people even found a way how to share SPI with the flash memory of the system.
If you want to use the IO pins of the esp8266 (they are not called GPIO in datasheet), you must accept the required boot state and use only circuit,
sensor or actuator that doesn't disturb it and can handle it.
io0 LOW tels the esp8266 to boot into bootloader flashing mode. It is evaluated by ROM software in the boot process. Pull-up circuit is required to achieve normal boot. So if you want to attach something to this pin, it must accept this conditions. For button it is ideal.
If you want to use io 0 or io 2 as output, use logic that is normally HIGH and make sure it is not connected direct or indirect to ground at startup.

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


text:
Reading +IPD response from serial.read() using Arduino UNO and ESP8266
I have a python server running on my PC and I am using an Arduino Uno (wifi enabled by a ESP8266 chip) as the client.
I can make the the server and client communicate using AT commands as shown below:
SoftwareSerial esp (8,9);

   void setup()
   {
   esp.begin(9600);
   esp.println("AT+CWMODE=3");
   delay(100);
   esp.println("AT+CIPSTART=\"TCP\",\"192.168.8.100\",5555");
   delay(1000);
   esp.println("AT+CIPSEND=3");
   delay(100);
   esp.println("bbb");
   delay(100); }

The string "bbb" is recieved on the server and the server responds back, which is shown in the serial monitor as:
+IPD,19:the string is found

I want to read this response and use it back in the code for further conditional statements. But i am unable to do this. So far i have tried these methods.
1st method by using esp.readString() as shown below:
String buffer="";
while (esp.available()>0)
    buffer+= esp.readString();
Serial.print(i4);

2nd by using esp.read() as shown below:
String buffer="";
char c;
while (esp.available()>0) {
    c= esp.read();
    buffer+=c;}
Serial.print(buffer);    // i have also tried using esp.write() directly for prinitng here intead of storing it in a buffer

These two methods returned with incomplete information in the response string buffer ie i only get:
busy s...

Recv 3 bytes

SEND OK

+IPD,19:the string

I can not get the entire response in the buffer as mentioned in the start. On the other hand if i execute the command AT+CWLAP and store its response in the buffer string, i get the entire thing. So i cant understand why is there a difference between the two.
Lastly i have also used esp.readBytes() as shown:
char c[500];
esp.readBytes(c,400);
esp.write(c);

This code gives me the whole response sometimes but sometimes it just gives a long garbage value. But the times it does give me the complete +IPD response, it switches some of the alphabets ie the string is found becomes the strjng is gound
If anyone could help me out i'll be very thankful.

A while(Serial.available()>0) does not guarantee, that all bytes have been received. Sometimes there is a small delay between bytes, which you cannot control. The Arduino will exit the while loop, but short after that, more bytes are received, without the program ḱnowing. Somehow your Arduino has to know, when the message is complete (through a delimiter character or maybe a timeout).

@chrisl i have also tried this using a for loop like so:
esp.println("bbb");  delay(100);  char c[100];  for(int i=0;i<80;i++){     c[i]= esp.read();     delay(10);     Serial.write(c[i]);    }
Which gives me the following output:
`busy s...
Recv 3 bytes
SEND OK
+IPD,19:the string⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮`
I assumed after this that the buffer must be empty thats why the reverse question marks appeared. I still have no clue on what to do next

The reverse question marks depict a character, that has no meaning in ASCII, e.g. a value greater than 127. The read() function returns -1,  when the buffer is empty, which translates to an unsigned value of 255. So you are right, that the buffer is empty there. That is strange. How many bytes do you receive correctly with this method?

@chrisl When i run the command AT+CWLAP i can get upto 400B in the buffer variable. But in the commands that receive a response from the server i.e. i use AT+CIPSEND and my sever sends a response which includes +IPD i can only get max 64B. I have shown this in the original question. I dont understand why this is happening because i have used the same reading technique for both commands


text:
Arduino BMP085 Barometric sensor blank serial monitor
I am a beginner as far as arduino and microcontrollers are concerned.
I am using a BMP085 barometric pressure sensor.I have made all the necessary connections to my arduino uno board and double checked them. What I want to do is get readings from the sensor and display them on my arduino serial monitor. The code I am using compiles and uploads without any error but when I open my serial monitor, it is blank. I tried using a humidity/temperature sensor before this and that sensor returns values to the serial monitor.
The barometric sensor is new and this was my first time usage.
Here is my sketch. I took it from here.
https://www.sparkfun.com/tutorials/253
Any help would be greatly appreciated.
the code
#include <Wire.h>

#define BMP085_ADDRESS 0x77  // I2C address of BMP085

const unsigned char OSS = 0;  // Oversampling Setting

// Calibration values
int ac1;
int ac2;
int ac3;
unsigned int ac4;
unsigned int ac5;
unsigned int ac6;
int b1;
int b2;
int mb;
int mc;
int md;

// b5 is calculated in bmp085GetTemperature(...), this variable is also used in bmp085GetPressure(...)
// so ...Temperature(...) must be called before ...Pressure(...).
long b5;

short temperature;
long pressure;

// Use these for altitude conversions
const float p0 = 101325;     // Pressure at sea level (Pa)
float altitude;

void setup()
{
  Serial.begin(9600);
  Wire.begin();
  bmp085Calibration();
}

void loop()
{
  temperature = bmp085GetTemperature(bmp085ReadUT());
  pressure = bmp085GetPressure(bmp085ReadUP());
  altitude = (float)44330 * (1 - pow(((float) pressure/p0), 0.190295));

  Serial.print("Temperature: ");
  Serial.print(temperature, DEC);
  Serial.println(" *0.1 deg C");
  Serial.print("Pressure: ");
  Serial.print(pressure, DEC);
  Serial.println(" Pa");
  Serial.print("Altitude: ");
  Serial.print(altitude, 2);
  Serial.println(" m");
  Serial.println();

  delay(1000);
}

// Stores all of the bmp085's calibration values into global variables
// Calibration values are required to calculate temp and pressure
// This function should be called at the beginning of the program
void bmp085Calibration()
{
  ac1 = bmp085ReadInt(0xAA);
  ac2 = bmp085ReadInt(0xAC);
  ac3 = bmp085ReadInt(0xAE);
  ac4 = bmp085ReadInt(0xB0);
  ac5 = bmp085ReadInt(0xB2);
  ac6 = bmp085ReadInt(0xB4);
  b1 = bmp085ReadInt(0xB6);
  b2 = bmp085ReadInt(0xB8);
  mb = bmp085ReadInt(0xBA);
  mc = bmp085ReadInt(0xBC);
  md = bmp085ReadInt(0xBE);
}

// Calculate temperature given ut.
// Value returned will be in units of 0.1 deg C
short bmp085GetTemperature(unsigned int ut)
{
  long x1, x2;

  x1 = (((long)ut - (long)ac6)*(long)ac5) >> 15;
  x2 = ((long)mc << 11)/(x1 + md);
  b5 = x1 + x2;

  return ((b5 + 8)>>4);
}

// Calculate pressure given up
// calibration values must be known
// b5 is also required so bmp085GetTemperature(...) must be called first.
// Value returned will be pressure in units of Pa.
long bmp085GetPressure(unsigned long up)
{
  long x1, x2, x3, b3, b6, p;
  unsigned long b4, b7;

  b6 = b5 - 4000;
  // Calculate B3
  x1 = (b2 * (b6 * b6)>>12)>>11;
  x2 = (ac2 * b6)>>11;
  x3 = x1 + x2;
  b3 = (((((long)ac1)*4 + x3)<<OSS) + 2)>>2;

  // Calculate B4
  x1 = (ac3 * b6)>>13;
  x2 = (b1 * ((b6 * b6)>>12))>>16;
  x3 = ((x1 + x2) + 2)>>2;
  b4 = (ac4 * (unsigned long)(x3 + 32768))>>15;

  b7 = ((unsigned long)(up - b3) * (50000>>OSS));
  if (b7 < 0x80000000)
    p = (b7<<1)/b4;
  else
    p = (b7/b4)<<1;

  x1 = (p>>8) * (p>>8);
  x1 = (x1 * 3038)>>16;
  x2 = (-7357 * p)>>16;
  p += (x1 + x2 + 3791)>>4;

  return p;
}

// Read 1 byte from the BMP085 at 'address'
char bmp085Read(unsigned char address)
{
  unsigned char data;

  Wire.beginTransmission(BMP085_ADDRESS);
  Wire.write(address);
  Wire.endTransmission();

  Wire.requestFrom(BMP085_ADDRESS, 1);
  while(!Wire.available())
    ;

  return Wire.read();
}

// Read 2 bytes from the BMP085
// First byte will be from 'address'
// Second byte will be from 'address'+1
int bmp085ReadInt(unsigned char address)
{
  unsigned char msb, lsb;

  Wire.beginTransmission(BMP085_ADDRESS);
  Wire.write(address);
  Wire.endTransmission();

  Wire.requestFrom(BMP085_ADDRESS, 2);
  while(Wire.available()<2)
    ;
  msb = Wire.read();
  lsb = Wire.read();

  return (int) msb<<8 | lsb;
}

// Read the uncompensated temperature value
unsigned int bmp085ReadUT()
{
  unsigned int ut;

  // Write 0x2E into Register 0xF4
  // This requests a temperature reading
  Wire.beginTransmission(BMP085_ADDRESS);
  Wire.write(0xF4);
  Wire.write(0x2E);
  Wire.endTransmission();

  // Wait at least 4.5ms
  delay(5);

  // Read two bytes from registers 0xF6 and 0xF7
  ut = bmp085ReadInt(0xF6);
  return ut;
}

// Read the uncompensated pressure value
unsigned long bmp085ReadUP()
{
  unsigned char msb, lsb, xlsb;
  unsigned long up = 0;

  // Write 0x34+(OSS<<6) into register 0xF4
  // Request a pressure reading w/ oversampling setting
  Wire.beginTransmission(BMP085_ADDRESS);
  Wire.write(0xF4);
  Wire.write(0x34 + (OSS<<6));
  Wire.endTransmission();

  // Wait for conversion, delay time dependent on OSS
  delay(2 + (3<<OSS));

  // Read register 0xF6 (MSB), 0xF7 (LSB), and 0xF8 (XLSB)
  Wire.beginTransmission(BMP085_ADDRESS);
  Wire.write(0xF6);
  Wire.endTransmission();
  Wire.requestFrom(BMP085_ADDRESS, 3);

  // Wait for data to become available
  while(Wire.available() < 3)
    ;
  msb = Wire.read();
  lsb = Wire.read();
  xlsb = Wire.read();

  up = (((unsigned long) msb << 16) | ((unsigned long) lsb << 8) | (unsigned long) xlsb) >> (8-OSS);

  return up;
}

wirings:
https://i.stack.imgur.com/oRX0V.jpg

Show us your code and your wiring. That your code compiles and that you double checked the connection doesn't mean, that there cannot be any wrong coding.

That web page has several snippets of code, so please do copy/paste the code you are trying into your question.

The most simple reason: Did you set your serial monitor to use baud rate 9600? Could you also add a Serial.println("SKETCH STARTING"); after the Serial.begin() call to verify that the sketch boots up?

Could it be that my sensor is faulty? If so, how do I check if my sensor is faulty? I took the entire ino file from the tutorial, and read about what each section of code does. The site did not provide any libraries so all the mathematical calculations are a part of the code.

the baud rate is 9600. I just checked it.

@MaximilianGerhardt I added the Serial.println("SKETCH STARTING"); as you instructed. The sketch boots up. I get a "Sketch starting" on the monitor. It is all blank after that.

The reading functions are blocking the program, until something is received. Please check, if you can contact the sensor via I2C/Wire by using the (I2C scanner sketch)[https://playground.arduino.cc/Main/I2cScanner]. If no device shows up, the wiring or the sensor isn't correct. When it is found, check if the found address is equal to the one you use.

Also you should show the wiring by making a schematic (for example with the tool in this question editor) or - if it works better for you - with something like fritzing. It is very hard to see the actual wiring on your low quality images

@chrisl Here is the schematic. https://learn.adafruit.com/assets/484 .
I tried contacting the sensor by running the sketch you linked above,no device comes up. The board is unable to communicate with the sensor.

Then as artag wrote you may have fried the sensor depending on what version you have

My version is 3.3 v version. I am aware of that, which is why i connected it to the 3.3 v pin. Is it still possible that i fried the sensor? Is there no sure shot way of checking it?

Not only the supply voltage is important. The UNO will output 5V on both SDA and SCL, which can fry the I2C hardware of the board. The only way to be sure is to check with a second module, that is still OK. Be sure to use a level shifter this time

There are several versions of breakout boards for the BMP085. The device itself is 3v3. Some breakouts provide a regulator so you can supply 5V. Some also perform level-shifting so you can drive the I2C lines at 5V and work correctly with the sensor's 3v3 levels.
It isn't clear which type you have there, but you seem to be powering it from 3v3 on the arduino. A photo of the other side of the sensor board would help.
If the sensor has a regulator, sourcing it from 3v3 will drop it a little (the regulator needs some overhead). This might mean the sensor is running at too low a voltage.
If the board has no regulator, then it's correct to power it from 3v3. However, the I2C lines also need conversion. You will be driving 5V into a 3v3 input, which can damage it. You will also be receiving 3v3 levels from the sensor into the 5V arduino, which will probably work but might not.
Ideally, put level shifters in between. They need to be bidirectional, like these : https://www.adafruit.com/product/757
In some cases you can get away with resistors only, but not easily on the bidirectional I2C bus. SPI is easier as the pins are unidirectional.

my sensor
http://2.bp.blogspot.com/-rYK6t2jDt_0/VxX02W1VNzI/AAAAAAAABCk/7W83W7ufzo8Kj97Ay0ioVDxBJE3vmqiNwCK4B/s1600/BMP085.jpg
is it possible that i fried the sensor? I connected it to the 3.3v pin on the uno board.
I did some reading and found out that the sensor has a 3.3v voltage regulator. I will try to connect it to the 5v pin.

It's possible, but it would depend on whether there are also level translators to protect the 3v3 control pins from the 5v arduino pins.

Adafruit says  :   V1 of the breakout uses 3.3V power and logic level only
V2 of the breakout uses 3.3-5V power and logic level for more flexible usage.


text:
Arduino Nano ATmega328P bootloader difference
There are two ATmega328P bootloaders, old and current.  What is the difference between these bootloaders?
I'm aware that Nanos sold by Arduino use the new bootloaders but I haven't been able to find any release notes about the bootloader.

from what I can see, the "old" bootloader is ???/bootloaders/atmega/ATmegaBOOT_168_atmega328.hex and the new one is ???/bootloaders/optiboot/optiboot_atmega328.hex - ??? depends on your system, but should be easy to find - online, see https://github.com/Optiboot/optiboot

I bootload all my '328P chip based boards as 16 MHz Arduino Uno, then I don't need to worry about selecting the right board type.

The bootloader currently shipped on the official Arduino Nano boards and selected via the Arduino IDE's Tools > Processor > ATmega328P after choosing Tools > Board > Arduino Nano is the same version of optiboot used by the Arduino/Genuino Uno:
https://github.com/arduino/ArduinoCore-avr/blob/master/boards.txt#L152
nano.menu.cpu.atmega328.bootloader.file=optiboot/optiboot_atmega328.hex

https://github.com/arduino/ArduinoCore-avr/blob/master/boards.txt#L72
uno.bootloader.file=optiboot/optiboot_atmega328.hex

The bootloader selected via Tools > Processor > ATmega328P (Old Bootloader) is the "ATmegaBOOT" bootloader.
As used by the Nano hardware definition, there are two significant differences between the two bootloaders:

Optiboot will not go into an endless reset loop after a watchdog reset. ATmegaBOOT will.
Optiboot expects the upload communication at 115200 baud. ATmegaBOOT, 57600. This is the reason why the old boards don't work with the Tools > Processor > ATmega328P selection and vice versa.

There is another very significant difference between the two bootloaders that, sadly, you will not benefit from with the new Arduino Nano board/hardware definition: Optiboot will fit in a 0.5 kB boot section, while ATmegaBOOT requires a 2 kB boot section. Unfortunately Arduino forgot to change the BOOTSZ fuse accordingly and so the opportunity to free up 1.5 kB of precious flash memory for the users of the Nano was lost. The willingness of Arduino to knowingly release flawed hardware has historic precedent.

I haven't been able to find any release notes about the bootloader.

Arduino's release notes have not yet adapted to the fact that hardware packages may be released independently of IDE releases ever since Arduino IDE 1.6.2. There is a note about the bootloader change in the IDE release notes for the next IDE release:
https://github.com/arduino/Arduino/commit/ec179e5af67b7f1eeb5e46d22034798f8b24b7cb
Other than that, you can consult the commit history:
https://github.com/arduino/ArduinoCore-avr/commit/1b14cc07331268e95eddcce2cc67e29ed667e62f

Can the nano be flashed with either bootloaders or are there hardware differences that the booloader depends on?

There are no hardware differences. If you're flashing the bootloader my advice is to do so with Tools > Board > Arduino/Genuino Uno selected because then you get all the benefits of optiboot, including the 1.5 kB extra flash memory. Just remember that you need to have the Uno board when you use your Nano after that.

*Uno board selected

It might be worth noting: I have just received a Nano "clone" of AliExpress, which (unusually for a clone) has a FT232R (instead of a CH34x), which means that it works nicely on my Mac. However, I found that I had to select the old bootloader to be able to upload sketches - which seems contra your post (stating that the new bootloader is used for the Nano). However, as my Nano is a clone, I guess that anything goes.


text:
How to fix Arduino restarting when two servos are powered by an external power?

Can anyone help me fix this? It always restarts when I power the servos with an external battery. I connected one battery to Arduino and one battery to servos, each 5V, but my Arduino keeps restarting.

Where is the supply for your Arduino board coming from?

I connect two batteries for Arduino and for the servo but  the Arduino keep restarting after few seconds

You are using same power supply for UNO and servo I guess.

The first thing I saw was a cartoon where apparently a schematic should be.  I'm not even going to look at the rest.  Automatic -1 and closing.

Are both those black wires connected together?

As @NickGammon says: are you sharing ground, or, as it looks like on the schematics, you have two grounds?

You will need to fix this on your own but I can suggest some things that you will likely need to investigate.

Evaluate what exactly causes the AVR to get reset. It is highly likely that long wires and current surges as loads are applied is causing either the GND or the VCC to the AVR to be compromised and initiating a brown out reset in the MCU.
Driving inductive loads without proper design may be putting high voltage spikes into your design that create havoc with proper software execution and/or risking serious damage to the silicon components. Make sure you take steps to eliminating such with clamp diodes, filter caps or zener diodes.
You will have to check your exact MCU data sheet but many parts have a reset reason register that your software can read to see what particular thing initiated the reset.
Lastly the most important thing is to make sure you have the proper tools for debugging problems like this. It is very common that you should have access to an oscilloscope so you can find the problems and learn how to fix them. The best way to learn how to design in a way that you avoid problems like this on the next project is to see first hand what went wrong and learn from it.

The reason here is, you are not able to provide enough current required for the servo. There are multiple ways to work around.

Change the code: Just try to rotate only one servo at a time. Rotate the second servo after servo1 finished rotation.
Use a 9V battery and connect it to the power socket of arduino [this could solve the issue if you are using normal servos]
Use separate power supplies for servo and Arduino. Use two different 5V supplies to power servo and arduino. Please don't forget to connect the grounds of both supplies together.


text:
NodeMCU - Vin pin as 5V output?
I know that Vin can be used to power the board but have also been reading that it can be used as a 5V output. Is it possible to assign Vin as an output as I would any other GPIO?
If I want to power an LED from GPIO 12, I would assign GPIO:
const int LEDpin_0 = 12; // D6, LED power pin

...and in the setup:
pinMode(LEDpin_0, OUTPUT);

I can then turn on and off the LED based on whether or not GPIO 12 goes HIGH or LOW.
Can I do the same with Vin without resorting to relays or other hardware?

The board will still need power (probably over USB?). You cannot change the power pin in code or switch it on/off. But if the 5V usb is going straight to the vin pin, then you can use it to power external components.

Im wondering if i can have 3Amps power supply source for this. Im not sure what regulator does the board have. cause 3amps is quite high for dev boards

There is confusion about what is and what isn't possible with this board. This is because there are different versions with different power arrangements.
NodeMCU 0.9
In this board the USB's 5V and the 5V pin are directly connected together. The combined result is then fed through a diode before entering the 3.3V voltage regulator.
With this arrangement the 5V pin will provide the exact same voltage that the USB port feeds the board. However it is dangerous to connect that pin to any power source - it may kill (or at the very least disable) the USB port in your computer - when the board is also connected to a computer through the USB port.
NodeMCU 1.0 and 1.1
On this version the USB's power is first fed through the diode and then to the 5V pin and the 3.3V regulator together.  This means that the 5V pin will show about 0.5V below whatever voltage is fed in through USB. This isolates the USB from the 5V pin so it becomes safe to provide power through the 5V pin whilst at the same time having the board plugged in to the computer - at the cost of having a slightly lower output from the 5V pin.

Original answer:
The VIN pin not directly connected to the USB's 5V supply (at least on the LoLin v3 board). this means the pin cannot be used as a 5V supply output.

You cannot control that voltage. It is always on, and always 5V (or whatever your USB port happens to provide - 4.75v - 5.25v).
You must never ever connect VIN to a power source and connect the USB socket. That can destroy the USB port in your computer. There is zero back-powering protection on that board.
Drawing more than 500mA from the VIN pin could cause the USB port of your computer to be shut down.

It is not directly connected. There’s a schottky diode between the USB 5V pin and the 5V pin.

This answer is not completely accurate. At best, it's no longer accurate. I can confirm that the 5V on my V3 board is NOT connected to the supply. When I meter it, I get 1.3V.

The edit made this answer gibberish. That is, either the first paragraph is correct, or the rest is, but they are directly contradicting one another, so they can't both be true.

my 2 cents:
A LoLin NodeMCU V3 when powered via USB in the Vin pin reads 2.2 V (don't know why) but... in the VV pin you can get the 5V coming from the USB; so if you need 5V use that pin.
The board if powered via Vin with 5V, the VV pin reads 2 V (don't know why either)
in any case you can always get 3V in the 3V pin.
Cheeers!

IMPORTANT WARNING: According to other sites around NEVER feed a NodeMCU via Vin (5V) and also connect it to a USB. You can blown your USB port or board.

the question was if you can use 5 V pin as gpio. (I know, it is hard to understand how can someone ask it)

Your comment is the only one I've found so far searching that states the LoLin NodeMCU has power on VV instead of Vin. I'm seeing that as well. Doesn't follow the NodeMCU spec. Although I agree with other comments that this doesn't necessarily relate to this question.

No you cannot use a Vin or VU pin as a GPIO pin which can be controlled by a program. Vin can be used as an input for 5V battery or as a 5V output when NodeMCU is powered by USB (except on NodeMCU v3 by LoLin).
On the V0.1 LoLin board, there are 2 diodes between the VIN and VU pins.  So you cannot get power from one to the other.  These diodes isolate the two possible sources of 5V power from each other while allowing the board to obtain the 5V needed by its its 3.3V power supply from either 5V source.
Other board versions might be different.
To control 5V sensor with help of GPIOs on NodeMCU you will need a logic shifter connected between your sensor and GPIO pin thats boost the 3v3 to 5V.

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


text:
Use external power - nodemcu 0.9
I'd like to deploy my project so I'm looking for a way to power the nodemcu.
I'd like to know if there's a way to power it with a 9V battery without any other external circuit.
Until now I've found information for the nodemcu 1.0 and it supports up to 20V on the VIN port. Here's the article I read:
http://henrysbench.capnfatz.com/henrys-bench/arduino-projects-tips-and-more/powering-the-esp-12e-nodemcu-development-board/
I'd like to use the two port: 5V and GND but I'm not sure, here there is no VIN port and I'd prefer to not burn my board.
Are there any better way to power my project?

you can feed more than 5v in, especially for short periods of time.

It looks like the 0.9 uses the SPX3819 regulator. That can run with up to 16V on the input, so 9V on the 5V pin (as long as USB never gets connected) should work fine.
Except: 9V PP3 batteries are useless. If it can even provide enough power to run the board (which is doubtful) it won't last more than a few hours.  You would have to ensure that you use very very deep sleep mode to get any semblence of longevity out of it.
The 3.3V regulator will be throwing away half to two-thirds of the power as heat. So wasteful. You would be better off investing in a 3.3V switch-mode ("buck") regulator circuit (cheap on eBay) to directly power the 3.3V pin of the board instead of 9V into the on-board regulator.

Thank you, I'm actually using DeepSleep in fact the board should sleep more or less for 6 hours, wake for few seconds (1 min max) and the go to deep sleep again. I cannot use a power bank because when the board is in deep sleep because it stop to provide power

About the 3.3V regulator, does the AMS1117-3.3 is ok? From here I read that the Vin-Vout should be between 1.5V and 12V, is it correct?
http://www.advanced-monolithic.com/pdf/ds1117.pdf

That is just as inefficient. But it can handle more current before it melts.

You want to look for a "UBEC" (that's the magic word). Something like this.


text:
How to test if PWM mode is working correcly?
I d'like to test if the PWM mode is working correctly on the pins of my Arduino Board. Do you know a simple schema to do this ?

There are my options:

The default way to do this is to use an oscilloscope. These can be quite expensive.
Use a logic analyzer if the voltage is logic/binary (0 and 3.3 or 5V). These are very cheap.
The easiest way to know if it works without the devices above, is to lower the speed drastically (using a divider in the software, like 1000 or more to get PWM widths of 100 ms to multiple seconds) and connect the PWM output with a resistor and a LED to GND. If the LED flashes faster, the PWM speed is high, otherwise low. By using a stopwatch you can roughly calculate the PWM speed (taking the divider into account) and after the test remove the divider.
If the PWM is controlled completely from your Arduino (probably not), you can use a software counter and print it out afterwards to see the speed.

ha ! I knew that this cheap Chinese oscillator i bought one day could finally be useful at something. thank you

Do you have a DSO150 (analog?) scope or a digital logic analyzer? Last are really easy (and much faster, 8 channels) and cost less than 10 dollars.

this is a DSO Shell from JYE Tech , really cheap and poor but should to the job :)

Sounds good, I don't have such a digital oscilloscope but planning to get one eventually. I have a very old analog one but it is very hard to use (bad CRT). Anyway with your oscilloscope it should be possible to find out the PWM speed.

I just tried it and my PWM works correctly : )

Good luck with your project.

You could just do a simple analogWrite, varying the duty cycle, with an LED/resistor. Fade the value up & down, see if the LED gets brighter & dimmer.


text:
Adding music to loop
Im newbie. I just wanted to ask how can i put my tmrpcm.play into loop. Im trying to put it in a loop but the problem is it didn't play. I also try adding a method and call the method into the loop but it give me the same problem also. It will just only play in the void setup.
Here's my code.
#include "SD.h"
#define SD_ChipSelectPin 4
#include "TMRpcm.h"
#include "SPI.h"

TMRpcm tmrpcm;

void setup(){
tmrpcm.speakerPin = 9;
Serial.begin(9600);
if (!SD.begin(SD_ChipSelectPin)) {
Serial.println("SD fail");
return;
}

tmrpcm.setVolume(5);
tmrpcm.play("Yeah.wav");
}

void loop(){  }

The library has a built in loop function:
audio.loop(1);             0 or 1. Can be changed during playback
                           for full control of looping.

See WIKI page of the library.
Btw, it is unclear if you mean by 'a loop' a while(true) loop or the void loop() function. Although it should not make a difference.

The TMRpcm library is non-blocking. That means, when you start playing it keeps playing in the background. If you put the play function in a loop it will just keep restarting what you are playing over and over again and you won't get to hear anything.
As Michel says, you can get it to loop automatically (tmrpcm.loop(1);), in which case you just leave it in setup() and leave loop() empty.
If you want to do it manually you should check to see if the sound has finished playing or not. The simplest way is:
loop() {
    if (!tmrpcm.isPlaying()) {
        tmrpcm.play("Yeah.wav");
    }
}

That is - if it's not playing then start it playing. When it finishes it'll not be playing any more, so it will start playing again.


text:
I am new to arduino please help me in understanding this code
while (client.connected()) {
  if (client.available()) {
    char c = client.read();
    Serial.write(c);

Why we require char c and what is the use of using this command Serial.write(c)

how much of the code do you understand?

client.read() returns exactly one byte from the serial input buffer for the port connected with object client. That is why you use a char variable. The name c is not relevant.
The next line, Serial.write(c) then writes that same character to the main serial port.
The code basically reads from one serial port and writes the same data immediately to the other serial port.

What you have there is simple "Serial pass-thru" code. Whatever a client receives gets printed on the serial terminal.
It can be written, line by line, in English like this:
- While the client is connected:
    - If there is some text available in the client:
        - Read one character from the client and store it in the
              variable "c" which is of "char" type.
        - Print that character out to the serial port.

The reason you use Serial.write(c); is so that you can see what has been received.


text:
How to rebuild Arduino core for ESP8266
I'm experimenting adding DHCP option 160 to dhcpserver.c in the Arduino core for ESP8266 and therefor need to rebuild the relevant parts.
I made an initial guess that I might be able to make the change by installing using git according to the instructions in the readme and just restarting the IDE. I wasn't surprised to learn that this didn't help. The modifications to dhcpserver.c did not make it to the device following restart of the IDE and a new upload.
From another forum I saw a suggestion that the following commands could be used to rebuild from source:
$ cd esp8266/tools/sdk/lwip/src
$ make install

Again the changes didn't make it to the device after restarting and uploading the sketch again.
Does anyone have any clearer instructions for how to build a new Arduino core for esp8266?

You do have the right LwIP variant selected in the menu don't you?

I'm away from the keyboard now but I don't remember even seeing a menu for lwip. I've selected a board from those available for esp8266 (nodemcu v1) and run a sketch that starts a WiFi AP.

@Majenko That would work as an answer; once I chose the "Compile from source" setting the additional DHCP option was seen in wireshark. Thanks!

There are four variants of LwIP bundled with the ESP8266 core:

V1.4 (Compile from source)
V1.4 (Precompiled)
V2 Lower Memory
V2 Higher Bandwidth

By default (for most boards) one of the V2 variants is selected. You need to change that to the V1.4 (Compile from source) for it to use the version that you have modified.


text:
Controlling multiple 24V solenoids with Arduino
I'm building a pump for which I need 4 medium strength solenoids (20-50N). 24V is probably the minimum I will need to put through them, but this is something I need to test, once I've got them working. At 24V they draw 400mA.
I've found various posts with very useful info, especially https://playground.arduino.cc/Learning/SolenoidTutorial and https://forum.arduino.cc/index.php?topic=417030.0
Will the attached sketch below work for one? If so what resistance should R1 be?
And if so can you see any problems with hooking up 4 working at different intervals?
The power supply is an LRS-350-24RS, and the Mosfet has a max gate source voltage of 35V. The 5v-24v optocoupler is off ebay -  https://www.ebay.co.uk/itm/152904980799
Many thanks for your help!!

Did you draw that schematic?

The resistor should be on the other (left) side of the optoisolator. The diode parallel to the solenoid should be the other way around.

I also think you need a pull down resistor on the gate of the mosfet.

You are attempting to source current into the MOSFET gate to turn it on? Then the transistor in the Opto is upside down.

@ Majenko Yes, but based closely on what I've seen from other posts

@ Crossroads OK cheers

No, it won't:

The diode D1 is backwards.
The opto-coupler is wired completely wrong.

You don't actually need the opto-coupler as long as the threshold voltage of the MOSFET is low enough for the Arduino to switch.  However if you do want (or need) to use it you should wire it like this:

simulate this circuit – Schematic created using CircuitLab
R1 is a pull-down that keeps the MOSFET off when not being turned on (just like with a button). The value doesn't matter much.  R2 is a resistor just like you use for any LED with an Arduino.  D1 must be connected reverse biased or it will just short out your solenoid. The opto-coupler must be connected with the transistor the right way around or it will not work (or melt, or create a black hole...)
To ditch the opto-coupler you can just treat it like any other load on the Arduino (as long as the MOSFET's threshold voltage VGS is below 4V):

simulate this circuit

@ Majenko OK cheers for that. Surely you need the optocoupler for this to work, as the Ardunio cannot take 24V, so where would you return the Arduino signal to the MOSFET back to?

Why would it be "taking" 24V?

Is there any reason for using a schottky diode, instead of a regular diode?

@Gerben They tend to have faster switching from reverse to forward bias, making them absorb the back-EMF better.

@Gerben "The most important difference between the p-n diode and the Schottky diode is the reverse recovery time (trr), when the diode switches from the conducting to the non-conducting state. In a p–n diode, the reverse recovery time can be in the order of several microseconds to less than 100 ns for fast diodes. Schottky diodes do not have a recovery time, as there is nothing to recover from (i.e., there is no charge carrier depletion region at the junction). The switching time is ~100 ps for the small-signal diodes, and up to tens of nanoseconds for special high-capacity power diodes. ...

With p–n-junction switching, there is also a reverse recovery current, which in high-power semiconductors brings increased EMI noise. With Schottky diodes, switching is essentially "instantaneous" with only a slight capacitive loading, which is much less of a concern." -- Wikipedia

Thank you for the information. Guess I will be using schottky diodes in the future as flybacks.

You don't need a pulldown resistor if you're driving the MOSFET from an Arduino; the Arduino's output is CMOS. You DO need to be sure that your MOSFET's input capacitance isn't so big that it overwhelms the Arduino's output stage, though. Otherwise, it represents a short-circuit until it's charged.

@TDHofstetter The pulldown resistor is there because the Arduino's GPIOs default to INPUT (Hi-Z) so the input to the MOSFET is floating until it's actively driven by the Arduino - and there is a delay at startup caused by the bootloader, so there's a couple of seconds where the relay could trigger erroneously at power up.

#Majenko True and good point, except that the MOSFET's gate would have leaked down long ago (they do leak) unless we're rebooting the Arduino immediaely after shutting it down with the MOSFET gate high, leaving no time for it to leak down. Very remote possibility, but a possibility.

The MOSFET, to be driven from Arduino directly, needs to have a Logic Level gate.
I've been using AOD514. Logic level gate, Low Rds, rated for 30V.
https://www.digikey.com/product-detail/en/alpha-omega-semiconductor-inc/AOD514/785-1357-1-ND/3060919
SMD only, they seem to have cancelled their thru-hole line of parts that I used to use.
I have up to 32 of them on a board with the gates driven by 74HC595 shift registers for driving 1A loads (only limited by trace widths, not the transistors), with diodes added at the coil if needed.
http://www.crossroadsfencing.com/BobuinoRev17/

Ah great thanks. I hadn't cottoned on when Majenko mentioned this above. Have now read up and will change to this LogicFET https://docs-emea.rs-online.com/webdocs/0791/0900766b8079135d.pdf .


text:
MQTT not working on ESP8266 (Nodemcu 0.9)
I'm trying to use NodeMCU on my ESP8266 (NodeMCU 0.9) but the board keep crashing and I don't understand why.
I tested the mqtt broker using command line and it works perfectly, so I can suppose that the problem is not the server.
I was following this guide but it doesn't seem to work with me.
Here's the code I wrote:
Previously:
#include <PubSubClient.h>
#define MQTT_SERVER    "1.2.3.4"
#define MQTT_PORT      1883
#define MQTT_USER     "user"
#define MQTT_PSW      "psw"
...
WiFiClient client;

Then:
PubSubClient clientMqtt(MQTT_SERVER, MQTT_PORT, this->client);
//Try mqtt connection
while (!clientMqtt.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (clientMqtt.connect("ESP8266Client", MQTT_USER, MQTT_PSW)) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(clientMqtt.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
}

//Try send message
clientMqtt.publish("bin", "test", true);

The code works correcty until clientMqtt.connect("ESP8266Client", MQTT_USER, MQTT_PSW) where at the first/second attempt crashes.
This is the output:
Attempting MQTT connection...
failed, rc=-2 try again in 5 seconds
Attempting MQTT connection...
failed, rc=-2 try again in 5 seconds
Attempting MQTT connection...

Soft WDT reset

ctx: cont
sp: 3ffefa90 end: 3ffefe30 offset: 01b0

>>>stack>>>
3ffefc40:  3ffe897d 40202c5d 3ffefcc4 40202dab
3ffefc50:  3ffe89b7 3ffefcc0 3ffefcc4 40203cdc
3ffefc60:  514d0400 00045454 3ffe89a7 40204cdc
3ffefc70:  3ffe89c0 3ffe89a9 00000000 3ffe88fa
3ffefc80:  3ffeeb70 3ffefdb0 3ffeedd8 3ffe88fa

The Soft WDT reset means that the software watchdog timer reset. Depending on the version of Arduino core to the ESP8266 using delay() can cause this to happen, though current versions handle this better, and using delay() does not cause problems. Make sure you are up-to-date with the Board Manager definitions for ESP8266-based projects.
This page has lots of information on the watchdog timers and especially notes how to use a tool called ESP8266/ESP32 Exception Stack Trace Decoder to determine exactly what line in your code caused the reset to happen.
This page notes that the PubSubClient library can cause problems with the watchdog feeding and gives examples of some alternative yield() and delay() functions you can include and call instead of the built-in versions, which help alleviate resets when using PubSub on ESP8266.
The software watchdog timeout is on the order of 3 seconds, so you can also try reducing your delay(5000) to something shorter, like delay(1000) while debugging, to rule out the 3-second WDT reset due to the delay() call.
Your output also indicates status -2 to the state() function. The documentation for PubSubClient notes that this means "the network connection failed". So one other thing to check is that your device actually connects to the WiFi network and that the MQTT server is listening on the IP address and port you specify.


text:
Is DateTime from RTClib giving garbage dates/times?
The RTC is working fine, but I'm having trouble with the DateTime class. Based on the following test, it seems like its math is wrong.
#include <RTRlib.h>
void loop()
{
    auto ts = TimeSpan(0, 8, 0, 0); // 8 hours
    auto zero = DateTime(0, 0, 0, 0, 0, 0);
    auto alarm = zero + ts;
    Serial.println(String("Zero date: ")+zero.year()+" "+zero.month()+" "+zero.day()+" "+ zero.hour()+":"+zero.minute()+" "+zero.second());
    Serial.println(String("Alarm as timespan: ")+ts.days()+"d "+ ts.hours()+":"+ts.minutes()+" "+ts.seconds());
    Serial.println(String("Alarm date: ")+alarm.year()+" "+alarm.month()+" "+alarm.day()+" "+ alarm.hour()+":"+alarm.minute()+" "+alarm.second());
}

My output is (repeating):
Zero date: 2000 0 0 0:0 0
Alarm as timespan: 0d 8:0 0
Alarm date: 2043 4 30 1:31 44

Also, when creating DateTime(0), I would expect the hours, minutes, and seconds to be zero. That's not the case. What's up with this library, and how did it get to be so popular if it doesn't work?

What is the value of alarmTime?

DateTime(0) isn't really supported as the library only works on dates after 2000. DateTime(0) will set the date to 1970, which looking at the source code doesn't work. But almost nobody would care. As for your primary issue, I wouldn't know why it isn't doing what you expect.

Try using the year 2001, just to be sure.

@Gerben My mistake, alarmTime is removed. Thanks for spotting that.And I find it strange that DateTime(0) isn't supported, since that is the default constructor!

Any DateTime class will have some limits on the range of dates supported. Unless the practical limits are less that the documented ones, that's not a bug. However, you are right in pointing out that the default constructor is not useful. I just opened an issue on this point.

You are experiencing the consequences of code that doesn't do sanity checking. The library allows for dates that do not make sense (in addition to giving us all a new reverse-Y2K bug of assuming only dates later than year 2000.
When you create DateTime(0, 0, 0, 0, 0, 0);, you are saying to use Month 0 and Day 0. Those have no meaning in date calculations, which always assume that the first month is 1 and the first day is 1.
The rest of the library's code assumes valid dates, so when you give it invalid dates, unexpected behavior is to be expected!
Of you only modify your zero assignment to DateTime(0, 1, 1, 0, 0, 0); you will see behavior that is more expected.

Thank you, I suspected I was doing something stupid. But that doesn't explain why the other constructor returns dates when given a number of seconds (DateTime(0)). Whether it's seconds since 1970 or 2000 (it should be the former), it does not look like a usage error to use that API for any non-negative argument, yet it does not give a sane date for small numbers.

Note that an RTC is meant to track real time, and since year 2000 will never happen again, there is no “reverse-Y2K bug” in that library. Or rather, that's a closed (invalid) bug. It does have a Y2100 bug though, but that's a limitation of the RTC hardware.

@EdgarBonet The comment above the class definition is, "Simple general-purpose date/time class". It's also not private and not part of a namespace. So no, it's not a real time date class. It's a general purpose date class, which happens to be buggy. Irrespective of the fact that adafruit doesn't want to fix it in their fork.


text:
How do I detect the Computer's operating system?
I'm working on an emoji keyboard and it requires different input depending on the OS it's connected to. I've written the relevant methods using Arudion's default Keyboard library and can manually set which one is used. I'm wondering if there is a method or library for Arduino (currently using a Adafruit Feather 32u4 Bluefruit LE) that allows me to detect the OS.
If not, I'll set up a switch, but that'll cost me pins.

This information is not formally available to a USB peripheral like an Arduino; there might be ways you could "fingerprint" OS behavior from deep in the library code of a Leonardo-type board, but that could trivially change.

@ChrisStratton Thanks. That answer the question. I'm going to have to find a work around.

If you can't get the OS from the USB port, why not use the existing keys/inputs to set the mode on startup? That is, if you tell the user to press different combinations of 2 buttons on startup, you have 4 (2 bits => 4 values) different paths on startup:
00 => Normal startup, don't change mode
01 => OS 1
10 => OS 2
11 => OS 3

Might do that, but I like the idea of a clear multi option switch for the user to be understand/set at any point.


text:
Serve currently uploaded code from Arduino
I'm creating a project where multiple ESP8266 12-E's are connected together. I want to use ArduinoOTA with the HTTP option (described here) and I want to have one ESP be able to send its code to another. I just need to figure out how to get the currently uploaded code in the form of cpp.bin in the Arduino language from the Arduino, without using an external computer, and then serve it (I can figure out the serving part though). How could I go about this?

see the ESP8266httpUpdate example

I've already seen that example, I just want to figure out a way to get the code uploaded to the ESP from the ESP. Thanks though!

I am not sure what the problem is? use SPIFFS to store the bin

OK, that's a good idea. I can't access the code without storing it though?

you want to clone the program of the esp to other esp?

Exactly, but I can't figure out how to get an ESP's own uploaded code


text:
Question about Variables
is there a way to use a previous assigned value to variable to adjust the step motor? what i mean is:
example:
Sensor reads 100 degrees so
Adjust the step motor to 100 degrees and hold, then after 10 min
the sensor reads 110 degrees so
Adjust the step motor (110 - 100) by extra 10 degrees
and so on..
I'm really new to this and i'm sorry if that's a stupid question :<

Start with example code for driving the stepper motor. Then calculate how many degrees equals one step. Use a variable to save the current Position of the stepper in units of steps. Everytime the Sensor reads a different value, calculate how many steps to take, run the stepper and maintain the variable.

I see you are getting close votes on your question. I strongly suggest you do some basic C (or C++) tutorials. Asking a "question about variables" is really nothing to do with motors or sensors. Do some tutorials and then you will understand how to use variables. The Arduino is programmed in C++ if that helps.

Based on your description, the program needs to know only the new target setting and the current position. That means you need two variables. Algorithmically, it would look as follows (written in C-like pseudo-code):
// initialize global variables (might need float instead of int)
int target_pos = 0;
int current_pos = 0;

void setup() {
    // add code to set up pin IO mode, prepare communication with the sensor...
}

// function to read the sensor
int ReadSensorFunc(void) {
    int reading = 0;   // local variable to store sensor reading
    reading = ...;     // add code to read sensor
    return reading;
}

// function to adjust the motor position
void AdjustStepMotorFunc(void) {
     // add code to to adjust the stepper to (target_pos-current_pos);
}

void loop() {  // repeat forever
    target = ReadSensorFunction()   // call sensor read function
    AdjustStepMotorFunc()           // call position adjustment function
    current_pos = target_pos        // update current position
    // add code to delay for 10 minutes
}

This code initializes the position as zero. In case it's not zero when the controller is turned on, you'll need additional code in setup() to assign current_pos the correct value based on user input.

Initially you read the value of sensor to some variable, like:
previous = readSensor();

Every ten minutes you have to call a function ( logic using timer interrupt / RTC /millis() ) which reads the current value from sensor and compares it with previous value to get the offset. Then you pass it to the function which adjusts motor speed. Update 'previous' variable
offset = readSensor()-previous;
previous = readSensor();
adjustSpeed(offset);


text:
Using USB or ethernet to carry digital signals
I need to send six digital signals about 4 feet through wires. An ethernet cable has 8 little wires that should do the trick. I could split the ends and solder them to my boards.
Is there an adaptor that will let me plug in the ethernet cable cable to my board and have access to the signal from each wire on a pin? If not, can I accomplish this through USB? Is there a more elegant solution than having six long wires?

You mean like a RJ-45 jack?

10BaseT cables have 4 twisted pairs.  USB cables have 4 wires, 2 for signal and 2 for power.  Careful how long you make the wire.  High speed digital signals like ones that a processor can make can not go far with out special attention.

something like https://www.ebay.nl/itm/Kit-RJ45-8-pin-Connector-and-Breakout-Board-For-Cat5-Cat5e-Cat6-Ethernet-Cables/131857340868 . Don't forget that you also need one wire for the GND connection.

@IgnacioVazquez-Abrams do you know of one that has pins at a right angle that can go down into a breadboard?

@Gerben perfect make that your answer I will accept it

@Gerben for bonus points which one carries the +/gnd for POE?


text:
Controlling DC motor with Pololu shield Arduino
I'm trying to power 2 DC motors with my Pololu DRV8835. I'm using the code found in this library. It works as expected BUT ONLY if the whole thing is powered via USB. When I try to power it through the shield with an external battery, the motors only beep. So the program AND the wiring have been tested.
PS.: I've also measured the voltage across the shield (M1A-M1B, M2A-M2B) and they only get like .01 V when powered via external battery. Also I'm using and Arduino Due.

We are going to need some sort of schematic or wiring diagram before anyone can help you. You can use the built-in schematic tool, or something like a screenshot from http://fritzing.org/download/ or drawn by hand.

the ESCs are driving 2 seperate BLDC motors (those work) -- https://imgur.com/a/v3P0W

My guess is that the ESCs are causing you a problem. The Arduino, for sure, is not made to be run off a modulated power supply. The ESCs are going to do very bad things to this circuit.

In our setup, the arduino only gives the signal to the ESC not power nor does the ESC give power to arduino. The only connection between the arduino and the ESC (apart from the signal) is that they run off of the same lipo battery

What's the battery pack voltage?

7.8V (measured with a multimeter), the package says 7.4

I think the best thing for you to do at this point is to go through the Arduino Due schematic and make sure your voltages (particularly in the power section) match when you are using battery vs USB power.

in both cases, when we measured the power pins on the shield, we got 7.8 V (if that's what you meant)

Don't connect your motors in series.

It didn't work when we connected only one motor either


text:
Control multiple WS2812B strips with different leds count
First of all, my English is not that good so sorry if I made any mistake.
I'm using the WS2812FX, an awesome WS2812 effect library base on Adafruit NeoPixel library to make a small controller for the lightning in my bedroom.

The question here is how do I use this library to control multiple WS2812b led strip with different leds count, like one strip with 30 leds the other with 55 leds but the effect will just cycle through each individual led of each strip.IF somehow I can add one more output pin to this.
Example : There is an effect call "Larson Scanner" will light up one led then it run from the first led to the last led and go back, I want it to do the same on both strips, on the 30 leds strip it goes from first led to 30th led then go back & on the 55 leds strips it goes from first led to the 55th led at the same time.
Hope you guys understand what I'm asking :(
Link to the library : https://github.com/kitesurfer1404/WS2812FX

If you want the effect to be syncronized between the strips (Start and stop for both strips in the same time) you can use the same signal line to control them. In the last part, where only one strip has LEDs, only this one would light up

Which Arduino are you using?

goes from first led to the 55th led at the same time ... are you saying that both strips have to scan from end to end in the same amount of time?

You might also look at the FastLed library.
I used it to control 4 rings of 43 lights here
https://www.youtube.com/watch?v=CGOxbehyoM4
https://github.com/FastLED/FastLED

The WS2812 chip requires highly timing dependent pulses to work, as I describe on my page about Neopixels. We are talking about pulse widths of 350 ns.
I suggest it would be impossible to add another strip "if I can add one more output pin to this". It's not a question of adding pins, it's being able to output pulses that fast. You can't do it, at least not on the AVR Arduinos, and I doubt that the ones with faster chips would do it either.
What you could do is connect the various strips together so it is really one long strip (assuming they aren't too far away from each other). The different strips could usefully have their own power supplies, but the data and ground would need to go from the Arduino into the first strip, then out to the second one, and so on.
Something like this:

As for synchronizing the strips, well that is just programming. If you want the first LED on the 30-LED strip to light at the same time as the first LED on the 55-LED strips, then you actually would need to light LED #1 and LED #31 at the same time.

Possible alternative
Actually what might work would be to send to strip #1 first, and then strip #2 after changing pins. That means you would have to interleave the sends. For example to make a pixel seem to run backwards and forward on two strips you make it move one pixel on the first strip, then one pixel on the second strip, and so on.
I'm not sure if the library you mentioned supports that, since the LED count is in the constructor. It looks like it might, as you can change the number of LEDs and the pin number.
You might be able to make two instances of the library object (with different names), initialize them both, and then interleave the sends between them.

Your alternative approach works, if you don't need the effects too fast and precise. I've done this with 5 strips (each in its own pin) with 240 LED strips. But this also depends on how complex the calculation of your pattern is.

i had some animations that were choppy, then i tried on an ESP32 and whooaa nelly, I had to manually delay() it down. best led driver ever...

The library repo itself already describes "segments". So you simply connect the 55-part strip's data-in to the data-out of the 30-part strip. Instantiate as one 85-part strip, and then define the segments and set patterns on each as appropriate.

I had the same question!
=> Use an arduino per LED strip :)
and, if it is necessary to interconnect them to synchronize them
In short, work around the problem
translated by Google :(


text:
Tian stops working after some hours
I'm having a very strange problem. I have a Tian that is programmed to send out sensor data to a server
every x seconds.
My program run well but after 14,15 hours of operation it stops working and I don't receive datas. The program is fast at the beginning, then after 2 to 3 hours before stopping, it becomes more and more slow with the message "timeout".
I think maybe a misuse of the Ciao library on my part could be at the root of the problem. Or maybe a modification at the program level could correct the problem. So if I can have some help about this..
(the problem doesn't come from the use of String, I have already tested use of array with cstrings and it doesn't work).
Here is the part of the program that I think is problematic (there is another CiaoReadWrite nearly similar to the first) :
void CiaoReadWrite1() { CiaoData data = Ciao.read("restserver");
if (!data.isEmpty())
{
  String id = data.get(0);
  String sender = data.get(1);
  String message = data.get(2);

  splitString(message,"=",LtT2,9);

  gen            =LtT2[0].toInt(); LtT2[0]="";
  belt           =LtT2[1].toInt(); LtT2[1]="";
  genReady       =LtT2[2].toInt(); LtT2[2]="";
  hvOnOff        =LtT2[3].toInt(); LtT2[3]="";
  beep           =LtT2[4].toInt(); LtT2[4]="";
  heart1         =LtT2[5].toInt(); LtT2[5]="";
  sendConf       =LtT2[6].toInt(); LtT2[6]="";
  heart2FB       =LtT2[7].toInt(); LtT2[7]="";

  beepFB         =beep;
  heart1FB       =heart1;
  sendConfFB     =sendConf;

  Ciao.writeResponse("restserver",id, String(baroAlti*100)+"="+baroHumi*10+"="+baroPres+"="+baroTemp*10+"="+beepFB+"="+heart1FB+"="+heart2+"="+sendConfFB+"="+
                                      secCust1+"="+secCust2+"="+secEmrgSW+"="+secloop+"="+secLoop1+"="+secLoop2+"="+gndSwGnd+"="+gndSwUGnd+"="+statusA1+"="+
                                      statusA2+"="+statusA3+"="+beltStat1+"="+beltStat2+"="+beltStat3+"="+beltStat4+"="+request+"=");
  request++;
}

}

You're using the String (upper-case 'S') functions, which allocate and de-allocate memory, a limited commodity, even with 64K. The standard heap management functions will tend to fragment the heap into pieces too small for further use. That can make new allocations slower because the heap has to be searched for a big-enough piece, and can eventually make it the heap grow toward the stack, until a collision (something gets overwritten) inevitable. We can't say for sure that this is your problem; we don't have enough information.
But try allocating one or a few buffers large enough for the worst case requirement, and use the C string functions instead (lower-case 's'), sprintf(), strcpy(), strcat(), etc. instead.

Well, if your program works some time and stops, the first thing you have to check is if there's some variable entering in overflow.
Maybe some variable is concatenating and after some time it goes overflow.
I haven't check your code or the lib, because that is a common problem and already happened with me.


text:
How can I send and receive data from an Arduino Uno to Arduino Mega using I2C?
I am trying to send data as a string from an Arduino Uno to another Arduino Mega. I have read about the I2C connection where we connect the RX to TX oppositely.
How to start and send and receive data between them? I have no idea how the code can be written.

At instructables there is a good post.
In short the code is
Master code:
// Include the required Wire library for I2C
#include <Wire.h>
int x = 0;
void setup() {
  // Start the I2C Bus as Master
  Wire.begin();
}
void loop() {
  Wire.beginTransmission(9); // transmit to device #9
  Wire.write(x);              // sends x
  Wire.endTransmission();    // stop transmitting
  x++; // Increment x
  if (x > 5) x = 0; // `reset x once it gets 6
  delay(500);
}

Slave code
// Include the required Wire library for I2C
#include <Wire.h>
int LED = 13;
int x = 0;
void setup() {
  // Define the LED pin as Output
  pinMode (LED, OUTPUT);
  // Start the I2C Bus as Slave on address 9
  Wire.begin(9);
  // Attach a function to trigger when something is received.
  Wire.onReceive(receiveEvent);
}
void receiveEvent(int bytes) {
  x = Wire.read();    // read one character from the I2C
}
void loop() {
  //If value received is 0 blink LED for 200 ms
  if (x == '0') {
    digitalWrite(LED, HIGH);
    delay(200);
    digitalWrite(LED, LOW);
    delay(200);
  }
  //If value received is 3 blink LED for 400 ms
  if (x == '3') {
    digitalWrite(LED, HIGH);
    delay(400);
    digitalWrite(LED, LOW);
    delay(400);
  }
}

In the instructables post a lot more explanation is shown.

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


text:
Formula to calculate energy required to power an Arduino board
Given an Arduino board with the following specs:
ATmega328 Arduino Nano AVR® ATmega MCU 8-Bit AVR Embedded Evaluation Board (link)
What is the mathematical formula to calculate how much energy/power would be required to keep the Arduino board on (meaning in "standby" mode, therefore not consuming any energy but the one required to keep it "alive")?
Please note I am new to all things electronics, Arduino but most importantly physics and maths. Thank you.

In the datasheet you can read how much every mode uses (normal mode, sleep mode etc). However, it also depends on which peripherals inside the CPU are active and all electronics around it. So make sure you read the datasheet of the entire development board, and not from the CPU itself.
The mathematical formula is reasonably simple: the total power is the sum of each component's Amperage * component's Voltage. But practicially this is hard to calculate.
The easiest way (but not mathematically) is probably just to measure the amperage in the development board, and the voltage and multipley them together.

Don't forget to account for the current required by the FT232RL (usb-to-serial) and the green power-led.

@Gerben that is what I meant to check the datasheet of the entire development board, not from the CPU itself.

I know. I just wanted to explicitly mention those.

@Gerben thanks ... and these a non negligible amount of current.

Thanks @MichelKeijzers et al. That is really helpful but still a bit "cryptic" for me (but mostly due to the fact that I am new to all this).
The reason I asked for how to calculate the amount of energy required to power the Arduino board is because I wanted to understand whether a solar panel (small, big, whichever fits the need) would be able to provide energy for the board to "do stuff" (provided the solar panel has the right amount of energy stored in it...).

In that case, try first without the solar panel. Do all the stuff you need on the Arduino. Than check how much voltage goes inside the Arduino (e.g. if you use the power adapter, check the voltage with a volt meter, if you use USB it's probably close to 5V). Than check the amperes you are using and multiply them together. However, depending on the the Arduino is doing it might fluctuate, so take the highest wattage (volts * amperes) to be safe.


text:
How to receive more than 64 bytes on Arduino?
I am receiving about 90 bytes on the serial port. But Arduino has a serial buffer of 64 bytes only. Because of this limitation I am unable to receive further bytes.
char c;

void read_response() {
  while(Serial.available > 0) {
    c=Serial.read();
    Serial.print(c,HEX);
    Serial.print(",");
  }
}

I tried using the above function to read the serial data, but it is able to read only 64 bytes.
Another approach I tried as follows:
char rxdata[]={};

void read_response() {
  while(Serial.available > 0) {
    int len= Serial.readBytes(rxdata, 90)
  }
}

With this approach too, I was receiving only 64 bytes.
Serial.flush() also doesn't work as it waits for current transmission to finish. And I do not have control on transmission. The transmitter is sending 90 bytes continuously.
Please give me some suggestions.

what baud rate? if you read the response without any delay after sending the request the Atmega should be fast enough to read the bytes from the buffer before it overflows

That read_response() function should work fine as it is - however you probably have a delay() before it that overflows the buffer. Read this: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

Also asked at: http://forum.arduino.cc/index.php?topic=542236 If you're going to do that then please be considerate enough to add links to the other places you cross posted. This will let us avoid wasting time due to duplicate effort and also help others who have the same questions and find your post to discover all the relevant information.

But Arduino has a serial buffer of 64 bytes only. Because of this limitation I am unable to receive further bytes.

This assertion is nonsense. Certainly there is a buffer, but that lets you receive up to 64 bytes (put there by the serial interrupt service routine) before you retrieve a single one.
All you need to do is expeditiously retrieve the data (that is, do a Serial.read()) fast enough that you remove the data from the buffer and store it into memory.
You need to post a Minimal, Complete, and Verifiable Example (MCVE) that demonstrates your problem. For example, are you doing delay(1000) before attempting to read serial data?
See my post about receiving serial data without blocking and also Async (Serial) peripheral interface - for Arduino .

You will need to adjust your concept of serial communication so that you don't rely on the complete 90 bytes of data to be transferred to the serial input buffer before you read it into RAM.
Instead you need to continually empty the hardware buffer into RAM as often as you run through loop(), and avoid using delay(), which will stop your program from being able to drain the buffer.
To know when you have reached the end of the transmission, you should either ensure that the incoming serial stream has a marker at the end (such as a '\n' character) or is always a fixed length (such as always exactly 90 bytes.)
As an example, here is a program that looks for '\n' as the end-of-data marker:
#DEFINE MAX_INPUT 90

char inputBuffer[MAX_INPUT+1]; // Handles up to 90 bytes in a c-style string, with a null character termination.

void setup()
{
  Serial.begin(115200); // initialization
  inputBuffer[0] = '\0'; //Initialize string to emtpy.
  Serial.println("Begin:");
}

void loop() {

  if (Serial.available()>0)
  {
    char input = Serial.read();
    static int s_len; // static variables default to 0
    if (s_len>=MAX_INPUT) {
      // Have received already the maximum number of characters
      // Ignore all new input until line termination occurs
    } else if (input != '\n' && input != '\r') {
      inputBuffer[s_len++] = input;
    } else {
      // Have received a LF or CR character

      // INSERT YOUR CODE HERE TO PROCESS THE RECEIVED DATA //
      // YOU COULD COPY TO A NEW VARIABLE WITH strncpy() OR //
      // SET A FLAG TO SAY TO START SOME OTHER TASK         //
      Serial.print("RECEIVED MSG: ");
      Serial.println(inputBuffer);

      memset(inputBuffer, 0, sizeof(inputBuffer));
      s_len = 0;             // Reset input buffer here if you
                             // have already copied the data.
                             // If you don't reset here, then
                             // you can't start receiving more
                             // serial port data. This is your
                             // 'software' serial buffer, contrast
                             // with the hardware serial buffer.
    }
  }
}

Good answer, but note that: 1. Storing s_len statically is simpler and more efficient than calling strnlen() on each received character. 2. You don't need to NUL-terminate on every received character, only once per full message. 3. Flushing the input buffer is not needed, and that could discard the beginning of the next message.

Ok on point 1. For point 2, my preference is to not leave unterminated strings laying around. For point 3, the code snippet is from my personal cache where I want to be able to signal EOL on CR+LF by detecting the first and discarding all the rest, but you have an excellent point. I will update my sample code.

This new version (2018-04-18 19:11:50Z) is prone to a buffer overflow, as the condition s_len==MAX_INPUT is only tested when input is either CR or LF.

Fixed that buffer overflow error. My original sample may have been inefficient, but it worked ;-)

just comment for 2) - I would set the last byte to zero beforehand, then I will never meet unfinished string, at worse I would meet so-far-readed string with attached part of some previous string (up to first zero - else the last byte of buffer or first zero terminating that previous string)

@gilhad: The buffer is all zeros to start width, as with any global (or local static) variable that is not explicitly initialized.


text:
Can only write 5V or 0V, not something in between
I'm working on a bigger project, and needs to give out a voltages between 0 and 5V. I've written this code:
int ledPin = 12;      // LED connected to digital pin

void setup(){
pinMode(ledPin, OUTPUT);   // sets the pin as output
}

void loop(){
analogWrite(ledPin, 255);
delay(2000);
analogWrite(ledPin, 0);
delay(2000);
analogWrite(ledPin, 127);
delay(2000);
analogWrite(ledPin, 128);
delay(2000);
}

If I've understood it right, this should first give about 5V, then 0V, then 2.5V and againg 2.5V. However my voltmeter only reads 5V and 0V, 2 seconds at each. I've attached my voltmeter to pin 12 and ground. The arduino board is also grounded.

You don't say what board you're using, but you may want to check that pin 12 is a PWM  pin on your board. You may find the page on analogWrite() on the Arduino site useful.

on Uno pwm pins are marked with ~

The PWM pins output a square wave from 0 to 5V. If you want something more like a DC level, then run the signal thru a Resistor-Capacitor (RC) Lowpass filter.
1K and 10uF should work well to smooth the squarewave.
http://sim.okawa-denshi.jp/en/CRtool.php
On an Uno, pins 3,5,6,9,10,11 are the PWM pins and output at a frequency of ~ 490 Hz or 980 Hz, with a duty cycle from 1 to 254. 0 is full off, 255 full on.

good info, but you shouldn't need a filter to satisfy a voltmeter, they are slow at math

@dandavis - on the contrary, the opposite.  DC voltmeters are not designed to measure changing signals; if you want to use one, you must first stabilize the signal such as with the proposed filter.  Otherwise you need to use an instrument appropriate to a changing signal, ie, a scope.

i just meant that both a dmm and analog meter will show about the same thing with or without RC, not accurately display the peak, duty, etc...

Most Arduino boards do not have true analog output that can produce voltage range. To check if a particular board has true analog output check the specs and look for pins labeled DAC or Digital-to-analog converter.  Be aware that the supported voltage range will vary depending on the board.
The analogWrite() function uses Pulse Width Modulation to simulate analog output.
If you need true analog output you will need to attach a Digital to Analog Converter(DAC) to the arduino. e.g. https://learn.adafruit.com/mcp4725-12-bit-dac-tutorial
UPDATE:
If your goal is to drive a motor with a SN754410 you should be able to use the PWM analog output to drive it at varying speeds.  Here is an example: http://web.ics.purdue.edu/~fwinkler/616/sn754410_Arduino.pdf

Now it works! It helped using an PWN pin. But should it not also work with one of the analog pins? Or are these pins actually only analog in the reading prosess?

A0-A5 are analog inputs only -- there is no true analog output on the UNO, only PWM.

Some ARM-based Arduinos (e.g. Due) have DACs on-board.


text:
Sending data from webserver to Arduino
Hello Arduino enthusiasts! I've been working on a keypad lock system for school lately and I need some advice.Basically, my code checks if the entered passcode is the same than a predefined passcode stored in a variable. I must code a local web server hosted by my Arduino Mega board that allows someone to change the correct passcode remotely via Ethernet. I have coded a working program, but I am sure it can be better designed or done in an easier way, this is why I'm asking for advice on how I could improve the performances of my program or make it shorter. If you need further explanation, let me know and I'd be happy to explain. Thank you!
Here's my code(or if you think it's plain, with colors):
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0x90, 0xA2, 0xDA, 0x0E, 0xA5, 0x7E };
IPAddress ip(192,168,1,250);
EthernetServer server(80);

String HttpHeader;
String nwCode="";
int curCode=19988;

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

  if(Ethernet.begin(mac)==0){
    Serial.println("Failed to use DHCP");
    Ethernet.begin(mac, ip);
  }
  Serial.println(Ethernet.localIP());
  HttpHeader="";
}

void loop(){

  EthernetClient client = server.available();

  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        if (HttpHeader.length() < 16){
           if(nwCode.length()<5){
             if(isDigit(c)){
               nwCode.concat(c);
             }
           }
        }
        if (c == '\n') {
          if(nwCode.length()==5){
            curCode=nwCode.toInt();
            Serial.println(curCode);
          }
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("");
          client.println();
          client.print("<form method=get>");
          client.print("<input type='password' name=code required>
");
          client.print("<input type=submit value=submit></form>");
          client.print("");
          nwCode="";

          client.stop();
        }
      }
    }
  }
}

In the void setup() I try to connect to the internet with DHCP, and if not, just connect with specified IP and MAC addresses. I also print the IP address used to host the webpage so we know what to type in our browser. Then in the void loop() I wait till someone visits the IP address and show them the webpage. Next, we read the incoming GET request(new passcode submitted) and make sure it's not any longer than 5 chars (correct passcode is 5 chars long), then I take only the numbers (remove GET and HTTP 1.1 from the request) and store them in the nvCode variable. Then if the request has ended and the passcode is 5 chars long, set the current code value to the new code(Without this step the serial monitor outputs 11 everytime the page is loaded or I make a request, I think this comes from the HTTP 1.1 and isDigit().)
I know there are better ways of doing this and the simpler and shorter the better, so any advice is much appreciated, thanks!
I have used Serial output for debugging purposes and to better show what the code is doing but I plan on removing that afterwards.
Here are the outputs:
This is what the Serial monitor outputs when I power the Arduino board.
(The IP is the address where the webpage is hosted)
This is the webpage hosted by the Arduino board.

After submitting a new passcode, it sends a GET request.

The Serial monitor output after sending the new passcode.

TL;DR the nwCode variable must collect the passcode entered in the HTML form and must set var curCode's value to it. nwCode being the new passcode code and curCode being the current passcode.
!UPDATE!
I just realized that I can change the passcode once, but if I try to change it again after, I get the wrong numbers on the serial monitor, so my code has a problem somewhere. Any help regarding this issue would be much appreciated.

also asked at https://forum.arduino.cc/index.php?topic=542266

+1 for properly indented code

@Juraj I asked on Arduino's forum too, but the answers weren't really what I was looking for.


text:
Arduino IDE libraries search
Where I can do search libraries on WEB, that similar search in IDE? I did not find search page on arduino.cc

The online analog of the Arduino IDE's Library Manager search feature is located here:
https://www.arduinolibraries.info/
That website is generated from the same index file Library Manager uses:
http://downloads.arduino.cc/libraries/library_index.json

You get widest search with Google. Write "arduino" and then the device or topic name.
Most of the libraries have a GitHub repository. You can use a search field on GitHub.
A list of selected libraries sorted by topic is on Arduino playground.

A good way to discover Arduino libraries on GitHub is the arduino-library topic: https://github.com/topics/arduino-library. It only contains repositories where the owner has bothered to add the topic but that's somewhat an indicator of how actively maintained the project is.

You can search the PlatformIO Library Database. It covers libraries for many architectures and platforms, but if you add framework:arduino to the start of your search it narrows it down to just Arduino libraries.
From there you can go to the homepage or repository for a library you want.
It doesn't have all libraries, only the ones that have been set up for PlatformIO support, but that is quite a lot of libraries now.


text:
Action while button is pressed
My issue is that I can't rotate the motors continuously. If I press any button, motor.step will be executed and then it stops, even though I didn't release the button.
This is my project so far.
Code:
#include <AFMotor.h>

//define steppers
AF_Stepper motor1(48, 1);
AF_Stepper motor2(48, 2);

char data;

void setup()
{

  motor1.setSpeed(200);  // 10 rpm
  motor2.setSpeed(200);  // 10 rpm
  Serial.begin(9600);
}

void loop()
{
  Serial.println(data);
  if (Serial.available())
  {
    data = Serial.read();
    if (data == 'A')
    {
      motor1.step(200, FORWARD, DOUBLE);
    }
    if (data == 'B')
    {
      motor1.step(200, BACKWARD, DOUBLE);
    }
    if (data == 'C')
    {
      motor2.step(200, FORWARD, SINGLE);
    }
    if (data == 'D')
    {
      motor2.step(200, BACKWARD, SINGLE);
    }
    if (data == 'E')
    {
    delay(50);
    }
  }
}

App Inventor blocks:

This statement: data = Serial.read(); consumes the data sent over the serial port, so to get continual movement, you will have to constantly feed in A or B, etc. from whatever is generating that data.
Alternately, you could define a 2nd set of single-character commands to accompany the start-rotation parts so that send one command to turn on the motor, and a different command to turn off the motor. You would need to add a variable to hold the current state (started or stopped) of each motor, and turn on or off those states depending on what commands come in from the user.
(untested code)
#include <AFMotor.h>

//define steppers
AF_Stepper motor1(48, 1);
AF_Stepper motor2(48, 2);

char data;
int8_t motor1state=0;  // 0=> Stopped, -1=>Reverse, 1=>Forward
int8_t motor2state=0;

void setup()
{
  motor1.setSpeed(200);  // 10 rpm
  motor2.setSpeed(200);  // 10 rpm
  Serial.begin(9600);
}

void loop()
{
  Serial.println(data);
  if (Serial.available())
  {
    data = Serial.read();
    if (data == 'A')
    {
      motor1state = 1;
    }
    if (data == 'B')
    {
      motor1state = -1;
    }
    if (data == 'C')
    {
      motor2state = 1;
    }
    if (data == 'D')
    {
      motor2state = -1;
    }
    if (data == 'F')
    {
      motor1state = 0;
    }
    if (data == 'G')
    {
      motor2state = 0;
    }
    if (data == 'E')
    {
    delay(50);
    }
  }

  if (motor1state>0)
  {
    // Step forward
    motor1.step(200, FORWARD, DOUBLE);
  }
  else if (motor1state<0)
  {
    // Step backward
    motor1.step(200, BACKWARD, DOUBLE);
  }
  else
  {
    // Do nothing
  }

  if (motor2state>0)
  {
    // Step forward
    motor2.step(200, FORWARD, SINGLE);
  }
  else if (motor2state<0)
  {
    // Step backward
    motor2.step(200, BACKWARD, SINGLE);
  }
  else
  {
    // Do nothing
  }
}

Thanks for you reply.
Now, if I press any button, the steppers won't stop rotating until I press any other button and then again, they won't stop. I'll somehow tweak this and maybe make a use of it. @jose

That's the point.

I just rebuilt the mobile app for the 'G' and 'F' cases, now everything's fine. Thank you, you're great! @jose

Everything's working correctly, but I am getting broken pipe error(516) messege randomly while I'am controlling the steppers? @jose

What does the other end look like? You added a bluetooth tag -- are you sending from an Android app? An error like that would not indicate a problem with the Arduino code, but with the bluetooth module or the Android side.

I'm sending from an android app. Bluetooth module was working fine til now. If you got time, you could send me a DM on twitter, as I just followed you, and I would be able to provide more specific information with screenshots included. @jose

Serial isn't a keyboard. When you send 'A' you send 'A'. Whatever that source is - if you send a single A you send a single A, and you receive a single A.
You will have to come up with some other protocol and write some special software on your computer that monitors the keys directly, and sends something along the lines of "I Pressed A" and "I Released A".