text:
Adafruit Flora V2 use onboard and external NeoPixels
I am working on wearable project using an Adafruit Flora V2, and for this project I need to use the onboard NeoPixel. I also need to use Neopixels that are attached to the D6 pin (is it a pin?). I have a line at the beginning of my program that says #define PIN 6. I found that I can use the onboard NeoPixel by changing this to #define PIN 8. Is there a way to use the onboard NeoPixel and the ones attached to D6. I already have everything wired up, and the rest of my program is written, I just need to use both pins. Thanks for any possible help.

using Flora v2?

@ARK Yes, edited

Do you have external Neopixels attached to D6. Because,
Adafruit Flora v2 has only one on-board Neopixel and that is internally attached to pin 8?

Yes, my  external NeoPixels are attached to D6.

The #define is just letting you use a nice name for the numeric value of the pin.  If you want to use two different pins, you use two different names.
So you might define them at the beginning something like:
#define BOARDLED 8
#define STRIPLED 6

Then you create a NeoPixel object that uses that pin.  In your case, you'll do this twice.
Adafruit_NeoPixel flora_led = Adafruit_NeoPixel(60, BOARDLED, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel strip = Adafruit_NeoPixel(60, STRIPLED, NEO_GRB + NEO_KHZ800);

And then you call the one you want to set/modify/show/etc.
strip.show();
flora_led.show();

Ok, I'll try that tomorrow. I don't have my Flora right now, but I will then. Thanks.

+1 Note that it's covered in AdaFruit's Überguide (https://learn.adafruit.com/adafruit-neopixel-uberguide/arduino-library) FAQ (second question).


text:
No response from device when trying to communicate with it via RS-232
I have an Arduino Uno with an RS-232 shield, and a servo drive that communicates via CAN or RS-232. I'm trying to communicate with this drive using an RS-232 cable, but I'm getting no response. I'm using the SoftwareSerial library on the Arduino to use digital pins 3 and 2 as rx and tx. Only pins 2 (RxD), 3 (TxD), and 5 (GND) of RS-232 are used to communicate with the drive. 19,200 is the default baud rate for the drive. The drive is powered with a dedicated power supply. The drive is supposed to echo every character received back to the sender.
I've had success using a simple Java program to communicate with the drive using the same kind of cable (although with a USB-to-serial converter). The drive echos all characters back, and the motor responds to the commands sent to the drive. The cable used has a female DB9 connector on one end (to communicate with the desktop) and a custom 3 pin connector on the other (to communicate with the drive).
I've also had success with the same Java program communicating with the Arduino (also with the converter). This cable has a female DB9 connector on one end (to communicate with the desktop) and a male DB9 connector on the other (to communicate with the Arduino).
But I've had no success exchanging data between the Arduino and the drive. There is no response back from the drive nor does the motor respond to any commands. The cable used for this has a male DB9 connector on one end (to communicate with the Arduino) and a custom 3 pin connector on the other (to communicate with the drive).
Each cable has been tested with a voltmeter to confirm that pins on one end are connected to the correct pins on the other end.
I'm at a loss here. Is there something I'm missing?
For your consideration, here is the Arduino code. It is the same whether it is connected to the desktop or the drive.
#include <SoftwareSerial.h>
#include <SPI.h>

const int rx = 3;               // software serial receive pin
const int tx = 2;               // software serial transmit pin
const int baudRate = 19200;     // 19,200 bits per second for read and write serial functions

SoftwareSerial serial(rx, tx);

/*
 * Initial, one-time setup
 */
void setup()
{
    Serial.begin(baudRate);     // open hardware serial communications
    serial.begin(baudRate);     // open software serial communications

    serial.println("MO=1;");      // start motor
    serial.println("JV=30000;");  // set velocity to 30,000 counts/second
    serial.println("BG;");        // begin movement
}

/*
 * Executes every tick
 */
void loop()
{
    if (serial.available())
    {
        Serial.write(serial.read());
    }

    if (Serial.available())
    {
        serial.write(Serial.read());
    }
}

Also, here is the Java code.
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class TwoWaySerialComm
{
    public TwoWaySerialComm()
    {
        super();
    }

    void connect(String portName) throws Exception
    {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if (portIdentifier.isCurrentlyOwned())
        {
            System.out.println("Error: Port is currently in use");
        }
        else
        {
            CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);

            if (commPort instanceof SerialPort)
            {
                SerialPort serialPort = (SerialPort)commPort;
                serialPort.setSerialPortParams(19200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

                InputStream in = serialPort.getInputStream();
                OutputStream out = serialPort.getOutputStream();

                (new Thread(new SerialReader(in))).start();
                (new Thread(new SerialWriter(out))).start();

            }
            else
            {
                System.out.println("Error: Only serial ports are handled by this example.");
            }
        }
    }

    /** */
    public static class SerialReader implements Runnable
    {
        InputStream in;

        public SerialReader(InputStream in)
        {
            this.in = in;
        }

        public void run()
        {
            byte[] buffer = new byte[1024];
            int len = -1;
            try
            {
                while ((len = this.in.read(buffer)) > -1)
                {
                    System.out.print(new String(buffer, 0, len));
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    /** */
    public static class SerialWriter implements Runnable
    {
        OutputStream out;

        public SerialWriter(OutputStream out)
        {
            this.out = out;
        }

        public void run()
        {
            try
            {
                int c = 0;
                while ((c = System.in.read()) > -1)
                {
                    //System.out.print(c);
                    this.out.write(c);
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args)
    {
        try
        {
            (new TwoWaySerialComm()).connect("COM4");  // COM4 is port of USB-to-serial converter
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

I've found the issue. The serial cable I was using was too long, introducing resistance to the signal. That's it!

source: Stack Exchange

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

sort: votes


text:
Arduino timer to turn a serve at a certain time
i am working on a project for my school tech class. Our goal is to make a vehicle that will travel along a cable and drop an egg to a target while going down the cable. i am using an arduino to to open a trap door with a servo after a certain amount of time that is set by two push buttons, and a third push button will control when the timer starts.
Here is my circuit

Here is the code:
#include <Servo.h>
#include <LiquidCrystal.h>

int b = 0;
int up = 0;
int down = 0;
int val = 100;

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

Servo myservo;

int pos = 0;

void setup()
{
  pinMode(b, INPUT);
  pinMode(up, INPUT);
  pinMode(down, INPUT);
  lcd.begin(16, 2);
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()
{
  digitalRead(down);
  digitalRead(up);
  digitalRead(b);
  lcd.setCursor(0, 0);
  lcd.print("milli seconds:");

  while (b == HIGH)
  {
    digitalRead(down);
    digitalRead(up);
    digitalRead(b);
    lcd.setCursor(0, 1);
    lcd.print(val);
    myservo.write(0);
    if (up == HIGH, down == LOW)
    {
      val + 1;
    }
    if (down == HIGH, up == LOW )
    {
      val - 1;
    }

    delay(val);
    myservo.write(100);
    delay(1000);
  }
}

you did not ask any questions ... you also did not say if anything is working incorrectly

The (pull-down) resistor on the top right button in on the wrong leg of the button.

in setup you are calling
pinMode(b, INPUT);
pinMode(up, INPUT);
pinMode(down, INPUT);

but b, up and down all equal 0 so this is what you are doing is :
pinMode(0, INPUT)
pinMode(0, INPUT)
pinMode(0, INPUT)

This doesn't do what you want at all, these need to be assigned to pins. All you are doing is repeatedly setting arduino digital pin 0 to INPUT 3 times.
secondly
while(b == HIGH)

will never fire since b is 0 and is never set to anything else. so it will never == HIGH
Finally,
digitalRead(down);

doesn't do anything useful; what it does is read from pin down which is set to 0, and then drops the return value on the floor
also, this,
if (up == HIGH, down == LOW)

is just very wrong, sholud be
if (up == HIGH && down == LOW)

anyway based on you scematic, fixing this code:
#include <Servo.h>
#include <LiquidCrystal.h>

const int B = 7;
const int UP = 8;
const int DOWN = 9;
int val = 100;

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

Servo myservo;

int pos = 0;

void setup()
{
  pinMode(B, INPUT);
  pinMode(UP, INPUT);
  pinMode(DOWN, INPUT);
  lcd.begin(16, 2);
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  lcd.setCursor(0, 0);
  lcd.print("milli seconds:");
}

void loop()
{
  // todo: debounce the switches
  int up = digitalRead(UP);
  int down = digitalRead(DOWN);
  int b = digitalRead(B);

  if (up == HIGH && down == LOW)
  {
     val += 1  // todo: handle overflow
  }

  if (down == HIGH && up == LOW )
  {
     val -= 1
  }

  lcd.setCursor(0, 1);
  lcd.print(val);

  if(b == HIGH)
  {
    myservo.write(0);
    delay(val);
    myservo.write(100);
    delay(val);
  }

}

this will do what the origonal code was trying to do, more or less, but the
proper way to do this would be (in psuedo-code):
// Setup pins etc.
// Setup(): pinMode(...) ... etc.
// Loop():
//   debounce buttons
//   handle up/down
//   record milliseconds when button is pressed
//   see how much time has passed
//   trigger servo when timer has passed

thanks for your response but it didn't work. the servo would just move randomly and the timer didn't work it just increased and then reset and increased again.

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


text:
Rotary Encoder on LoLin NodeMcu increases value when rotating right/left
I have a test program running on my LoLin NodeMcu board, with a Rotary Encoder connected.
I use Task.h and RotaryEncoderTask.h from this library: https://github.com/Makuna/Task (though my issue is the same when I use example code from here: https://tkkrlab.nl/wiki/Arduino_KY-040_Rotary_encoder_module
Link to RotaryEncoderTask.h: https://github.com/Makuna/Task/blob/master/examples/RotaryEncoder/RotaryEncoderTask.h
The problem
When I turn the knob right and left a bit quickly, multiple successive times, the current value of the rotary encoder increases, rather than staying at the same value.
I've read something about interrupts, and I believe the issue is there somewhere, but I am not able to comprehend it enough to set it into practice.
Here is the code I am running:

 /*
 * Pin mappings on LoLin:
 *
 * static const uint8_t D0   = 16;
 * static const uint8_t D1   = 5;
 * static const uint8_t D2   = 4;
 * static const uint8_t D3   = 0;
 * static const uint8_t D4   = 2;
 * static const uint8_t D5   = 14;
 * static const uint8_t D6   = 12;
 * static const uint8_t D7   = 13;
 * static const uint8_t D8   = 15;
 * static const uint8_t D9   = 3;
 * static const uint8_t D10  = 1;
*/
// RotaryEncoder
// This demonstrates the use of the custom Task object feature of Task library
// It will instance one custom RotaryEncoderTask to monitor three pins that a
// rotary encoder is connected to and make call backs when they change state;
// the press button will have debouce and auto repeat support;
// the rotary will tell direction and keep track of "clicks" rotated
// This requires a standard rotary encoder be attached to the defined pins,
//
// Usefull information will be sent to the serial monitor
//
// make sure that you connect your rotary encoder correctly, include gnd and Vcc (+)

#include <Arduino.h>

// nothing special about these pins, just make sure they don't collide with
// other active features
#define ClockPin 5  // labeled either as CLK or as A
#define DataPin 4   // labeled either as DT or as B
#define ButtonPin 0 // labeled as SW

// include libraries
#include <Task.h>

// include sub files
#include "RotaryEncoderTask.h" // this implements the rotary encoder task

TaskManager taskManager;

// foreward delcare functions passed to task constructors now required
void HandleButtonChanged(EncoderButtonState state);
void HandleRotationChanged(int8_t rotationDelta);

RotaryEncoderTask RotaryTask(HandleRotationChanged,
    HandleButtonChanged,
    ClockPin,
    DataPin,
    ButtonPin);

void setup()
{
    Serial.begin(57600);
    while (!Serial); // wait for serial monitor to connect

    taskManager.StartTask(&RotaryTask);

    Serial.println("Running...");
}

void loop()
{
    taskManager.Loop();
}

void HandleButtonChanged(EncoderButtonState state)
{
    if (state == EncoderButtonState_Pressed)
    {
        Serial.println("Pressed - ");
    }
    else if (state == EncoderButtonState_Released)
    {
        Serial.println("Released - ");
    }
    else
    {
        Serial.println("Auto-repeat - ");
    }
}

void HandleRotationChanged(int8_t rotationDelta)
{
    if (rotationDelta > 0)
    {
        Serial.print("clockwise = ");
    }
    else
    {
        Serial.print("counter-clockwise = ");
    }

    Serial.println(RotaryTask.RotationValue());
}

Here is the result, where you see the current value increasing:
counter-clockwise = -1
counter-clockwise = -2
counter-clockwise = -3
counter-clockwise = -4
counter-clockwise = -5
counter-clockwise = -6
counter-clockwise = -7
counter-clockwise = -8
counter-clockwise = -9
clockwise = -8
clockwise = -7
clockwise = -6
clockwise = -5
clockwise = -4
clockwise = -3
clockwise = -2
clockwise = -1
clockwise = 0
counter-clockwise = -1
counter-clockwise = -2
counter-clockwise = -3
counter-clockwise = -4
counter-clockwise = -5
counter-clockwise = -6
counter-clockwise = -7
counter-clockwise = -8
counter-clockwise = -9
counter-clockwise = -10
counter-clockwise = -11
clockwise = -10
clockwise = -9
clockwise = -8
clockwise = -7
clockwise = -6
counter-clockwise = -7
counter-clockwise = -8
counter-clockwise = -9
counter-clockwise = -10
clockwise = -9
clockwise = -8
clockwise = -7
counter-clockwise = -8
clockwise = -7
clockwise = -6
clockwise = -5
counter-clockwise = -6
counter-clockwise = -7
counter-clockwise = -8
counter-clockwise = -9
clockwise = -8
clockwise = -7
counter-clockwise = -8
clockwise = -7
counter-clockwise = -8
counter-clockwise = -9
counter-clockwise = -10
counter-clockwise = -11
clockwise = -10
counter-clockwise = -11
clockwise = -10
counter-clockwise = -11
clockwise = -10
counter-clockwise = -11
counter-clockwise = -12
counter-clockwise = -13
counter-clockwise = -14
counter-clockwise = -15
counter-clockwise = -16
counter-clockwise = -17
counter-clockwise = -18
clockwise = -17
clockwise = -16
counter-clockwise = -17
counter-clockwise = -18
counter-clockwise = -19
counter-clockwise = -20
counter-clockwise = -21
counter-clockwise = -22
counter-clockwise = -23
counter-clockwise = -24
counter-clockwise = -25
clockwise = -24
clockwise = -23
counter-clockwise = -24
counter-clockwise = -25
clockwise = -24
counter-clockwise = -25
counter-clockwise = -26
clockwise = -25
counter-clockwise = -26
clockwise = -25
counter-clockwise = -26
counter-clockwise = -27
counter-clockwise = -28
counter-clockwise = -29
clockwise = -28
counter-clockwise = -29
counter-clockwise = -30
counter-clockwise = -31
counter-clockwise = -32
clockwise = -31
clockwise = -30
counter-clockwise = -31
counter-clockwise = -32
counter-clockwise = -33
counter-clockwise = -34
clockwise = -33
counter-clockwise = -34
counter-clockwise = -35
counter-clockwise = -36
counter-clockwise = -37
counter-clockwise = -38
clockwise = -37
clockwise = -36
clockwise = -35
counter-clockwise = -36
clockwise = -35
counter-clockwise = -36
counter-clockwise = -37
clockwise = -36
clockwise = -35
clockwise = -34
clockwise = -33
clockwise = -32
counter-clockwise = -33
counter-clockwise = -34
clockwise = -33

I guess that you should not use serial print in the callbacks. Especially if they are called by the ISR.

Okay? Why and what can I use instead? Thanks :-)

Move the print from the callbacks to the loop function. Print periodically or on value change.

are your sure the library uses interrupts or pin change interrupts for the encoder pins? because the behavior you explained is the expected if checking encoder pins at regular intervals rather than using pin change interrupts.

I don't know enough about interrupts to answer, really. The RotaryEncoderTask.h can be found here: https://github.com/Makuna/Task/blob/master/examples/RotaryEncoder/RotaryEncoderTask.h

From that code '
Task(MsToTaskTime(5)), // check every five millisecond, 1-10 ms should be ok' so it checks every 5ms, I think there is a chance for it to mis one.

Write some code where you print the encoder value in the loop. And in your interrupts you only change this value. Keep the interrupt as short as possible, you don't have to print there as your loop will already do so.

Also, check the datasheet of this unit, I believe it has two pins. When both are open or both closed, you know the direction when the next state is one open and one closed.

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

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


text:
Wifi stopped connecting (Wemos D1 Mini)
I am stumped.  I have a few Wemos D1 Mini boards that were working on the local WiFi yesterday, yet today none of them will connect.  More puzzling is that I can flash Tasmota on them and they all connect to the WiFi, but none with this code that was working yesterday.  Any tips would be appreciated.

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(wifi_ssid);

  //Connect to WiFi network so we can reach the MQTT broker and publish messages to topics.
  WiFi.mode(WIFI_STA);
  WiFi.begin(wifi_ssid, wifi_password);

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

  Serial.println("");
  Serial.print(F("WiFi connected, "));
  Serial.print(F("IP address: "));
  Serial.println(WiFi.localIP());
}

did you update the esp8266 boards package?

Thanks for the response.  No updates- I just turned on my PC to continue on my project from the previous day, and none of the Wemos devices will connect to the WiFi.  But I can flash them with Tasmota and they connect to WiFi, so it's not a hardware issue.

I think it problem with your wifi master or with your slaves. But if few slaves can't connect to master wifi it can't be problem with your slaves. That restart your computer.
It can be problem with avrdude or Arduino IDE.

and what version of the arduino esp8266 package you use? does it use the same SDK version as the Tasmota firmware?

It looks like Version 2.2.2 of the WiFiesp library.  But I've changed nothing.  The sketch flashed and worked yesterday, but not today.

2.2.2 is very old. install 2.5.2

I went to a PC that has never seen Arduino- installed the latest IDE, the latest esp8266 boards and the latest esp8266WiFi library.  Same result.  Itis starting to look like a Router problem, but why are esp nodes compiled earlier still connecting with no problem?  Why can Tasmota connect now with no problem?

Fixed.
My router is ancient and does not support WPA.  As of ESP8266WiFi library Version 2.5.0, WPA is is the preferred mode.  The solution is to get a better router, or add WiFi.enableInsecureWEP(); before calling WiFi.begin().
WiFi.enableInsecureWEP();
WiFi.begin(wifi_ssid, wifi_password);

Solved.  (sort of).  This is a working workaround.
I have determined that if I use ESP8266WiFi library Version 2.5.0 or later, all I get from WiFi.status() is WL_NO_SSID_AVAIL.
By reverting to ESP8266WiFi library Version 2.4.2, I can get a connection with the same sketch.
(Juraj's comments pushed me in the direction of trying older library versions.)


text:
Exception 29 ESP12E Arduino
I am getting exception 29 every time I make request to HTTP using GET function. I am requesting HTTP every 20-30ms but using millis I am only reading request at 100ms in order to avoid any overflow or incomplete close connection, but still I am getting an exception after reading some 100 request.
What should I do now?
Here is my code and my Exception Decoder result as well

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

#define RED_LED     12

WiFiServer server(80);

const char* ssid = "Led_Downlight1";
char GetString[100];
unsigned int long RedValue;
unsigned long previousMillis = 0;
const long interval = 100;

void setup()
{

  Serial.begin(115200); //Start communication between the ESP8266-12E and the monitor window
  Serial.println();
  Serial.print("Configuring access point...");

  WiFi.mode(WIFI_AP);
  WiFi.disconnect();
  delay(100);
  WiFi.softAP(ssid);
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.print("SoftAP IP: ");
  Serial.println(WiFi.softAPIP());

  server.begin();
  Serial.println("Server started");
}

void loop()
{

  WiFiClient client = server.available();
  if (!client)
  {
    return;
  }

  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= interval)
  {

  Serial.println("Somebody has connected :)");

  previousMillis = currentMillis;
  String incoming = client.readStringUntil('\r');
  Serial.println(incoming);
  client.flush();
  incoming.toCharArray(GetString, 100);

  char *get = strtok(GetString, " ");
  char *request = strtok(NULL, " ");
  char *rtype = strtok(NULL, " ");

  if (request != NULL)
  {
    char *part = strtok(request, "/");
    bool seenSTA = false;
    bool seenRGBW = false;

    while (part)
    {
      if (!strcmp(part, "RGBW"))
      {
        seenRGBW = true;
      }

      else if (seenRGBW)
      {
        if (!strncmp(part, "R=", 2))
        {
          RedValue  = atoi(part + 2);
          analogWrite(RED_LED, RedValue);
          Serial.print("\n");
          Serial.print("Red:");
          Serial.print(RedValue);

          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println(""); //  do not forget this one
          client.println("<!DOCTYPE HTML>");
          client.println("");
          client.println("Red value: ");
          client.println(RedValue);
          client.println("

");
          client.println("");

          Serial.println("Client disonnected");
        }
      }
      part = strtok(NULL, "/");
    }
  }
 }
}

You have raised this same question as an issue with the authors of the ESP8266 core. If they can't answer it what hope do we have?

I hope somebody can come up with the solution

I get exception 29 when trying to do http.GET, but only when I'm using code that has another large object in memory. Looks like we're running out of memory to do the http.GET(). Now I'm looking for resources to look into that more deeply!


text:
Char* and string conversion from an ESP8266 web server
I have the following Arduino code for configuring a wifi connection through a simple webpage:
I declare char* ssid;. Later I read a value from a SPIFFS config file where q_ssid is declared as a string and successfully populated from the file:
strncpy(ssid, q_ssid.c_str(), 10);

In the line above, I am limiting it to exactly 10 as that is the length of my wifi AP name that this connects to. If I change the initial char* to char ssid[10];, all works well, but SSIDs can have varying names, and if I do not use 10 chars, then the trailing spaces prevent connection in the statement WiFi.begin(ssid, password);.
On the web client handler that reads in values from the user, I use this:
String q_ssid = server.arg("ssid");
strncpy(ssid, q_ssid.c_str(), 10 );

How can I dynamically assign the size of char* ssid; so that it can be used with the correct number of characters for the AP name that the user has stored from the webpage?
Any help is greatly appreciated.
Thanks.

What you need to do is creating a fixed string, this can be done in two ways:
static:
char ssid[100];

Where 100 is the maximum length ever possible. Note that this will always use up 100 bytes, even if less are used (e.g. your string length is 5.
dynamic:
char* p_ssid = malloc(100);

This way a pointer is created to a dynamically created string that can hold 100 characters. Disadvantage is that using malloc in a microcontroller can cause empty memory 'holes' when freeing/mallocing a lot.
With either way you can than use a normal strncpy or strcpy (in first case use &ssid to get a pointer to the ssid).
Also don't forget to add 1 to the length because of the trailing \0 to denote the string is ended.
Thus for storing 10 characters, you need an 11 char sized array.

Thank you for your response. I did do this size 10 to prove that this worked but only copied in 10 characters and not n+1. I will up it to 32 which is the size that I am thinking for the maximum. Do I add the terminating null character at the end after copying in the string characters?

if you do a strcpy I think it will automatically copy the \0

With strncpy it depends if it fits (if there are 10 characters to copy in a 10 byte buffer, than the \0 will not fit), so you have to make it one bigger

strncpy() copies up to the maximum specified. If the number of characters, including trailing zero end of string character, is less than or equal to maximum then the end of string character will be copied as well. However if the string being copied is longer than the maximum specified then there will not be a zero character terminator. When sizing the string buffer you must specify the number of characters you want plus one to include the end of string character. char myS[MAX_COUNT + 1]; and then strncpy (myS, aString, MAX_COUNT); followed by myS[MAX_COUNT] = 0; ensures end of string.


text:
Input 4-digit number using 4*4 keypad and show in serial monitor
#include <Keypad.h>

int myNum[4];

const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad 8,7,6,5
byte colPins[COLS] = {9, 8, 7, 6}; //connect to the column pinouts of the keypad 4,3,2,1
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );

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

void loop() {
  Serial.println("Enter four-digit num -");  // request for input
  for (int i = 0; i < 4;){
    if(keypad.getKey()!= NO_KEY) {
      myNum[i] = keypad.getKey();
      i = i+1;
    }
  }
  Serial.print("Entered number is = ");
  Serial.print(myNum[0]);
  Serial.print(myNum[1]);
  Serial.print(myNum[2]);
  Serial.println(myNum[3]);
  delay(500);
}

I want that when I press a 4-digit number on the keypad it should be shown in the serial monitor. This code gives 0000 when I press any key on keypad.

keypad.getKey() is non-blocking as you can read here: it will return a value immediately, even if no key is pressed.  You have a for loop which will increment i each time, and you also increment it yourself. So what's happening is that your code is immediately making four readings, all of which are no-key-pressed so it doesn't store them, and then printing whatever happens to be in the myNum buffer.
Instead, you need to wait each time until a key is pressed, and only then move to the next digit. There are of course many ways you could do this.  I hope this is clear:
#include <Keypad.h>

int myNum[4];

const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad 8,7,6,5
byte colPins[COLS] = {9, 8, 7, 6}; //connect to the column pinouts of the keypad 4,3,2,1
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );

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

void loop() {
  Serial.println("Enter four-digit num -");  // request for input

  for (int i = 0; i < 4; ++i){
    while((myNum[i] = keypad.getKey())==NO_KEY) {
      delay(1); // Just wait for a key
    }
    // Wait for the key to be released
    while(keypad.getKey() != NO_KEY) {
      delay(1);
    }

  }

  Serial.print("Entered number is = ");
  Serial.print(myNum[0]);
  Serial.print(myNum[1]);
  Serial.print(myNum[2]);
  Serial.println(myNum[3]);
  delay(500);
}

You are welcome. If the answer helps you, please consider accepting it.

when i compile it there is a error code "Serial does not name a type" .

I assumed you had tested your original code, since you described how it didn't work. No?

@kasun That kind of error usually occurs when you try to execute a statement outside of any function. Did you omit a curly brace around setup() or loop()? Show the exact code that gives you the error!

thnks friend . thats { is bother  me

for (int i = 0; i < 4; ++i){
while((myNum[i] = keypad.getKey())!=NO_KEY) {
delay(1); // Just wait for a key
}
}  its not working properly. can u send me a full code for that

Put that in your code where you previously had the for() loop.

I did it but its not working properly. can u send me a whole code.

I've included the rest of the code above and fixed a bug (sorry).  I've also added some code to make sure the first key is released before reading the next key. If it still isn't working, please describe exactly how it behaves and how that is wrong. But it would be better if you tried to debug it yourself - that way you'll understand what it happening.

#include <Keypad.h>

char myNum[4];

const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad 8,7,6,5
byte colPins[COLS] = {9, 8, 7, 6}; //connect to the column pinouts of the keypad 4,3,2,1
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );

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

void loop() {
  Serial.println("Enter four-digit num -");  // request for input

  for (char i = 0; i < 4; ++i){
    while((myNum[i] = keypad.getKey())==NO_KEY) {
      delay(1); // Just wait for a key
    }
    // Wait for the key to be released
    while(keypad.getKey() != NO_KEY) {
      delay(1);
    }

  }

  Serial.print("Entered number is = ");
  Serial.print(myNum[0]);
  Serial.print(myNum[1]);
  Serial.print(myNum[2]);
  Serial.println(myNum[3]);
  delay(500);
}


text:
Problem with my 2 motor system
I am trying to operate two DC motors at once using a L293D chip. I have managed to control them however, one of the motors has a slight problem. Whenever I start the program (attached below), one of the motor (I tried switching them, it isn't a problem due to the motor itself) has a counterclockwise spin for a second before starting to spin clockwise as it is suppose to. When it is spinning counterclockwise, the other motor is not doing any movements.
Is something wrong in the code or in the circuit? (I've also attached a hyperlink to my circuit which I found online, as well as my code)
Thank you
#define E1 11  // Enable Pin for motor 1
#define E2 10  // Enable Pin for motor 2
#define I1 12  // Control pin 1 for motor 1
#define I2 13  // Control pin 2 for motor 1
#define I3 8   // Control pin 1 for motor 2
#define I4 9   // Control pin 2 for motor 2

void setup() {
  pinMode(E1, OUTPUT);
  pinMode(E2, OUTPUT);
  pinMode(I1, OUTPUT);
  pinMode(I2, OUTPUT);
  pinMode(I3, OUTPUT);
  pinMode(I4, OUTPUT);
}

void loop() {
  analogWrite(E1, 255); // Run at full speed
  analogWrite(E2, 255); // Run at full speed
  digitalWrite(I1, HIGH);
  digitalWrite(I2, LOW);
  digitalWrite(I3, HIGH);
  digitalWrite(I4, LOW);
  delay(4500);
  // change direction
  digitalWrite(E1, LOW);
  digitalWrite(E2, LOW);
  delay(2000000000000);
  analogWrite(E1, 255);  // Run at full speed
  analogWrite(E2, 255);  // Run at full speed
  digitalWrite(I1, LOW);
  digitalWrite(I2, HIGH);
  digitalWrite(I3, LOW);
  digitalWrite(I4, HIGH);
  delay(000);
}

http://hw.sudarmuthu.com/wp-content/uploads/sites/2/2013/06/basic-bot1.png

I'm having trouble compiling your code Max. It's failing on this line: delay(2000000000000);
The last line of code: delay(000); doesn't seem to be doing anything useful and can be removed.
I do not have a L293D IC to test the following code with so I need you to test it for me please.
#define E1 11  // Enable Pin for motor 1
#define E2 10  // Enable Pin for motor 2

#define I1 12  // Control pin 1 for motor 1
#define I2 7   // Control pin 2 for motor 1 (change pin 13 to pin 7)
#define I3 8   // Control pin 1 for motor 2
#define I4 9   // Control pin 2 for motor 2

void setup() {
  pinMode(E1, OUTPUT);
  pinMode(E2, OUTPUT);
  pinMode(I1, OUTPUT);
  pinMode(I2, OUTPUT);
  pinMode(I3, OUTPUT);
  pinMode(I4, OUTPUT);

  // Disable motors
  digitalWrite(E1, LOW);
  digitalWrite(E2, LOW);
}

void loop() {

    // Set direction first
    digitalWrite(I1, HIGH);
    digitalWrite(I2, LOW);
    digitalWrite(I3, HIGH);
    digitalWrite(I4, LOW);

    // Enable motors
    analogWrite(E1, 255);
    analogWrite(E2, 255);

    // Motors run for 4.5 seconds
    delay(4500);

    // change direction

    // Disable motors
    digitalWrite(E1, LOW);
    digitalWrite(E2, LOW);

    // Give the motors time to stop if required
    delay(500);

    // Change motor direction
    digitalWrite(I1, LOW);
    digitalWrite(I2, HIGH);
    digitalWrite(I3, LOW);
    digitalWrite(I4, HIGH);

    // Enable motors
    analogWrite(E1, 255);
    analogWrite(E2, 255);

    // Motors run for 4.5 seconds
    delay(4500);

    // Disable motors
    digitalWrite(E1, LOW);
    digitalWrite(E2, LOW);

    // Give the motors time to stop if required
    delay(500);
}

It works! I switch the cable from pin 13 to 7 and now there is no longer that problem! Thanks. Yeah the code is weird but it is because I edit the times (as in sometimes I do use the last line). Thank you! Do you know why putting it as pin 13 caused this problem?

#define I2 13  // Control pin 2 for motor 1

Pin 13 is the LED and is blinked by the bootloader. You will have to use a different pin for your motor.


text:
Digital Sound sensor
I am having trouble with my digital sound sensor.  My goal: Clap 2 times and a led goes on. So I wrote this code. I don't know if it is correct or not. This happens: If I clap, from the serial monitor I don't get one HIGH, but a few (I tried changing the sensitivity of the soundsensor, but it doesn't help), but in my code I have some conditions where only 1 HIGH at a time is allowed. Thus, I don't know if my code is incorrect, or my sensor isn't working well.  Can you guys help me please? This is my code:
int soundPin = 13;             // Digital soundPin
int ledPin = 7;
int claps = 0;                 // The amount of times I clapped
int readingState ;             // The first reading from the soundPin
int readingState2 ;            // The second reading from the soundPin
int soundDetectionTime ;       // The time after the first clap
int soundDetectionTime2 ;      // The time after the second clap
int timeBetweenSounds = 1000;  // The time between the sounds I want. There
                                  is an If-statement further on.

void setup(){
  pinMode(soundPin, INPUT);
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop(){
  readingState = digitalRead(soundPin);    // The first reading form the
                                              soundPin (digital pin)

  Serial.println(readingState);

  if (readingState == HIGH){               // If the reading from the
                                             soundPin is HIGH, then start
                                             timing. Also claps value
                                             increased by 1 and the
                                             second reading is happening.
    soundDetectionTime = millis();
    claps++ ;
    readingState2 = digitalRead(soundPin);

      if (readingState2 == HIGH){          // If the above statement is
                                              true, then this if-statement
                                              is executed. If the second
                                              reading is HIGH,
                                              soundDetectionTime two will
                                              start counting
    soundDetectionTime2 = millis();    // Also the claps get increased by 1,
                                          so now claps = 2.
        claps++;
   }
   }

   if ((soundDetectionTime - soundDetectionTime2) > timeBetweenSounds &&
claps==2){                            // If there is 1 second between the
                                         two readings and if I clapped
                                         twice, then LED is HIGH.
    digitalWrite(ledPin, HIGH);
   }
   }

UPDATE: I managed to get two HIGHs seperate from each other and the led is now on. So the problem must be the sensor giving me too much HIGHs if I clap once, like: 0,0,0,0,1,1,1,0,0. What do you guys think?

What is hooked up to the sound pin? Can you provide a schematic? link to the sensor?

This is the sensor: https://hobbyking.com/en_us/keyes-microphone-sound-detection-sensor-module-for-arduino.html?gclid=CjwKCAjwhLHaBRAGEiwAHCgG3rTULQSiOsXd9Uxke7d5vLY9ZFFI-MktrlDSSUPvsXlvcahoxTs2nBoCKK8QAvD_BwE&gclsrc=aw.ds&___store=en_us Also, the schematic is very easy. I connected the GND and the 5V. And the digital pin of the sound sensor to a digital pin on the arduino.

Here is a "stripped down version" of a sketch I used to replicate the Clap On, Clap Off lamp switch we had in the 1980's.  It works with the KY-038 sound sensor module you currently have. You will need to install the VirtualDelay Library.
The sound sensor module is very sensitive. A quarter turn of the potentiometer around the "sweet spot" makes a huge difference. Too sensitive, and the digital output is constantly high. If it's not sensitive enough, then you have to physically "tap" the microphone to get a high/low transition out of it.
Please note: This sketch uses delay() which is "blocking code" and it's use is usually not recommended.
#include "avdweb_VirtualDelay.h"
byte clapCounter = 0;
const byte soundSensorPin = 2;
const unsigned long loopDelay = 1;
const unsigned long clapCounterDelay = 400;
unsigned long clapCounterTimerDuration = 1000;
unsigned long previousMillis = 0;

void setup(){
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop(){

  // Timer object.
  static VirtualDelay clapCounterTimer;

  // Get the current time.
  unsigned long currentMillis = millis();

  // Check for a clapping sound (1 ms works good). If too much time
  // elapses here, you could miss the "beginning" of the clap.
  if(myTimer1(loopDelay, currentMillis) == 1){

    // Clap detected.
    if(digitalRead(soundSensorPin) == 1){

      clapCounter += 1;

      // When the first the clap is detected, start a timer
      // to reset the clap counter to 0 after 1 second.
      if(clapCounter == 1){
        clapCounterTimer.start(clapCounterTimerDuration);
      }

      // Delay execution of the loop. 400 ms works good.
      delay(clapCounterDelay);

      // If a second clap is detected, toggle the LED ON/OFF.
      if(clapCounter > 1){
        digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
      }

    }
  }

  // Reset the clap counter to 0 after 1 second. If
  // you don't do this, you could clap once, wait a
  // minute, then clap again and the LED will change state.
  if(clapCounterTimer.elapsed()){
    clapCounter = 0;
  }

}

// Clap loop timer.
byte myTimer1(unsigned long loopDelay, unsigned long currentMillis){
  if(currentMillis - previousMillis >= loopDelay){previousMillis += loopDelay;return 1;}
  else{return 0;}
}

EDIT: To answer your question regarding the multiple High to Low transitions from the module's digital output, you can use a DSO to look at the relationship between the analog and digital signals it produces.
In the following image, the digital signal (yellow trace) and the analog signal (blue trace) are superimposed over each other. The white dashed line (E), is set to 2.8 VDC which is approximately the analog output pin's voltage with ambient room noise. Once you clap in front of the microphone, this wave form is generated.

The entire clap lasts about 5.6 ms and the module gives you 18 High to Low transitions on it's digital output pin. When the analog voltage drops below a certain voltage, the digital output goes High. When the analog voltage goes above that voltage, the digital output goes Low.
The problem is, the sound of a person clapping generates a noisy signal and the sound sensor module does not know the difference between noise and the sound you want to trigger it.
Instead of using delay() like I did, you could increment a "clap counter"  to equal "1" on the first Low to High transition of the digital output pin. Next, start a non-blocking millis() timer that waits before you read the digital output pin again. If digital out is High after 400 ms, it's your second clap so change the LED state. A second millis() timer could reset the "clap counter" to 0 after 1 second.

Thank you so much man, I think it wil work now. I am going to try now

Your logic is flawed; you don't have any delay between readingState and readingState2 other than a serial.Print() which you shouldn't rely on for a delay.
You need to keep track of state in your loop. You need to capture the time of the first input, see it go low, then record the time of the second input. N.b. time between instructions is blindingly fast even on 'slow' proccessors.
something like:
// edit: just gonna refactor a bit
// edit: added debounce
unsigned long start, end, time;
int state = 0;
...
#define BOUNCE 10
int dbounce(unsigned long time, unsigned long start, unsigned long len)
{
    return (time - start) > len;
}
...
void loop()
{
  pin = digitalRead(soundPin);
  time = millis();
  switch(state)
  {
  case 0:
      if (pin == HIGH)
      {
        start = millis();
        state = 1;
      }
      break;
  case 1:
      if dbounce(time,start,BOUNCE)
          break; // one way to debounce
      if( pin == LOW)
          state = 2;
      break;
  case 2:
      if(pin == HIGH)
      {
         end = millis();
         state = 3;
      }
      break;
  case 3:
      if(dbounce(end,start,1000))
      {
         // do stuff
      }
      state = 4;
      break;
  case 4:
      if((pin == LOW) && dbounce(time,end,BOUNCE)) //another way to debounce
         state = 0; // start over
      break;
  }
}

So, should I do it with the pulseIn function? That way I can measure the time between HIGH and LOW. How do you recommend me doing it. I just started a week ago with Arduino, I am not very familiar with different coding techniques.

@jan pulse in measures how long the pin is high for, you might be able to pulseIn(pin, HIGH); start = millis(); pulsein(pin, HIGH); end = millis(); if(end-start) ...

@jan it just occured to me that time = pulseIn(pin, LOW); might do exactly what you want.

But the sound sensor still is a problem. Because it gives me a lot of HIGHs when I clap, not just one. Sometimes it gives: 0,0,1,0,1. The I have two HIGHs very fast with one clap

@jan I added debouncing to the code, and made it a little better; hope you understand how this works.


text:
L298N, HC-05 Simple Bluetooth remote car not running in Arduino
Arduino board type used in this session is Arduino Uno R3 DIP/SMD CH340
Below is the description of wiring and code in Arduino to assemble a Bluetooth RC car using android smartphone:

Tested the motor dc result both of wheel works (can spin forward and or backward). power direct from the battery.
Tested HC-05 bluetooth moduled. The phone can paired the bluetooth module.
Tested out1 out2 out3 and out4 on L298N using direct power from the battery the wheel spinning (forward and or backward).
The code for the Bluetooth rc simple car used below as described.

The car failed to move (forward, backward, turn left/right). how to make the motor dc and or the motor stepper works remotely. thank you

    #include
    SoftwareSerial mySerial(12, 13); // RX, TX
    #define m1 3
    #define m2 5
    #define m3 9
    #define m4 10
int data=0,kec=0;
boolean forward=true;

int fast[11]={0,80,100,120,140,160,180,200,220,240,255};

void setup()
{
  pinMode(m1,OUTPUT);
  pinMode(m2,OUTPUT);
  pinMode(m3,OUTPUT);
  pinMode(m4,OUTPUT);

  mySerial.begin(9600);
 }

void motorOut(unsigned char lpwm, unsigned char rpwm, boolean arrow){
   if(arrow==false){
      digitalWrite(m3,HIGH);
      digitalWrite(m1,LOW);
      analogWrite(m4,255-lpwm);
      analogWrite(m2,rpwm);
   }
   else{
     digitalWrite(m3,LOW);
     digitalWrite(m1,HIGH);
     analogWrite(m4,lpwm);
     analogWrite(m2,255-rpwm);
  }
}

void loop(){
  if(mySerial.available()>0){
    data=mySerial.read();
    if (data =='0') { kec=0;}
      else if (data =='1') { kec=1;}
        else if (data =='2') { kec=2;}
          else if (data =='3') { kec=3;}
            else if (data =='4') { kec=4;}
             else if (data =='5') { kec=5;}
              else if (data =='6') { kec=6;}
                else if (data =='7') { kec=7;}
                  else if (data =='8') { kec=8;}
                    else if (data =='9') { kec=9;}
                      else if (data =='q') {kec=10;}

  //S= Stop
 if (data == 'S')
 { motorOut(0,0,false); }

//F=Forward
if (data=='F')
{ motorOut(fast[kec],fast[kec],true); }

//I=turn right forward
if (data=='I')
{ motorOut(fast[kec],((fast[kec])/2),true);}

//G=turn left forward
if (data=='G')
{ motorOut(((fast[kec])/2),fast[kec],true); }

//R=turn right
if(data=='R')
{ motorOut(fast[kec],0,true); }

//L=turn left
if(data=='L')
{ motorOut(0,fast[kec],true); }

//B=back
if(data=='B')
{ motorOut(fast[kec],fast[kec],false); }

//H=turn left back
 if (data=='H')
   { motorOut(((fast[kec])/2),fast[kec],false); }

//turn right back
   if (data=='J')
    { motorOut(fast[kec],((fast[kec])/2),false); }
  }
}

you forgot to ask a question

what tests have you done?

Instead of writing many if-else if statements, use a simple switch(data){ case '0':

What data gets send to mySerial? Can you confirm, that the correct data is actually received? Maybe echo it back to the source. If this doesn't work, your serial connection doesn't work (maybe because the HC-05 isn't really connected). If it works, try to drive the motor through the driver, by connecting the corresponding pins to 5V. If this doesn't work, your driver connection is not correct. You should provide a schematic instead of photos.

nothing displayed data from serial monitor.
HC-05, icon indicator green in android phone (success conecting to the car).
L298N, the motor run after i give direct power to PIN 5 and Ground.
the battery 4 x 1.2 alkaline or 9v

sorry for my careless. finaly its works....wrong pin assign the main problem....should be IN1, IN2, IN4 and IN3 not IN1, IN2, IN3 and IN4. thank you for all hands for help before


text:
Why I'm getting this error: invalid conversion from 'const char*' to 'char' [-fpermissive]?
Why I'm getting this error?
invalid conversion from 'const char*' to 'char' [-fpermissive]
Here is my simple sketch:

const char data = "should";

//I have also tried:
//const char* data = "should";

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

void loop() {
  Serial.print("this " + data + " work");
}

No, it should not work this way. You are cofusing data types. char respresents a single character. So your first statement should be invalid. The second attempt looks reasonable but I'd use const char data[] instead. Now your string concatenation does not work at all because you are not using C++ Strings. Only those offer string concatenation with +.

the easy way in arduino:  Serial.print("this " + String(data) + " work");

const char data = "should";

In this case data is a single character, not a string. So it can store 's' but not "should".
Serial.print("this " + data + " work");

No, that will never work, even if you get your data types correct.  You do not concatenate strings like that. All you are doing is attempting to add the addresses of two string literals to the address of a string constant. If that were possible (the  compiler doesn't let  you) you'll get gibberish (or a crash) as it tries to print out whatever is at that address.
Instead break it down:
Serial.print("this ");
Serial.print(should);
Serial.print(" work");

You'll get gibberish as it tries to print out whatever is at that address. — no, you'll get compilation error. You can subtract pointers in C++, but not add.

@Ruslan Actually, in that specific instance you get a compilation error because the operands differ between a const char * for the variable and a const char[6] for the first literal. If you cast the literals as const char * you can subtract one and only one, otherwise you get differing arguments between the results of one subtraction (int) and the other string literal. The point I am making above though is that you do not concatenate strings by using +. Whether the syntax is "right" for something that is completely wrong anyway is neither here nor there.

You don't have to cast: the array will decay to a pointer before any arithmetic. But yes, the second subtraction would indeed cause an error because it'd try to subtract const char* from ptrdiff_t.

Ah yes, when subtracting it decays fine (as long as you only have one bit of arithmetic, otherwise you have to cast the result). When trying to (wrongly) add it doesn't decay, it just complains.

Not sure what your saying there... Did you get truncated?

Thought as much. Been there, done that.

There's no operator overloading there.

A char can only store one character.
and const char* data can store a pointer to a string.
You can copy it with strcpy:
const char* data = malloc(7);
if (data != 0)
{
    strcpy(data, "should");
}

This will create 7 bytes, which can store "should" (adding 1 byte extra for the \0 byte to denote the end of a string.
However, in your case you can create a const string like:
const char data[7]="should";

or
const char data[]="should";

Tere is no space allocated that fits the string. :(

Added also memory check

Even now your code won't compile. And anyway, no point in using dynamic memory just to store a static string.

@Ruslan edited (this time compiled)


text:
Water tank false trigger
I am trying to make a simple water overflow protection system for my home. I have created it using BC547 and NodeMCU (ESP8266). I have a simple circuit like this:

The problem here is I have 2 wires going into the tank. Which suppose to complete the circuit as soon as water touch both the wires. But the problem here is its by default complete the circuit without even touching, this is happening only in my rooftop water tank. I tried this circuit locally on my desk first and it is working fine. I feel the problem can be humidity inside the tank? Can this be a reason for false trigger?
Here is how I have my code.

    #define RELAY_1 D1
    #define TANK_CONNECTION D4
void setup() {
  Serial.begin(115200);
  delay(10);

  Serial.println("Started");
  secondsTick.attach(1, ISRwatchdog);

  //Set relay pins to outputs
  pinMode(RELAY_1, OUTPUT);
  pinMode(TANK_CONNECTION, INPUT);

  digitalWrite(RELAY_1, relay_on);
  delay(100);

}

void loop() {
  tankFull();
  delay(100);
}

void tankFull(){

  Serial.println(digitalRead(TANK_CONNECTION));
   if(!digitalRead(TANK_CONNECTION) && relay_on == 0){
      Serial.println(motorOnCount);
      motorOnCount++;
      motorOffCount = 0;
      if(motorOnCount >= 10){
        Serial.println("Motor Turn OFF");
        digitalWrite(RELAY_1, HIGH);
         if (client.connected()) {
            client.publish(motor_status, "off", true);
            client.publish(tank_full, "on", true);

          }
        motorOnCount=0;
        relay_on = 1;
      }
      delay(100);
   } else{
      motorOffCount++;
       if (client.connected()) {
          client.publish(tank_full, "off", true);
       }
      //Serial.println(motorOffCount);
      if(motorOffCount>=100){
        motorOffCount=0;
        motorOnCount = 0;

      }
   }
}

Obviously this is not the full code. I am just trying to share the pattern of its working for basic understanding of the setup I have.
Any one have idea about why its always shows circuit complete even without touching the wires. I have tried with 5v as well and 3.3v as well which are present on NodeMcu Board. But none of them worked properly.

try pinMode(TANK_CONNECTION, INPUT_PULLUP); since you need a pullup resistor with that circuit

OK. And value of resistor will also make a difference here?

With the INPUT_PULLUP you enable the internal pullup resistor of the MCU. Mostly this is something in the range of 10kOhm, but this is not critical here. The value of the resistor at the base of the transistor also shouldn't be critical. The transistor has only have a considerable less impedance when turned on, than the internal pullup resistor. 1kOhm seems ok. You can try smaller values, when it doesn't activate correctly after you actived the internal pullup resistor

Please try the INPUT_PULLUP. If that works, I will formulate a proper answer.

Sure I will try that in sometime and update you regarding this.

Water isn't as conductive as you might think or some conductive sediment way be bridging the connection, instead look into water level switches which don't have those issues.

@ratchetfreak I understand that. But the problem is, my both the wires are in AIR not in water yet. And yet its showing water tank full! So air looks conductive here :)

@user3201500 which is why I mentioned the conductive sediment

@ratchetfreak any suggestions for water level switch, I will be more happy if I can get some idea about how much water I have in my tank.

I'd suspect it won't be much EMI proof. And if you have long wires the INPUT_PULLUP might not be enough.

@KIIV yes they are long wires. And true, INPUT_PULLUP didn't work as well.

@chrisl any other suggestion? Because the one you gave is enough. :( No solution I can find around. But I have seen a thousand of alarms and other things work on same concept.

Sugestion is to move the transistor as close to the sensor as possible. That means 3wires (two for the power and one signal). Well, basically use something like arduino Water Sensor.

Certainly the issue is from EMI but not from the collector side as from the transistor base even the wires are shorter on that side as I understand from the comments.
It's a common mistake to let the transistor base floating, see here a different application but with the same cause and result, the transistor is turning on apparently with no reason. With the base floating the EMI current has no other path than through the transistor base where is amplified by beta ( 110 to 800 for BC547).
Put a 10Kohm resistor between the transistor base and emitter to  let a path for EMI currents to the ground. Try different values, smaller if you still have false triggering, higher if the sensor is not turning on the transistor.
Of course, use  INPUT_PULLUP but the internal resistor is to high 30 to 100 kohm, better use an external resistor arround 10k or lower form the transistor collector to 3V3 to ensure a good noise margin on the collector side to.

simulate this circuit – Schematic created using CircuitLab


text:
PIR motion sensor (HC-SR501) false results with NodeMCU
I have a PIR sensor which I use to detect the motion and turn ON and OFF the lights on the basis of it.
I have PIR connected with NodeMCU (ESP8266) based board. I find that sometimes it trigger false positive value. Even when there is no motion. As per my understanding I think any of the following reasons can be there:

I have NodeMCU close to it. So may be because NodeMCU heatness triggers it.
Some hot air blow near it. But I don't know. It trigger the false positive even in mid-night.
It can be trigger by mosquitoes.
I have my other electric wires going from near by.

I am considering these scenarios correct? If yes then how can I prevent from them?
I tried to put it in a box and make it tightly pack. but still its false trigger. I checked even with multiple sensors and have same problem.
Any suggestions to protect this? I also check people put capacitor to smooth it. And put some resistance on Vin.
My Vin of PIR is connected to 5v and OUTPUT pin to D2.
For reference I am having this code for checking.

#define SIGNAL_PIN D2

void setup()
{
  Serial.begin(115200);
  pinMode(SIGNAL_PIN, INPUT_PULLUP);
//  digitalWrite (SIGNAL_PIN, LOW);
}

void loop() {

    static uint32_t lastSeenHigh = millis();
    static bool pirState = false;
    Serial.println(digitalRead(SIGNAL_PIN));

    // If it's active then record that fact along with the time
    if (digitalRead(SIGNAL_PIN) == HIGH) {
        lastSeenHigh = millis();
        pirState = true;
    } else {
        if ((millis() - lastSeenHigh) > 10000) {
            pirState = false;
        }
    }

    if (pirState == true) {
        Serial.println("Pir Is active");
    }
//
    if (pirState == false) {
      Serial.println("PIR sensor inactive");
    }
    delay(1000);
}

Basic PIR sensor (HC-SR501) contain sensitivity adjustment that will adjust the sensitivity range. Here the link that will help you with adjustment PIR

i tried doing adjustments. And it didnt work the way i wanted it.

can you share your code and schematic?

Change INPUT_PULLUP to INPUT_PULLDOWN as you are looking for HIGH event.

LOL. Those sensors and boards are so cheap I built two motion sensors. Lights come on only when both agree there is movement in the room. I'm using Home Assistant to coordinate the automation, but maybe something ingenious could be done for them to communicate directly.

@azoe, Haha, I have been thinking about doing the same thing. That set-up works well, right?

I was also going through the same issue. But finally, the issue got resolved.
The issue is the PIR sensor that comes with ESP8266 can work with 3.3V as well as 5V.
By default, the wiring is connected to the 5V which may work fine for the Arduino device but not for ESP8266.
I just removed the red cable (power cable) from the connector and connected to the other side where you can see H. That side also there are 3 pins.
Remove the jumper completely and connect to the first PIN from top.
Just make sure you leave the GND and OUTPUT as it is, but only the RED wire will be connected to the first pin on the other side of the PIR sensor.

I glued some aluminum foil onto a piece of a cereal box and folded it around the PIR sensor. Works like a charm!

Nice Hack, is it reliable can you share a image how it looks like in the end ?

I had the same issue. PIRs have very sensitive circuitry and can be triggered by the WiFi signal from the ESP8266. The answer is to move them apart and with some decoupling of the power supply lines you should see much better performance. My PIR and ESP are now a couple of metres apart and I use shielded cable to connect them together.

I had the same issue. I tried various solutions on the net. Finally i solved my issue like this.

Supplied the PIR sensor 3.3 v (from the NodeMcu board) instead of 5v (my main PS is 5V)
Connected VCC (3.3v) cable to "HIGH PIN" of trigger pins instead of main (+) pin.
It's not generate false positive signals about 2 hours.

Actually, I'm applied that solution -> https://www.youtube.com/watch?v=2HbbQIqJHoE


text:
Arduino based IR remote control - Transmission issue
I created a circuit of a 25 key IR remote controller for my RuneAudio device. The device is a standalone ATmega328P-PU running at 3V (2 AAA batteries) with 8 MHz internal clock. The circuit has 5 rows and 5 columns and uses Arduino keypad library. The code is mostly a copy of Nick Gammon's code (http://www.gammon.com.au/forum/?id=11497&reply=4#reply4), with slight modification for my purpose.
Following is the circuit (R1=1K, R2=10K, R3=62 Ohm):

Following is the code I am using:
#include <Keypad.h>
#include <avr/sleep.h>
#include <avr/power.h>
#include <IRremote.h>

const byte ROWS = 5;
const byte COLS = 5;
byte keynum;

char keys[ROWS][COLS] =
{
  {'E', 'D', 'C', 'B', 'A'},
  {'J', 'I', 'H', 'G', 'F'},
  {'O', 'N', 'M', 'L', 'K'},
  {'T', 'S', 'R', 'Q', 'P'},
  {'Y', 'X', 'W', 'V', 'U'}
};

byte rowPins[ROWS] = {9, 10, 11, 12, 13}; // Keypad row pins
byte colPins[COLS] = {4, 5, 6, 7, 8};     // Keypad column pins

unsigned long IRCode[25] =  {0xB54A38C7, 0xB54A30CF, 0xB54AE191, 0xB54ADCDD, 0xB54AD6C3, 0xB54AE5ED, 0xB54A50AF, 0xB54A9867, 0xB54AB04F, 0xB54A48B7, 0xB54AD02F, 0xB54AFCF7, 0xB54AF56C, 0xB54AEFEE, 0xB54AEAA0, 0xB54A02FD, 0xB54B176F, 0xB54B100D, 0xB54B08F6, 0xB54B031D, 0xB54A42BD, 0xB54AC23D, 0xB54A1AE5, 0xB54A7887, 0xB54A827D};

// Number of items in an array
#define NUMITEMS(arg) ((unsigned int) (sizeof (arg) / sizeof (arg [0])))

// IR setup (NEC remote)
const byte IRledPin = 3;
const int NumBits = 32;

// Define
Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
IRsend irsend;

// turn off interrupts until we are ready
ISR (PCINT0_vect)
  {
  PCICR = 0;  // cancel pin change interrupts
  } // end of ISR (PCINT0_vect)

ISR (PCINT1_vect)
  {
  PCICR = 0;  // cancel pin change interrupts
  } // end of ISR (PCINT1_vect)

ISR (PCINT2_vect)
  {
  PCICR = 0;  // cancel pin change interrupts
  } // end of ISR (PCINT2_vect)

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

  // Pin change interrupt masks (See list on Nick Gammons original code)
  PCMSK0 |= bit (PCINT1);   // Pin 9
  PCMSK0 |= bit (PCINT2);   // Pin 10
  PCMSK0 |= bit (PCINT3);   // Pin 11
  PCMSK0 |= bit (PCINT4);   // Pin 12
  PCMSK0 |= bit (PCINT5);   // Pin 13
  Serial.begin(9600);
}

void reconfigurePins ()
{
Serial.print("1 Reconfig pins");
Serial.println("");
  byte i;
  for (i = 0; i < NUMITEMS (colPins); i++)
  {
    pinMode (colPins [i], OUTPUT);
    digitalWrite (colPins [i], HIGH);
  }

  for (i = 0; i < NUMITEMS (rowPins); i++)
    {
    pinMode (rowPins [i], INPUT_PULLUP);
    }   // end of for each row
Serial.print("2 DONE Reconfig pins");
Serial.println("");
  }  // end of reconfigurePins

void goToSleep ()
{
Serial.print("3 inside SLEEP");
Serial.println("");

  // Set up keypress detection
  byte i;
  for (i = 0; i < NUMITEMS (colPins); i++)
  {
    pinMode (colPins [i], OUTPUT);
    digitalWrite (colPins [i], LOW);
  }

  for (i = 0; i < NUMITEMS (rowPins); i++)
  {
    pinMode (rowPins [i], INPUT_PULLUP);
  }  // end of for each row

  // Check no pins pressed (otherwise wake on a key release)
  for (i = 0; i < NUMITEMS (rowPins); i++)
  {
    if (digitalRead (rowPins [i]) == LOW)
    {
  Serial.print("ROW LOW: ");
  Serial.print(rowPins [i]);
Serial.println("");
      reconfigurePins ();
      return;
    }
  }

  // Overcome any debounce delays built into the keypad library
  delay (10);

  // At this point, pressing a key should connect the high in the row to the
  // to the low in the column and trigger a pin change
Serial.print("4 Going to SLEEP");
Serial.println("");

  set_sleep_mode (SLEEP_MODE_PWR_DOWN);
  sleep_enable();

Serial.print("5 AWAKE");
Serial.println("");

  byte old_ADCSRA = ADCSRA;
  // Disable ADC to save power
  ADCSRA = 0;

  power_all_disable ();  // turn off various modules

  PCIFR  |= bit (PCIF0) | bit (PCIF1) | bit (PCIF2);   // clear any outstanding interrupts
  PCICR  |= bit (PCIE0) | bit (PCIE1) | bit (PCIE2);   // enable pin change interrupts

  // Turn off brown-out enable in software
  MCUCR = bit (BODS) | bit (BODSE);
  MCUCR = bit (BODS);
  sleep_cpu ();

  // Cancel sleep as a precaution
  sleep_disable();
  power_all_enable ();   // enable modules again
  ADCSRA = old_ADCSRA;   // re-enable ADC conversion

  // Put keypad pins back how they are expected to be
  reconfigurePins ();
Serial.print("6 Leaving SLEEP");
Serial.println("");

}

void loop ()
{

  byte key =  kpd.getKey();
  if (!key)
  {
Serial.print("CALLING SLEEP");
Serial.println("");

    // Sleep if no key is pressed
    goToSleep ();
    return;
 Serial.print("After RETURN");
Serial.println("");

  }

  // Subtract ASCII value of first key value to obtain HEX array argument
  keynum = key - 'A';
Serial.print("SENDING IR.....................................................................................");
Serial.println("");

  // sendNEC(unsigned long data, int nbits);
  irsend.sendNEC(IRCode[keynum], NumBits);
Serial.print(IRCode[keynum]);
Serial.println("");

}

The sketch compiles and uploads just fine. It detects key presses and sends out IR signals. But it misses around half of the key presses. I am testing on a breadboard using a single key - R1C5 (S5 in the schematic).
I must admit that despite spending a lot of time on ATmega328 datasheet and Nick's blogs on power saving, I am not able to fully understand the power saving features due to my not-so-mature skills and the complexity of overall project (Raspberry Pi based rune audio + TDA7439 based tone controller + ATmega based power switch for Pi + 2channel Audio amplifier + this IR remote).
I added a few serial prints to check what is happening. The serial outs seem to be out of sync and last message before sleep is "CALLING SLEEP" whereas I expected it to be "4 Going to SLEEP". And adding serial print mysteriously reduces the number of misses.
Following is the serial output, just after power on and a single key press:
EP
3 inside SLEEP
4 Going to SLEEP
5 AWAKE
1 Reconfig pins
2 DONE Reconfig pins
6 Leaving SLEEP
SENDING IR.....................................................................................
3041540295
CALLING SLEEP
3 inside SLEEP
ROW LOW: 9
1 Reconfig pins
2 DONE Reconfig

The following happens after multiple key presses:
CALLING SLEEP
3 inside SLEEP
ROW LOW: 9
1 Reconfig pins
2 DONE Reconfig pins
SENDING IR.....................................................................................
3041540295
CALLING SLEEP
3 inside SLEEP
ROW LOW: 9
1 Reconfig pins
2 DONE Reconfig pins
CALLING SLEEP
3 inside SLEEP
ROW LOW: 9
1 Reconfig pins
2 DONE Reconfig
CALLING SLEEP
3 inside SLEEP
4 Going to SLEEP
5 AWAKE
1 Reconfig pins
2 DONE Reconfig pins
6 Leaving SLEEP
CALLING SLEEP
3 inside SLEEP
ROW LOW: 9
1 Reconfig pins
2 DONE Reconfig
CALLING SLEEP
3 inside SLEEP
4 Going to SLEEP
5 AWAKE
1 Reconfig pins
2 DONE Reconfig pins
6 Leaving
CALLING SLEEP
3 inside SLEEP
4 Going to SLEEP
5 AWAKE
1 Reconfig pins
2 DONE Reconfig pins
6 Leaving
CALLING SLEEP
3 inside SLEEP
4 Going to SLEEP
5 AWAKE
1 Reconfig pins
2 DONE Reconfig pins
6 Leaving
CALLING SLEEP
3 inside SLEEP
4 Going to SLEEP
5 AWAKE
1 Reconfig pins
2 DONE Reconfig pins
6 Leaving
CALLING SLEEP
3 inside SLEEP
4 Going to SLEEP
5 AWAKE
1 Reconfig pins
2 DONE Reconfig pins
6 Leaving SLEEP
CALLING SLEEP
3 inside SLEEP
ROW LOW: 9
1 Reconfig pins
2 DONE Reconfig pins
SENDING IR.....................................................................................
3041540295
CALLING SLEEP
3 inside SLEEP
ROW LOW: 9
1 Reconfig pins
2 DONE Reconfig

It would be of great help if someone could show me the light here.

Ok. Replaced long serial print strings with single digits where these stand for:
1= 1 Reconfig pins
2= 2 DONE Reconfig pins
3= 3 inside SLEEP
4= ROW LOW=
5= 4 Going to SLEEP
6= 5 AWAKE
7= 6 Leaving SLEEP
8= CALLING SLEEP
.....= SENDING IR
I see where it is failing.  Now getting the following serial out:
6
1
2
7
8
3
49
1
2
8
3
49
1
2
8
3
49
1
2
8
3
49

So the program wakes on keypress (6), then reconfigures the pins (1,2), leaves the sleep function (7) enaters the main (8). Here byte key =  kpd.getKey() DOES NOT detect a keypress and calls sleep again (3). Sleep DOES detect a low row 9 (4-9).
After this it gets stuck in a loop of main and sleep functions till key press is over. For now the problem seems to be with kpd.getKey().

I added a few serial prints to check what is happening. The serial outs seem to be out of sync and last message before sleep is "CALLING SLEEP" whereas I expected it to be "4 Going to SLEEP".

Printing to Serial doesn't send data to your computer. It just adds that data to a TX buffer, and then an interrupt sends each character one byte at a time.
Your prints are happening, but aren't being sent from the queue before the MCU goes to sleep.
You should add
Serial.flush();

before actually going to sleep to ensure that all data from the TX buffer has been sent. That way your messages will actually be meaningful.
Also if you send more than 64 bytes of data through Serial in a short space of time it will block and wait for some data to be sent out of the TX buffer. The buffer is only 64 bytes in size, so if there is no room left it has to wait for the interrupt.  That waiting slows your entire sketch down and can affect the way the sketch operates.  A bit like quantum physics - the act of observing the operation of the sketch changes the operation of the sketch.


text:
9x servo on Arduino Nano?
I saw this project with multiple servos: In Servo We Trust! Let's control 135 servos with a single Arduino! I wanted to miniaturize this project.
BUT instead of triangles i will use SQUARES.
:EDIT: summing UP
For now project stops, not forever. I bought 9 servos on aliexpress and im waiting for them to be delivered. Also, im making a 3D project in AutoDesk Maya 2018, planning and will sbow you the results soon how im gonna make it work.
I was thinking about adding 1 more servo and hc sr06 distance sensor. I was thinking about the sensor will detect person, servos and mirrors will also follow the person. But idk if im gonna make it to the final project.

I bought arduino nano that will be powered from the battery
All servos will be powered with electricity from the wall 5V 5A.The servos wont be on heavy load so it will be enough i think.If any problem occurs I will use 10A.

ALSO SORRY for not editing this POST earlier.
I would like to thank everybody for giving me such a great advices, I will post my AutoDesk project soon.

Here are the specifications of the SG90 (from FEETECH (Fitec) FS90 9G Mini Servo with Accessories)

The FG90 is similar in specification to the SG90. From the website:

The FS90 is a 9 g analog servo from FEETECH (formerly known as Fitec) which is similar in form and function to the Towerpro SG90. The specifications state that this servo has a 120° operating angle for standard servo pulses between 900 µs and 2100 µs. As with most servos, the pulse range can be expanded to achieve an expanded operating angle, but the limits of which are not specified by FEETECH.

From this answer to Power supply circuit for powering SG90 servo. How to handle high current requirements?, lets assume each servo (best case) needs 250 mA, as you state that the load per servo is relatively low.
Let's say that the Nano requires 280 mA, see this answer to What is the maximum power consumption of the Arduino Nano 3.0?
Using a single 5V supply to power both servos and Arduino. The current rating needs to need at least:
I = (9 x 0.25) + 0.28
I = 2.53 A

Or power rated
P = I x V = 2.53 x 5
P = 12.65 W

You probably want more than that, so get a 5 V 5 A supply to be on the safe side. So, no, a battery will not suffice.

I wanted to make separetly power for nano and servos, but this way will work too.

I wanted to buy these: https://pl.aliexpress.com/store/product/4pcs-PKCELL-1-2V-4-5A-2100mAh-NiMh-Rechargeable-Batteries-Flat-Top-For-Soldering/918700_32822951027.html?spm=a2g17.search0104.3.44.7b6621e1Ks4oz8&ws_ab_test=searchweb0_0,searchweb201602_4_10152_10151_10065_10344_10068_10342_10343_10340_10341_10696_10084_10083_10618_10304_10307_10820_10821_10301_10843_10059_100031_10103_10624_10623_10622_10621_10620,searchweb201603_13,ppcSwitch_5&algo_expid=774f7647-2d15-445d-af5c-46e6fb9b3e5a-6&algo_pvid=774f7647-2d15-445d-af5c-46e6fb9b3e5a&priceBeautifyAB=0.

4*1,2V=4,8V and 8400mAh and 5A. Will it be enough?

Or poeer from the wall and converter from 230V to 5V and 5A. This seems like a cheaper option and more reliable. It costs like 7$. So can i use this power to the arduino nano and power sergos from the Vin pin 5V? The 5A wont be to much for arduino nano? If not ill use just ppwer from the battery to the nano and servos will be povered from the wall

@LazyArtistSQuex you can power them separately (with sufficient power supplies) but you must connect the ground lines together (only the ground) to ensure everything has the same reference for the voltage.

@LazyArtistSQuex: Nano runs off 5V. The Nano will draw as much current as it requires, so you could use a 5 V 20 A supply and the Nano will be fine. The supply does not force the current into the Nano (or any device), the device pulls what is needed from the supply (and no more). Only the voltage of the supply has to match (and not exceed) the (maximum) voltage requirements of a device (i.e. the Nano). The supply only has to provide the minimum required current, in order for the device to operate correctly but it can provide more and the device will not break. Does that make sense?

Thank you for your answer. It seems more clear now. I edited my post;))

I'm afraid that with PWM controler I won't be able to do that.

Chances are that any PWM controller is going to let you control each output independently.
According the the servo library documentation, the library can handle up to 12 servos on a single Arduino, so your project should be feasible. It will however reduce the number of PWM pins available from 6 down to 4.

Will a 9V battery power all these servos?

No! Not a chance.
Typical 9g servos consume 150 mA without any load, and stall at ~700-900 mA. A typical 9v has ~500 mAh capacity, and most data sheets show loads of ~100-150 mA max. Your 9v might be able to supply a few amps for a few seconds before they heat up and slow down.
If your load is very light 9 servos will consume ~900 mA; an ideal 9v would last at most 30 min with this load, but real batteries aren't ideal and will heat up and loose efficiency.
Near maximum load your 9 servos will draw ~7000-9000 mA, well beyond the capabilities of a 9v. However those numbers are for 5v so you could cut them all in half.
If you used an appropriate 5v step-down DC-DC supply you might be able to power all 9 servos for a few seconds before the batter overheats and gives up.
If you powered them directly, the servos will have to dissipate more heat, and will draw extra power, could damage the servos if the batter could supply enough juice.

Yes, I know. But i need only 9 servos and PWM controller can operate on 16. From this forum: http://rcarduino.blogspot.com/2012/04/servo-problems-with-arduino-part-1.html, I know that i need separetly battery to power arduino and servos. Let me do a schematic of what im thinking. I'll post it in a minutes.

Here's the photo. In nano there's 10 digit pins. I'll take 9 and control each servo separately. Will it be fine? What about the voltage to power the servos? 9V battery will do?

@LazyArtistSQuex 9g servos don't take much power; a 9v should power at least one, but I don't know about trying to power 9 at once with a single 9v, n.b. the operating voltage of most 9g servos is 4-6v

If the servo operates on 4-6V, doesn't 9V will be too much for a single one? How about I buy this only to power 9 servos? https://pl.aliexpress.com/item/1pc-3S-11-1V-1500mAh-35C-Lipo-Battery-XT60-T-Plug-for-RC-Car-WLtoys-V950/32827187894.html?spm=a2g0s.13010208.99999999.293.110d3c006Q80BG. I've read that one servo takes 500mA. So for 9 will me 4,5A. I can not find information how many amps this battery provides.

@LazyArtistSQuex it's not the voltage that's the problem, its the capacity. The battery you linked claims to be 35C, so 1.5 aH * 35C = 52.5 A max discharge, which would drain that batter in under 2 min; If the specs claimed are accurate.

Now i understand. Sorry, it's 3 a.m. and i've been thinking of this for nearly 3h.
So it's not all about the voltage. I can use 5V battery but i need higher capacity. If i use 10'000 mAh the servos will drain it in about 13 minutes. It's okay but battery like this costs around 20$.
Another option might be power directly from the electricity from the outlet. Of course i suppose I'll need voltage converter from 230V to 5V. Will this work?

@LazyArtistSQuex a 10 Ah batter will run a 10A load for an hour, that would only occur under the heaviest load for your servos stall==maximum load; under a light load, a 10 Ah Battery could last 10 hours or longer for 9 servos @ ~ 1 A total, so it totally depends on the load the servos will experience; yes wall power will work you will need a power supply, of course

Okay. So let's make things clear. I don't need PWM servo controller, i can only use arduino nano for 9 servos.
Power problem:
I power arduino nano with the battery. I power servos with the wall electricity, but i need voltage converter from 230V to 5V and it needs to be at least 9-10A. The servos will not be on heavy load. Just small turns like on the video from the project.

@LazyArtistSQuex for a light load you can get away with less than 10A, 5A may suffice for a light load, 2A for a very light load.

Or use two 5A supplies. Couple like these  http://www.mpja.com/5-Volt-DC-Plug-Power-Supply-4A-Regulated/productinfo/18520+PS

@CrossRoads just out of curiosity how am I gonna connect TWO of this cables (how to plug in them). I was thinking about this: https://www.shemeck.pl/851-rs-25-5-zasilacz-impulsowy-25w-5v-5a.html?gclid=Cj0KCQjwnNvaBRCmARIsAOfZq-0V5hE3NSN0M3dAXipw7TWMhuBYspNMe47AFRVXle7X0Jt_RA42adUaAthOEALw_wcB as a power for servos.

You can drive upto 20 servos on an Arduino Nano - here's the EXCELLENT software for this: http://www.lamja.com/?p=504
Most servos can run well using high voltages (e.g. 9v) while still accepting PWM signals much lower (e.g. 3.3v) - here's a video showing that working fine:  https://youtu.be/9ZCiQgjcx3k
See Greenonline's answer table (or servo datasheets) to work out your power budget.  9v will work, but is probably more than the servos would like: 6v is more usual.

Servos don't use PWM, not really. What they need is a pulse that is ~ 1mS wide every 20mS (50 Hz) to turn full one direction, ~ 1.5mS wide to be centered, and about 2mS wide to turn fully the other direction.  Or centered, +/- ~ 60-75 degrees or so.
(0.9mS to 2.1mS per the data above).

So, what you are telling me I won't be able to connect 9 servos directly to arduino nano? https://www.google.com/search?newwindow=1&biw=1366&bih=673&tbm=isch&sa=1&ei=JX1XW-u8OdGWsAejsZW4Cg&q=arduino+nano+pwm&oq=arduino+nano+pwm&gs_l=img.3..0l2j0i30k1l7j0i8i30k1.8231.8911.0.9245.4.4.0.0.0.0.333.566.2-1j1.2.0....0...1c.1.64.img..2.2.565...0i67k1.0.yGDezZalT9M#imgrc=Et2rxIh3mJeo-M:

The Servo.h library will control up to 12 servos on a 328P based board, such as the Nano. But it's not using PWM to do to it.  You will need a decent power supply to power them if you plan on moving 9 at once for any length of time.  Perhaps two or three of something like this http://www.mpja.com/5-Volt-DC-Plug-Power-Supply-4A-Regulated/productinfo/18520+PS/ and don't forget power connectors http://www.mpja.com/55_21mm-Power-Jack-Screw-Terminals/productinfo/19454+PL  Be sure to connect all Gnds together.

Thanks for the power supply answer. So arduino nano will be suitable for my project or use another board?

12 > 9, so yes, it will suitable.

Great, now i need the parts to come. Also i need to design the case that will hold all components (i will make it from wood). Will update in short time. Thanks Sir.

Cheapest way is that you should buy couple of LM7805 wire it in parallel now power arduino and other servos from this 7805. Connect pwm pins of servos to the nano.
Voltage regulator built inside arduino cant provide much current to all servos.
Also connect ground of all of your power sources together.