text:
Modifying smart watch or activity armband with further sensors
I want something like an activity armband where I would like to add an bend sensor or EMG sensor for simple hand gesture recognition tasks. I could probably build it from scratch with arduino-like parts, but it will be much more bulky then the ones on the market and I would rather not reinvent those things that already do what I want. This is the type of device I am thinking about.
Is there an feasible task to try to modify an existing activity armband or smart watch by adding one of these sensors? If so, do you have any suggestions of what should be considered? Should I try something completely different? I am open to ideas.
I have a background in Physics and Computer Science with an basic understanding of electronic devices but I am eager to learn.

there are a few DIY, open source armband or watch models like :
https://www.tindie.com/products/ttgo/t-wristband-diy-programmable-smart-bracelet/
which has the sources and tutorials on :
https://github.com/Xinyuan-LilyGO/LilyGO-T-Wristband
it's based on ESP32 and is Arduino ready.the space constraint may not allow for adding a new sensor, but it already comes with a few onboard sensors.
after getting along with ESP32 and the TTGO libraries (which are all provided by the manufacturer LilyGo) that wouldn't be too hard to design a custom band.


text:
Typedef struct not working
I made this simple code but I'm getting the following error
exit status 1
'RGB' does not name a type

typedef struct
RGB
{
        double r;
        double g;
        double b;
};

RGB led;

RGB func(){
  RGB temp;
  return RGB;
}

I am not getting the error on "RGB led" but just on the function.
Does anyone know a solution for this? Thanks!

The typedef syntax is "typedef [known type] [new name];" so RGB would go after the closing brace of the structure definition. Or see @edgarbonet's post for another alternative.

In plain C, structs are identified by "struc tags", which do not live in
the same namespace as type names. Thus, if you declare
struct RGB {
    ...
};

a variable of this type should be declared as
struct RGB led;

In order to avoid the inconvenience of repeatedly typing struct, a
common idiom is to define it as a type:
typedef struct {
    ...
} RGB;

RGB led;

The Arduino environment, however, is based on the C++ programming
language. In C++ struct tags are types, and you thus do not need the
typedef:
struct RGB {
    ...
};

RGB led;

This is the recommended idiom in C++: just remove the typedef.

There are 2 errors:
you are returning a class type, and not the temp object
  RGB func(){
    RGB temp;
    return RGB; --> return temp;
  }

To use your typedef you should put the struct "name" after the braced parenthesis:
typedef struct
{
    double r;
    double g;
    double b;
} RGB;

This works, thanks!

source: Stack Exchange

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

sort: votes


text:
Arduino Measuring Microwave Leakage
I want to measure if my microwave has a leakage using Arduino. Ideally, I would like to get the exact number measured by mW/cm2 (similar to HT-M2 devices). Any advice which Arduino module can do it?

No Arduino can do it. Instead a microwave detector will do it, and the Arduino will control it and process the data.

@Majenko, that's what the OP asked. "Any advice which Arduino module can do it?". They are looking for Arduino compatible components that will measure microwave radiation. Personally, I have no idea if there are microwave measurement devices that have serial interfaces that are easy to connect to an Arduino. I will say that a quick search on HT-M2 revealed dedicated Microwave leakage detectors for less than $15 US. You're not going to compete with that.

@Davithbul, post a link to a microwave detector datasheet and someone here will be able to tell you if the detector is arduino compatible

@DuncanC you are right price wise HT-M2 is not expensive, but for my use case, I need to monitor constantly using some microcontroller - Arduino or Raspberry Pi.

@jsotola I was not able to find the datasheet for HT-M2, but I will still look for it. Thank you for advice.

you asked about a module that can be used with an Arduino ... the HT-M2 is not a module, it is a self contained device

@jsotola Right, I meant maybe it would be possible to understand which exact module does HT-M2 use and use the same module to connect from Arduino.

it probably does not use a standalone module that you could extract from the device ... it probably contains a "front end" of a radio receiver ... just an antenna, a tuned circuit and a demodulator ... the output of the circuit is a voltage level that varies with signal strength

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


text:
Uploading a sketch without using the usb cable
I've lost my usb cable used to upload a Sketch to my arduino from my laptop. I do have my Bluetooth 4.0 module. Can I use it to upload my sketches?

What bluetooth module is is exactly?

You can use the ICSP pins, but you can't drive those with Bluetooth. https://www.arduino.cc/en/tutorial/arduinoISP

In your case, it would be easier to buy a new cable. But you asked a very interesting question in general. I'll have to think about it. Some thoughts: If you did not connect the USB to Serial part of the Arduino, you should be able to connect the RX and TX pins of the Arduino to the Bluetooth module (if the module is connectable to an UART see @chrisl s comment) ). Then you need a driver on the Laptop that simulates the Bluethooth connection to the Module as a COMx port (like to USB to SERIAL driver does). Possibly you need access to the reset pin also.

Specifically I asked about the module, because every bluetooth slave device will give the master specific endpoint types (could be audio, HID or Serial interface for example). Devices like HC-06 and HC-05 will present Serial interface endpoints. The OS of the PC should then handle the bluetooth device accordingly and create a virtual com/serial port for it, that you can use. But we currently cannot know, if your bluetooth module does this.

I think @chrisl explained it well.  In case you did not understand, inside Bluetooth, like inside USB, there exists many protocols that people do not think about as the computers "just take care of it".  You would need to use the Bluetooth serial port protocol on your computer and have on hand some sort of Bluetooth adapter hardware that supports the Bluetooth serial protocol complete with serial port wires that are logic level compatible with the particular Arduino processor you are using.  However, after thinking about all that, clearly, it would be much easier to purchase a new USB cable.


text:
ds3231 rtc module weekly alarm
I have a ds3231 and Arduino UNO and I need to get an interrupt from ds3231 once a week for example every Fridays. I've searched a lot in the internet and forums but did not find any library or code that have weekly alarm or some of them that had, they didn't work well.
I also read the data sheet of ds3231 but didn't understand how to set the registers of it.
can anyone help?

check the DS3231 libraries in IDE in "Manage Libraries"

I never really like using the "alarm" function of the DS3231. I'd just check the data and time every loop (, or every few seconds). See if the day-of-week is different from the previous time I check. If so, and the day-of-week is Friday, run the code. This way you can have as many "alarms" as you want instead of using the (I think) two alarms in the DS3231.

Are you using the /INT/SQW pin of DS3231 to trigger the alarm?

@smajli  Yes Im using that.


text:
Check if the board is in sleep mode
I'm using seep sleep mode with UNO with a simple sketch that turning on an LED and then goes to sleep. as far as the ATmega328p datasheet in sleep mode part showing the wake up sources and deactivated clock sources in deep sleep mode and the I/O clock becomes deactivate so we expect when the board goes to sleep the LED should become off because of no clock. but it doesn't happen and LED keeps ON in sleep mode. what is the problem?7 and how can we even find out that the board is on sleep mode or not?

