text:
OLED (I2C) and Micro SD card module not working together in Arduino
I am trying to write some data to SD card and read it back to serial monitor as well as display it to the OLED.
Both the sd card and oled work separately but they seem to be interfering with each other when combined. I have used Arduino SD and Adafruit OLED libraries.
Connections from Arduino Uno to Micro SD card module-
5V to SD VCC
GND TO SD GND
PIN 10 TO SD Chip Select
PIN 11 TO SD MOSI
PIN 12 TO SD MISO
PIN 13 TO SD SCK

Connections to OLED-
3.3V to OLED VCC
GND TO OLED GND
A4 TO OLED SDA
A5 TO OLED SCK

Here is the code -
#include <SPI.h>
#include <SD.h>

File myFile;

#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET     -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  while(!Serial) {
    ;
  }

  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // CODE GETS STUCK HERE. DISPLAY NEVER INITIALISES
  }
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(29,29);
  display.print("INITIALISING");
  display.display();
  delay(5000);

  if (!SD.begin(10)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  myFile = SD.open("test.txt", FILE_WRITE);

  if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing 1, 2, 3.");
    // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }

  display.clearDisplay();

  myFile = SD.open("test.txt");
  if (myFile) {
    Serial.println("test.txt:");
    while (myFile.available()) {
      Serial.write(myFile.read());
      display.setCursor(0,0);
      display.print(myFile.read());
      display.display();
      delay(5000);
    }
    // close the file:
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

void loop() {
  // put your main code here, to run repeatedly:

}

Code gets stuck at OLED initialization as mentiontioned above. If I replace these lines-
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // CODE GETS STUCK HERE. DISPLAY NEVER INITIALISES
    }

To this-
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);

I have run I2C scanner code on OLED so the address "0X3C" is correct.
The OLED still doesn't work and SD card initialises but arduino is writing wrong data to TXT file on SD card like this-
teóting 1,à2, ó®

Instead of -
testing 1, 2, 3.

I have also tried using U8G2 library's sketches with SD card in case Arduino was running out of RAM but it still doesn't work. I have also changed SD chip select to Arduino digital pin 4 but still same results.
On browsing and experimenting more,I found MISO OR MOSI PIN of SD maybe interfering with SDA/SCL pins of OLED. Maybe wiring needs to change.
ANY SUGGESTIONS???

I recently had a similar issue with I2C, make sure only one of the modules the I2C pullup resistors.

I am new to this, please can you explain in detail.

Post a link to your both modules.

For OLED - "https://www.amazon.in/Generic-0-96-Display-Module-Arduino/dp/B01GNZEM22/ref=sr_1_10?adgrpid=57784712326&ext_vrnc=hi&gclid=Cj0KCQiAkKnyBRDwARIsALtxe7hvU7JNkEkK9sgmz4vHRgCd4Wk9_GVjZXkkyP9KDhzt6beU8AOcoiwaAtrwEALw_wcB&hvadid=294141455465&hvdev=c&hvlocphy=9061654&hvnetw=g&hvpos=1t1&hvqmt=e&hvrand=8620698541412480040&hvtargid=kwd-301353041996&hydadcr=26462_1900820&keywords=oled+128x64&qid=1582009576&sr=8-10"

For SD Card - "https://www.amazon.in/Storage-Memory-Shield-Adapter-Arduino/dp/B00HFQEKI0"

The microSD is not I2C, it uses serial connection. so what I was suggesting is not the case. hopefully someone will help you out.

I just switched to U8G2 Library from Adafruit OLED library and used its u8x8 examples which does not use any RAM. It was a RAM issue. Thanks for looking into it. @ElectronSurf

Glad you fixed it, good luck with your project.

YOU CAN TRY THIS CODE https://forum.arduino.cc/index.php?topic=510106.0 ........

A pullup resistor is needed for I2C, and adding them might fix some errors.


text:
cannot connect ESP8266 web server after some time
I am new to ESP8266 and found an example about turning a LED ON/OFF using web interface. It works well but after some time (few minutes) i cannot open the web page (in my case it is http://192.168.100.23 and i made it static IP). It keeps 'waiting for 192.168.100.23'. I can ping the IP. Can someone please help to find what the problem is? Thank you very much!
Below is the code:
#include <ESP8266WiFi.h>
#define LED D2
const char* ssid = "myAP";
const char* password = "32133213";
unsigned char status_led=0;
WiFiServer server(80);

void setup() {
  Serial.begin(115200);
  pinMode(LED, OUTPUT);
  /*WiFi.persistent( false );
  WiFi.setAutoConnect(true);
  WiFi.mode(WIFI_STA);*/
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  server.begin();
  Serial.println("Server started");
  Serial.println(WiFi.localIP());
}

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

  Serial.println("new client");
  while(!client.available())
  {
    delay(1);
  }
  String req = client.readStringUntil('\r');
  Serial.println(req);
  client.flush();
  if (req.indexOf("/ledoff") != -1)
  {
    status_led=0;
    digitalWrite(LED,LOW);
    Serial.println("LED OFF");
  }
  else if(req.indexOf("/ledon") != -1)
  {
    status_led=1;
    digitalWrite(LED,HIGH);
    Serial.println("LED ON");
  }
  String web = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
  web += "\r\n";
  web += "\r\n";
  web += "
LED Status
\r\n";
  web += "
\r\n";
  if(status_led==1)
      web += "LED On\r\n";
  else
      web += "LED Off\r\n";
  web += "
\r\n";
  web += "
\r\n";
  web += "\r\n";
  web += "<button>LED On</button >\r\n";
  web += "\r\n";
  web += "
\r\n";

  web += "\r\n";
  web += "<button>LED Off</button >\r\n";
  web += "\r\n";

  web += "\r\n";
  web += "\r\n";

  client.print(web);
}

I added WiFi.setSleepMode(WIFI_NONE_SLEEP); but it does not help. I found another script that is working well so far (after 1 day). I am new so i do not know what problem is but i think it needs to free memory and close connection. Below is the new code for those who get the same problem!
// Load Wi-Fi library
#include <ESP8266WiFi.h>
#define LED D2
// Replace with your network credentials
const char* ssid     = "myAP";
const char* password = "32133213";
// Set web server port number to 80
WiFiServer server(80);
// Variable to store the HTTP request
String header;
// Auxiliar variables to store the current output state
String outputState = "off";
// Assign output variables to GPIO pins

// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;
void setup() {
  Serial.begin(115200);
  // Initialize the output variables as outputs
  pinMode(LED, OUTPUT);
  // Set outputs to LOW
  digitalWrite(LED, LOW);

  // Connect to Wi-Fi network with SSID and password
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  // Print local IP address and start web server
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  server.begin();
}
void loop(){
  WiFiClient client = server.available();   // Listen for incoming clients
  if (client) {                             // If a new client connects,
    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    currentTime = millis();
    previousTime = currentTime;
    while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
      currentTime = millis();
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();

            // turns the GPIOs on and off
            if (header.indexOf("GET /on") >= 0) {
              Serial.println("light on");
              outputState = "on";
              digitalWrite(LED, HIGH);
            } else if (header.indexOf("GET /off") >= 0) {
              Serial.println("light off");
              outputState = "off";
              digitalWrite(LED, LOW);
            }

            // Display the HTML web page
            client.println("<!DOCTYPE html>");
            client.println("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            // CSS to style the on/off buttons
            // Feel free to change the background-color and font-size attributes to fit your preferences
            client.println("");

            // Web Page Heading
            client.println("
ESP8266 Web Server
");

            // Display current state, and ON/OFF buttons for GPIO 5
            client.println("
State " + outputState + "
");
            // If the output5State is off, it displays the ON button
            if (outputState=="off") {
              client.println("
<button class=\"button button2\">TURN ON</button>
");
            } else {
              client.println("
<button class=\"button\">TURN OFF</button>
");
            }

            client.println("");

            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }
}

The esp8266 enters modem sleep in STA mode without WiFi traffic. You can turn off the sleep mode with WiFi.setSleepMode. The possible parameters are WIFI_NONE_SLEEP, WIFI_LIGHT_SLEEP or WIFI_MODEM_SLEEP.
After some longer time the servers on esp8266 with arduino core usually get inaccessible even it the esp8266 connects as client to other servers or still sends UDP messages. It is a known issue with some possible workaround documented.

Thank you very much for your quick reply. I will work around on it.

source: Stack Exchange

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

sort: votes


text:
How to save data in arduino when it's power goes off
I am doing a project 'arduino based switch operation'. Here the user needs to set a time to turn on relay and set time to turn it off. The problem is that I want to supply power to arduino using adapter connected to the ac supply (where the relay will also be connected). When the on time is set and if power goes off for some time then this system doesn't work. I want to save the data in arduino so that it will retain the data if power comes back.. So that my relay is operated on time..
How to do it guys???

See this answer https://arduino.stackexchange.com/a/72370/14490

Maybe I don't understand the question, but should the idea not be: the Arduino is always on, and the on and off time depends if the relay goes on/off... If you want the Arduino to be switched off too, you need at least some battery power and using sleep mode i.c.m. with an interrupt pin trigger set to some real time clock to be able to 'awake'  it.

It is unclear, if you want to power off the Arduino in regular operation, or if you just want to save the time settings in case of a power outage. Please make this clearer

Look up EEPROM. it is a memory that saves content even though power is off.
You can write data in EEPROM and when power comes back read it back.
there are safe ways to write in EEPROM without corrupting it.

Beside Georgi's answer, I would like to tell  you some details.
First :
a microcontroller can have a built-in EEPROM like the ATMega328 inside an Arduino UNO/Nano/mini, if not you would need to attach an external one, it can have may interfaces like SPI or IIC etc...
Second :
an EEPROM can hold only a specified amount of data, it can be 512byte like one on the ATMega328 microcontrollers, it can be only 64byte on others.
Third :
an EEPROM have addresses so for example in 8-bit EEPROM one address can hold only 8bits so values from (0-255) like on the ATMega328
Fourth : how to use it
In the beginning of your code you should first include the eeprom library
#include <EEPROM.h>

Then you would for example assign value "24" to one of the address on the EEPROM let's say address "1"
So you will use
EEPROM.write(1,24);

Of course you can power off you board and repower it again and that particular address will have the assigned 8-bit value "24".
To read back
EEPROM.read(24);

I hope that might help you or anyone else.
And as a side note an EEPROM have defined write and read cycles ~10000 maybe ~100000 after that amount it May not work.
Original documentation : here

You Can do that by using RTC (Real Time Clock Module ) in your project.

And how would you do that? "How do I get from New York to Trenton?" "You can drive." Hardly helpful.

Sure, hardly helpful. But similar to the question. The title question "How to save data in arduino when its power goes off" smells like EEPROM, additionally...

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


text:
STM32Ethernet UDP misses some packets
Using STM32Duino on Nucleo F429ZI:
#include <LwIP.h>
#include <STM32Ethernet.h>
#define UDP_TX_PACKET_MAX_SIZE 512
#include <EthernetUdp.h>

IPAddress remoteIP;
unsigned int remotePort;

EthernetUDP Udp;
uint8_t packetBuffer[UDP_TX_PACKET_MAX_SIZE];

void setup()
{
  Serial.begin(115200);
  IPAddress localIP = /***/;
  IPAddress netmask = /***/;
  IPAddress dns = /***/;
  IPAddress gateway = /***/;

  Ethernet.begin(localIP, netmask, dns, gateway);
  uint8_t *mac = Ethernet.macAddress();

  int port = 8888;
  Udp.begin(port);
}

void loop()
{
  processUDPMessage();
}

void processUDPMessage(void)
{
  while (int size = Udp.parsePacket())
  {
    if (size > 0) parsePacket(size);
  }
}

void parsePacket(int size)
{
  remoteIP = Udp.remoteIP();
  remotePort = Udp.remotePort();

  Udp.read(packetBuffer, size);
  Serial.println((char *) packetBuffer);
}

If I received at least 4 packets at the same time, one of them is not received. Each packet is less than 50 byte long.
Is there anything I could do to improve the reliability of my code?

are you sure it is STM32duino by Roger Clark and not STM32 by STM? does STM32Duino  support F4 and STM32Ethernet? the experts are here https://www.stm32duino.com

The STM32 Core is by STM, the STM32duino STM32Ethernet library is by "Various" and STM32duino LwIP is by Adam Dunkels.

UDP is, by definition, unreliable. If you want more reliability then use TCP.

@Majenko, sorry I don't agree. This is a problem in my code, not in the UDP protocol. I use it since 10 years and I never missed a packet. Here I miss packets every time they are sent. It's a different thing :)

@Mark My point is: that UDP is not a reliable protocol ("reliable" has a specific meaning in networking). That means that the protocol that you design with it must be tolerant of dropped packets. Yes, there may well be problems with your code or with the IP stack in use, but if you designed your protocol properly then it shouldn't care that you lost some packets.

Yes, but this is the second step in my opinion. At first my code should work at least in a predictable environment.


text:
How to stop program while Servo is rotating
If I code like this:
motor.write(0);
Serial.println("Before");
motor.write(180);
Serial.println("After");

Both "Before" and "After" is instantly printed, while the motor is still rotating.
I want "After" or whatever statement to be executed AFTER the motor
reaches 180 degree.
How can I implement this? Is it possible to read Servo's statement?
Btw, I don't want to put delay after write(), so other than that strategy.

Hobby servos don't provide feedback: you can't know when they have reached their target position.

How can I implement this? Is it possible to read Servo's statement?

No, it is not possible. When you do a servo.write() it just changes the PWM duty cycle. It's then up to the servo to use that to set its position. The Arduino has no concept at all of the current position of the servo.

Btw, I don't want to put delay after write(), so other than that strategy.

The only other way, besides delaying or otherwise using millis() to wait for a predefined period after your write would be to implement some form of feedback between the shaft of the servo and the Arduino. Maybe a potentiometer, or rotary encoder would do the job.

Well, I just ripped off rotary encoder from my old mouse

That was great idea, thank you very much. Can you recommend me a good arduino library to use with rotary encoder?

It's not possible with the servo alone, but you could add feedback. Some options:

An encoder (may be expensive or not available for your servo) will tell you the position.
You could also make your own encoder by connecting a potentiometer to the axis. The resistance of the pot will be related to the position of the servo.
if you don't need to be exact something simple like a switch at the limit you want to reach.
If it doesn't have to be exactly when the position is reached, you
could measure the average time it takes (under load) to move from the
minimum angle to the maximum angle. This will be the longest it ever
takes to move. Then in your code wait 150% of that time before
proceeding (to give a bit of a buffer "just in case").

As Majenko said, if you don't want to use a delay, use millis() or micros() to track the current and previous times a line in the loop executed; if the difference is larger than the required delay, the time has elapsed and you can proceed with the rest of the loop. This way you can track time without having to "block" the rest of the loop while you wait.


text:
Is it possible to run a monochrome LCD without driver circuit with an Arduino Uno?
I have an old monochrome LCD panel that I removed from a calculator. The LCD panel has no standard input pins, because it's directly connected to a driver on which the calculator software runs.
Is it possible to run the LCD without the calculator software? All pins of the LCD would be available (marked in blue). The pins marked in red were connected to the keyboard of the calculator.

Depending on what it is you want to do with it; you could connect the Arduino to the keypad pins, and have the Arduino "type" the number you want to show. Though it's a bit more tricky than that, since the keypad is a matrix, so you'd have to time the fake button presses, so it's in sync with the calculator scanning the button matrix.

google lcd driver waveforms to get an idea of the kinds of signals you would have to generate .... here is one example https://aardvarklabs.files.wordpress.com/2013/04/waveforms.png ..... the problem with LCDs is that you cannot have a net voltage across a display element ... all the voltages placed across an element over a period of time must add up to zero ... the duration of positive voltages and the duration of negative voltages have to be equal, otherwise the display element will become damaged

In theory, maybe yes, in practice it will be hard job.
Some things you need to find out:

Find the exact model of the LCD
Find its datasheet
I see an enormous amount of pins (especially the blue ones), so you need (a lot of) multiplexers or shift registers.
Speed of the Arduino, is it enough to drive this LCD?
You have to solder this to test.

Normally such LCDs are custom designed, mass produced displays especially for this calculator product. Thus it is very unlikely to find a datasheet or even a meaningful part number for it.
Most likely the pins on the LCD are directly connected to the corresponding fields on the LCD. In an LCD you have liquid crystals between two electrodes, which change their orientation, when a voltage is applied to the electrodes, which changes the light absorption of the layer. You need to apply the correct voltage to a pair of pins to activate their field. Most likely all of the fields or a few groups of them have a common electrode (which would be 1 pin). Without any documentation you are bound to experiment with the display, until you have found the correct voltages and pin arrangements. You might break the display in the process (for example through excess voltage).
I haven't done this myself, but googling gives an interesting result:

This project, where they hacked the LCD of a cheap calculator for a waveform generator (though the display seems to be way less complex than yours) They seem to use 1.5V as voltage, so this might be a good starting point.

Your display has many pins. Depending on the Arduino model, that you use, you will fast run out of pins to use. You can try arranging the pins into a matrix, which would mean multiplexing the fields (turning them on and off fast one after another). Or you can buy additional parts to extent your pin count, for example shift registers.

As jsotola wrote in the comments (and as several forum threads on web web state), you should not put a constant voltage onto the display, since this will damage it. (I guess the liquid crystals will degrade fast because of their polarity, which make the work in the first place). Instead you have to place an alternating voltage at the pins, which changes it's polarity. The  net voltage (The integrated voltage over time) must be zero. Thus you need to alternate the applied voltage. If you provide a span of 1.5V, you need to change between +0.75V and -0.75V.
As the display shouldn't need too much current and the voltage requirement is relative to the LCD ground, you might get way by setting the LCDs ground with a voltage divider to 2.5V and then operating around that. Though I'm not sure about that.
Otherwise you might need to actually change the polarity. This would also just need 1 extra digital output pin as the ground pin. One polarity would be the LCDs ground pin to Arduino's ground (outputting LOW at the digital pin) and the other pins to the needed positive voltage (HIGH divided down over a voltage divider or similar). The other polarity would be LCDs ground pin to the needed positive voltage (HIGH divided down over voltage divider) and the other pins to ground (outputting LOW).

As described above, hooking this bare LCD to the Arduino is not done fast and easy. You can try it, if you like to do it. But if you want to get your project (whatever it is) done fast, you should instead buy a LCD with integrated controller, which are mostly ready to use, and for which there are already libraries.


text:
ESP8266 compilation error: "previous declaration of 'HTTPMethod HTTP_HEAD'"
I have an ESP8266 program that used to work but is now failing to compile with this error:
C:\...\Arduino\libraries\WiFiManager/WiFiManager.h:25:24: note: in expansion of macro 'PROGMEM'

 const char HTTP_HEAD[] PROGMEM            = "<!DOCTYPE html><html lang=\"en\"><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\"/><title>{v}</title>";

                        ^

In file included from C:\...\MyEsp.ino:14:0:

C:\...AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WebServer\src/ESP8266WebServer.h:33:39: error: previous declaration of 'HTTPMethod HTTP_HEAD'

 enum HTTPMethod { HTTP_ANY, HTTP_GET, HTTP_HEAD, HTTP_POST, HTTP_PUT, HTTP_PATCH, HTTP_DELETE, HTTP_OPTIONS };
                                   ^

I don't recall changing anything, except maybe updating some libraries. Any ideas what could be causing this?  Here are my includes from the ESP8266 program:
#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>

#include <DNSServer.h>            //Local DNS Server used for redirecting all requests to the configuration portal
#include <ESP8266WebServer.h>     //Local WebServer used to serve the configuration portal
#include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager WiFi Configuration Magic

#define SERIAL_BUFFER_SIZE 256

You need a newer version of the WiFiManager.h library. This issue was fixed August last year.

Strange. WiFiManager.h didn't show up in my 'Updateable' libraries but you're right.


text:
displaying a 3 digit clock time on a 4 digit 7 segment display
I purchased one of these 4 digit 7 segment displays using a TM1637.
I installed the TM1637 display library from the libraries manager and included it:
(#include <TM1637Display.h>).
I am trying to display the time, and I would like, preferably, to display 3 digit times with a colon, but without the leading zero.
I found this great reference online for using the library., and saw the usage for numbers with colons:
showNumberDecEx(number, dots, leading_zeros, length, position)
according to the guide, to have the colon in the center, you would pass 0b01000000 as the dots parameter.
And I figured that if I then want to display, for example, the time 1:36, then my number parameter would be 136, my leading_zeros parameter would be 0 (false), my length would be 3 for a 3 digit number, and my position would by 1 to start the number in the zero-indexed second position:
display.showNumberDecEx(136, 0b01000000, false, 3, 1); //displays 5136
But this displayed 5136 with no colon.
I tried a number of other things, including:
display.showNumberDecEx(136, 0b01000000, true, 3, 0); //displays 13:66
display.showNumberDecEx(136, 0b01000000, false, 3, 0); //displays 13:6A
I finally found code from this site, which works to display the time (albeit with a leading zero), but I don't fully understand it:
display.showNumberDecEx(1*100+36, 0x80 >> 1, 1, 4, 0);
I get that 1*100+36 represents number of hours plus minutes, but I don't get the 0x80 >> 1 bit. I'm assuming the rest of it is just saying make it a 4 digit number and add a leading zero.
Can anyone possibly:
* help me understand the above working code
* tell me an easier way to construct a time so that I can ideally just pass a 3 or 4 digit number and have it automatically render out a clock time with separating colon
* tell me why my previous attempts were incorrect

I tested your first code line and it outputs a right aligned 136 without colon at my display. (Said I have only a colon at the middle and no decimal points)
The 5 at the fist digit (and also the A at your third code line) must have been set somewhere beforehand. The function does not change the unused digit, so it will stay whatever you set it to beforehand (Even from before the last reset of the Arduino. The display doesn't reset with the Arduino). You can set the segments for that digit to zero (or set all segments to zero, to clear the complete display) before you show the decimal number.
About the colon: Here it is important on which position you start the printing of the number. The colon/decimal point bitmask, that you provide the function with, is seen from the starting position, that you provide. The middle colon of a 4 digit display is wired to the second digit. When providing 1 as the starting position, you start with the second digit. Thus the colon bitmask must set the most significant ("first") bit, to enable the middle colon, since it belongs to the first digit, that is processed by the function. Meaning:
position = 0 and bitmask = 0b10000000 --> colon/decimal point at first digit on
position = 0 and bitmask = 0b01000000 --> colon/decimal point at second digit on
position = 0 and bitmask = 0b00100000 --> colon/decimal point at third digit on
position = 1 and bitmask = 0b10000000 --> colon/decimal point at second digit on
position = 1 and bitmask = 0b01000000 --> colon/decimal point at third digit on
position = 2 and bitmask = 0b10000000 --> colon/decimal point at third digit on
position = 2 and bitmask = 0b01000000 --> colon/decimal point at fourth digit on

The 0x80 >> 1 is just a different representation of your binary number. 0x80 is the hexadecimal form of the binary 0b10000000. The >> operator shifts the byte to the right, here by one digit. Thus:
0x80 >> 1 = 0b10000000 >> 1 = 0x40 = 0b01000000

So the code, that you found, enables the colon/decimal point at the second digit.

tell me an easier way to construct a time

Easier it relative. I used such a display in a project to display a time and used two showNumberDecEx() calls; one for the minutes and one for the seconds:
display.showNumberDecEx(seconds, 0x00, true, 2, 2);
display.showNumberDecEx(minutes, 0x40, true, 2, 0);

Having directly minutes and seconds may make it easier for you. About the no-leading-zeros: Since the library always prints left to right, you need to handle that by yourself. But that is rather easy. One if statement to check, if the minutes are greater than 9 or not. Depending on that you set the position to 0 or 1.
display.showNumberDecEx(seconds, 0x00, true, 2, 2);
if(minutes > 9){
    display.showNumberDecEx(minutes, 0x40, false, 2, 0);
} else {
    display.showNumberDecEx(minutes, 0x80, false, 1, 1);
}

You could put that into a function, so that you don't have to write this code multiple times.
Note: For my last code snippet to work, you should first clear the display (or optionally only the first digit), so that no number from before will be displayed there.

In your last code snippet, the case minutes ≤ 9 won't work as expected since, as you put it yourself, “the function does not change the unused digit, so it will stay whatever you set it to beforehand”.

That's true. I assumed implicitly, that the display is cleared beforehand. I will add a note for that.

Always start by reading the docs. The README of the TM1637 display
library gives a short summary of the available functions, then states
“Please refer to TM1637Display.h for more information.” It would thus
seem the authoritative documentation is the header file itself, which is
indeed rich ins structured comments. According to it, the
signature of showNumberDecEx() is
void showNumberDecEx(int num,
                     uint8_t dots = 0,
                     bool leading_zero = false,
                     uint8_t length = 4,
                     uint8_t pos = 0);

where the parameters have the following meanings (emphasis mine):

num: the number to be shown
dots: dot/colon enable [...]
leading_zero: when true, leading zeros are displayed, otherwise
unnecessary digits are blank
length: the number of digits to set
pos: the position of the most significant digit
(0 - leftmost, 3 - rightmost)

The length and pos parameters control which digits are set. It is
important to note that any digits that are not set are left as is.
Note also that, if you are setting more digits than needed to display
the number, the leftmost digits are either zeros or blank, depending
on the value of leading_zero. And that is exactly what you want: you
want the leftmost digit to be blank.
Here are some examples of what various calls display:
display.showNumberDecEx(136, 0x40, true,  3, 1)  →  "X1:36"
display.showNumberDecEx(136, 0x40, false, 3, 1)  →  "X1:36"
display.showNumberDecEx(136, 0x40, true,  3, 0)  →  "13:6X"
display.showNumberDecEx(136, 0x40, false, 3, 0)  →  "13:6X"
display.showNumberDecEx(136, 0x40, true,  4, 0)  →  "01:36"
display.showNumberDecEx(136, 0x40, false, 4, 0)  →  " 1:36"

In the examples above, “X” means “whatever was previously left there”,
as the corresponding digit is not updated by the call. The last example
is the one you want. Incidentally, the last three parameters of this
example have their default values. You can thus achieve this simply
with:
display.showNumberDecEx(136, 0x40);

You can also follow chrisl's advice and display the hours and minutes
separately:
int hours = 1;
int minutes = 36;
display.showNumberDecEx(hours, 0x40, false, 2, 0);
display.showNumberDecEx(minutes,  0, true,  2, 2);

No need to separately handle the case where hours is larger than 9.


text:
NodeMcu Communication to RS485 Device using TTL to RS485 converter

Good day everyone,
           I am facing a problem when trying to use nodemcu  (Nodemcu ESP8266 Lolin V3) to communicate with an RS485 device. I sent an enquiry frame to the device and got the response in bytes. However, the response is not meaningful as it cannot be converted to readable ASCII characters.

           I used the built in Serial for this purpose. Hence i debug the program by sending the program flow state and data received to a server as shown in the Web UI below :-

The response that i expect is the ASCII bytes:-
AFC54D48355CC030B14ED8D4B459

which is completely different than what is shown in the Web UI above.
Here is the connection and the code that i have tried so far:-

The code :-
#include<ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

int enable_pin = 5; //DE and RE pin is jumped together to Nodemcu D1 pin.

String link = "http://someserver.ngrok.io"; //the server

void setup() {
  pinMode(enable_pin,OUTPUT);
  sendActivity("baud_rate_is_set");
  Serial.begin(9600);
  delay(2000);
  digitalWrite(enable_pin,HIGH); //mcu - master : meter - slave
}

void loop() {
  int timeout = 5000;
  int delay_unit = 100;
  byte request[] = {0xb7,0xb7,0xaf,0x3f,0x30,0xb7,0xb4,0xb4,0x36,0x33,0x35,0xb1,0x21,0x8d,0x0a};
  sendActivity("send_enquiry_frame");

  //write
  Serial.write(request,sizeof(request) / sizeof(request[0]));
  digitalWrite(enable_pin,LOW);

  //delay & timeout
  sendActivity("start_waiting_5s");
  int current_delay = 0;
  while(current_delay <= timeout)
  {
    current_delay = current_delay + delay_unit;
    delay(delay_unit);
  }
  sendActivity("done_waiting_5s");

  //get the response part
  if(Serial.available())
  {
    sendActivity("serial_data_available");
    byte serial_receive_buff[200];
    Serial.readBytes(serial_receive_buff,200);
    char buff[200];
    array_to_string(serial_receive_buff,200,buff);
    sendResponse(buff);
  }
  else{
    sendActivity("serial_data_not_available");
  }
  delay(3000);

}

void sendActivity(String act)
{
  HTTPClient http;
  http.begin(link+"/api/activity/"+act);
  int code = http.GET();
}

void sendResponse(String data)
{
  HTTPClient http;
  http.begin(link+"/api/data/"+data);
  int code = http.GET();
}

void array_to_string(byte array[], unsigned int len, char buffer[])
{

    for (unsigned int i = 0; i < len; i++)
    {
        byte nib1 = (array[i] >> 4) & 0x0F;
        byte nib2 = (array[i] >> 0) & 0x0F;
        buffer[i*2+0] = nib1  < 0xA ? '0' + nib1  : 'A' + nib1  - 0xA;
        buffer[i*2+1] = nib2  < 0xA ? '0' + nib2  : 'A' + nib2  - 0xA;
    }
    buffer[len*2] = '\0';
}

Can anyone point out what i messed up ? I am stuck on this problem for few days. Thanks a lot.

I can get an ASCII string if i convert the bytes

i forgot to mention that the expected byte after some conversion should be "/EMH5@01NXT4Y". What i actually get when trying to convert the response from the rs485 interface did not yield this.


text:
Fixing serial communication , condition for serial data available checks out even after reading all the data sent
I have been working on monitoring an aquaculture , where I log the environment variables (temp. , humidity, gas sensor data) to firebase and control feeding mechanism via an app(where data can also be viewed)
The setup has all sensors connected to Uno Board, which transmits data serially to esp8266.
Pin 2 of Uno is connected to Pin 2 of esp8266
Pin 3 of Uno is connected to Pin 3 of esp8266
Right now the boards are being powered by USB ports in the computer.
My understanding is that, once all the data are read, the Serial.available() becomes 0 and the while() loop will not execute again, but it worked again and reads data.. to  avoid sending same data over and over again(to FireBase), I used Boolean values to take care of.
The data should be available only once per 30 seconds, so after a string is fully read, I was able to see that pgm entered into while() loop and reads one/two values

// uploaded to esp8266 Lolin(wemos) d1 r2 and mini

#include<ESP8266WiFi.h>
#include<FirebaseArduino.h>
#include<SoftwareSerial.h>

// Set these to run example.
#define FIREBASE_HOST "@#$%^.firebaseio.com"
#define FIREBASE_AUTH "********"

#define WIFI_SSID "###########"
#define WIFI_PASSWORD "&^*^*%$#"

SoftwareSerial esp(D2,D3);

float temp_fb;
float gas_fb;
float hum_fb;

unsigned long last_chk = 0 ;
unsigned long time_elapsed;

bool t_ar , h_ar , g_ar = false ; //chk arrival of all data b4 sending

char r;
String cu_st = "c";

int found = 1;

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

  // connect to wifi.
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("connecting");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }

  Serial.println("connected: ");
  Serial.println(WiFi.localIP());

  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
}

void loop()
{
  time_elapsed = millis();
  if(time_elapsed - last_chk > 5000){
    Serial.print("checking for data from arduino...\tfeeder state\t");
    Serial.println(cu_st);
    last_chk = time_elapsed;
    time_elapsed = millis();
  }
   while(esp.available()>0)
  {
     if(found == 1)
     {
      Serial.println("................found data...............") ;
      found = 0;
     }
     r = esp.read();
     //Serial.print("first char\t"); just for debugging purposes
     //Serial.println(r);
     switch(r)
     {

      case 't':
      {
        Serial.println("got t...") ;
        t_ar = true;
        temp_fb = esp.readStringUntil(',').toFloat();
        break ;
      }

      case 'g':
      {
          Serial.println("got g...") ;
          g_ar = true;

          gas_fb = esp.readStringUntil(',').toFloat();;
          break ;
      }

      case 'h':
      {
        Serial.println("got h...") ;
        h_ar = true;

        hum_fb = esp.readStringUntil(',').toFloat();
        break ;
      }

      case 'c':
      {
        cu_st = "c" ;
        Firebase.setString("feeder" ,"c");
      }
      default: break;

     }

  }

  found = 1 ;

  if(g_ar and t_ar and h_ar)
  {
     //writing to firebase
     Serial.println("got the set.. to fb now");
     Firebase.setFloat("GAS SENSORinst" ,gas_fb);
     Firebase.setFloat("HUMIDITY SENSORinst" ,hum_fb);
     Firebase.setFloat("TEMP SENSORinst" ,temp_fb);
     Firebase.pushFloat("GAS SENSOR" ,gas_fb);
     Firebase.pushFloat("HUMIDITY SENSOR" ,hum_fb);
     Firebase.pushFloat("TEMP SENSOR" ,temp_fb);
  }

  t_ar , h_ar , g_ar = false ;

  cu_st = Firebase.getString("feeder");

   if (cu_st == "o")
   {
    Serial.println("\t\trecd req to feed");
    esp.print('o');
   }

}

The arduino sends data every 30 Sec.
The servo connected to Arduino was having jitters every time the data was being sent(apparently due to not enough power to supply for all devices connected and both Softwareserial and servo having same timer) so I have added a LED just for trial
For some reason, if block in close_feed() is always executed.
//uploaded to arduino Uno
#include <SoftwareSerial.h>
#include<TimerOne.h>

SoftwareSerial ArduinoUno(3,2);
#include<Servo.h>
#include "DHT.h"

//Servo feeder;

int send_rate = 30000; //every 30 secs send data
unsigned long last_time_stamp = 0;
unsigned long cur_time = 0;

String sen_vals = "";
#define led 13
int feeding = 0 ;
const int gas = 0;//gas sensor o/p
#define DHTPIN 8
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

void setup()
{
  // put your setup code here, to run once:
  Serial.begin(9600);
  ArduinoUno.begin(4800);
  pinMode(led,OUTPUT);
  //feeder.attach(11);
  //feeder.write(85);
  Timer1.initialize(10000); //every 10 millisecond check for arrival of feed command
  Timer1.attachInterrupt(feed_cmd); //chk feed_cmd for every 10 mS
   dht.begin();

  pinMode (3,INPUT); //recieve from esp
  pinMode (2,OUTPUT); //transmit to esp

}

void feed_cmd()
{
  while(ArduinoUno.available())
  {
    char valve = ArduinoUno.read();

    if(valve=='o')
    {
       digitalWrite(led, HIGH);
       //feeder.write(0);
       feeding = 1;
       ArduinoUno.print("c");
       valve = "";
    }
  }
}

void close_feed()
{
  if(feeding == 1)
  {

    feeding = 0;
    delay(5000);
    //feeder.write(85);
    digitalWrite(led,LOW);
    Serial.println("I am closing feeder");

   }
}

void send_data()
{
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  String ht = String('h')+String(h)+String(',')+String('t')+String(t)+String(',');

  float raw_v = analogRead(gas);
  String g = String('g')+String(raw_v)+String(',');

  sen_vals = ht + g ;

  Serial.println(sen_vals);
  ArduinoUno.print(sen_vals);
}

void loop()
{
  // put your main code here, to run repeatedly:

  close_feed();
  cur_time = millis();
  if(cur_time > last_time_stamp + send_rate)
  {

    last_time_stamp = cur_time;
    send_data();

  }

}

Some how some blocks are executed even when they shouldn't be.. I wrote the code, but I cant figure out where the code fails, used a lot of serial prints to see how the flow of the code, but it only confused me further!
If somebody can take a look at this code and point out the flaws..I'll greatly appreciate it.
EDIT: I have changed he code as suggested below, but now the Arduino is receiving random things as input(pic attached)
I have added the changed code too(I know this post is getting bigger and bigger, but i thought making changes to already existing code here won't be good for readability )
void setup() {
  Serial.begin(9600);
  esp.begin(4800);

  // connect to wifi.
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("connecting");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }

  Serial.println("connected: ");
  Serial.println(WiFi.localIP());

  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
}

void loop()
{
  time_elapsed = millis();
  if(time_elapsed - last_chk > 5000){
    Serial.print("checking for data from arduino...\tfeeder state\t");
    Serial.println(cu_st);
    last_chk = time_elapsed;
    time_elapsed = millis();
  }
   while(esp.available()>0)
  {
     if(found == 1)
     {
      Serial.println("................found data...............") ;
      found = 0;
     }
     r = esp.read();
     //Serial.print("first char\t");
     //Serial.println(r);
     switch(r)
     {

      case 't':
      {
        Serial.println("got t...") ;
        t_ar = true;
        temp_fb = esp.parseFloat();
        break ;
      }

      case 'g':
      {
          Serial.println("got g...") ;
          g_ar = true;

          gas_fb = esp.parseFloat();;
          break ;
      }

      case 'h':
      {
        Serial.println("got h...") ;
        h_ar = true;
        hum_fb = esp.parseFloat();
        break ;
      }
      default: break;

     }

  }

  found = 1 ;

  if(g_ar and t_ar and h_ar)
  {
     //writing to firebase
     Serial.println("got the set.. to fb now");
     Firebase.setFloat("GAS SENSORinst" ,gas_fb);
     Firebase.setFloat("HUMIDITY SENSORinst" ,hum_fb);
     Firebase.setFloat("TEMP SENSORinst" ,temp_fb);
     Firebase.pushFloat("GAS SENSOR" ,gas_fb);
     Firebase.pushFloat("HUMIDITY SENSOR" ,hum_fb);
     Firebase.pushFloat("TEMP SENSOR" ,temp_fb);
  }

  t_ar , h_ar , g_ar = false ;
  if (cu_st == "c")
  {
    sent = 0;
  }
  cu_st = Firebase.getString("feeder");
   if (cu_st == "o")
   {
    Serial.println("\t\trecd req to feed");
    if(sent == 0)
    {
      esp.print('o');
      sent =1;
      cu_st = "c";
      Serial.println("setting feeder to close in firebase");
      Firebase.setString("feeder" ,"c");

   }

  }
}

#include <SoftwareSerial.h>

SoftwareSerial ArduinoUno(3,2);
#include<Servo.h>
#include "DHT.h"

//Servo feeder;

int send_rate = 30000; //every 30 secs send data
unsigned long last_time_stamp = 0;
unsigned long cur_time = 0;
unsigned long close_time = 0;
unsigned long open_time = 0;
#define led 13
int feeder = 0 ;
const int gas = 0;//gas sensor o/p
#define DHTPIN 8
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

void setup()
{
  // put your setup code here, to run once:
  Serial.begin(9600);
  ArduinoUno.begin(4800);
  pinMode(led,OUTPUT);
  //feeder.attach(11);
  //feeder.write(85); //closing position
   dht.begin();

  pinMode (3,INPUT); //recieve from esp
  pinMode (2,OUTPUT); //transmit to esp

}

void feed_cmd()
{
  while(ArduinoUno.available())
  {
    char valve = ArduinoUno.read();
    Serial.print("feeder cmd recd ");
    Serial.println(valve);
    if(valve=='o')
    {
       digitalWrite(led, HIGH);
       //feeder.write(0); //open position
       open_time = millis();
       feeder = 1 ;
       Serial.println("I am opening feeder");
    }
  }
}

void close_feed()
{

  if(feeder == 1)
  {
   close_time = millis();
   if(close_time - open_time > 5000)
  {
    feeder = 0;
    digitalWrite(led , LOW);
    Serial.println("I am closing feeder") ;
  }
  }
}

void send_data()
{
  float h = dht.readHumidity();

  float t = dht.readTemperature();

  float raw_v = analogRead(gas);

  ArduinoUno.print("h");
  ArduinoUno.print(h);
  ArduinoUno.print(",t");
  ArduinoUno.print(t);
  ArduinoUno.print(",g");
  ArduinoUno.print(raw_v);
  ArduinoUno.print(",\n");
}

void loop()
{
  // put your main code here, to run repeatedly:

  feed_cmd();
  close_feed();
  cur_time = millis();
  if(cur_time - last_time_stamp > send_rate)
  {

    last_time_stamp = cur_time;
    send_data();

  }

}

Thanks for your time!!!

I cannot really narrow down the source of your observed problems, since the problem descriptions are not clear enough. But there are some obvious problems/potential for making it better in your code.
In the Uno Code:

It is totally unnecessary to use a timer interrupt for reading the SoftwareSerial interface. Instead you should write your loop() function non-blocking, meaning, that it does not wait for something to happen, but it will execute other code in the meantime (so no delay in close_feed()). Then you can just read the serial data in the loop function. You are saving a timer this way.
In send_data() you are using the String class to concat a string of human readable data together and then send it. Using the String class in that way is evil, since on every concat operation it will allocate a new buffer for the string, deleting the old one. That makes Swiss cheese out of your heap memory (called heap fragmentation). That can lead to instability. Look at Majenko's blog entry about the Evils of Arduino Strings for more information. Instead of concatting you should simply print the information one after another:
Serial.print("h");
Serial.print(h);
Serial.print(",t");
Serial.print(t);

and so forth.
Your handling of the millis() function should be different. It will roll over after 52 days. To prevent, that your code misfunctions at that time, you need to always take the time difference:
if(cur_time - last_time_stamp > send_rate)

instead of
if(cur_time > last_time_stamp + send_rate)

In the ESP Code:

Your SoftwareSerial read code seems weird to me, but I think it should work. I would introduce a message protocol to the data stream, meaning to mark the end of a full message (a message containing one frame with all relevant data) with a special delimiter character, for example a newline character \n. Then you can read the message until this character into a buffer and then process the message as a whole.

That's about what I can say to this point. If you need a more focused answer, you have you describe further and more detailed the symptoms (what behavior you are seeing and what you expected).

thanks for pointing out some good practices and details ... will work this out...

As far as the issues go, I'm struggling to put it to words... Eg. When the pgm starts, there's no pblm, but when I give command to open from App, it just starts printing I am closing feeder  continuously , that shouldn't be happening right, because we set feeding =0 and only way it goes into if block of close_feed() is if feed_cmd() got invoked again, but that shouldn't happen because we've already read from the incoming serial.. Hope I've explained my issue!!!

You send the feeding character o continuously based on the Firebase value "feeder". It that value reset directly after you have set it? If not, meaning if the Firebase value "feeder " stays "o", the esp will continuously send the character 'o', which will cause the Arduino to continuously close the feeder.

Yes, I get the flow now.... But I thought once Arduino receives the open cmd, by sending "c" to esp, which in turn writes to firebase , this shouldn't be happening I'll re-write it so that esp itself will send "c" to firebase right after sending open cmd to arduino... (funnily enough, that's how i had it earlier, but since the feeder valve was not responding, i thought maybe the value change was changing too quick and "c" was being read skipping "o" cmd )

You should only send the "o" cmd once to the Uno. Even if you immediately send "c" back to the ESP, the ESP most likely will already have send several "o" commands to the Uno. So just send it once instead of continuously

any suggestions as to why this new behaviour has occurred.?


text:
Free touch big electrodes (arduino zero)
I want to try making big electrodes 20cm*1 cm
but i got an effect i dont understand.
In the picture red and blue are the diffrent electrodes
at first touch the blue  one and it rises.
then i touched the red  one and it rises.
when i touch both electrodes both signals dropps ??
when itouch both with gloves both rise ??
i think its not allowed to touch the pure cooper
Also i would like to know whats the output from the mesure funktion of the  free touch libary  (physical dimension ,like time or voltage??)
#include "Adafruit_FreeTouch.h"

Adafruit_FreeTouch qt_2 = Adafruit_FreeTouch(A1, OVERSAMPLE_4, RESISTOR_50K, FREQ_MODE_NONE);
Adafruit_FreeTouch qt_3 = Adafruit_FreeTouch(A2, OVERSAMPLE_4, RESISTOR_50K, FREQ_MODE_NONE);

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

  while (!Serial);
  Serial.println("FreeTouch test");
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);

  if (! qt_2.begin())
    Serial.println("Failed to begin qt on pin A1");
  if (! qt_3.begin())
    Serial.println("Failed to begin qt on pin A2");

}

void loop() {
  int counter,result2,result3, result = 0;

  counter = millis();
  result = qt_2.measure();
  result2=result;

  counter = millis();
  result = qt_3.measure();
  result3=result;
    Serial.print(result2);
    Serial.print(" ");
    Serial.println(result3);
  delay(200);
}

the problem was that i touch de the electrodes on the copperside instead for the rearside

You need to provide more information. How have you wired the electrodes to the Arduino? Which library do you mean (provide a link to it)? And please show your code in your question. You can edit your question by clicking the "edit" link under it

is there a way using mutalcapactiance sensors without the qtouch lib   or do i have to use atmelstudio to use qtouch on my arduino zero


text:
How can I use Wemos D1's TX pin as OneWire?
I'm building a thermostat control with a Wemos D1 Mini. The ILI9341 display uses almost all the pins, and all I have left are the RX, TX, A0 and D0 pins. However I can't get any valid readings from these pins. According to the various wemos pinouts, I should be able to use RX/TX as onewire pins. As soon as I set the pin to a different one, and replace the wire there, I have correct readings. What am I missing with using these pins?
I'm connecting the display as stated in this arcticle: link
I also found this site which shows that I should be able to set these two pins as IO pins.
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <OneWire.h>
#include <DallasTemperature.h>

#ifndef STASSID
#define STASSID "wifiname"
#define STAPSK  "password"
#endif

const char* ssid = STASSID;
const char* password = STAPSK;

ESP8266WebServer server(80);

OneWire oneWire(1);
DallasTemperature sensors(&oneWire);

void handleRoot() {
  sensors.requestTemperatures();
  server.send(200, "text/plain", String(sensors.getTempCByIndex(0)));
}

void setup() {
  pinMode(1, FUNCTION_3);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }

  server.on("/", handleRoot);
  server.begin();
  sensors.begin();
}

void loop() {
  server.handleClient();
}

The documentation of the Wemos D1 mini states that the IO pins except the D0 pin have one wire functionality. I looked into the official PINout  https://wiki.wemos.cc/products:d1:d1_mini and found that TX and RX are not marked as IO pins. A0 is only marked analog. Your code does not contain any lines for the ILI display so I don't know how you used the other pins. Perhaps you could use the D0 pin instead of one of the others, that would then be free to use for the one wire access.

Yeah, but the same site says, that it has 11 IO pins, and this matches with this pinout diagram: https://www.luisllamas.es/wp-content/uploads/2018/09/pinout-wemos-mini-d1.png I'll update my question with containing the display pinout as well.

I do not trust that pin out diagram very much. They marked the 5V pin as GND. ;-) Seriously: I'm not an Wemos mini expert, so I hardly can argue against the 11 IO-Pin claim. But from the observation you told us, I would say, the RX and TX Pin might be unusable for your purposes. As the mini uses the ESP8266 in it's own context (i.e with an USB to Serial converter) which connects the RX/TX pins to another chip (CP2104 or so), this could/would make the RX/TX pins unusable for purposes other than UART communication. You can find schematics here https://escapequotes.net/wemos-d1-mini-pro/


text:
Can we burn Arduino bootloader into any microcontroller chip?
I am new to this Arduino community
I noticed on youtube that while the prototype is complete people purchase new ATmega328p chips and flash bootloaders into them using in-system-programmers so that the chip could actually understand and interpret the instructions that are written in the high-level language if I am right(No I was wrong, it's actually the compiler that sits on Arduino). so I thought what if we could burn the atmega328p bootloader into any other microcontroller. So that we could program it in Arduino programming language(C/C++). Is this possible? sorry if I am dumb, but I wanted to know. And can anyone tell me whether could we use ATmega328p for production purposes(consumer electronics)? Thanks in advance.

the purpose of the bootloader is to make upload of the code over UART possible. nothing else. the use of higher language possibility is provided by compiler

thanks @Juraj that really makes some sense

The compiler itself is not loaded on or run by the microcontroller. For compiled languages, like C, the compiler produces machine code that the microcontroller can run by itself. You're probably thinking of interpreted languages, like Python, that do require an interpreter to exist on whatever hardware is used to run the code.

You do realize it's quite simple to program an ATmega328p in C and other languages without Arduino, right? It's part of the megaAVR family and can be reached with the Atmel Studio.

The answer needs to have multiple parts:
Yes, in principle you can create a bootloader for any microcontroller, which acts like the Arduino's.
Please be aware that there are different bootloaders, not just the common STK500 compatible one. Each of these bootloaders implements a certain protocol to transfer the binary code to the target system.
Additionally, some protocols also include commands to restart the microcontroller, to set configuration registers, and maybe more.
You need to read the bootloader's documentation to become familiar with its capabilities.
But it is your decision whether such a bootloader on a non-AVR system or an non-Arduino-AVR system is good for you.
No, the bootloader does not enable the microcontroller to "understand" the high-level language.
The standard Arduino IDE uses the specific compiler for the target microcontroller to translate the C++ source code to machine language. The resulting binary commonly runs on this target microcontroller only.
The bootloader just implements the protocol. In general, it is completely unaware of the meaning of the transferred data.
Microcontrollers in general use different processors with possibly different machine languages, contain different kinds of memory of different sizes, include different sets of different peripherals. But you know this for sure. You need to write and compile your source code for the specific part you're targeting.
Yes, you can use ATmega328P for a consumer product, as Michel already said.
You need to take the common measures that you take with any part of your product, though.

Thank you so Much @the busybee . Now I completely understand about bootloaders and what actually they are meant for .  Your answer is ultimate ...

Upvoted your (better/detailed) answer. I was assuming (and still do) that he meant to upload an AtMega328 bootloader into any other MCU. You can (as you say) create a bootloader for any MCU acting like an Arduino, but those will be different kind of boatloaders per MCU (type).

Thanks a lot! Please keep your answer because of its details about selecting an MCU for production purposes. -- Your assumption about the OP might be right. ;-) But who knows who else comes around because of the question's title.

You cannot just load a sketch into any microcontroller, because every microcontroller has different memory layout, peripherals, ways of uploading, FLASH size etc.
You can use the atMega (or any microcontroller) for production purposes though. Of course each MCU type has operation conditions (like min/max temperature), so in e.g. automotive or military environments not all MCUs are allowed to be used, but for consumer electronics, afaik all MCUs can be used (meaning they will pass by themselves the needed certifications, which may not be true for components added and the circuit/enclosure resulting out of it).

Note: It's not Atmel who will stop you using all MCUs for all applications, it's your customers who will stop you. And for a consumer product, possibly the laws about what customers should be able to expect (so basically your customers).

@user253751 Thanks for this addition.


text:
Access Control System with an 4x3 Keypad & RFID-RC522
hey guys I have a access control system working perfect with rfid and keypad.
I would like to implement : If the PIN is entered more than 3 times incorrectly the card is disabled.
someone could give a help or a tip?
here is my code:  https://pastiebin.com/5e4c315d97d5e
#include <Keypad.h>                 // This sketch uses the Keypad.h library
#include <SPI.h>                    // This sketch uses the SPI.h library
#include <MFRC522.h>                // This sketch uses the MFRC522.h library

#define SS_PIN 10                   // Define SS_PIN of the RC522 RFID Reader to digital pin 10 of the Arduino
#define RST_PIN 9                   // Define RST_PIN of the RC522 RFID Reader to digital pin 9 of the Arduino
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.

int RedLed    = A3;                 // Red LED output is analog pin A3
int GreenLed  = A4;                 // Green LED output is analog pin A4
int Buzzer    = A5;                 // Buzzer output is analog pin A5
unsigned long Timer;                // Variable for the Timer

const byte ROWS = 4;                // Four rows
const byte COLS = 3;                // Three columns

char Keys[ROWS][COLS] = {           // Define the symbols on the buttons of the keypads
  {'1','2','3',},
  {'4','5','6',},
  {'7','8','9',},
  {'*','0','#',}
};

byte rowPins[ROWS] = {5, 4, 3, 2};  // Connect to the row pinouts of the keypad
byte colPins[COLS] = {8, 7, 6};     // Connect to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(Keys), rowPins, colPins, ROWS, COLS); // Initialize an instance of class NewKeypad

int RightCard;                      // Variable for a known Mifare Card
int RightPinCode;                   // Variable for valid key input in combination with a known Mifare Card
int WrongPinCode;                   // Variable for a invalid key input in combination with a known Mifare Card
int PinCodeCounter;                 // Variable Counter for counting the number of pincode inputs on the keypad

int Code1Correct;                   // Variable for the first correct digit (Code) input on the keypad
int Code2Correct;                   // Variable for the second correct digit (Code) input on the keypad
int Code3Correct;                   // Variable for the third correct digit (Code) input on the keypad
int Code4Correct;                   // Variable for the fourth correct digit (Code) input on the keypad
int Code5Correct;                   // Variable for the fifth correct digit (Code) input on the keypad
int Code6Correct;                   // Variable for the sixth correct digit (Code) input on the keypad
int Reset;                          // Reset for the loop

int MifareCard1;                               // We need this specific variable to determine the valid PinCode in combination with the UID nummer of the Mifare Card
const int Code1MifareCard1 = '6';              // Determine here the first digit of your 6 digit PIN
const int Code2MifareCard1 = '6';              // Determine here the second digit of your 6 digit PIN
const int Code3MifareCard1 = '6';              // Determine here the third digit of your 6 digit PIN
const int Code4MifareCard1 = '2';              // Determine here the fourth digit of your 6 digit PIN
const int Code5MifareCard1 = '2';              // Determine here the fifth digit of your 6 digit PIN
const int Code6MifareCard1 = '2';              // Determine here the sixth digit of your 6 digit PIN

int MifareCard2;                               // We need this specific variable to determine the valid PinCode in combination with the UID nummer of the Mifare Card
const int Code1MifareCard2 = '1';              // Determine here the first digit of your 6 digit PIN
const int Code2MifareCard2 = '1';              // Determine here the second digit of your 6 digit PIN
const int Code3MifareCard2 = '1';              // Determine here the third digit of your 6 digit PIN
const int Code4MifareCard2 = '3';              // Determine here the fourth digit of your 6 digit PIN
const int Code5MifareCard2 = '3';              // Determine here the fifth digit of your 6 digit PIN
const int Code6MifareCard2 = '3';              // Determine here the sixth digit of your 6 digit PIN

void setup()

{
  Serial.begin(9600);                                     // Initialize serial communications with the PC
  SPI.begin();                                            // Initialize the SPI bus
  mfrc522.PCD_Init();                                     // Initialize the MFRC522
  pinMode (RedLed, OUTPUT);                               // Define RedLed as OUTPUT
  pinMode (GreenLed, OUTPUT);                             // Define GreenLed as OUTPUT
  pinMode (Buzzer, OUTPUT);                               // Define Buzzer as OUTPUT
}

void loop() {

//----------------------------------------------Code for the reset function of the loop--------------------------------------------------------------------------------------------------------

if (Reset == 1)                                           // If Reset has value 1 (HIGH) all variables will be reset to 0 and the RC522 RFID reader will be waiting for a new Mifare Card.
{
  RightCard = 0;
  MifareCard1 = 0;
  MifareCard2 = 0;
  RightPinCode = 0;
  WrongPinCode = 0;
  Code1Correct = 0;
  Code2Correct = 0;
  Code3Correct = 0;
  Code4Correct = 0;
  Code5Correct = 0;
  Code6Correct = 0;
  PinCodeCounter = 0;
  delay (50);
  Reset = 0;
}

//----------------------------------------------Code for the control for a valid pincode within the timelimit of 7 seconds after presenting/offering a valid Mifare Card ---------------------------

if (millis()- Timer > 7000 && RightCard == 1)            // If the Timer will be larger as 7 seconds and a valid Mifare Card is offered, reset value will be high.
   {                                                     // This means that you have after presenting a valid card, 7 seconds to enter a valid code or the loop resets.
    Reset = 1;
    Serial.println("CardAccesOff");
   }

//----------------------------------------------Reading the presented/offered Mifare Card at the MFRC522 -----------------------------------------------------------------------------------------

if   (mfrc522.PICC_IsNewCardPresent() &&
      mfrc522.PICC_ReadCardSerial())
    {

//----------------------------------------------Code for detect the first Mifare Card in the Database. This is a UID number with 4 pairs of digits. Example: 69 7C 01 9C------------------------------------
     if
     (mfrc522.uid.uidByte[0] == 0x69   &&                // Fill in the first digits of the UID number of your Mifare card
      mfrc522.uid.uidByte[1] == 0x7C   &&                // Fill in the seconds digits of the UID number of your Mifare card
      mfrc522.uid.uidByte[2] == 0x01   &&                // Fill in the third digits of the UID number of your Mifare card
      mfrc522.uid.uidByte[3] == 0x9C)                    // Fill in the fourth digits of the UID number of your Mifare card

     {
      RightCard = 1;                                     // The offered Mifare Card is known in the database, set variable "RightCard" to 1
      MifareCard1 = 1;                                   // This Mifare Card is known as Mifare Card 2 in the Database, so set variable MifareCard2 to value 1.
      digitalWrite (Buzzer, HIGH);                       // Make a beep for the accepted Mifare Card
      delay (150);                                       //
      digitalWrite (Buzzer, LOW);                        //

      PinCodeCounter = 0;                                // Reset the PinCodeCounter to 0
      Timer =  millis();                                 // Reset the Timer. The 7 seconds limit is running now for a valid PinCode
      Serial.println("CardAccesOn");                     // Print the text "CardAccesOn" to the serial monitor
      delay (200);                                       // Wait 200 milliseconds
      }

//-----------------------------------------------Code for detect the second Mifare Card in the Database. This is a UID number with 4 pairs of digits. Example: EB 70 C0 BC----------------------------------------------
     if
     (mfrc522.uid.uidByte[0] == 0xEB   &&                 // Fill in the first digits of the UID number of your Mifare card
      mfrc522.uid.uidByte[1] == 0x70   &&                 // Fill in the seconds digits of the UID number of your Mifare card
      mfrc522.uid.uidByte[2] == 0xC0   &&                 // Fill in the third digits of the UID number of your Mifare card
      mfrc522.uid.uidByte[3] == 0xBC)                     // Fill in the fourth digits of the UID number of your Mifare card

    {
      RightCard = 1;                                       // If the offered Mifare Card is known in the database, set variable "RightCard" to 1
      MifareCard2 = 1;
      digitalWrite (Buzzer, HIGH);                         // Make a beep for the accepted Mifare Card
      delay (150);                                         //
      digitalWrite (Buzzer, LOW);                          //

      PinCodeCounter = 0;                                  // Reset the PinCodeCounter to 0
      Timer =  millis();                                   // Reset the Timer. The 7 seconds limit is running now for a valid PinCode
      Serial.println("CardAccesOn");                       // Print the text "CardAccesOn" to the serial monitor
      delay (200);                                         // Wait 200 milliseconds
    }

    }

//-----------------------------------------------Code for accepting a valid MifareCard + valid PinCode-------------------------------------------------------------------------------------------------

if (Code6Correct == 1 && RightCard == 1)                    // If the PinCode is the correct and you did enter this within 7 seconds
  {
    RightPinCode = 1;                                       // Variable RightPinCode will be set to 1

    digitalWrite (GreenLed, HIGH);                          // Make a nice beep for the correct Pincode and set the Green LED high for 1 second
    delay (150);                                            //
    digitalWrite (Buzzer, HIGH);                            //
    delay (150);                                            //
    digitalWrite (Buzzer, LOW);                             //
    delay (50);                                             //
    digitalWrite (Buzzer, HIGH);                            //
    delay (150);                                            //
    digitalWrite (Buzzer, LOW);                             //
    delay (500);                                            //
    digitalWrite (GreenLed, LOW);                           //

    Serial.println("Correct PinCode");                      // Print the text "Correct PinCode" to the serial monitor
    Reset = 1;                                              // Reset the loop
  }

//-----------------------------------------------Code for refusing a valid MifareCard + invalid PinCode------------------------------------------------------------------------------------------------

if ((Code6Correct == 0) && (PinCodeCounter >= 6) && (RightCard == 1))       // If you offered a valid Mifare Card and the Pincode is not correct and you already entered 6 digitkeys
  {
    WrongPinCode = 1;                                                       // Variable WrongPinCode will be set to 1
    Serial.println("WrongCode");                                             // Print the text "WrongKey" to the serial monitor
    Reset = 1;                                                              // Reset the loop
  }

//-----------------------------------------------Code for refusing a Wrong/Invalid PinCode or the Timer (7seconds) expired----------------------------------------------------------------------------

if ((WrongPinCode == 1) || (millis()- Timer > 7000 && RightCard == 1))      // If you offered a valid Mifare Card and  you entered a wrong PinCode or the timer (7 seconds) expires
  {
    digitalWrite (Buzzer, HIGH);                                            // Make a long beep and set the Red LED HIGH for the wrong code or timer expiry
    digitalWrite (RedLed, HIGH);                                           //
    delay(1500);                                                            //
    digitalWrite (Buzzer, LOW);                                             //
    digitalWrite (RedLed, LOW);                                             //

    Serial.println("WrongCode or Timer expired");                           // Print the text "WrongCode or Timer expired" to the serial monitor
    Reset = 1;                                                              // Reset the loop
  }

//-----------------------------------------------Code for counting the inputs on the keypad----------------------------------------------------------------------------------------------------------

char KeyDigit = keypad.getKey();                                           // Get the DigitKey from the keypad

if ((RightCard == 1) &&                                                    // If you offered a valid Mifare Card and any DigitKey on the keypad is pressed
    ((KeyDigit == '1') ||
    (KeyDigit == '2')  ||
    (KeyDigit == '3')  ||
    (KeyDigit == '4')  ||
    (KeyDigit == '5')  ||
    (KeyDigit == '6')  ||
    (KeyDigit == '7')  ||
    (KeyDigit == '8')  ||
    (KeyDigit == '9')  ||
    (KeyDigit == '0')  ||
    (KeyDigit == '*')  ||
    (KeyDigit == '#')))

    {
      PinCodeCounter++;                                                       // PinCodeCounter value +1 for every press on any Digitkey on the keypad
      digitalWrite (Buzzer, HIGH);                                            // Make a short beep for a DigitKey press on the keypad
      delay (50);                                                             //
      digitalWrite (Buzzer, LOW);                                             //
    }

//-----------------------------------------------Code for determine the correct PinCode for MifareCard1----------------------------------------------------------------------------------------------------------

if ((KeyDigit == Code1MifareCard1) && (RightCard == 1) && (Code1Correct == 0) && (MifareCard1 == 1))           // If you offered the valid MifareCard1, first PinCode and you did not entered it before (Otherwise we conflict with same KeyDigits)
    {
      Code1Correct = 1;                                                                                // Variable Code1Correct is set to 1
      return;                                                                                // Return to begin loop
    }

if ((KeyDigit == Code2MifareCard1) && (Code1Correct == 1) && (Code2Correct == 0) && (MifareCard1 == 1))        // If you offered the valid MifareCard1, second PinCode and you did not entered it before (Otherwise we conflict with same KeyDigits)
    {
      Code2Correct = 1;                                                                                // Variable Code2Correct is set to 1
      return;                                                                                // Return to begin loop
    }

if ((KeyDigit == Code3MifareCard1) && (Code2Correct == 1) && (Code3Correct == 0) && (MifareCard1 == 1))         // If you offered the valid MifareCard1, third PinCode and you did not entered it before (Otherwise we conflict with same KeyDigits)
    {
      Code3Correct = 1;                                                                                // Variable Code3Correct is set to 1
      return;                                                                                // Return to begin loop
    }

if ((KeyDigit == Code4MifareCard1) && (Code3Correct == 1) && (Code4Correct == 0) && (MifareCard1 == 1))         // If you offered the valid MifareCard1, fourth PinCode and you did not entered it before (Otherwise we conflict with same KeyDigits)
    {
      Code4Correct = 1;                                                                                // Variable Code4Correct is set to 1
      return;                                                                                // Return to begin loop
    }
if ((KeyDigit == Code5MifareCard1) && (Code4Correct == 1) && (Code5Correct == 0) && (MifareCard1 == 1))         // If you offered the valid MifareCard1, fifth PinCode and you did not entered it before (Otherwise we conflict with same KeyDigits)
    {
      Code5Correct = 1;                                                                                // Variable Code5Correct is set to 1
      return;                                                                                // Return to begin loop
    }

if ((KeyDigit == Code6MifareCard1) && (Code5Correct == 1) && (Code6Correct == 0) && (MifareCard1 == 1))         // If you offered the valid MifareCard1, sixth PinCode and you did not entered it before (Otherwise we conflict with same KeyDigits)
    {
      Code6Correct = 1;                                                                                // Variable Code6Correct is set to 1
      return;                                                                                // Return to begin loop
    }

//-----------------------------------------------Code for determine the correct PinCode for MifareCard2----------------------------------------------------------------------------------------------------------

if ((KeyDigit == Code1MifareCard2) && (RightCard == 1) && (Code1Correct == 0) && (MifareCard2 == 1))              // If you offered a the valid MifareCard2, first PinCode and you did not entered it before (Otherwise we conflict with same KeyDigits)
    {
      Code1Correct = 1;                                                                                // Variable Code1Correct is set to 1
      return;                                                                                // Return to begin loop
    }

if ((KeyDigit == Code2MifareCard2) && (Code1Correct == 1) && (Code2Correct == 0) && (MifareCard2 == 1))           // If you offered a the valid MifareCard2, second PinCode and you did not entered it before (Otherwise we conflict with same KeyDigits)
    {
      Code2Correct = 1;                                                                                // Variable Code2Correct is set to 1
      return;                                                                                // Return to begin loop
    }

if ((KeyDigit == Code3MifareCard2) && (Code2Correct == 1) && (Code3Correct == 0) && (MifareCard2 == 1))           // If you offered a the valid MifareCard2, third PinCode and you did not entered it before (Otherwise we conflict with same KeyDigits)
    {
      Code3Correct = 1;                                                                                // Variable Code3Correct is set to 1
      return;                                                                                // Return to begin loop
    }

if ((KeyDigit == Code4MifareCard2) && (Code3Correct == 1) && (Code4Correct == 0) && (MifareCard2 == 1))          // If you offered a the valid MifareCard2, fourth PinCode and you did not entered it before (Otherwise we conflict with same KeyDigits)
    {
      Code4Correct = 1;                                                                                // Variable Code4Correct is set to 1
      return;                                                                                // Return to begin loop
    }
if ((KeyDigit == Code5MifareCard2) && (Code4Correct == 1) &&  (Code5Correct == 0) && (MifareCard2 == 1))         // If you offered a the valid MifareCard2, fifth PinCode and you did not entered it before (Otherwise we conflict with same KeyDigits)
    {
      Code5Correct = 1;                                                                                // Variable Code5Correct is set to 1
      return;                                                                                // Return to begin loop
    }

if ((KeyDigit == Code6MifareCard2) && (Code5Correct == 1) &&  (Code6Correct == 0) && (MifareCard2 == 1))         // If you offered a the valid MifareCard2, sixth PinCode and you did not entered it before (Otherwise we conflict with same KeyDigits)
    {
      Code6Correct = 1;                                                                                // Variable Code6Correct is set to 1
      return;                                                                                // Return to begin loop
    }

}

thank you very much.

Add  int passCount = '0'; to the top of your file and then increment that value by one every time the wrong password gets entered (For example replace Reset = 1; with passCount ++; on line 199)
And add passCount = '0' to your reset on line 85.
And add another if statement to reset loop if password has been entered more than 3 times. if (passCount == 3) {Reset = 1;}
Hope this helps :-)
EDIT:
You can comment out/delete the If statement on lines 222 - 232 if ((WrongPinCode == 1) || (millis()- Timer > 7000 && RightCard == 1)).
And add your Buzzer and Led code to the if statement above (same statement with passCount ++; in it)
The timeout reset will be take care of code on lines 108 - 112.