Why do you think, that the output will be turned off, when going to sleep? As of my understanding, the value of the pin cannot change in sleep, since the latch does not have a clock signal. But that doesn't mean, that the output is turned off.

use the LED to indicate sleep mode ... turn off led upon wakup

The IO doesn't require the clock to keep its current state. It only requires it to change state.
There is no real external signal provided by the chip to indicate if its in sleep mode or not. However you could monitor the current consumption of the chip and when it drops below a certain threshold you can assume that it is in sleep mode.

You could easily set the LED output LOW just before you call going_to_sleep(), and set it HIGH when going_to_sleep() returns. There would be two short periods where the LED signal would indicate sleeping but the processor is running:

between the LED going LOW and the processor actually entering sleep; and
between the processor waking and the LED going HIGH.

But at these times the processor could not respond to your external system anyway.


text:
Arduino Nano Fried on Music Reactive Led Strip
I'm doing a project that involves an Arduino Nano, a sound detection microphone module and a RGB Led strip (individually adressable leds). I also bought an accumulator so I can connect everything straight to the outlet.
The problem is that on 12V this accumulator cannot power the led strip at all and when I connected it to the laptop the Nano micro USB fried after I did about 4 tests.
My question is why can't the accumulator power everything and why the Nano got fried from the laptop which should have even less power? Would an Arduino Mega solve the problem or is it something about the wiring? (the wiring was checked by someone with experience)

How big is your strip (how many LEDs)? And are you providing it with power through the Arduino?

what is an accumulator?

I assume you are powering the Nano through VIN or USB, and you are then powering the LED strip from the Nano's 5V pin.

From the 12V battery the current flows through an LM1117 linear voltage regulator. Draw too much current (>800mA) and it will overheat and either shut down (if it's a good one) or melt (if it's an inferior Chinese clone).
From USB the current flows through an SS1P3L diode with a maximum rating of 1.5A. If you draw more than that you will blow the diode and the board will appear dead.

So basically you're drawing too much current.
The proper way of powering a setup like this is:

USB connection to power the Arduino only
12V into a 5V switching ("buck") regulator rated for at least the maximum current the LED strip needs
5V switching regulator into the LED strip directly
Connect the ground of the 5V to the ground of the Arduino

or

12V into a 5V switching ("buck") regulator rated for at least the maximum current the LED strip needs
5V switching regulator into the LED strip directly
5V switching regulator also to the 5V (and ground) pin of the Arduino to power the Arduino

or
As above but with a 5V power supply instead of the 12V and switching regulator
Note that it is important that your supply can provide you with at least as much current as the peak current your system will need.  If that is a problem then you can split the LED strip into chunks and power each chunk separately from a lower current supply.


text:
ESP32 Cannot assign value to string. Getting wrong value
Hello I have problems with strings in my sketch. I assingn values to my string (for example tempStrReturn) in the functions setNr1, setNr2. If i pass the value 1 to the function i get "" or "application/x-www-form-urlencoded" when there should be 1. I don't understand why this is happening.
If you see the output printout from the function setNr1 i get "" then after assigning the value (nr1+"") to the tempStrReturn i still get "". After i use the tempStrReturn in the setNr2 function it asigns a mishmash value to it.
I dont use the tempStrReturn, she is just there for showing the error. When i change the int values of nr1 or nr2 that i want to assign to the string, the value mishmash in the strings changes. With the same numbers the string value has always the same mishmash.
OUTPUT:
192.168.43.140
Function setNR1............
Got: 0
NR1 int: 0
tempStrReturn before:
tempStrReturn after:
Function setNR2............
Got: 1
NR2 int: 1
tempStrReturn before:
tempStrReturn after: application/x-www-form-urlencoded
Function setID...........
String id: ID
Set msgId to: 0
Set msgPos to: 1
Function setNR1............
Got: 1
NR1 int: 1
tempStrReturn before: ID
tempStrReturn after: application/x-www-form-urlencoded
Function setNR2............
Got: 1
NR2 int: 1
tempStrReturn before: application/x-www-form-urlencoded
tempStrReturn after: application/x-www-form-urlencoded
Function setH...........
nr1: 1
nr2: 1
Created value: 11
Original value in string: 0
nrX: 0 nrPos: 1 Value i want to enter: n/x-www-form-urlencoded
Value afther assignment: n/x-www-form-urlencoded

MY CODE:
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <FS.h>
#include <Wire.h>

const char* ssid = "Ti";
const char* password = "1234567891234";
// Stores LED state
String ledState;
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);

#define ledPin 2  //BuiltInLed is inverted
#define countMax 2500
#define multiplyMax 100
int count = 0, multiply = 0, msgDel = 0;
int nr1=0, nr2=0,msgPos, msgId, msgVar;
String inOut[10][10];
String tempStr1, tempStr2, tempStrReturn;
bool oneShot = false;

//***************************************

/*Set value of String[] on the nrPos to val*/
void inOutSet(int nrX, int nrPos, String val)
{
  Serial.print("Original value in string: "); Serial.println(inOut[nrX][nrPos]);
  Serial.print("nrX: ");Serial.print(nrX);Serial.print(" nrPos: ");Serial.print(nrPos);
  Serial.print(" Value i want to enter: "); Serial.println(val);
  inOut[nrX][nrPos] = val;
  Serial.print("Value afther assignment: ");Serial.println(inOut[nrX][nrPos]);
}

String inOutGet(int nrX, int nrPos)
{
  return inOut[nrX][nrPos];
}

String dataRequest(int roomNr)
{
  tempStrReturn = "";
  Serial.println("Preparing to send data as word...");
  Serial.print("Value in TempStringReturn before: "); Serial.println(tempStrReturn);
  tempStrReturn = "g" + roomNr;
  tempStrReturn = tempStrReturn+".";
  Serial.print("Adding g and . : "); Serial.println(tempStrReturn);
  nr1 = 0; nr2 = 0;

  for (int i = 0; i < 9; i++)
  {
    Serial.print("Data Request: "); Serial.println(msgId);
    tempStrReturn = tempStrReturn+inOut[roomNr][i];
    Serial.print("Ading value from inOut: "); Serial.println(tempStrReturn);
  }
  Serial.print("Returning value: ");
  Serial.println(tempStrReturn);

  return tempStrReturn;
}

//saves value to nr1 as int
String setNr1(String var)
{
  Serial.println("Function setNR1............");
  Serial.print("Got: "); Serial.println(var);
  nr1 = var.toInt();
  Serial.print("NR1 int: "); Serial.println(nr1);
  Serial.print("tempStrReturn before: "); Serial.println(tempStrReturn);
  tempStrReturn = nr1+"";
  Serial.print("tempStrReturn after: "); Serial.println(tempStrReturn);
  return nr1+"";
}

//saves value to nr2 as int
String setNr2(String var)
{
  Serial.println("Function setNR2............");
  Serial.print("Got: "); Serial.println(var);
  nr2 = var.toInt();
  Serial.print("NR2 int: "); Serial.println(nr2);
  Serial.print("tempStrReturn before: "); Serial.println(tempStrReturn);
  tempStrReturn = nr2+"";
  Serial.print("tempStrReturn after: "); Serial.println(tempStrReturn);
  return nr2+"";
}

//Creates values for the array
String setID()
{
  Serial.println("Function setID...........");
  msgId = nr1;
  msgPos = nr2;
  nr1 = 0; nr2 = 0;
  tempStrReturn = "ID";
  Serial.print("String id: "); Serial.println(tempStrReturn);
  Serial.print("Set msgId to: "); Serial.println(msgId);
  Serial.print("Set msgPos to: "); Serial.println(msgPos);
  return "ID";
}

//Creates value from nr1 and nr2
String setH()
{
  Serial.println("Function setH...........");
  msgVar = (nr1*10)+nr2;
  Serial.print("nr1: "); Serial.println(nr1);
  Serial.print("nr2: "); Serial.println(nr2);
  nr1 = 0; nr2 = 0;
  if (msgVar >= 99)  {  msgVar = 100;  }
  Serial.print("Created value: "); Serial.println(msgVar);
  inOutSet(msgId, msgPos, msgVar+"");
  return "H";
}

String getIO()
{
  nr1 = nr1/10;
  return dataRequest(nr1);
}

String processor(const String& var){
  Serial.print("Processor in: ");  Serial.println(var);
  return var;
}

void setup() {
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
  Serial.begin(9600);

  //Filling the inOut array
  for (int i = 0; i < 10; i++)
  {
    for (int x = 0; x < 10; x++)
    {
      inOut[i][x]= "0";
    }

  }

  if(!SPIFFS.begin()){Serial.println("\nSPIFFS chyba!"); return;}

  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }

  // Print ESP32 Local IP Address
  Serial.println(WiFi.localIP());

  // Route for root / web page
  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(SPIFFS, "/index.html", String(), false, processor);//change
  });

  //route to favicon
  server.on("favicon.ico", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(SPIFFS, "/favicon.png", "image/png");
  });

  // Route to load style.css file
  server.on("/style.css", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(SPIFFS, "/style.css", "text/css");
  });

  // Route to javascript
  server.on("/main.js", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(SPIFFS, "/main.js", "text/javascript");
  });

// Nr1 of the msg
  server.on("/0", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr1("0").c_str());
  });
  server.on("/1", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr1("1").c_str());
  });
  server.on("/2", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr1("2").c_str());
  });
  server.on("/3", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr1("3").c_str());
  });
  server.on("/4", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr1("4").c_str());
  });
  server.on("/5", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr1("5").c_str());
  });
  server.on("/6", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr1("6").c_str());
  });
  server.on("/7", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr1("7").c_str());
  });
  server.on("/8", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr1("8").c_str());
  });
  server.on("/9", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr1("9").c_str());
  });
// Nr2 of the msg
  server.on("/X0", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr2("X0").c_str());
  });
  server.on("/X1", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr2("X1").c_str());
  });
  server.on("/X2", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr2("X2").c_str());
  });
  server.on("/X3", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr2("X3").c_str());
  });
  server.on("/X4", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr2("X4").c_str());
  });
  server.on("/X5", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr2("X5").c_str());
  });
  server.on("/X6", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr2("X6").c_str());
  });
  server.on("/X7", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr2("X7").c_str());
  });
  server.on("/X8", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr2("X8").c_str());
  });
  server.on("/X9", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setNr2("X9").c_str());
  });
//end commands for use the nr values
  server.on("/ID", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setID().c_str());//Set ID nr
  });
  server.on("/H", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", setH().c_str());//Set value to id
  });
  server.on("/G", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", getIO().c_str());//Get value
  });

  // Start server
  server.begin();
}

/*-------------LOOP---------------*/
void loop() {
  count++;
  if (count > countMax)  {    multiply++; count = 0;  }
  if (multiply > multiplyMax)
  {
    if (!oneShot)
    {
      setNr1("0");
      setNr2("1");
      setID();
      setNr1("1");
      setNr2("1");
      setH();
      oneShot = true;
    }

    if (nr1 != 0 || nr2 != 0)
    {
      msgDel++;
      if (msgDel > 5)
      {
        nr1 = 0; nr2 = 0;
        Serial.println("DELETING...");
        msgDel = 0;
      }

    }

    //delay(60000);
    multiply = 0;
  }
}

Also posted at StackOverflow

nr1+"" is not how you convert an integer to a String. All you are doing there is taking the value of nr1 and adding it to the address of a string constant that consists of just a \0. Then assigning that to a String.
The results of such an operation are undefined.
Instead you should go:
tempStrReturn = String(nr1);

which will create a new String object, populate it with the text representation of the value of nr1 then copy that content into the tempStrReturn String.
However I would recommend avoiding using String, even on a chip as capable as the ESP32. Instead use C strings (NULL terminated character arrays) which are far less wasteful of resources.

My point is to add it to a String array. In the function setH i add it via inOutSet() to the two dimensional array inOut[][]. I then send a string message to my website that is completed in dataRequest(). It adds part of the array to one string that i send back to my website. I know that String is a little bit overkill for the poor processor. Any better idea?

Why use strings at all? You have numbers. Store them as such. You only care about them being stringified when you construct your HTTP request.

80%of the values are numbers but not all. I wanted to have one inOut array with all my values. I try to make a web gui. This inOut array will store the values of Analog values, digital values or messages like "Something overfilled". I created the Website and the javascript so that i doesnt need to change the html, css or javascript. All i need to do is to program the sketch.

Do you really need to store the text "Something overfilled" in your array? Why not just a simple flag that says something overfilled, then when you construct your request you say "Is the something overfilled flag 1? Yes? Ok, send 'something overfilled'".

I use it as addresses. inOut[0][1] is the first item on the first page. It should be modular. I don't know in advance which address will be int and which string or what will be the text in it

I understand now The array should be int and only when i complete the string request i add the messages. Thank you I will do so. You helped me alot


text:
I2C comunication, ESP->Nano on endTransmission no ACK fron nano
i am trying to communicate between ESP(master) and arduino nano(slave). This is only a prototype and all works fine. But i want to  add multiple arduinos and therefor i need to detect if the arduino is connected.
I use the return function from wire.endTransmission as shown in i2c scanner to detect devices. But it doesnt work.
On the arduino i have this program:
#include <Wire.h>

const int16_t I2C_SLAVE = 0x22; // 0x22 = 34 cize izba 3(30)