did not work :(

@raduken The idea of David seems correct to me. But: I would use int passCount = 0; instead of const int passCount = '0';. The const makes the variable immutable and '0' is not the digit zero but the character zero so you start the count with '0' = 48. Likewise you should reset the variable with passCount = 0 instead of passCount = '0'.

did not work, my code gets in a loop and never stops :(, could you help me? thank you

@raduken Add some outputs at strategic places. Follow the logic and the contents of variables with them. Invest some thinking, try to understand. This is one kind of debugging.

1.initialize a global variable int failcount=0,MiFareCardMode=0;

for reset put it in an if statement that checks fail count

   if(failcount==0)
                {reset code}```

in this piece of code increase the failcount number(line 195:200)
also add an if statement to check which card was detected
initialize a global variable to set the card status
MiFareCardMode(0=unblocked,1=card1 block,2=card2 block)

if ((Code6Correct == 0) && (PinCodeCounter >= 6) && (RightCard == 1))
  {
    WrongPinCode = 1;
    Serial.println("WrongCode");
    Reset = 1;
    failcount++       ///here increase the value with each wrong password
    if (failcount>=3)
     {   if(MifareCard1==1)
              MifareCardMode=1; ///create a variable for mode (blocked OR non blocked)
         if(MiFareCard2==1)
               MifareCardMode=2;
}
 failcount=0; }

4.In lines 125:142 put them in an if statement which check the variable MiFareCardMode
       if(MiFareCardMode==0)
                 {
                    lines 125 to 142
                    }
         if(MiFareCardMode==1)
                   { Serial.println("Card 1 blocked permanently");
                    //add anything you want to do after blocking }

4.In lines 146:163 put them in an if statement which check the variable MiFareCardMode for card 2
    if(MiFareCardMode==0)
          {   lines 146:163  }
    if(MiFareCardMode==2)
           {Serial.println("Card2 blocked permanently");}

Please format your answer correctly, so that it readable.

i got a bit confused, do you mind put all this code in a pastebin please? thank you.

Your code written more complex, than it has to be, and you have much repeated code, that makes it harder to understand and change the code. So I will first describe, how to shorten and generalize your code. That will make it easier to implement new features, like invalidating a card after 3 wrong PIN entries.

Handling the RFID cards: Currently you are using single variables for each card (for example RightCard). Your if statements all have to reference these single variables for each card, which makes it hard to not write repeated code. Instead you should use arrays to store the information. See this piece of code:
#define MAX_CARD_N        2
#define SERIAL_LENGTH     4
uint8_t card_serials[MAX_CARD_N][SERIAL_LENGTH] = {
    {0x69, 0x7C, 0x01, 0x9C},
    {0xEB, 0x70, 0xC0, 0xBC}
};

#define PIN_LENGTH        6
char card_pins[MAX_CARD_N][PIN_LENGTH] = {
    {'6','6','6','2','2','2'},
    {'1','1','1','3','3','3'}
};

int current_card = -1;
uint8_t current_pin_position = 0;
bool pin_correct = true;

What happens here? First we set defines for later use, where we can centrally set the number of cards, that we want to use, and the length of their serial data. Then we declare a 2 dimensional array, which stores the serial for each card (for example in a loop). We can now access the serials of the cards by simple integer indices. Then we do the same with the PINs of these cards. (And declare variables for holding the current card index, the current pin position and the correctness of the pin for later use.) We can implement a function, that will give us the index of the currently scanned card in our card arrays:
int find_card(){
    if(mfrc522.uid.uidByte[0] == 0x00) return -1;
    for(uint8_t card_index=0; card_index < MAX_CARD_N; card_index++){
        uint8_t found_card_flag = 1;
        for(uint8_t serial_index=0; serial_index < SERIAL_LENGTH; serial_index++){
            if(card_serials[card_index][serial_index] != mfrc522.uid.uidByte[serial_index]){
                found_card_flag = 0;
                break;
            }
       }
       if(found_card_flag){
           return card_index;
       }
   }
   return -1;
}

This function will return -1, if the scanned card serial can not be found in our card_serials array. If it was found, the function returns the index of the card. I also added an if statement at the start, that forbids to find cards with the first element being zero, which will come in handy at a later time (I only used the first element here for making it easy, but you can also check every of the 4 serial bytes, if you want to forbid zeros everywhere in the serial).
Organizing your code: Currently you have many individual if statements, which all need extra variables, so that you can execute the right code at the right situation. A better approach for something like this is a Finite State Machine (FSM). It is an important concept, that sound more difficult, than it is. Basically you divide your code into different states, where specific things should happen. Actions or specific situations can do a transition to a different state. Every state only executes it's own code. The current state is held in a variable, called state variable. In my answer to this question I already explained the principle in detail (including some graphs). You should really learn this principle; it changed my coding style completely for better.
I would use 2 different states: WAIT_FOR_CARD and WAIT_FOR_PIN, so that we can seperate the RFID and the keypad code. Look at this piece of code:
enum State {WAIT_FOR_CARD, WAIT_FOR_PIN};
State state = WAIT_FOR_CARD;

void loop() {
    switch(state){
      case WAIT_FOR_CARD:
          if(mfrc522.PICC_IsNewCardPresent() &&
             mfrc522.PICC_ReadCardSerial()){
              int scanned_card = find_card();
              if(scanned_card != -1){
                  current_card = scanned_card;
                  current_pin_position = 0;
                  code_correct = true;
                  // Insert code for correct card in here (buzzer, setting timestamp, ...)
                  state = WAIT_FOR_PIN;
              } else {
                  // Insert code for incorrect card in here
              }
          }
          break;
      case WAIT_FOR_PIN:
          char KeyDigit = keypad.getKey();
          if(KeyDigit != NO_KEY){
            if(KeyDigit != card_pins[current_card][current_pin_position]) pin_correct = false;
            current_pin_position++;
            if(current_pin_position >= PIN_LENGTH){
                if(pin_correct){
                    // Insert code for correct pin in here
                } else {
                    // Insert code for wrong pin in here
                }
                current_card = -1;
                state = WAIT_FOR_CARD;
            }
          }
          break;
    }
}

We first define our states as an enum, since this makes the code more readable. Then we declare a state variable from that enum. In the loop() function we use a switch case statement to execute the code corresponding to the current state. In the WAIT_FOR_CARD state, we are constantly scanning for a new card. If we found one, we check with the find_card() function, if we have the serial of this card saved in our array. If yes, we set our variables accordingly, execute the needed code for a valid card and then set the state variable to the next state. The break will get us out of the switch statement, but on the next loop iteration, we are now executing the other case (since we changed the state variable). We are now constantly checking for a pressed key. If the pressed key was not the one defined in our PIN array for the current position, we set pin_correct to false (If every key is correct, it will stay true. If any is incorrect, it will get set to false). We increment the PIN position and then check if we reached the end of the PIN, where we decide, if the PIN was correct or not, doing the appropriate things, and at the end reset our current_card variable and the state variable. (I left out the timeout feature. When you have understood the FSM principle, it should be easy to add this to the code.)
This code is better structured and way shorter. Also it can easily handle extensions (more cards, other functions,...). You can add more states and transitions to insert new features.
Disabling cards on 3 wrong pin entries: I assume, that you want, that 3 incorrect PIN entries will disable the RFID card, so that it is no longer accepted as valid. For that you could remove the corresponding serial from the card_serials array. First we need to track the number of consecutive wrong PIN entries. For that I would use another array and a define for the max number of wrong entries (here 2, since 2 wrong entries are still allowed; the third wrong entry will trigger the invalidation of the card):
uint8_t pin_strikes[MAX_CARD_N] = {0};
#define MAX_STRIKES    2

When we have a wrong PIN, you can increment this counter by 1:
pin_strikes[current_card]++;

When we have a correct PIN, we want to reset this counter:
pin_strikes[current_card] = 0;

After incrementing in the case of a wrong PIN we can check, how many times the pin was already wrong consecutively, and then remove the serial, if it was too much:
if(pin_strikes[current_card] > MAX_STRIKES){
    for(uint8_t i=0; i < SERIAL_LENGTH; i++) card_serials[current_card][i] = 0;
    current_card = -1;
}

We should reset the current_card variable here, since this index doesn't point to a valid card anymore. We can invalidate the card by setting the serial to zero, since we ruled out all card with a zero in the first byte at the start of the find_card() function.

many thanks for your time and explanation, i got a bit confused, do you mind put all this code in a pastebin please? thank you.

@raduken Why should I copy above code into a pastebin? You can copy the code from the question. Or do you ask for a full working code? If yes, then you will be disappointed. I don't have a full working code. I habe written the above snippets solely for this answer. It is your part to put that all together. If something in my answer is confusing, please explain what exactly, and I will try to explain it better