void setup() {
  Wire.begin(I2C_SLAVE);

}

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

}

on the ESP i am trying this:
Wire.beginTransmission(I2C_adress[adress]);
int error = Wire.endTransmission();

Serial.println(error);

It returns only 2 (received NACK on transmit of address)
Why? When i have other code on the slave (with onRecive and onRequest all works and comunicates)
Thank you.

you have two aduinos with the above program?

Please show complete compilable programs for both Arduino and ESP

Thank you guys.

I'm a fool, I tried to detect other devices in the setup function before the Wire.begin(PIN_SDA, PIN_SCL,  I2C_MASTER);
I Found it only because of you. The rubber duck. I started to write the program down to post it here and bingo.
That was the reason why the master had the "NACK" answer. The master was not started yet.
Thank you


text:
SoftwareSerial Stopped Working
I have been browsing the internet for about 3 hours now, it appears other people have had the same problem but I can't find a solution for it.
Basically yesterday I received my first GSM module and I was playing around with some AT commands in the serial monitor and it was working absolutely fine, today I'm getting nothing.
It's not related to the module though, even the basic SoftwareSerial example doesnt work now. All that's printed is "Goodnight moon!" and it never prints "Hello, world?". It's like it's not able start the serial communication or something.
Any help would be much appreciated!
 #include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Native USB only
  }

  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  mySerial.println("Hello, world?");
}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

Where do you expect to see "Hello world"? It's being sent to your GSM module, so how can you possibly see it on serial?

@Majenko it was probably echoed back in command mode, buffered and sent back in the main loop. But the question isn't clear, user1796225 even though that didn't work did you try pressing enter a few times and typing "ATI" or a similar command to see if you get something back?


text:
How to quit flash mode on HM-10?
I have an HM-10 BLE module connected to Arduino Leonardo. It forwards UART from my computer:
#define btSerial Serial1

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

    while (!Serial) {
        delay(50);
    }

    Serial.println("Initialized on 9600");

    btSerial.begin(9600);
    while (!btSerial) {
        delay(50);
    }

    Serial.println("BT initialized on 9600");
}

void loop() {
    if (btSerial.available()) {
        Serial.write(btSerial.read());
    }

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

In general, it works fine, but I've decided to flash it and sent AT+SBLUP command to it, and it's in flash mode now.
Later I've realized that I can't flash it because Parallels Desktop's COM forwarding does not work fine (I work on macOS).
And now I can't quit from the flash mode — it just does not respond to AT commands (however, btSerial is alive).
I've tried to reset the Arduino, disconnect BT for several minutes — it's still in flash mode. How to quit this mode?

you must flash some firmware

If you disconnected power from the HM-01 and it's still in flash mode the next time you power it, I would guess, that entering flash mode erases the firmware. Thus you would have to burn a new firmware to it. But thats just a guess


text:
Arduino Zero RTC alarm not running loop
Using an ATSAMD21 with the Arduino core, I'm running into an issue where the RTCZero alarm callback won't continue running the loop() function. If I schedule another alarm inside the callback, the second alarm will execute the loop() function after the callback is done. Every second time it works, every other time it doesn't.
Minimal example in which I expect the LED to change state every 2 seconds, which does not happen:
#include <RTCZero.h>
#include <time.h>

RTCZero rtc;

void setup()
{
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);

  rtc.begin();
  rtc.attachInterrupt(alarmMatch);
  schedule_wake_up();
  rtc.enableAlarm(rtc.MATCH_HHMMSS);
}

void loop()
{
  digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
  schedule_wake_up();
  rtc.standbyMode();    // Sleep until next alarm match
}

void schedule_wake_up() {
  time_t wakeupTimestamp = rtc.getEpoch();
  wakeupTimestamp += 2;
  struct tm *wakeupTimeStruct = gmtime(&wakeupTimestamp);

  rtc.setAlarmSeconds( wakeupTimeStruct->tm_sec );
  rtc.setAlarmMinutes( wakeupTimeStruct->tm_min );
  rtc.setAlarmHours( wakeupTimeStruct->tm_hour );
}

void alarmMatch()
{
  // Do nothing, just wake up
}

Arduino IDE 1.8.9
RTCZero ver 1.6.0
SAMD core ver 1.8.4 and 1.6.20 tried

I ended up deleting my copy of RTCZero and installing a new one via the Arduino IDE library manager. This solved the issue.
The difference between my local copy and the upstream one is in the standbyMode() function. I had the following PR merged into my local copy of this function:
https://github.com/arduino-libraries/RTCZero/pull/46/files
After I installed the clean copy I went and replaced the standbyMode() function's content with the following:
https://github.com/arduino-libraries/ArduinoLowPower/blob/892594adbccf45b198fc067ea994048c76523936/src/samd/ArduinoLowPower.cpp#L18


text:
Help with Receiver / Transmitter (nRF24L01+)
Dear fellow Arduino users,
My two friends and I are having trouble on an Arduino project we are working on. We are using two Arduino Uno's and trying to have one of them send a signal to another one by a press of a button using NF24L01+ (with the antenna). Our transmitter code is as follows:

// create an RF24 object
RF24 radio(9, 8);  // CE, CSN
// the number of the pushbutton pin
const int buttonPin = 3;
// variable for reading the pushbutton status
int buttonState = 0;
//address through which two modules communicate.
const byte address[6] = "00001";
void setup()
{
  Serial.begin(9600);
  Serial.println("nrf24L01+ Transmitter Starting!\n");
// initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
radio.begin();
  radio.setRetries(15, 15);
//set the address
  radio.openWritingPipe(address);
radio.setPALevel(RF24_PA_MAX);
//Set module as transmitter
  radio.stopListening();
}
void loop()
{
  buttonState = digitalRead(buttonPin);
if (buttonState == 1) {
    Serial.write("Sending the following message: \n");
//Send message to receiver
const char text[] = "\t Hello, friend!";
Serial.write(text);
Serial.write("\n\n");

radio.write(&text, sizeof(text));

delay(1000);

}
}

On the receiver side, we have the following:

//create an RF24 object
RF24 radio(9, 8);  // CE, CSN

//address through which two modules communicate.
const byte address[6] = "00001";

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

  radio.begin();

  //set the address
  radio.openReadingPipe(0, address);
  radio.setPALevel(RF24_PA_MAX);

  //Set module as receiver
  radio.startListening();
}

void loop()
{
  //Read the data if available in buffer
  if (radio.available())
  {
    Serial.print("hello");
    char text[32] = "";
    radio.read(&text, sizeof(text));
    Serial.println(text);
  }
}

However, we are not receiving any signal on the receiving end. We are pretty sure all our pins are correct. We are wondering if anyone had any advice on how we could troubleshoot. Thank you.

you need code running on the receiver end

You also need to check wiring on both devices.


text:
Digispark uploading not working in KDE Neon (Linux)
I am using KDE Neon and have downloaded the Arduino IDE via the Snap store. It worked well with the ESP8266 and other Arduions. But when I tried to upload a simple sketch or an example sketch to my Digispark, I get an error message. I have selected the right Board and the micronucleus programmer. I have also installed libusb. But I always get the following error message:
/home/myusername/snap/arduino/41/.arduino15/packages/digistump/tools/micronucleus/2.0a4/micronucleus: error while loading shared libraries: libusb-0.1.so.4: cannot open shared object file: No such file or directory

Maybe https://github.com/micronucleus/micronucleus/wiki/Ubuntu-Linux helps.

Install libusb-0.1-4 in whatever package manager KDE Neon uses.

I had the same problem when using the snap package of the Arduino IDE. I solved the problem by installing the Arduino IDE from the official web page: https://www.arduino.cc/en/software
You might have to run the Arduino IDE with sudo or better add a custom udev rule in case you now get following assertion error:

'micronucleus_connect: Assertion `res >= 4' failed.'

Solving the assertion error is further described in following post: https://digistump.com/board/index.php?topic=106.0

Thank you for your answer! It is working now.


text:
LCD screen stops displaying after DC motor starts
LCD screen stops displaying after DC motor starts
I have 3 main components: LCD, thermal resistor, and a DC motor running a fan. The LCD displays the temperature reading from the thermal resistor and then after it hits a certain temperature the motor turns on.
A few seconds after the motor has been turned on the LCD will go blank (but still powered on). I tried connecting a 100uF electrolytic capacitor across between the logic supply pins on the LCD and a 0.47 µF ceramic between the motor terminals.
I did this because i'm assuming since the motor in operation (its commutator) produces voltage/ current "spikes" they can be coupled back through the common power supply. This could provide some immunity against them actually getting to the display driver and interfering with its operation.
What I did kind of helped, but I feel like I am missing something. Any suggestions?
(the link is to the picture of my circuit I quickly made online)

What is the voltage at the LCD and motor when the motor is running? Is the motor not simply overloading the Arduino's power supply?

Where did you draw this circuit online?

what happens if you disconnect the motor?

@ThomasWeller, google image search reveals     https://www.tinkercad.com

@StarCat LCD is at 4.82V and the motor is at 4.0V

@StarCat I tried connecting a 9v battery through the port to help aid the board, but I still get the same issue. I am thinking about just using a 5V relay to trigger the fan and just isolate the DC motor as a whole and see if that works

Those voltages don’t look too bad (but not great either). Does your program keep running and does the display return to normal after the motor has stopped? Isolating the motor sounds like a plan.

A brush DC electric motor and many other similar devices will produce random noise as well as uneven power demands and should be powered independently of logic circuits such as processors and LCDs.  It is very difficult to mediate noise sources and almost always better to remove them from where they are causing harm or unexpected results.
It is also important to power a project with a supply capable of providing more than the expected amperage during highest demand.  Many will calculate the highest amperage demand and select a power supply which is rated at double the amperage.
If you are using batteries, note that a 9 volt battery (which usually contains 6 cells) on average supplies about 500mAh.  Not much and likely not enough to run a motor with out momentarily dropping the voltage.  Where as a D-size battery supplies about 15000mAh.  Different battery chemistries change the mAh rating drastically.  500mAh and 15000mAh are about what one may expect from Alkaline batteries.
If using a USB power source, note that older USB ports are only obliged to supply 500mA at any given time.  If this current limit is exceeded, the voltage may drop under 5 volts.
There are many designs on the internet where the motor is powered from the Arduino.  This may be possible for smaller motors however you are having unexpected behavior.  Consider using one or more of the following suggestions to mitigate your problems:

Avoid low mAh batteries such as common 9 volt batteries.  Instead use a battery that can provide higher mAh like D Size cells.
Avoid powering noisy or current demanding devices directly from the Arduino.  Consider an independent power supply and use a common ground.
It may be possible to use a single power supply with good results if the power supply is rated at higher amperage than the peak total maximum amperage.


text:
Trying to use Timer0 on Arduino Mega
I've recently been looking at Timers and I'm trying to generate a PWM frequency at 250000Hz using Timer0 on PIN 4. When I set OCR0A = 63 I get nothing from the light however when I set OCR0A = 125 it turns on ( 128000Hz - according to the formula in the datasheet unless I've been working it out wrong). What's the reason for it not working when OCR0A = 63
#include <DmxSimple.h>

void setup() {
  // put your setup code here, to run once:
  Serial.begin(250000);
  pinMode(2,OUTPUT);  // SHIELD DRIVER OUTPUT ENABLE
  digitalWrite( 2 , HIGH); // SHEILD DE HIGH
  DDRG |= bit(DDG5);

  TCCR0A = 0;
  TCCR0B = 0;
  TCNT0 =  0;

  TCCR0A = bit(COM0A1)| bit(COM0B1)| bit(WGM01)| bit(WGM00);
  TCCR0B = bit(WGM02) | bit(CS00);
  OCR0A = 63 ;
  OCR0B = 31;

}

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

(1,PORTG |= (1<<5));
(1,PORTG &= ~(1<<5));

}

Except for the loop code (that shouldn't be affecting anything, as it's using alternate pin function) and pointless COM0A1, I can't see any problem. Well, except one of my multimeters showed the wrong frequency, second one shows correct 248.76kHz and 50% pulse width.

@KIIV Could the DmxSimple library be causing a problem ? . I don't have an oscilloscope or multimeter to check the output frequency  but your multimeter showed 250kHz when OCR0A = 63 ?

DmxSimple uses Timer2 so it shouldn't be a problem. At least as far as you don't use anything millis related, like delay or so (because it's updated by Timer0 overflow and it won't happen with that changes)

I've made sure to leave any delays out . I'm not sure what the issue could be . Would it worth changing to see if it works in Fast PWM mode when TOP = 0xff

Btw, what light? Why do you need such short period?

It's a non branded DMX light that I had . The period is not necessary . I'm just trying to get a distinct modulated that signal that can be picked up by the photodiode. I was previously trying to get OOK modulation to work but was unable so I'm now trying PWM . Any suggestions would be much appreciated


text:
Cannot call function in call back for onRequest()
I am a NOOB!  Trying to use the ZS-042 RTC module to retrieve the current time and send it back to the RPi over I2C.  I can call the function and spool it to Serial but when I try to call the function to update the global variables from within the call back function for onRequest() the Ardiuno (Micro) crashes.
#include <Wire.h>

// LED on pin 13
const int TEMP_PIN1 = A0;
const int RELAY_PIN1 = 4;
const int SAMPLE_TIME = 100;
const byte RPI_I2C_ADDRESS = 0x08;
const int DS3231_I2C_ADDRESS = 0x68;

byte number = 0;
byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;

/*
 * RTC Setup
 */
// Convert normal decimal numbers to binary coded decimal
byte decToBcd(byte val)
{
  return( (val/10*16) + (val%10) );
}
// Convert binary coded decimal to normal decimal numbers
byte bcdToDec(byte val)
{
  return( (val/16*10) + (val%16) );
}
void setDS3231time(byte second, byte minute, byte hour, byte dayOfWeek, byte
      dayOfMonth, byte month, byte year)
{
  // sets time and date data to DS3231
  Wire.beginTransmission(DS3231_I2C_ADDRESS);
  Wire.write(0); // set next input to start at the seconds register
  Wire.write(decToBcd(second)); // set seconds
  Wire.write(decToBcd(minute)); // set minutes
  Wire.write(decToBcd(hour)); // set hours
  Wire.write(decToBcd(dayOfWeek)); // set day of week (0=Sunday, 6=Saturday)
  Wire.write(decToBcd(dayOfMonth)); // set date (1 to 31)
  Wire.write(decToBcd(month)); // set month
  Wire.write(decToBcd(year)); // set year (0 to 99)
  Wire.endTransmission();
}

/*
void readDS3231time(byte *second,
    byte *minute,
    byte *hour,
    byte *dayOfWeek,
    byte *dayOfMonth,
    byte *month,
    byte *year)
{
  Wire.beginTransmission(DS3231_I2C_ADDRESS);
  Wire.write(0); // set DS3231 register pointer to 00h
  Wire.endTransmission();
  Wire.requestFrom(DS3231_I2C_ADDRESS, 7);
  // request seven bytes of data from DS3231 starting from register 00h
  *second = bcdToDec(Wire.read() & 0x7f);
  *minute = bcdToDec(Wire.read());
  *hour = bcdToDec(Wire.read() & 0x3f);
  *dayOfWeek = bcdToDec(Wire.read());
  *dayOfMonth = bcdToDec(Wire.read());
  *month = bcdToDec(Wire.read());
  *year = bcdToDec(Wire.read());
}
*/

void readDS3231time()
{
  Wire.beginTransmission(DS3231_I2C_ADDRESS);
  Wire.write(0); // set DS3231 register pointer to 00h
  Wire.endTransmission();
  Wire.requestFrom(DS3231_I2C_ADDRESS, 7);
  // request seven bytes of data from DS3231 starting from register 00h
  second = bcdToDec(Wire.read() & 0x7f);
  minute = bcdToDec(Wire.read());
  hour = bcdToDec(Wire.read() & 0x3f);
  dayOfWeek = bcdToDec(Wire.read());
  dayOfMonth = bcdToDec(Wire.read());
  month = bcdToDec(Wire.read());
  year = bcdToDec(Wire.read());
}

void displayTime()
{
  //byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;
  // retrieve data from DS3231
  //readDS3231time(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month, &year);
  readDS3231time();
  // send it to the serial monitor
  Serial.print(hour, DEC);
  // convert the byte variable to a decimal number when displayed
  Serial.print(":");
  if (minute<10)
  {
    Serial.print("0");
  }
  Serial.print(minute, DEC);
  Serial.print(":");
  if (second<10)
  {
    Serial.print("0");
  }
  Serial.print(second, DEC);
  Serial.print(" ");
  Serial.print(dayOfMonth, DEC);
  Serial.print("/");
  Serial.print(month, DEC);
  Serial.print("/");
  Serial.print(year, DEC);
  Serial.print(" Day of week: ");
  switch(dayOfWeek){
  case 0:
    Serial.println("Sunday");
    break;
  case 1:
    Serial.println("Monday");
    break;
  case 2:
    Serial.println("Tuesday");
    break;
  case 3:
    Serial.println("Wednesday");
    break;
  case 4:
    Serial.println("Thursday");
    break;
  case 5:
    Serial.println("Friday");
    break;
  case 6:
    Serial.println("Saturday");
    break;
  }
}

void flash_data(int loops)
{
   for (int i = 0; i < loops; i++)
   {
      digitalWrite(LED_BUILTIN, HIGH);
      Serial.println("LED Pin HIGH: "+String(digitalRead(LED_BUILTIN)));
      delay(50);
      digitalWrite(LED_BUILTIN, LOW);
      Serial.println("LED Pin LOW: "+String(digitalRead(LED_BUILTIN)));
      delay(50);
   }
}

// callback for received data
void receiveData(int byteCount)
{
  Serial.println("Receiving Data... ");
  if ( Wire.available() ) {
    number = Wire.read();
  }
  Serial.println("Data Received: "+String(number));
}

void sendData() {
  Serial.println("Sending Data on Request");
  //byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;
  // retrieve data from DS3231
  //readDS3231time(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month, &year);
  readDS3231time();
  //char buf1[20];
  //sprintf(buf1, "%02d:%02d:%02d %02d/%02d/%02d",  hour, minute, second, dayOfMonth, month, year);
  //Serial.print(buf1);
  Wire.write("Hello");
}

void setup() {
  Serial.begin(57600);
  do {
    delay(500);
  } while (!Serial);

  delay(500);
  Serial.println("Initializing Wire I2C on "+RPI_I2C_ADDRESS);
  // Join I@c bus as slave with RPI_I2C_ADDRESS 8
  Wire.begin(RPI_I2C_ADDRESS);

  Serial.println("Setting call back for Wire.onReceive");
  Wire.onReceive(receiveData);
  Wire.onRequest(sendData);

  //Setup pin 13 as output and turn LED off
  Serial.println("Setting LED Pin up for Output");
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(RELAY_PIN1, OUTPUT);
  pinMode(TEMP_PIN1, INPUT);
  Serial.println("Turning LED off");
  digitalWrite(LED_BUILTIN, LOW);
}

float getVoltage(int pin)
{
  // This function has one input parameter, the analog pin number
  // to read. You might notice that this function does not have
  // "void" in front of it; this is because it returns a floating-
  // point value, which is the true voltage on that pin (0 to 5V).
  return (analogRead(pin) * 0.004882814);
  // This equation converts the 0 to 1023 value that analogRead()
  // returns, into a 0.0 to 5.0 value that is the true voltage
  // being read at that pin.
}

/*
 * MAIN LOOP
 */
void loop() {

  if ( number > 0 ) {
    //Serial.println("Flash Data: "+String(number));
    flash_data(number);
    float voltage, avgVoltage, degreesC, degreesF;
    if (number == 1) {
      digitalWrite(RELAY_PIN1, HIGH);
    } else if (number == 2) {
      digitalWrite(RELAY_PIN1, LOW);
    } else if ( number == 3 ) {
      voltage = getVoltage(TEMP_PIN1);
      //gets and prints the raw data from the lm35
      Serial.print("Voltage: ");
      Serial.print (voltage);
      Serial.println(" ");
      // Now we'll convert the voltage to degrees Celsius.
      // This formula comes from the temperature sensor datasheet:
      degreesC = (voltage - 0.48) * 100.0;
      Serial.print("CELSIUS: ");
      Serial.print(degreesC);
      Serial.println("*C ");
      //converts celsius into fahrenheit
      degreesF = degreesC * (9.0/5.0) + 32.0;
      Serial.print("FAHRENHEIT: ");
      Serial.print(degreesF);
      Serial.println("*F");
    } else if ( number == 4 ) {
       displayTime();
    }
    number = 0;
  } else {
    byte pinValue = bitRead(LED_BUILTIN, 3);
    if ( digitalRead(LED_BUILTIN) == HIGH ) {
      digitalWrite(LED_BUILTIN, LOW);
    }
  }
  delay(SAMPLE_TIME);
}

Any guidance would be appreciated!
THanks

Could you please show a schematic of your circuit? Do you really want your Arduino to be both a master and a slave on the I2C bus? Why not connect the Pi through Serial?

The onRequest and onReceive callback functions are called from inside an ISR. Thus you cannot use any code in there, that relies on interrupts to work. Serial writes or prints for example will only work, as longs as the buffer is not full (since the actual communication is handled by interrupts). If the buffer is full, the serial code will either block or loose data (depending on the version of the Arduino core. Not blocking in an ISR is a relatively new change). Such things also hapoen with other interrupt driven functions.
Let's take your codes logic particular in the onRequest callcack function. As written above, this is called from an ISR. The Wire library was contacted by the master to send data to it. With this callback the library uis asking you, what to answer the master. During that time, the current transmission (master read, slave send) is already active, but the slave is stalling the transaction, until the data is ready, meaning until you exit the onRequest callback. Now inside the callback you try to initiate another transaxtion on the same I2C bus, now as a master. The same I2C bus, where there is already a transaction going on. That cannot work. The former slave cannot take the control over the bus, since the first master haven't released it yet (as you tried this in the middle of it's transaction. So you are not only using interrupt driven functions in an ISR, you are also trying to reconfigure hardware, that you just got an interrupt from (which is a bad idea, unless you really know, what you are doing). The library has configured the hardware as slave and in the middle of the transaction you try to configure it as master.
I don't know, why you even try to do this. Since you already have the RTC on the same bus as the Pi, why not making the Pi the only master and let it directly poll the RTC? Why do you need the Arduino between them?
If you really really need the multi master setup for whatever reason (though I cannot think of one), you have to do the transactions independent of one another. The Arduino could poll the RTC regularly, when the bus is free, and buffer the results. Then it could send these results to the Pi, when it requests the Arduino to do that.

Note: I'm currently not up to date, how good the multi master support in the Wire library is these days. It incorporated the possibility for multi master since a long time, but when I checked last time, the bus arbitration was not implemented (meaning that if 2 masters try to send at the same time, the bus gets stalled). If it is still this way, you shouldn't use multi master with the Wire library.

Thanks chrisl! Sorry everyone. I realized moments after posting that I am conflicting between the 2 I2C devices in the way I am trying to do this which I think aligns with chrisl's post. DUH! I should be able to make a request to the RTC directly from the RPi via it's address given they are both on the same I2C bus. I will post this definitely once I've tested but I am pretty sure that's what is wrong. Total Bone Head Move.


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:
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.

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

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.


text:
How to connect to MQTT broker with TLS?
I have ESP8266 which is connecting to MQTT broker and it is working ok using user+pass with following code:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

const char* ssid = "WIFINAME";
const char* password = "WIFI_PASS";

const char* mqtt_server = "SERVER_IP";
const char* mqttUser = "user";
const char* mqttPassword = "pass";

WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;

void setup_wifi() {

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

  WiFi.begin(ssid, password);

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

  randomSeed(micros());

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

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') {
    digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
    // but actually the LED is on; this is because
    // it is active low on the ESP-01)
  } else {
    digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
  }
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    if (client.connect(clientId.c_str(), mqttUser, mqttPassword)) {
      Serial.println("connected");
      client.subscribe("CoreElectronics/test");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  pinMode(BUILTIN_LED, OUTPUT);
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void loop() {

  if (!client.connected()) {
    reconnect();
  }
  client.loop();
}

As this is insecure usage I have setup TLS on MQTT broker and I can connect over command line:
mosquitto_sub --cafile ca.crt -h server_ip  -t "#" -p 8883 -d --cert client.crt --key client.key

Problem is that I cannot find any working (for me) sample with using TLS connection on ESP8266 client.
I have tried generating self-signed certs by manually script and over LetsEncrypt.
Thank you

If PSK is acceptable, there are probably some tutorials over at adafruit.com or discussions in their forum.

You could make the following changes to your code by making use of WifiClientSecure (which is already part of the ESP8266 Wifi library).
The tricky part is finding out the SHA1 fingerprint for your own MQTT server and hard coding it into the *fingerprint PROGMEM = "..."  part (for example by examining the certificate via a PC browser and copying the SHA1 fingerprint).
Alternatively, you could set the connection to setInsecure. This means that the connection will be encrypted but it will accept any server certificate without checking.
...
const char* mqttPassword = "pass";

WiFiClientSecure espClient;     // <-- Change #1: Secure connection to MQTT Server
PubSubClient client(espClient);

// Change #2: Set the SHA1 fingerprint for the connection -->
static const char *fingerprint PROGMEM = "44 14 9A 3F C3 E9 F1 F3 84 1A B4 9F B6 4D 19 8A B2 92 31 D6";
...
...
void setup() {
    ...
    setup_wifi();

    espClient.setFingerprint(fingerprint);   // <-- Change #3: Set the SHA1 fingerprint
    // Alternative: espClient.setInsecure;

    client.setServer(mqtt_server, 8883);  // <-- Change #4: Set the port number to 8883
    client.setCallback(callback);
 ...

Good luck!

where I need to put ca.crt, client.crt and client.key?

You won't need them if you use the setFingerprint method. You only need the fingerprint.

I get error 'class PubSubClient' has no member named 'setFingerprint' and also for setInsecure. Which PubSubClient is latest and best for use?

solved. changed client.setFingerprint(fingerprint); -> espClient.setFingerprint(fingerprint);

My bad, I will fix it in the answer.

@StarCat Wouldn't this allow anyone who knows the (accessible) fingerprint to pretend to be the server?

Not really.The fingerprint is a cryptographic hash of the server’s public key. It’s computationally extremely hard to reconstruct a public key from the fingerprint (or a different public key that produces the same fingerprint, called a “collision”).

There is an example of client certificates here.
https://github.com/espressif/arduino-esp32/blob/master/libraries/WiFiClientSecure/examples/WiFiClientSecure/WiFiClientSecure.ino
I believe the answer by @StarCat should be expanded to use the ca cert and client certs.  With MQTT, we don't want clients being faked either.


text:
arduino atmega32u4 beetle extract hex code
I made a program using the Arduino Atmega32U4.
As a security issue, I tried to extract the hex code because I wanted to know if this program was duplicated.
avrdude -C"\avrdude.conf" -v -V -patmega32u4 -carduino -PCOM15 -b9600 -D -Uflash:w:C:\test\sketch_jun07b.ino.hex:i
This is what I executed in Command Line.
Avrdude ended with the following error: avrdude: stk500_getsync () attempt 1 of 10: not in sync:
Can you tell me if there is no risk of extracting and duplicating hex code from beetle or chipset unlike arduino board?

what does the error message mean?

it is unclear what you are asking ... what do you mean by unlike arduino board?   ... what kind of risk are you talking about?

I know that I can extract hex code from the Arduino board, is this information wrong? I'm trying it and that's the biggest risk

yes you can read the content of memory .... i suggest that you investigate the error message before you go further .... you still have not said what risk you are talking about

Launched Arduino USB type product.
I don't want this product duplicated, so I've run a hex code extraction beforehand.
Connecting to programmer: .. Now I face to face this error... TT

What programmer? Connected via ISP I suppose? You would probably want -c stk500v1in that case. Also, -U flash:w:xyz:i tries to write a hex file to your device, with xyz being the path. You'd want that to be -U flash:r:xyz:i

Just set a lock bits properly and it won't be so easy to read out the flash.


text:
Missing ArduinoJson/DynamicJsonBuffer.hpp
I have read other posts regarding ArduinoJson that recommend using a library version no later than 5.14.3.  That recommendation is more than a year old - is it still the recommended library version?

I have only ever used ArduinoJSON 6 and never had any problems with it. Unless you need version 5 for compatibility with some old system then I would say use 6.

version 6 breaks backward compatibility so you can't upgrade from 5 to 6 without migrating all sketches to classes of version 6 of the library. (or using some workaround by having the version 5 of the library in a renamed folder)


text:
What is the difference betwen “ESP8266Wifi.h” and “WiFiEsp.h” libraries?
I'll start a project using NodeMCU V3 WiFi Module, which uses esp8266 chip. However, I am undecided as to which library to use. I don't want use a serial bridge with an arduino, I think it is better to use NodeMcu in Standalone mode.
So, here's my question: which library should I use? And, regarding the type of use, what is their difference? (both libraries reference looks like the same for me)
p.s.: I also heard about the "WiFi.h" library. Does it work only on WiFi shields for arduino or does it also work on esp8266?

It's quite simple:

ESP8266WiFi.h - Runs on the ESP8266 to control the WiFi.
WiFiEsp.h - Runs on an Arduino to communicate with an ESP8266 module with AT commands
WiFi.h - Runs on an Arduino to work with the Arduino WiFi shield.

So the one you want, which is part of the ESP8266 core, is ESP8266WiFi.h.

Thanks! But let me ask you one more question: is the syntax the same for both libraries? At least in the examples I saw, they looked the same.

No idea. Probably only superficially of at all.


text:
IR Remote with Arduino
I want to build a remote with Arduino Nano. I have viewed many tutorials in the web, but I don't have the IR Receiver (TSOP1740). Is there any way to use Jjust an IR Led as the receiver?

When you want the Ardiuno to be the remote, why do you need a receiver on it? A normal renote (like for a TV) only sends, it does not receive

I need the receiver to record the signal sent by the remote. Then the recorder signal will be plaayed when the equivalent button on the arduino remote is pressed.

If using the $0.10 1838 Chinese IR receivers, they require different timing than the expensive ones. They work great with this modified library, however: https://github.com/ElectricRCAircraftGuy/IRLib

No, you can't use just an IR LED as the receiver.  While it is true that an IR LED can also be an IR receiver the voltages it generates are really really small. So you would need an amplification circuit. On top of that the TSOP1740 includes a band-pass filter to isolate the carrier frequency of the transmitted signal from the background light, which you would also need to implement.
So yes, while you could use an IR LED as a receiver, you need a large amount of support circuitry with it (which takes expertise not relevant to this website) to get it to do anything useful.

I know, the TSOP1740 has an internal amplifier, but I only have an UA741, aand am afraid that if I use that for amplification, the signal will be heavily distorted. Nevermind, I will just look up my TV model and search for the remote signals

I don't know...I think I might actually be able to make a plain IR LED, with no support circuitry or external amplifier, read an IR signal. I think this is one of those cases where with enough knowledge you can use software to make up for missing hardware, and I think it just may be possible. For the sake of this question it's out of the question, but I just might make this a challenge I'm willing to take on one of these days. I have some ideas, but I suspect I could use capacitive touch digital pin sensing to time for loop counts as a means of reading the signals, then digitally filter.

Related: https://www.instructables.com/id/Arduino-Use-LED-as-a-light-sensor/

If you could sample the incoming signal from the LED fast enough you could then pass it through a biquad band-pass filter to isolate the right carrier frequency then either pass it through a biquad low-shelf filter to recover the signal or arrange for simple OOK detection. It is something that could be done in software, but I'd not want to do it on an Arduino, instead choosing something that has an FPU or DSP built into it.

You could make a remote without a receiver.  It would require knowing what signals to send.  The receiver is to essentially help in training your arduino by letting it detect the signal from an already working remote and then replay it on the LED.
You can't make a receiver with JUST an LED. (Majenko's got this one covered).


text:
Stm32 Blue Pill Internal ADC Voltage Reference Configuration
I am programming an STM32F103C8T6 Board in Arduino IDE. I want to change the value of the internal Voltage Reference for the ADC. How can I achieve this in Arduino ide?

What do you mean you want to change the value? The value is 1.2V. That's not something you can change. Do you mean you want to use the internal reference voltage? Or that you want to use some other external voltage as the reference voltage?

unlike AVRs, stm32 internal voltage reference can't be used as a measurement max reference. it's there just for application calibration. your reference only depends on the VDDA pin and  1) it has to be always connected to a supply and 2) must be between 2~3.6V

I want to change change the internal reference voltage, to something else other than the 1.2 v fixed reference. Like in avr microcontrollers, there is an external adc voltage reference pin for setting the reference voltage. Thats all.

Which Arduino? The IDE is an interface to lots of chips, and they will have different ways of setting the ADC reference voltage.


text:
ESP32 WiFi server.send(); is it exclusive to ESP328266 modules, Arduino?
Is the function server.send(); exclusive to ESP8266 modules, Arduino?  Where can I find documentation regarding the application of this function with an ESP32 module with WiFi?

the ESP32 HTTPServer library

For ESP32, the equivalent implementation is in the WebServer library.

Thank you for your response, much appreciated!