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

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

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

In the instructables post a lot more explanation is shown.


text:
ESP8266 12e Arduino IDE outputs garbage values on serial monitor
I recently started using the ESP8266 12E (Amazon link) and hooked the board up to the Arduino IDE.
When trying to run any of the example sketches, all sketches compile and upload correctly. The blink sketch correctly causes the LED to blink, however, in the serial monitor a varying and large quantity of junk characters appear:

The first thing I investigated was of course the baud rate. Online, documentation for the ESP8266 indicate 115200 as the correct baud rate, but on the bottom of the device, the baud rate is listed as 9600.
The junk characters, of course, appear whether the baud rate is 9600 or 115200. Using trial-and-error, I tried each other option. I've also tried several USB to micro-USB (c) cables. They're the same ones I use to charge my phone - is that the issue?
Am I missing something simple here? I searched each of the other Stack Exchange questions about garbage serial monitor values and they all seemed to indicate that the baud rate was the culprit, or that the CL / NR values needed to be changed. Experimentation with these did not result in removing the characters.

The baud rate you specify in your program and the baud rate in the serial monitor must match. The ESP8266 outputs a boot message at its own baud rate (varies from model to model - try 57600) before it executes your sketch.
For example:

You can choose any (within reason) baud rate in your program as long as you also choose the same baud rate in whatever is communicating with it (such as the serial monitor in the IDE). If you want to see the boot messages then the serial monitor will have to be set to the right baud rate.

Thank you for your response -- I am unsure how to view this boot message. I am currently using Windows 10, and don't have (readily accessible) a working Linux installation. I can access one in a few hours, however.
The baud rates appear to match - in the Arduino IDE Tools > Baud Rate menu + the serial monitor menu & the code itself, they all read 115200.
I changed them do 57600 and did not notice a change yet

... "If you want to see the boot messages then the serial monitor will have to be set to the right baud rate." ... What isn't clear about that? Where does your host OS come into it?

I hit the enter key pre-maturely -- see the edit to the comment above

I am doing that all the time ;) The baud rate in the tools menu is purely for performing the upload of the code. The baud rate in your code is purely for your own communication from within your code. The only baud rate that has any bearing at all on the boot messages is the one in the serial monitor's drop-down list. Try different values in there. Or just ignore the boot messages as they aren't that interesting.

Experimenting more with the Baud Rates -- I learned that 74880 produces an accurate boot message (see link below):
link
I still get a funky "y" character (y with umlaut)  ÿ
Is the EOL / CR / NL values for my serial monitor incorrect?
Phew, this has been quite an educational process. I very much appreciate your help, Majenko!

The ÿ is usually associated with the line being dropped or otherwise going dead, usually at the end of transmission, or just as transmission starts. It's basically corruption and is pretty much normal.

I had what I think is the same problem you did.  I posted my solution to it here:
Link to my solution
It seems that the ESP can upload code at 115200, but it can't talk to the serial monitor at that baud rate.  The solution is to programatically change the baud rate within your sketch.  The change in baud rate doesn't 'stick'.  You have to include it in your sketch so it is set every time the sketch is run.
Hope that helps.

source: Stack Exchange

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

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

sort: votes


text:
How I can send data information without work WiFi to LCD?
Hi everyone I am beginning learn coding and the second language English. I have small project I use Arduino uno , esp8266 , dht11 , lcd I2C and use blynk app in my project I have the code and work probably when WiFi ON but I have question How I can get the information data from dht to lcd without open the WiFi. Now I get information ( Temp and humidity ) on LCD when WiFi ON only. How I can make Temp and humidity display on LCD with and without WiFi.
#include <BlynkSimpleShieldEsp8266.h>
#include <DHT.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 20, 4);
char auth[] = "*******************************";
char ssid[] = "***********";
char pass[] = "*********";
#include <SoftwareSerial.h>
SoftwareSerial EspSerial(2, 3); // TX, RX
#define ESP8266_BAUD 9600
ESP8266 wifi(&EspSerial);
#define DHTPIN 8
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

void setup()
{
  Serial.begin(9600);
  lcd.init();
  lcd.backlight();
  EspSerial.begin(ESP8266_BAUD);
  Blynk.begin(auth, wifi, ssid, pass);
  dht.begin();
}

void loop()
{
  LCD();
  int h = dht.readHumidity();
  int t = dht.readTemperature();
  Blynk.virtualWrite(V1, t);
  Blynk.virtualWrite(V2, h);
}
void LCD()
{
  int h = dht.readHumidity();
  int t = dht.readTemperature();
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(" ******************");
  lcd.setCursor(3, 1);
  lcd.print("TEMP: ");
  lcd.print(t);
  lcd.setCursor(3, 2);
  lcd.print("HUM : ");
  lcd.print(h);
}

you just read the tenperarure and humidity and then display the values on the lcd ... why would you need wifi?

because use as IOT by Blynk

So take the code that writes to the lcd out of the function that is called by your timer and simply call it from loop.  Use the blink without delay style of timing with millis to make it happen at one second intervals.  There are thousands of tutorials on how to handle timing on Arduino without blynk.

Thanks dear,,, You can help me more for this because I don't have idea

Start with a simple example that just prints the values from the DHT11 and work your way up from there. The code you included does some very strange and unnecessary things and I do not recommend you re-use it. Where did this code come from?

Thanks I try to make the code easy but still the same problem to display on LCD without WiFi On

I´m working with a nano v3 (clone) and a esp-01 as wifi shield to send data from sensors like dht11, a DS18B20 and a light sensor based on ldr from an hidroponic system and controls a water pump and 1 water heater with a 2 relay module. I use Blynk app to read this data because I don't want to go see an lcd outside the house. So my sketch do somethings similar to yours and others not, obviously. But I´ve got the same problem. I´ll like to run my sketch without need to be connected to blynk like in case I´ve lost connection for some how. I noticed that in your sketch there are some things that

Blynk.connected() returns true when hardware is connected to Blynk Server, so you can guard Blynk code with
if( Blynk.connected() ){
  // do Blynk things here
}

// Update the LCD anywhere outside of the above "if" statement.

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


text:
Adafruit RTC DS3231 Crashing Arduino Uno
I am having some issues with a new DS3231 Precision RTC module. I have made connections as in the guide linked, and when used, the serial output from the Arduino is garbled, and the arduino apparently crashes, endlessly flowing garbled messages (which appear to be bits of the beginning of the first serial output).
Sometimes I can get better output, but only up until I try to set the datetime, where it then crashes, with endless garble.
Code used to set datetime (all vars given are ints):
rtc.adjust(DateTime(year, month, day, hour, minute, second));

The way I have things wired is the same as on the guide listed. I am basing my code off of the example on the guide (which is the same as on the guide), yet the example code functions well.
Relevant excerpt(s) from my code:
//includes
#include <Servo.h> //for running the servo
#include <Wire.h> //required for RTClib
#include "RTClib.h" //to run the real time clock functionality. https://github.com/adafruit/RTClib

boolean timingEnabled = true;
RTC_DS3231 rtc;
void setup(){
  Serial.begin(9600);
  if(timingEnabled){
    //clock
    boolean rtcOn = rtc.begin();
    Serial.print(String(rtcOn) + "\n");
    if(! rtcOn){
      Serial.print("Couldn't find RTC. Timing Disabled\n");
      timingEnabled = false;
    }else{
      if(rtc.lostPower()){
        Serial.println("Clock lost power.\n");
        setTime();//set the clock
      }
    }
  }
}

Since it was asked for, full code (minus loop()):
/* Sketch for Arduino to run the automatic cat feeder.
 *
 *
 */

//includes
#include <Servo.h> //for running the servo
#include <Wire.h> //required for RTClib
#include "RTClib.h" //to run the real time clock functionality. https://github.com/adafruit/RTClib

//status indicator values
const int onboardLedPin = 13;

//buzzer values
const boolean buzz = true; //turns on and off the buzzer functionality
const int buzzerPin = 8;
const int buzzLength = 250;
const int buzzDefaultFreq = 1000;
const int buzzFeedStartFreq = 2000;
const int buzzFeedEndFreq = 500;
const int buzzBattWarnFreq = 2000;
const int buzzConfirmFreq = 100;

//Servo setup
Servo dispenserServo;
const int servoPin = 11;
const int feedServoSpinTime = 2000;
const int STOP = 90;
const int SPIN_CLOCKWISE = 180;
const int SPIN_COUNTER_CLOCKWISE = 0;

//clock
boolean timingEnabled = true;
RTC_DS3231 rtc;
String feedTimes[] = {"7:00"};

//button
const int buttonPin = 7;
int buttonVal = 0;

//other
const int mainWait = 5000;

/*
 * Does a buzz if it is set to.
 */
void doBuzz(int frequency, boolean wait){
  if(buzz){
    tone(buzzerPin, frequency, buzzLength);
    if(wait){
      delay(buzzLength);
    }
  }
}

/*
 * Default function to not wait for buzz to finish.
 */
void doBuzz(){
  doBuzz(buzzDefaultFreq, false);
}

void checkButton(){
  buttonVal = digitalRead(buttonPin);
}

/*
 * Determines if it is time to do the feeding.
 */
boolean isFoodTime(){
  if(!timingEnabled){
    return false;
  }
  DateTime curTime = rtc.now();

  String hr = String(curTime.hour());
  String mn = String(curTime.minute());

  String time = hr + ":" + mn;

  for(int i = 0; i < sizeof(feedTimes); i++){
    if(feedTimes[i] == time){
      return true;
    }
  }

  return false;
}

String formatDateTime(DateTime dtIn){
  return String(dtIn.month()) + "/" + String(dtIn.day()) + "/" + String(dtIn.year()) + " " + String(dtIn.hour()) + ":" + String(dtIn.minute()) + ":" + String(dtIn.second());
}

String formatDateTime(){
    formatDateTime(rtc.now());
}

int getNumFromButton(int startAt){
  doBuzz(buzzFeedEndFreq, true);
  int longPressLength = 500;
  int output = startAt;
  bool counting = true;
  do{
    checkButton();
    if(buttonVal == HIGH){
        delay(longPressLength);
        checkButton();
        if(buttonVal == HIGH){
          counting = false;
        }else{
          output++;
          doBuzz(buzzConfirmFreq, true);
          delay(longPressLength);
        }
    }
  }while(counting);
  doBuzz(buzzConfirmFreq, true);
  delay(buzzLength);
  doBuzz(buzzConfirmFreq, true);
  return output;
}

void setTime(){
  //rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  //Serial.print("Setting the clock... ("+formatDateTime()+")\n");
  delay(buzzLength);
  delay(buzzLength);
  doBuzz(buzzConfirmFreq, true);
  delay(buzzLength);
  doBuzz(buzzConfirmFreq, true);
  delay(buzzLength);
  doBuzz(buzzConfirmFreq, true);
  Serial.print("Getting Year... (");
  int year = getNumFromButton(2000);
  Serial.print(String(year) + ")\nGetting Month... (");
  int month = getNumFromButton(1);
  Serial.print(String(month) + ")\nGetting Day... (");
  int day = getNumFromButton(1);
  Serial.print(String(day) + ")\nGetting Hour... (");
  int hour = getNumFromButton(0);
  Serial.print(String(hour) + ")\nGetting Minute... (");
  int minute = getNumFromButton(0);
  Serial.print(String(minute) + ")\nGetting Second... (");
  int second = getNumFromButton(0);
  Serial.print(String(second) + ")\n");
  delay(buzzLength);
  doBuzz(buzzConfirmFreq, true);

  Serial.print("Finished getting numbers.\n");
  rtc.adjust(DateTime(year, month, day, hour, minute, second));
  Serial.print("Clock set to: " + formatDateTime() + "\n");
}

/*
 * Setup of things:
 *  - status led
 *  - buzzer
 *  - servo
 */
void setup(){
  Serial.begin(9600);
  Serial.print("\nBeginning setup of the CatFeeder.\n");
  // status led
  pinMode(onboardLedPin, OUTPUT);
  // buzzer
  pinMode(buzzerPin, OUTPUT);
  doBuzz();
  //servo
  dispenserServo.attach(servoPin);
  pinMode(servoPin, OUTPUT);
  dispenserServo.write(STOP);

  if(timingEnabled){
    //clock
    boolean rtcOn = rtc.begin();
    Serial.print(String(rtcOn) + "\n");
    if(! rtcOn){
      Serial.print("Couldn't find RTC. Timing Disabled\n");
      timingEnabled = false;
      doBuzz(buzzConfirmFreq, true);
      delay(buzzLength);
      doBuzz(buzzConfirmFreq, true);
      delay(buzzLength);
      doBuzz(buzzConfirmFreq, true);
      delay(buzzLength);
      doBuzz(buzzConfirmFreq, true);
    }else{
      if(rtc.lostPower()){
        Serial.println("Clock lost power.\n");
        setTime();
      }
    }
  }
  if(!timingEnabled){
    Serial.print("Timing disabled. Will only actuate on button press.\n");
  }else{
    Serial.print("Current time: " + formatDateTime());
  }

  //button
  pinMode(buttonPin, INPUT);

  Serial.print("Finished setup.\n\n");
}

Full code size:
Binary sketch size: 12,416 bytes (of a 32,256 byte maximum)

I'm assuming you read the text below the picture "Oops i removed the Power wire from 5V to the Vin rail before taking this pic, don't forget it!", and corrected that issue. Are you able to set and read the date/time using the ds3231.ino sketch that came with the library?

If you never see anything right then check to make sure you have the serial monitor set to the same baud rate as the sketch.  Otherwise you'll have to show some complete code that exhibits the issue.  The problem obviously isn't in the setup function.

@VE7JRO I did, originally had it on the 3.3v, as I thought I saw somewhere that it could run on it. I moved it to 5v as a debugging measure. As stated above, It seems to work properly with the example code.

@Delta_G unfortunately I have alot of code in this build already, hence the cut back example I gave. Tomorrow I will see about providing more

I don't see how anyone could possibly spot the problem without being able to see it.  Look for the obvious suspects like a buffer overrun or something.

@Delta_G Added full code, without loop(), as problems start before it

Memory is never allocated for the result of formatDateTime().
Or more exactly there is a local variable inside formatDateTime() which has memory allocated as the string is built, then formatDateTime() returns a pointer to this memory, but as soon as the formatDateTime() exits this memory is freed, hence when Serial.print() is called and passed this pointer the memory at this pointer that used to hold the string may have already been reused.

So how might I solve this then? How would you change it?

Ah! You were close..... I forgot to return on the formatDateTime() overriding function, causing the issue. Weird how it compiled though. Used to more error checking here I guess. Since the issue was in the realm of your answer (and it led me to solving the issue) I will mark this as accepted.

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


text:
How to add one JsonDocument to another in ArduinoJson
I'm utilizing this json library: https://arduinojson.org/
I am attempting to write a function that creates a response object, and wraps an already built json document:
    void sendResponse(
            ResponseType state,
            JsonDocument *response
    ) {
        DynamicJsonDocument doc(256);

        doc[F("state")] = responseTypeFromEnum(state);
        doc[F("response")] = response; //breaks; how to do?

        this->sendJson(&doc);
    }

This fails of course, and I don't see a great solution anywhere...
I know I could use createNestedObject(), but this seems to require re-creating the given json object by hand? This would be a sub-optimal case.
Is there a way to easily wrap an existing JsonDocument in another?
Looking to take
{
  "some": "other document"
}

And wrap it like
{
  "state":"OK"
  "response": {
    "some": "other document"
  }
}

You can add a JsonDocument inside another one, but you must pass the document by value, not by pointer.
Since you receive a pointer, you need to dereference it before trying to assign:
doc[F("response")] = *response;

Node 1: you could avoid this problem by passing response by reference, like so:
void sendResponse(ResponseType state, const JsonDocument &response) {
  DynamicJsonDocument doc(256);

  doc[F("state")] = responseTypeFromEnum(state);
  doc[F("response")] = response;

  this->sendJson(doc);
}

Node 2: calling the assignment operator (=) causes a deep copy of the response document. You could avoid this copy by calling shallowCopy() instead:
doc[F("response")].shallowCopy(response);

Node 3: unfortunately shallowCopy() is unavailable on ArduinoJson 7.

Interesting on Node 3.. Looks like shallowCopy() only came out in 6, so why is it gone in 7? Is there no equivalent there?
Looks like I'm currently using 6 though, compiles fine for me. Thanks for the point

Sorry, "Node" was supposed to be "Note" :-) Indeed, I removed shallowCopy() because JsonDocument doesn't store pointers to variants anymore. Instead, it stores indexes relative to the current document. It would be possible to recreate shallowCopy() but it would require extra plumbing (so extra weight), and I don't think it's worth it.

Thanks for the note!
I might personally argue that some extra code plumbing is worth a potentially large amount of end RAM usage savings to support :) (assuming it's not astronomically hard to do so)

Right, but on the other hand, it's not that difficult to avoid this situation. See the the upgrade guide for an example.


text:
ArduinoJson reading `null` from Serial
I have a setup that reads from serial when I sense that there is something to be read (and always assume that what is sent to the arduino is valid json):
void setup(){
    Serial.begin(9600);
    while (!Serial) continue;
}

void loop() {

    if(Serial.available()){
        StaticJsonDocument<256> doc;

        deserializeJson(doc, Serial);

        serializeJson(doc, Serial);
        Serial.println();
    }
}

Given the following input from ArduinoIDE's serial monitor (Set to newline setting, 9600 baud):
{"hello": "world"}

This produces the following:
{"hello": "world"}
null

I have two questions:

Is this setup correct/ how I should be waiting and retrieving json from serial?
Why the additional null input? Looks like there is something still in the serial buffer even after the first iteration?
How to detect the second case where the resulting document gets re-serialized as null? Comparing to 0, NULL, and nullptr seem to not work Figured this one out, found out about DeserializationError

Upon utilizing DeserializationError, looks like the null parsing had an error of EmptyInput

what is sending the data? ... what is the actual data that is sent?

The Arduino IDE serial console

manual input data then .... what are the serial console settings? ... there is more than one setting

Updated to show setup function

I said serial console settings

Updated to show settings (newline, 9600 baud)

As observed on your serial console settings, it mentions both newline and 9600 baud. Let's break this down:
Issue with Serial Communication

Partial Payloads: You are currently assuming that when Serial.available() returns true, the entire JSON payload has been received. However, due to the nature of serial communication (especially at 9600 baud), data can arrive in fragmented chunks. Invoking deserializeJson() on a partial JSON payload can result in incomplete or corrupted data.

End-of-Message Ambiguity: Lacking a definitive end-of-message marker makes it challenging to discern when a complete JSON payload has been received. For instance, when sending {"hello": "world"} from the Arduino IDE's serial monitor, it automatically appends a newline (or a carriage return based on your configuration). This newline is then misinterpreted as another JSON payload, leading to the undesired null output.

How you can solve this:

Use a Delimiter: Choose a specific character or sequence to act as an end-of-message delimiter. The newline character (\n) is a typical choice, especially if data is exclusively sent from the Arduino IDE's serial monitor. Nevertheless, if you anticipate newlines within your JSON data, you might consider another distinct character, like #.

Read Until Delimiter: Adjust your code to continuously read characters from the serial port until the chosen delimiter is encountered. Upon receipt of the entire message, it can then be parsed.

Code Example
Here's a sample code employing the newline character as a delimiter:
const int maxBuffer = 256;
char serialBuffer[maxBuffer];
int bufferPos = 0;

void setup() {
    Serial.begin(9600);
    while (!Serial) continue;
}

void loop() {
    if (Serial.available()) {
        char inChar = Serial.read();

        if (inChar == '\n') {  // EOM
            serialBuffer[bufferPos] = '\0';
            processMessage(serialBuffer);
            bufferPos = 0;  // Reset buffer pos
        } else if (bufferPos < maxBuffer - 1) {  // Avoid buffer overflow
            serialBuffer[bufferPos++] = inChar;
        }
    }
}

void processMessage(char* message) {
    StaticJsonDocument<256> doc;

    DeserializationError error = deserializeJson(doc, message);

    if (error) {
        Serial.println("Failed to parse JSON");
    } else {
        serializeJson(doc, Serial);
        Serial.println();
    }
}

This way you ensure the entirety of message is parsed and received and therefore avoiding unwanted null outputs.
I hope this helps ^_^


text:
How to light up RGB Leds at the exact same time?
I have 2 sets of RGB Leds, each set is driven by 3 OUTPUT analog pins of the arduino, as illustrated below:

The code is supposed to put on HIGH the 6 analog pins at the same time so that the Leds light up all at the same time, but when I run it, there's a latency between the 2 groups of Leds.
Here's the code:
const int r[2] = {3, 9};
const int g[2] = {5, 10};
const int b[2] = {6, 11};

const int red[3] = {255, 0, 0};
const int green[3] = {0, 255, 0};
const int blue[3] = {0, 0, 255};

int* colors[3] = {red, blue, green};

void setup() {
    for(int i=0;  i<2; i++){
        pinMode(r[i], OUTPUT);
        pinMode(g[i], OUTPUT);
        pinMode(b[i], OUTPUT);
  }
}

void setColor(int r, int g, int b, int color[]){
    int R = 255 - color[0];
    int G = 255 - color[1];
    int B = 255 - color[2];
    analogWrite(r, R);
    analogWrite(g, G);
    analogWrite(b, B);
}

void loop() {
    for(int c=0; c<3; c++){
      setColor(r[0], g[0], b[0], colors[c]);
      setColor(r[1], g[1], b[1], colors[3-c-1]);
      delay(1000);
    }
}

I should point out that the values of the resistors are in my circuit are different than in the diagram.
Is there something wrong in the wiring or in the code that prevents the Leds from wiring all at the same time?
EDIT: I tried the code one more time on the arduino and all Leds lit up at the same time. That happened in the past, but sometimes there's just a latency that I can neither explain nor fix...

How should 3 groups of each 3 ints fit into an array of type int and size 3? you need either a 2 dimensional array or a bigger type (like long, which has 4 bytes instead of the 2 bytes of int)

You can't use red, blue and green as ints in colors[], they are int*s, and you can't call setColor() with 5 arguments. Does this even compile for you?

@it worked event with that... I edited the code to correct the problem and checked that the code compiled on the arduino IDE.

How big is the latency? Maybe you reflect if the delay(1000) is at the right place. analogWrite() will take some time to execute, but it should be only a few milliseconds and I doubt that one would notice. If he latter is the case, you should try direct port manipulation

How much latency are we talking about? Seconds or just fractions of a second? If your code and your hardware are correct, the time between the lighting of the two LEDs should be imperceptible.


text:
Not Able to communicate with ESP8266
I just bought an Esp8266(not the node MCU) and tried connecting it with Arduino without a USB to serial converter but in vain. I am a beginner and don't know what to do. It is not responding to AT commands. Can anyone give me a detailed step by step process to connect it?
I am using Arduino UNO R3.
This is my connection diagram:-

I uploaded an empty code(Bare minimum example code), just to see if the AT commands are working, but it failed to respond. I reflashed it, then also it is not working.
when I type AT it shows nothing. But if I shake it, sometimes it shows gibberish.

Right now all I'm trying to go is get you to bring it up to the state of being an answerable question.  Already looks better than what you started with. Still a ways to go.  I'm confused as to what the thinking behind "uploaded an empty code" is.  How were you thinking that would help?

Does this answer your question? Arduino Uno with ESP8266-01 with AT

Hey @Juraj I tried to send some commands, it shows gibberish and wdt reset with rst_cause:4

If it shows gibberish when you shake it, you have a bad connection somewhere. Also, what code are you trying this with? Do the baud rates match and did you set them to a low enough value (9600 recommended)?

Hey, thanks for replying. Just bought another one and it worked properly.


text:
L298N Motor Driver not working
I am using a L298N motor driver to connect a motor with NodeMCU. But i did a few tests since a few tests while learning how to control it now when i connect it the motor doesn't even work. Then i removed the nodemcu and just used the motor driver to control the motor, then also it did not work. I don't know why.
I am new to controlling motors and this is my first time.
Also I am using 9v battery to power the motor driver.
l298n- https://www.amazon.in/gp/product/B08SK2ZPYD/ref=ppx_yo_dt_b_asin_title_o00_s00?ie=UTF8&psc=1
nodemcu - https://www.amazon.in/Lolin-NodeMCU-ESP8266-CP2102-Wireless/dp/B010O1G1ES/ref=sr_1_2?dchild=1&keywords=nodemcu&qid=1617973657&s=industrial&sr=1-2

Please post the schematic of your wiring.

Add links to each hardware item.  9V batteries are very poor choice for motors.

@gil so which battery do you suggest. I also suspected that it was not getting enough power.

I do not know your skills, and resources so I decline to make a recommendation. I use LAB power supplies and size batteries when the project if finished.


text:
Using millis(), in nested loops
I am using millis() to flash some lights (neopixels) on an arduino pro mini. The problem is that I cannot flash the lights for the desired period. More specifically, the lights flash for ~250 ms, whereas I want to flash for 9 seconds! Here is a simplified version of what I am doing.
In loop(), I have a while loop (let's call it loop 1) that should run for 250 ms. Inside loop 1, I call a function flash(), that has to run for 9 seconds! I put another loop (loop 2) after loop 1, that would run for 3 seconds.
Here is the bigger picture...I actually want a radio to wake up for 250 ms. If in that time interval it receives anything, flash() will be called that will flash the lights for 9 secs. If it doesn't receive anything it will simply go to sleep for 3 secs, then come back alive for 250 ms, so on and so on
void loop() {
    previousMillis = millis();
    while (millis() - previousMillis < awake_interval) {  //awake_interval = 250 ms
        flash();  //flash for 9 seconds
    }

    previousMillis = millis();
    while (millis() - previousMillis < sleep_interval);  //sleep_interval = 3 secs
}

The flash() function looks like this,
void flash() {
    unsigned long x = millis();
    while(millis() - x < flash_time){  //flash_time = 9 secs
        lights_on();
        delay(t1);
        lights_off();
        delay(t2);
    }
}

I put loop 2 in there because without it the lights flash forever. This makes sense because all the code is in an infinite loop - void loop().
For debugging, I put serial prints after entering the loops. It seems that nesting two loops (in my case flash() inside loop 1), both of which uses millis() is the source of the problem. If that is true, how else should I do this? If that is not the problem, any ideas will be appreciated.
Edit: The suggestions made by @VE7JRO and @ratchet freak are neat but I was still having problems making my thing work. Turns out it was a problem with one my initializations. I am posting my whole code below (that uses LEDs). I guess I should post the correct code as an answer.
const long sleep_interval = 3000;
const long awake_interval = 250;
const int ledPin = 3;

const uint8_t flash_time = 9000;  //bug
const uint16_t t1 = 5;
const uint16_t t2 = 495;

void flash() {
    unsigned long x = millis();
    while(millis() - x < flash_time){
        digitalWrite(ledPin, HIGH);
        delay(t1);
        digitalWrite(ledPin, LOW);
        delay(t2);
    }
}

void setup() {
    Serial.begin(57600);
    pinMode(ledPin, OUTPUT);
}

void loop() {
    unsigned long x = millis();
    while(millis() - x < awake_interval){
        Serial.println("flash time!");
        flash();  //overflow will occur
    }

    unsigned long y = millis();;
    while (millis() - y < sleep_interval) {  //sleep_interval = 3 secs
        Serial.println("Sleep time!");
    }
}

Post your full code.

your  'while (millis() - previousMillis < sleep_interval);'  is nothing else like delay(sleep_interval). rewrite your code to one main loop, executing lights_on() and lights_off() on 'timeline schedule'

@Juraj I don't understand what you mean by "timeline schedule". And I cannot use delay, because it's blocking, and this won't go with the rest of the (bigger) program

I was wrong being too confident about my whole code. When people suggested posting my whole code, I should have just done it!!!
Anyway, here is the mistake I made. I initialized the variable flash_time as an 8-bit integer. Of course, 8 bit can only hold up to 255. I am trying to store 9000!!! The following code has this bug fixed.
const long sleep_interval = 3000;
const long awake_interval = 250;
const int ledPin = 3;

const uint16_t flash_time = 9000;  //bug fixed by using uint16_t instead of uint8_t
const uint16_t t1 = 5;
const uint16_t t2 = 495;

void flash() {
    unsigned long x = millis();
    while(millis() - x < flash_time){
        digitalWrite(ledPin, HIGH);
        delay(t1);
        digitalWrite(ledPin, LOW);
        delay(t2);
    }
}

void setup() {
    Serial.begin(57600);
    pinMode(ledPin, OUTPUT);
}

void loop() {
    unsigned long x = millis();
    while(millis() - x < awake_interval){
        Serial.println("flash time!");
        flash();
    }

    unsigned long y = millis();;
    while (millis() - y < sleep_interval) {  //sleep_interval = 3 secs
        Serial.println("Sleep time!");
    }
}

So, nested loops that use millis() to determine the terminating conditions work just fine, even if loop 1 runs for 250 ms and loop 2 (that's inside loop 1) runs for much longer, like 9 seconds.
Apologies if I have wasted too much of people's time.

Use a state machine instead:
bool  flashing;
unsigned long lastflashingChange;

void loop() {
    unsigned long currentMillis = millis;
    if(flashing){
        flash();  //update flash state and change IO pin
        if (lastflashingChange - currentMillis >= awake_interval) {  //awake_interval = 250 ms
            flahsing = false;
            //turn off the led
            lastflashingChange = currentMillis;
        }
    } else {
        if (lastflashingChange - currentMillis >= sleep_interval) {  //awake_interval = 250 ms
            flashing = true;
            //possible initialize flash state
            lastflashingChange = currentMillis;
        }
    }
}

And a similar bit of code inside flash()
bool flashOn;
unsigned long lastFlashLightChange;
void flash() {
    unsigned long x = millis();

    if(flashOn){
        if (lastFlashLightChange - x >= t1) {
            flashOn = false;
            lights_off();
            lastFlashLightChange = currentMillis;
        }
    } else {
        if (lastFlashLightChange - x >= t2) {
            flashOn = true;
            lights_on();
            lastFlashLightChange = currentMillis;
        }
    }

}

This one looks really good...going to try it. But the line previousMillis = millis(); in your first block of code isn't really necessary, right?

@Tahseen no it isn't necessary.

This is smart but it will not flash the lights for 9 seconds, but only 250 ms (that is awake_interval). Here is the bigger picture...I actually want a radio to wake up for 250 ms. If in that time interval it receives anything, flash() will be called that will flash the lights for 9 secs. If it doesn't receive anything it will simply go to sleep for 3 secs, then come back alive for 250 ms, so on and so on

@Tahseen you can choose other ways to change state than just the time having elapsed. Just change the condition in the if. You can also have more states, change the bool to an enum and change the if/else to a switch.

Here is a sketch to get you started. It doesn't use delay or any libraries. I don't have any NeoPixel devices so I used the Arduino built in LED for testing purposes. Just remove the "myTimer4" function and related code/variables to stop the blinking LED. I don't know what type of "radio" you are using so I used a character inputed in the serial monitor to simulate a radio signal being received. There are several serial print statements throughout the code for testing purposes as well.
const unsigned long delayTime = 3000;
const unsigned long delayTime2 = 250;
const unsigned long delayTime3 = 9000;
const unsigned long delayTime4 = 500;
unsigned long previousMillis = 0;
unsigned long previousMillis2 = 0;
unsigned long previousMillis3 = 0;
unsigned long previousMillis4 = 0;
byte checkForData = 0;
byte dataReceived = 0;
byte flashLED = 0;
byte doOnce = 0;

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

void loop(){

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

  // First event.
  if(checkForData == 0){
    if(myTimer1(delayTime, currentMillis) == 1){
      Serial.println("3 second timer done");
      checkForData = 1;
      previousMillis2 = currentMillis;
    }
  }

  // Second event.
  if(checkForData == 1){

    // Your radio code here to check for data.

    // I'm simulating data input from your device using the serial monitor.
    if(Serial.read() > 0){dataReceived = 1;}

    if(myTimer2(delayTime2, currentMillis) == 1){
      Serial.println("250 ms timer done");
      checkForData = 0;
      previousMillis = currentMillis;
      if(dataReceived == 1){
        flashLED = 1;
        previousMillis3 = currentMillis;
        dataReceived = 0;
      }
    }
  }

  // Third event.
  if(flashLED == 1){
    if(doOnce == 0){
      flash(1);
      doOnce = 1;
    }
    if(myTimer3(delayTime3, currentMillis) == 1){
      Serial.println("9 second timer done");
      flashLED = 0;
      flash(0);
      doOnce = 0;
      digitalWrite(LED_BUILTIN, LOW);
    }
  }

  // Fourth event.
  if(myTimer4(delayTime4, currentMillis) == 1 && flashLED == 1){
    //Serial.println("500 ms timer done");
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
    previousMillis4 = currentMillis;
  }

}

// Function to send data to the NeoPixel device.
void flash(byte startStop){
  if(startStop == 1){Serial.println("flash function started");}
  if(startStop == 0){Serial.println("flash function ended");}
}

// First event timer.
byte myTimer1(unsigned long delayTime, unsigned long currentMillis){
  if(currentMillis - previousMillis >= delayTime){previousMillis = currentMillis;return 1;}
  else{return 0;}
}

// Second event timer.
byte myTimer2(unsigned long delayTime2, unsigned long currentMillis){
  if(currentMillis - previousMillis2 >= delayTime2){previousMillis2 = currentMillis;return 1;}
  else{return 0;}
}

// Third event timer.
byte myTimer3(unsigned long delayTime3, unsigned long currentMillis){
  if(currentMillis - previousMillis3 >= delayTime3){previousMillis3 = currentMillis;return 1;}
  else{return 0;}
}

// Fourth event timer.
byte myTimer4(unsigned long delayTime4, unsigned long currentMillis){
  if(currentMillis - previousMillis4 >= delayTime4){previousMillis4 = currentMillis;return 1;}
  else{return 0;}
}

Your logic is wrong. If you update previousMillis with millis() value in the first line, you are always subtracting the time difference between the the first and second lines of your code (which is the same you are doing in the loop inside flash()). If what you need is to get the time passed since the program started running, you need to have a fixed variable for that in setup() instead of updating it every time in loop().
Even so, I don't see why millis() is necessary in your case. Using delay() would be much more simple and still get the job done. Example:
void setup() {
delay(250);
}

void loop(){

    for(int i = 0; i < 9; i++){
        digitalWrite(LED, HIGH);
        delay(time);
        digitalWrite(LED, LOW);
        delay(time);

        delay(1000 - 2*time); //Delays the loop exactly one second per iteraction
    }

}

I cannot use delay, because it's blocking, and this won't go with the rest of the (bigger) program. Could you please expand a bit more on your idea of putting a fixed variable in setup()? My while loops are trying to determine the period of time to stay inside.

@Tahseen: You wrote “I cannot use delay” and yet you are using it in flash(). So what’s the deal?

Exactly... I didn't understand what you mean by "it's blocking", what's the reason you can't use it?

I used it in flash() to have the effect of lights turning on and off. But if I use it in the actual while loop, other things that I hope to incorporate in the future cannot work. For example, I want to use a radio that wakes up for 250 ms, sees if it has any command, then goes to sleep for 3 secs. If it received a command in that 250 ms interval, the arduino will flash the lights for 9 secs

the lights flash for ~250 ms, whereas I want to flash for 9 seconds!

that logic doesn't make sense. Essentially you want to eat a 2 hour meal within 5 seconds.
your code reflects that kind of logic: when the execution exits flash(), it must also exit the while loop in loop().
so think exactly what you want to do, write it down and then code to it.


text:
How to toggle LED on button press?
I want to have a LED turn on when I push a button and go off when I push the button a second time.
This code doesn't work:
const int buttonPin = 4;
const int motorPin =  10;
const int ledPin = 6;
 int x = 1;
// variables will change:
int buttonState = 0;

void setup() {
  // initialize the LED pin as an output:
  pinMode(motorPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
}

void loop(){
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH && x==1) {
     digitalWrite(motorPin , 1);
     x=0;
    }
  if (buttonState == HIGH && x==0){
    digitalWrite(motorPin, 0);
    x=1;
  }
  delay(1);
}

What could be wrong?

So is your LED connected to pin 6 or pin 10? You have pin 6 named ledPin but you are changing motorPin in your loop.

What's your circuit? Can you provide a schematic? Also, what is "doesn't work?" Is it lit up for any amount of time?

Reading your question I also suspect you don't have a pull-down resistor on the input pin.

At the moment, you've got two main problems. Firstly, both your if statements are being triggered one after the other. This is because the first if statement sets x to 0, which is part of the condition the second if statement looks for.
The second problem is that you're not monitoring the previous state of the button. buttonState will appear HIGH every time round loop, even if the button has been held down for several seconds. The result is that the output pin will be quickly getting turned on and off all the time.
What you need to do is store the last known state of the button. On every iteration of the main loop, only respond to the button if it's currently HIGH, and if it was LOW last time round the loop. You also need to make sure your two if statements are mutually exclusive; i.e. if you trigger one then don't trigger the other by mistake too, or it will cancel it out.
Something like this should work better:
// This will store the last known state of the button
int oldButtonState = LOW;

void loop()
{
  // Get the current state of the button
  int newButtonState = digitalRead(buttonPin);

  // Has the button gone high since we last read it?
  if (newButtonState == HIGH && oldButtonState == LOW) {

    if (x == 0) {
      // Toggle on
      digitalWrite(ledPin, HIGH);
      x = 1;

    } else {
      // Toggle off
      digitalWrite(ledPin, LOW);
      x = 0;
    }
  }

  // Store the button's state so we can tell if it's changed next time round
  oldButtonState = newButtonState;
}

As noted elsewhere, you still need to debounce the button, otherwise you're likely to get some false-positives. That can be done in hardware or software. A really simple way to get around it temporarily is to put in a delay of several milliseconds every time you detect the button changing state. It's not perfect, but it might be enough to get you started.

Don't forget to turn ON the LED:
digitalWrite(ledPin, HIGH);

And OFF:
digitalWrite(ledPin, LOW);

I just grabbed the version from the ones above here and made is somewhat smaller in terms of code. Feel free to use it in your Arduino app.
// This will store the last known state of the button
int lastButtonState = LOW;

void loop()
{
  // Get the current state of the button
  int currentButtonState = digitalRead(buttonPin);

  // Has the button gone high since we last read it?
  if (currentButtonState == HIGH && lastButtonState == LOW) {
     // Switch the state of the output
     digitalWrite(ledPin, !digitalRead(ledPin));
  }

  // Store the button's state so we can tell if it's changed next time round
  lastButtonState = currentButtonState;
}

You are not handling debouncing at all. Mechanical buttons typically bounce for a few milliseconds after an "on" press. Arduino software (or some specialist hardware) needs to handle this. This really matters when you expect a button to toggle some output pin.

You don't need a separate variable to store the state of the LED. The output pin register does that already. So you can toggle the LED simply with
    digitalWrite(ledPin, !digitalRead(ledPin));

or if you prefer
    if(digitalRead(ledPin))
       digitalWrite(ledPin, 0);
    else
       digitalWrite(ledPin, 1);

In you code the loop executes many times while the key is bouncing. If you delay by at least 50mS after the key press is first detected, and you have toggled the led and turned on the motor, then you have effectively debounced the button. If you hold the key down continously the led will toggle every 50mS (plus a little overhead)

// When first time program launches it confused to press push button twice. Well replace it with this

if (x == 1) {
    // Toggle on
    digitalWrite(ledPin, HIGH);
    x = 0;
} else {
    // Toggle off
    digitalWrite(ledPin, LOW);
    x = 1;
}

What happens if I hold the button? Think about that.

check this code. I have made some changes in your code. its working.
const int buttonPin = 2;
const int motorPin =  6;
const int ledPin = 13;
int x = 1;
// variables will change:
int buttonState = 0;

void setup() {
  // initialize the LED pin as an output:
  Serial.begin(9600);
  pinMode(motorPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
}

void loop() {

  buttonState = digitalRead(buttonPin);
//  Serial.println(x);
  if(buttonState == LOW && x == 1)
  {
    Serial.println("buttonState == HIGH && x == 1");
    digitalWrite(ledPin, HIGH);
    delay(500);
    x = 0;
    Serial.println("x == 0");
  }
  else if (buttonState == LOW && x == 0)
  {
    Serial.println("buttonState == HIGH && x == 0");
    digitalWrite(ledPin, LOW);
    delay(500);
    x = 1;
    Serial.println("x == 1");
  }
  delay(1);
}

success case tested OK,modified from arduino examples.UNO r3,atmega 328
try it !!!!!
/*  The circuit:
  - pushbutton attached to pin 2 from +5V
  - 10 kilohm resistor attached to pin 2 from ground
  - LED attached from pin 13 to ground (or use the built-in LED on most
    Arduino boards)
*/

// this constant won't change:
const int  buttonPin = 2;    // the pin that the pushbutton is attached to
const int ledPin = 8;       // the pin that the LED is attached to

// Variables will change:
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

void setup() {
  // initialize the button pin as a input:
  pinMode(buttonPin, INPUT);
  // initialize the LED as an output:
  pinMode(ledPin, OUTPUT);
  // initialize serial communication:
  Serial.begin(9600);
}

void loop() {
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);

  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    // if the state has changed, increment the counter
    if (buttonState == HIGH) {
      // if the current state is HIGH then the button went from off to on:
      buttonPushCounter++;
      Serial.println("on");
      Serial.print("number of button pushes: ");
      Serial.println(buttonPushCounter);
    } else {
      // if the current state is LOW then the button went from on to off:
      Serial.println("off");
    }
    // Delay a little bit to avoid bouncing
    delay(10);
  }
  // save the current state as the last state, for next time through the loop
  lastButtonState = buttonState;

  // turns on the LED every four button pushes by checking the modulo of the
  // button push counter. the modulo function gives you the remainder of the
  // division of two numbers:
  if (buttonPushCounter % 2 == 0) {
    digitalWrite(ledPin, LOW);
  } else {
    digitalWrite(ledPin, HIGH);
  }
}

Pinouts, pullups and logic errors have been addressed elsewhere, so I will focus on switch debouncing.  Debouncing, in my opinion, is best handled in software (rather than hardware) for large volume production costs and lazy programmers (like me).  For small projects a simple pullup / cap circuit offers better reliability and improved speed, but I'm just lazy in my old age.  Also keep in mind that switch bounce worsens significantly over the life of a switch.  I've seen new PB's with bounce < 20 ms worsen to over 300 ms with reasonable usage, so keep that in mind with projects that become semi-permanent.
Here's what I use for a software solution on a fairly bouncy SPST NO pushbutton. In this case, I'm using NO PB to GND with 1K external pullups, since I personally don't want to depend on whether or not the internal pullup still works on older devices I may have abused in a former life.... Of course, arguments could be made for various areas still needing cleanup, improved encapsulation, quicker response, higher quality, etc., but this works for me for now.
inSw.h:
class inSw
{
private:
    volatile boolean swState;           // current state ( 0 / 1 ) of switch

public:
    uint8_t  pinNum;
    volatile unsigned long lastPush;    // Time (millis() ) when last switch push detected
    unsigned long debTime = 30;         // Time (micros() ) required to debounce switch

    void init(uint8_t sw);
    boolean readState(void);
} ;

inSw.cpp:
void inSw::init(uint8_t sw) {
    pinNum = sw;
    pinMode(sw, INPUT);
    swState = 0;
    lastPush = millis();
};

boolean inSw::readState() {
//  swState = digitalRead(pinNum);
return swState;
}
void setupSwitches(void) {
    swS1.init(I2C_SOA);     // pin D20
    attachInterrupt(digitalPinToInterrupt(swS1.pinNum), swS1Press, FALLING);
}

Interrupt Service Routines are placed outside Setup() and Loop(), with the attachInterrupt (above) called from inside Setup().  This allows the switch to break long-running routines, such as Stepper.step(10000) which bangs against the limit switch on step 14....
void swS1Press() {
    unsigned long now = millis();
    if (swS1.lastPush < (now - swS1.debTime)) { // if newly pushed
        RunStop.toggle();
        swS1.lastPush = millis();       // sw last pushed now

        if (RunStop.val == RS_RUN)
            digitalWrite(LED_PIN, HIGH);   // set the LED on
        else
            digitalWrite(LED_PIN, LOW);   // set the LED off
    }
}

Lastly, just remember to check the switch state at various points inside loop().  I use this switch as an emergency stop switch, and the onboard LED to ensure it triggers.

hello sachleen try this code it working I edited from your code
// This will store the last known state of the button
const int buttonPin = A15;   // change as per your button attached.
const int motorPin =  12;   //
const int ledPin = 13;
 int x = 1;
// variables will change:
int buttonState = 0;
int oldButtonState = LOW;

void setup() {
  // initialize the LED pin as an output:
  pinMode(motorPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  // Get the current state of the button
  int newButtonState = digitalRead(buttonPin);

  // Has the button gone high since we last read it?
  if (newButtonState == HIGH && oldButtonState == LOW) {

    if (x == 0) {
      // Toggle on
      digitalWrite(ledPin, HIGH);
      x = 1;

    } else {
      // Toggle off
      digitalWrite(ledPin, LOW);
      x = 0;
    }
  }

  // Store the button's state so we can tell if it's changed next time round
  oldButtonState = newButtonState;
}

Rahul, next time please select your code, and press Ctrl+K to indent it 4 characters. That way it displays better on the page.


text:
How to read RPS for fast rotation with status change method in Arduino?
I'm trying to calculate the coming RPS from rotary encoder. I am  trying to get it by checking the status with digitalRead. However, I can not get more than 6 RPS. Any solution? I will be obliged for your help.
Following is the code.
float rps;

void setup() {
  Serial.begin(9600);
  DDRC &= ~_BV (1); // pinMode (A1, INPUT);
}

void loop() {
  static int lastReedState;
  static unsigned long lastTransition;
  int reedState = (PINC & _BV (1)) == 0; // digitalRead (A1);
  // On a rising transition of the reed switch:
  if (reedState == LOW && lastReedState == HIGH) {
    // HIGH LOW measuring the low period
    // Compute time since last valid transition.
    unsigned long now = micros();
    unsigned long revolutionTime = now - lastTransition;
    // measuring the High period
    // Compute the RPS
    rps = 1.00 / (12.00*revolutionTime) *1000000.00;
    // 12 is rotary encoders resolution
    // Remember this transition.
    lastTransition = now;
  }
  // Remember last state.
  lastReedState = reedState;
  Serial.println(rps);
}

Just asking, what Arduino do you use? Why  not using interrupt?

I am using Arduino Uno. As the matter of fact I have to read 8 input. in that case interrupts become very complicated.

have you tried using multiple PulseIn()?

When I use PulseIn(), it will affect other process after a while. Therefore, I avoid using such function.

Your code is so slow because of Serial.println(rps);. You should at least embed this statement inside something like if (millis() - lastTimePrinted >= PRINT_PERIOD) { ... } and not try to print faster than your baud rate (960 bytes/s).

Use interrupts, and use commands sei() and cli() to turn on and off interrupts. While you do important things turn off the interrupts and when count RPS turn them on again.

Consider using code similar to that shown in answers to the following questions: Reading from a KY-040 rotary encoder with Digispark; and Read RC receiver channels using Interrupt instead of PulseIn; and Can external interrupts be OR'd together on the '328 (Uno)?.
The first answer illustrates a fast-operating state machine to handle quadrature-encoded signals, ie rotary-encoder inputs.
The second answer illustrates handling of multiple encoders via a single interrupt routine, using a pair of two pin-change-interrupt (PCI) pins per encoder.  The method assumes pins of a pair are in the same port.  Most Arduino IO pins are PCI capable; some are not; on some models of Arduinos, some PCI pins aren't brought out to headers, or aren't recognized as PCI by the IDE, as noted in the question Why PJ0 and PJ1 are not reporting as PCINT pins.
The third answer includes code from the first two, and also has a sketch that displays a table of PCI vectors and masks.  This table assists in planning pin layouts to reduce ISR overhead.  For example, if you have half a dozen encoders, you might attach three of them to six pins on one port (and one vector), and the other three to six pins on another port (and another vector).  Or you might put two encoders on each of three ports.  The latter method might run, on average, a little faster (eg a microsecond or so per ISR invocation).

For one channel I'd use Input Capture capability on Timer/Counter 1. Without debouncing it'll be pretty easy.
If you want to read 8 inputs simultaneously, you can use Pin Change interrupts and Timer/Counter 1 as a timebase. If you don't use Serial communication, you can use whole PORTD, otherwise you can use for example 4 channels on PORTC and 4 channels on PORTD. But again, debouncing will be little bit challenging.

I am wondering If it is possible to use more than one interrupt in either PORTC or PORTD . Because I did in that way and could not get proper result for more than one interrupt per either port.

@zalt For Pin Change Interrupts no, there is one Interrupt source for each Port. You have to figure out, which lines were changed. However there is an Arduino library PinChangeInt where you can register callback function for each input.

Implemented with a state machine, quadrature coding does not need debouncing.  Bounce can cause invalid states or extra states,  but they cancel out.

@jwpat7 Right, I've missed it's about rotary encoder(s) and his code looks like he's using something like reed switches.

Ok . So far done for one. I have another question. I make new question.

authors: ปวิชญา ทองบพิตร


text:
Multiple GSM shields on one Arduino
I am looking for a way to listen for received text messages on multiple numbers. When I came across the Arduino and its shields, I thought to myself this might be the perfect way to do just that.
One of the modules / shields I found on the internet by watching a youtube video is the TC 35 GSM.
I have been reading multiple questions here regarding the "stacking" of shields, and the usual reply is "check what pins / if they are using the same pins". Though these questions were not GSM module specific, and did not include stacking the same shields.
So I am very curious if this is possible. Let's say I want to listen to 10 SIM cards at once for received messages, will this be possible by stacking the modules on one Arduino?
Thanks!

The short answer is, no, you can't just stack them, but yes, it is possible (though not trivial) to connect ten or more of these to a single Arduino board and have it monitor all of them.
Note that the following explanation is simplified, possibly over-simplified, in the interests of brevity and giving you a general idea of what you're in for if you try this. Many of the details (as I mention below) could easily be one or several questions of their own.
You didn't give the datasheet for the board you're considering, so I'll work from the description of a similar board (though not an Arduino shield) using the same chip, the Cytron Technologies TC35 GSM Development Board.
Arduino shields connect various pins of their chips to pins on the Arduino board. In many (perhaps most) cases you can't have two different devices connected to the same Arduino pin, so if you were just going to plop another board on it would have to have special support for changing the pins it's using (often via jumpers) or being able to have several boards communicating on the same pins. The GSM chip you're considering uses two dedicated pins for serial communication transmit and receive; these are the pins you'll need to rewire if you're going to use multiple boards on a single Arduino.
What kind of rewiring you'll need to do depends on how many you really want. The Arduino Uno has 14 digital I/O pins, two of which are usually used for the USB serial interface to the computer, giving you six devices if you dedicate a pair of pins to each device. Since the communication rate with the boards is quite slow (9600 bps, see below) you could multiplex many of these on one pair of Arduino pins via a number of different techniques (such as using shift registers); this alone is complex enough that a different question could be devoted just to considering the possible choices, with further questions on the details of implementing each choice. You should consider, if you're interfacing with a PC, using multiple Arduino microcontrollers each with only one or a few GSM chips talking to them, talking to a PC via USB, and doing further processing on the PC.
If you're using a lot of boards you'll need to make sure you can supply enough power to them; you may need to use a power source outside the Arduino board itself. An Arduino powered from its USB interface can pull no more than 500 milliamps (because that's the USB limit). If you're using a separate power supply and the Arduino's on-board regulator, the limitation will be based on the electrical and thermal limitations of that regulator; this blog post is one detailed discussion of that.
There's also the issue of level shifting; Arduino boards usually do digital I/O at 5 volts or 3.3 V; this chip looks like it talks at 2.65 V and you or the board you're using will need to handle that. If the board you're using doesn't do appropriate level conversion there are other questions (such as this) that discuss the details of particular level-conversion solutions.
Once you have pins connected to the devices you'll need to talk to them; this involves the lower level "framing" parts of the serial protocol and the higher-level command set.
For framing the GSM chip appears to use the low-speed serial protocol framing that's standard in the computer world; aside from the voltage level difference it's the same as used in RS-232 communications between a computer and a modem or other "serial" device. The setting from the data sheet I used is "9600bps, 8-1-N, No Flow Control" which is slow enough that the microcontroller itself can easily communicate with quite a number of these without any extra hardware using bit banging. A 16 MHz Arduino executes something approaching 16 million instructions per second (most instructions are one clock cycle), giving you over 1500 instructions per bit-time to read a bit from every attached device, do the processing to turn the bits into bytes, and process the resulting messages. If you're careful with your programming, and depending on what you're doing, it shouldn't be too hard to deal with even up to a couple of dozen GSM chips, though this is almost certainly not a trivial programming job that you're going to do with standard Arduino libraries.
The higher level command set is also pretty much the same as old-fashioned computer-modem comunication; the GSM chip (and thus pretty much any board that uses it) talks standard PC-style serial protocol at 9600 bps using the AT command set. You'll see messages such as
+CMGR: "REC READ","+60125651453",,"12/07/31,10:0702+32"
Hello

when you receive an SMS and similar ones when you send an SMS.

The data sheet for the Siemens TC35 says "The  data  interface  is  implemented  as  a  serial  asynchronous  transmitter  and  receiver conforming  to  ITU-T  RS-232  Interchange  Circuits  DCE.  It  operates  at  CMOS  level  (2.65V).
All RS-232 signals on the ZIF connector are low active."
this is actually a low-voltage  equivalent of "RS232" serial. Real RS232 uses -12V and +12V signalling for binary 0 and 1 but most modern devices work with logic levels, often inverted (e.g. 0V and ~3.3V).
Most Arduinos support in hardware only a single logic-level serial interface. A few Arduinos, like the Arduino Mega, will support up to four logic-level RS232 interfaces.
Using a software library, you can emulate a serial port over the digital IO pins but the Arduino will quickly run out of processing power if you try to emulate several RS232 interfaces.

will this be possible by stacking the modules on one arduino?

Almost certainly not. I doubt the daughterboard ("shield") designers made provision for that. At the least you'd have to re-route the serial interface to nonstandard pins and check that the power requirements don't exceed what the Arduino can supply.
If you can find a module that communicates over I2C or SPI there might be a better chance of getting it to work.

I think this should read TTL logic, not low-voltage RS232. See RS-232 vs. TTL Serial Communication. Low-voltage RS232 implies that a low voltage is still a 1 and a high voltage is still a 0, however TTL actually inverts the logic, it isn't just the same logic at a lower voltage.

Not directly stacking, no. You could do a dirty trick where you bend the serial pins out sideways, letting the stack handle all the power and ground and wakeup pins and stuff. Then handle the serial communications with each module separately.
The Uno and similar only have a single UART (serial port) each, but you can emulate more with "software serial", aka "bit-bang" techniques. These are full of caveats and I wouldn't wish them on a newbie.
The Mega2560 has four UARTs, so you're getting closer. You'd need to use wires coming off those sideways-bent pins to bring the signals down to the different tx/rx pins per UART, but I could see it working.
You can also add UARTs over SPI/I2C, but that's getting into a good bit of program complexity. Look at the SC16IS750 or the MAX3100 for starters.
(There's also a horrible, horrible hack emerging in my mind: Connect a single transmit line to a demux chip, so you can pick a single TC35 to talk to at any given moment. Bus all the receive lines together with resistors/diodes. Hope you never end up in a situation where two are talking at once.)


text:
Arduino to mysql database?
I found a lot of methods on the internet and I was wondering what would be the best method to send data from sensors connected to Arduino to a MySQL database in a WAMP server continuously.

There is no absolute "best" way, there is only the way that "works best for your situation".
In a nutshell, the different methods that I can think of, and their pros and cons, are:

Simple HTTP GET with parameters

Quick to implement, light weight, but not very secure or robust. Perfectly fine for things like "send the temperature once a minute" etc, but crafting very long GET requests with lots of parameters can severely impact on both your RAM and your sanity.

HTTP POST request

Like the GET request it's fairly simple to implement, but needs more RAM since you need to know the size of the data you're sending first so you can send a Content-length header.  You can send much more that way though, assuming you have the resources for it.

SOAP

This is basically HTTP POST but with a specially XML formatted body.  It has the advantage that it's a standard protocol for transferring data and commands around the place, so there are plenty of resources to help you.  The main problem is crafting the XML at the Arduino side.

Custom TCP

Connect to a special port to communicate with your own software.  You define all of the protocol, but you have to write all (or most) of the software too.  This can be more like a serial connection to your computer but through the network.  Good for sending larger amounts of data, such as images from a camera, etc.

Custom UDP

If you want to send lots of small values very frequently this is probably the best bet.  Harder to implement than most of the others, but the light-weight nature of UDP means you can send data much more rapidly.  Of course, with UDP, you run the risk of losing packets since it's very much a "fire and forget" protocol - you send a packet and hope it gets there.  Fine if you don't mind missing the odd bit of data, say for higher speed temperature logging.  Of course, you have to write the server side software yourself, but there's plenty of resources to help you with that online.
So it's really not a case of "best" but "most suitable".  Define what the data is and how often you want to send it, then think about how complex you are willing to get with your programming.
Nine times out of ten a simple HTTP GET request fits the bill.

thank you @Majenko my project consists of sending LM35, LDR, PIR motion data along with the status of couple led and switches so what's the most suitable way for me ?

That depends how often you want to send. Some of it you would want to send periodically (temperature) but others you can send only when they change state. GET is probably easiest, but use different GET calls for the different types of data.

I am new to arduino so I would guess that I have to send temperature data every 1 min and the stat of switch and led every 1 seconde.

No, you would send temperature as fast as you want to (every minute is fine) but you only need to send the state of the button when someone presses the button.

okay that seems right so what method should I use ? @Majenko

If it's just one set of sensors, HTTP GET is fine.

to be exact it is :

1x ldr.
2x PIR motion.
1x LM35.

That's nothing ;)  HTTP GET would do it fine.

Thanks alot @Majenko :). Do you have a link with steps to connect with HTTP GET method ?

WebClientRepeating example in the Ethernet library?

no I meant a project that uses that method on arduino on the internet

The example shows you how to make the GET request - just modify it to add your parameters.  The server side of the project is outside the remit of this site. If you can't program your server in whatever language your server uses (PHP?) to accept that data and store it in your database, then you will have to ask about it elsewhere.


text:
Transferring OV7670 data with SPI port
I bought an OV7670 camera and I would like to use the following code:
https://github.com/ComputerNerd/ov7670-no-ram-arduino-uno
But I wonder whether it is possible to use SPI instead of I2C when I transfer the image data through Arduino to other breakout boards.

I2C is not used to get the pixel data. That is used only to configure the ov7670. You can read the pixel data by reading the IO PORTS and then send the data via SPI.


text:
Humidity values returned by DHT22 sensors failing after some time
I've built a weather station using Arduino that measures temperature/humidity and pressure using an Adafruit 8266 HUZZAH. Temperature and Humidity are measured using a DHT22 sensor a ordered from AdaFruit. The project was completed about 4 months ago and for the first three months has returned what appears to be good data. Eventually, the humidity values started returning garbage, values around 1%.
I replaced the DHT22 sensor with another, this time from a random eBay seller. This also worked fine for about a week (humidity values appear to look good in the 20-60% range).
Then all of a sudden, they dropped to 1% again.
If I run the DHTtester program (instead of my program) against the sensor and my Uno development board, the result is also 1% humidity for this sensor.
 DHTxx test!
 Humidity: 1.00 %   Temperature: 19.20 *C 66.56 *F  Heat index: 17.96 *C 64.33 *F
 Humidity: 1.00 %   Temperature: 19.20 *C 66.56 *F  Heat index: 17.96 *C 64.33 *F

So at this point, I know the problem is not with my program (happens with both my program and the DHTtest program), not with my Arduino (happens with both the 8266 in "the field" and my Uno on my couch). So something must be happening to the sensors in the field, where they work for a week to a few months, and then fail?
Any ideas?
I'm beginning to think some bug/critter is eating or doing something to the sensor (maybe they are attracted to it because it's warmer), but anyway is there a good way to shield if this is the case without affecting the values? Any other way to see what is going on?
 // Example testing sketch for various DHT humidity/temperature sensors
 // Written by ladyada, public domain

 #include "DHT.h"
 #define DHTPIN 2     // what pin we're connected to

 // Uncomment whatever type you're using!
 //#define DHTTYPE DHT11   // DHT 11
 #define DHTTYPE DHT22   // DHT 22  (AM2302)
 //#define DHTTYPE DHT21   // DHT 21 (AM2301)

 // Connect pin 1 (on the left) of the sensor to +5V
 // NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
 // to 3.3V instead of 5V!
 // Connect pin 2 of the sensor to whatever your DHTPIN is
 // Connect pin 4 (on the right) of the sensor to GROUND
 // Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

 // Initialize DHT sensor.
 DHT dht(DHTPIN, DHTTYPE);

 void setup() {
   Serial.begin(9600);
   Serial.println("DHTxx test!");
   dht.begin();
 }

 void loop() {
     // Wait a few seconds between measurements.
     delay(2000);
     // Reading temperature or humidity takes about 250 milliseconds!
     // Sensor readings may also be up to 2 seconds 'old'
     float h = dht.readHumidity();
     // Read temperature as Celsius (the default)
     float t = dht.readTemperature();
     // Read temperature as Fahrenheit (isFahrenheit = true)
     float f = dht.readTemperature(true);

     // Check if any reads failed and exit early (to try again).
     if (isnan(h) || isnan(t) || isnan(f)) {
         Serial.println("Failed to read from DHT sensor!");
         return;
     }

     // Compute heat index in Fahrenheit (the default)
     float hif = dht.computeHeatIndex(f, h);
     // Compute heat index in Celsius (isFahreheit = false)
     float hic = dht.computeHeatIndex(t, h, false);

     Serial.print("Humidity: ");
     Serial.print(h);
     Serial.print(" %\t");
     Serial.print("Temperature: ");
     Serial.print(t);
     Serial.print(" *C ");
     Serial.print(f);
     Serial.print(" *F\t");
     Serial.print("Heat index: ");
     Serial.print(hic);
     Serial.print(" *C ");
     Serial.print(hif);
     Serial.println(" *F");
}

Try the sensor resetting procedure.

my current workaround is to connect the DHT with a screw terminal instead of soldering them in, and then just swap them out when they start to fail

This is how it looks when they fail.
The DHTxx are very low cost sensors, optimised for cheap volume production.
We don't know under what condition you actually use your sensors. Also, there's the phenomenon of knock-offs and low-grade selling.
In his comprehensive test, Robert J. Smith found a failure rate of 33% and concludes a mean life expectancy of one to two years.
A slightly more expensive alternative is the SHT series of temperature and humidity sensors. My personal experience is that they tend to tolerate some abuse (i.e. complete submersion in water) and don't age as quickly.
Link:

failure analysis: http://www.kandrsmith.org/RJS/Misc/Hygrometers/dht22_first_failure.html
general writeup: http://www.kandrsmith.org/RJS/Misc/Hygrometers/calib_dht22_dht11_sht71.html#conclusions

I have had the exact same experience using a DHT11 with Huzzah. I found that the problem tends to happen after high humidity conditions (>85% relative), my solution was to place silicone caulk and heatshrink tubing around the connections to prevent dew buildup. That solved my problem with my third replacement. It has been two months now with no issues.

Can't really help as I have the same problem ! , DHT22 on an ESP8266 has failed twice , while a DHT11 on a similar system has worked faultlessly for months (Thingspeak 27272) , DHT11 is inside the house while the DHT22 is below the house in the carport, Only thing I have come up with is that the DHT22 MAY be failing due to exhaust/hydrocarbon fumes from the car startups
Art

This should probably be a comment.


text:
How can I analyse large packets on an Arduino?
I'm trying to send a large packet to an Arduino with an ethernet shield on it. I'm using the built-in RX buffer of the W5100 controller to store the data, but I need more memory (at least 16K of buffer space, the W5100 only has 8K of RX buffer space). I have control over the server side of things as I'm writing the server process myself, so I can take solutions on that side.
Is there some hack I can use in the TCP protocol to have the packet broken up?
Edit: I'm using the SFML 2.1 network API on the server side.

TCP does indeed allow telling the other end about your buffer window.  I'd be a bit surprised if the actual link level packets are individually too big.  But an Arduino is not a good choice where you need large buffers - by the time you added the ethernet shield you could have had orders of magnitude more memory at a comparable price.

@ChrisStratton The person I'm working with on this with insists on using arduino for this. On the server side I'm kind of treating the large string I need to send as one big packet.

If you are using TCP on a conventional system, you have very little visibility into what a "packet" is.  It's quite likely that your single network API call payload gets transmitted as many smaller packets. In an embedded implementation sometimes the layers collapse and you do have more detail, but the Arduino side shouldn't have to claim more than one link-level packet worth of data at a time.

@ChrisStratton, please confirm that the Arduino is not capable of receiving the "many smaller packets" and that the the OP should just send smaller packets. He could add a memory shield and fix the overflow, but that wouldn't address his question about TCP.

An application developer does not "send packets" over TCP, they send data which the TCP and lower level stacks packetize.  If the Arduino can or cannot receive the small link level packets depends on the software stack on the Ethernet module. Getting it to properly set its TCP window should help too, as that should stop data flow until the Arduino has drained the module's buffer.  Anyone proposing a "memory shield" (as in RAM) needs to have their head examined, as using the right MCU for the job is drastically faster and cheaper.

This sounds like a job for WireShark; https://en.wikipedia.org/wiki/Wireshark.

All you need to do is analyse the packet on-the-fly using a state machine.
http://www.gammon.com.au/statemachine
You certainly don't need to hold the entire packet at once, however you do need room for the information the packet contains.
Say, for example, that the packet, although wordy, contains 4 x 32-bit numbers of interest. All you need memory for is those 4 numbers, plus a minor extra amount for the current data you are processing (eg. the current state, and the current number being assembled).
Conceptually it is like streaming a movie to your PC. The PC doesn't need to hold the whole movie, it just needs to hold the current frame, and a few seconds in advance, just to keep things running smoothly.

As usual, Nick to the rescue. Your website is a treasure trove!


text:
Can't connect my ESP-12F to WiFi with my Arduino Uno
Recently I bought this wifi adapter for my IOT projects that I connected to my arduino uno that seems to not working.
I have tried with the arduino ESP8266WiFi library with RX connected to pin 0 and TX connected to pin 1 I have also tried the softwareSerial and still the same result that is, in the serial monitor i always get "error" or I get nothing
Thank you in advance and sorry if I made a mistake in the post, I am new to StackExchange :)
edit (added code to question):
#include <SoftwareSerial.h>

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

void setup() {
  // Open serial communications
  Serial.begin(115200);
  // set the data rate for the SoftwareSerial port
  // if this doesnt work you for you then try different baud rate
  ESPSerial.begin(115200);
  ESPSerial.println("Ready to take AT commands");
}

void loop() { // run over and over
  if (ESPSerial.available()) {
    // reads input from serial console and writes to esp8266
    Serial.write(ESPSerial.read());
  }
  if (Serial.available()) {
    // reads input from esp8266 and writes to serial console
    ESPSerial.write(Serial.read());
  }
}

Please add your source code as text to your post and what is your expected output? Also please tell us for which board the shown code is.

did you set in Serial Monitor the line ends?

@TarickWelling I am using arduino uno and I was expecting to enter some at commands.

gpo0 goes to ground to program the module


text:
Help with Bluetooth shield
Hey guys I have this Bluetooth shield

Does anybody know how I can get it to connect to Arduino?
I can't find any guides on it.
I have this serial program that I want to use to turn on a led.
but I can't seem to enter AT mode, or get any indication that besides it connecting to my Mac it's receiving or transmitting any signals.
Anybody got any tips for tutorials/tips for tests for a MAC OSX user?
UPDATE: here is a better foto

I'm trying to run this Arduino code. that uses a 1 to turn a led on and a 0 to turn it off. I want to send these 1's and 0's through a Mac program called Bluterm. I connect it to the HC-05 BUT it doesn't send me anything back. (THE LED IS GREEN, IT'S CONNECTED ON MAC AND ON BLUTERM)
Here is my Arduino code:

int led = 13;
int value = 0;

void setup() {
  Serial.begin(9600);
  pinMode(led, OUTPUT);

}

void loop() {
  if (Serial.available() > 0) {
    value = Serial.read();
    delay(5);

    if (value == '1') {
      digitalWrite(led, HIGH);
      Serial.println("LED IS ON");

    }

    if (value == '0') {
      digitalWrite(led, LOW);
      Serial.println("LED IS OFF");

    }

  }
  }

UPDATE 2: Here is the code from the PDF that was shipped with my shield:

unsigned int timeout=0; unsigned char state=0;
ISR(TIMER2_OVF_vect) {
TCNT2 = 0; timeout++;
if (timeout>61) {
state=1;
timeout=0; }
}
void init_timer2(void) {
//Timer2 Service
TCCR2A |= (1 << WGM21) | (1 << WGM20);
TCCR2B |= 0x07; // by clk/1024
ASSR |= (0<<AS2); // Use internal clock - external clock not used in Arduino
TIMSK2 |= 0x01; TCNT2 = 0; sei();
}
void setup() {
//Timer2 Overflow Interrupt Enable
Serial.begin(9600);
pinMode(2,INPUT); pinMode(13,OUTPUT); attachInterrupt(0,cleantime,FALLING); init_timer2();
}
void loop() {
switch(state) {
case 0:
digitalWrite(13,LOW); break;

case 1: digitalWrite(13,HIGH); Serial.print("Hellow BT"); break;
} }
void cleantime() {
timeout=0;
state=0; }

Anybody can help me decipher this code? none of this looks familiar to me
thanks guys,
juriaan
UPDATE 3:

UPDATE 4

Comments are not for extended discussion; this conversation has been moved to chat.

Look, much as I think we would all like to help you, this isn't a forum, where you take post after post to troubleshoot. The intent of the site is to answer specific problems, in such a way that other people may benefit from the answer. If you want to interactively problem-solve the Arduino Forum may be a better fit for you. Just to help you out, someone on the Arduino Forum seems to be asking a similar question.

Perhaps you could chat with them and work together to find a solution?

You need to understand the basics before you try running code to "do things":

The shield can run in two modes: AT command mode, which is used to configure it, and Transparent UART mode, which is used to communicate.
Communication with the Arduino is done through UART serial, and the pins used for that communication are selected using the big bank of jumpers.
Nothing will happen until you have configured the shield using AT commands.

To progress you really need the manual for the shield. This should be available from wherever you purchased it.  That will detail:

What the positions of the jumpers mean
What the AT command set of the module is
What the baud rate is which you need to use to communicate

And if it's any good:

Example code

Once you have at least the first set of those bits of information you can write some software for the Arduino which will pass anything received on Serial through to the bluetooth shield, and anything received from the bluetooth shield back through to Serial.  You can then use the serial monitor in the IDE to interact with the shield and configure it in the way you need it.
Once you know how to configure it you can then write some better software for the Arduino that does any startup configuration you need and then operates on the data coming in through Transparent UART mode.

The only thing of information I have from them is: https://hackerstore.nl/PDFs/BTShield.pdf . It tels me about BAUD rate of 9600. But nothing on the usage of the pins, I have mailed the retailer for more information


text:
not able to resolve "a function-definition is not allowed here before '{' token "
I, being new to Arduino started off by making a simple lcd watch which also shows the temperature.
Everything was working fine untill this error came up
"a function-definition is not allowed here before '{' token
"
And I have done everything to resolve the problem. I wrote the function from scratch. I read somewhere that a function definition can't come within  a function, so I made it a Global function(though, personally I somehow don't feel that it's true). But even then the error managed to survive.
Being completely frustrated I don't know what to do. Can anyone please help me out ?
here's my code :-
#include < LiquidCrystal.h >

  const int rs = 12,
    en = 11,
    d4 = 5,
    d5 = 4,
    d6 = 3,
    d7 = 2,
    lm = A0;
int input;
float temp;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void tem() //Calculates Temperature
{
  int i = analogRead(lm);
  float temp = 500.0 * i / 1024;

  lcd.print("Temp : ");
  lcd.print(temp);
  lcd.print(" ^C");

}

void Clock(int h = 0, int m = 0, int s = 0, char ch = 'A') {
  int H = h;

  char ampm = ch;

  void mornight(char ampm) //changes am to am to pm and vice versa
  { //THE RED HIGHLIGHTED ERROR LINE
    String AMPM;
    if (ampm == 'A')
      AMPM = "PM";
    else
      AMPM = "AM";

  }
  while (H != 12) //HOUR'S LOOP
  {
    for (int M = m; M <= 59; M++) //MINUTE'S LOOP
    {
      for (int S = s; S <= 59; S++) //SECOND'S LOOP
      {
        delay(1000);
        lcd.clear();

        if (H < 10) {
          lcd.print('0');
          lcd.print(H);
          lcd.print(':');
        } else {
          lcd.print(H);
          lcd.print(":");
        }
        if (M < 10) {
          lcd.print('0');
          lcd.print(M);
          lcd.print(':');
        } else {
          lcd.print(M);
          lcd.print(":");
        }
        if (S < 10) {
          lcd.print('0');
          lcd.print(S);
          lcd.print(AMPM);
        } else {
          lcd.print(S);
          lcd.print(AMPM);
        }
        lcd.setCursor(0, 1);
        tem(); // shows temperature

      }
      s = 0;
    }
    m = 0;
    if (H == 23) {
      H = 1;
      mornight(ampm);
    } else
      H++;
  }
}

void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(0, 1);
  Clock(10, 1, 20);

}
void loop() {

}

Your line:
void mornight(char ampm)

Is trying to define a function called mornight() inside of Clock().
Functions are "global" if they are defined outside of any other function. I can't see what you tried in order to make this function global, but besides object-oriented programming, plain functions are always global.
A "non-global" function would mean defining a class and declaring the function inside the class definition; but even then you have to define the function (that is, the actual instructions in the function) outside of any other class or function definition.

Move function void mornight(char ampm) outside of function void Clock(int h = 0, int m = 0, int s = 0, char ch = 'A') {
as the error message says, function can't be defined inside functions


text:
what is wrong with my code for buttons
int "buttons"[6];

int "buttons"[0] = 2;

When i upload the code to the board it says:
exit status 1
expected unqualified-id before string constant

please, take a coding course

"buttons" is not a valid identifier (i.e., not a valid variable name) because it does not start with a letter or underscore.
You should not repeat the type when you want to refer to the already-declared variable.

You declare the variable like:
int buttons[6];  // A 6-element array of integers

And if you want to refer to a specific element in the array:
buttons[0] = 2; // Let the first element of the array be the value 2.


text:
U8glib funny problem
I have strange problem with u8glib library. I have code:
void void_Menu_draw_func_men()
{
  if ( menu_redraw_required != 0 ) {
   u8g.firstPage();
    do  {
     Menu_draw_func_men();
   } while( u8g.nextPage() );
   menu_redraw_required = 0;
  }
}

void Menu_draw_func_men()
{

  u8g.setFont(u8g_font_6x13);
  u8g.drawStr(30, 0, "Funkcje");
  u8g.drawStr(15, 15, "Zerowanie modulu");
  u8g.drawStr(15, 30, "Modul na max");
  if(menu_pos == 0){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(144); u8g.enableCursor(); u8g.setCursorPos(10,20);}
  if(menu_pos == 1){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(144); u8g.enableCursor(); u8g.setCursorPos(10,35);}
  u8g.setPrintPos(5, 50); u8g.print("R:  "); u8g.print(pot_R , 2); u8g.print("   L:  "); u8g.print(pot_L , 2);

  Serial.println("func md");//just for check...

}

And oled display shows only cursor and I can move that cursor as I change menu_pos value. But no letters or values are printed on screen. Only cursor...
If I copy and paste only code from void Menu_draw_func_men(); to other part of my program:
void void_Menu_draw_test_man()
{
  if ( menu_redraw_required != 0 ) {
   u8g.firstPage();
    do  {
     Menu_draw_test_man();
   } while( u8g.nextPage() );
   menu_redraw_required = 0;
  }
}
void Menu_draw_test_man()
{

  u8g.setFont(u8g_font_6x13);   //replace this dwo lines
  u8g.drawStr(0, 0, "wykonywanie tefsdfs man...");

}

Everything works perfect... I was trying to change void name, and I don't know where is problem...
This is on Arduino Uno; I have 66% used of program memory, and 60% used of dynamic memory.
Maybe you have some idea?...

Your void_Menu_draw_test_man() function checks menu_redraw_required
Does your other part of the program update that variable? Do you call void_Menu_draw_test_man() from the loop() function?
It may help if you show the complete code, rather than small segments, since there are variables, such as menu_redraw_required, which are not changed anywhere in what is visible.
Note also that u8glib is no longer updated in favor of u8g2

I will check u8g2 library, maybe my u8glib couse problem...

about loops, I have while functions till i press back button, and then I back to main menu. It work fine

menu_redraw_required is in every code segment, but all segments are in while loop, there is no chance to update menu_redraw_required in different part code... My code is quite big now... but, when I enter to Menu_draw_func_men(), cursor is turned on, I can move it. I also add Serial.print(); to be sure that I enter to this void Menu_draw_func_men();. And I have always receive in console, a confirmation.
This is how I enter to selected screen from main menu:
if (digitalRead(KEY_SELECT) == LOW)
  {
    in_mmenu = false;

    switch(menu_current)
    {
      case 0:
        menu_redraw_required = 1;
        key_choose();
        break;
      case 1:
        menu_redraw_required = 1;
        test_auto();
        break;
      case 2:
        menu_redraw_required = 1;
        test_man();
        break;
      case 3:
        menu_redraw_required = 1;
        pot_read_menu();
        break;
      case 4:
        menu_redraw_required = 1;
        other_options(); **//previously i was function_menu**
        break;
    }

All screen works properly on almost the same code, only last screen on menu have problem...
See pictures how it looks. I also add code to "wybor klucza" menu. Just print part.

How I enter to void_Menu_draw... works fine in others screens. Just small part for entering methode.
 if(digitalRead(KEY_NEXT) == LOW)
{unit++; if(unit >= UNIT_ITEMS + 1)
{unit = 1;}
menu_redraw_required = 1; void_Menu_draw_keyMenu(); delay(200);}

and
void void_Menu_draw_keyMenu()
{
  if ( menu_redraw_required != 0 ) {
   u8g.firstPage();
    do  {
     Menu_draw_keyMenu();
   } while( u8g.nextPage() );
   menu_redraw_required = 0;
  }
}
void Menu_draw_keyMenu()
{

  u8g.setFont(u8g_font_6x13);
  u8g.drawStr(30, 0, "Wybor klucza");
  u8g.drawStr(15, 15, "Zespol:  "); u8g.drawStr(60, 15, menu_unit_num[unit - 1]);
  u8g.drawStr(15, 30, "Numer mod:  ");  u8g.drawStr(78, 30, menu_mod_num[module - 1]);
  u8g.drawStr(8, 50, "Modul to 2 silniki!");
  if(menu_pos == 0 && in == false){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(144); u8g.enableCursor(); u8g.setCursorPos(10,20);}
  if(menu_pos == 1 && in == false){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(144); u8g.enableCursor(); u8g.setCursorPos(10,35);}
  if(menu_pos == 0 && in == true){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(148); u8g.enableCursor(); u8g.setCursorPos(110,20);}
  if(menu_pos == 1 && in == true){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(148); u8g.enableCursor(); u8g.setCursorPos(110,35);}

}

I show you 2 more codes. There are the same, this one void_Menu_draw_test_man works, this one Menu_other_options not. Notice that I change name from functions_men to other_option, just to be sure that name don't cause this issue. I aleso update u8glib to last version. I try use u8g2 library but i will have to change almost everything...
void test_man()
{
  menu_redraw_required = 1; void_Menu_draw_test_man();
  while(digitalRead(KEY_BACK) == HIGH)
  {
    if(digitalRead(KEY_PREV) == LOW){menu_pos = 1; menu_redraw_required = 1; void_Menu_draw_test_man(); delay(200);}
    if(digitalRead(KEY_NEXT) == LOW){menu_pos = 0; menu_redraw_required = 1; void_Menu_draw_test_man(); delay(200);}
  }
  menu_redraw_required = 1;
  u8g.disableCursor();
  in_mmenu = true;
}

void void_Menu_draw_test_man()
{
  if ( menu_redraw_required != 0 ) {
   u8g.firstPage();
    do  {
     Menu_draw_test_man();
   } while( u8g.nextPage() );
   menu_redraw_required = 0;
  }
}
void Menu_draw_test_man()
{

  u8g.setFont(u8g_font_6x13);
  u8g.drawStr(40, 0, "Funkcje");
  u8g.drawStr(15, 15, "Zerowanie modulu");
  u8g.drawStr(15, 30, "Modul na max");
  if(menu_pos == 0){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(144); u8g.enableCursor(); u8g.setCursorPos(10,20);}
  if(menu_pos == 1){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(144); u8g.enableCursor(); u8g.setCursorPos(10,35);}
  u8g.setPrintPos(5, 50); u8g.print("R:  "); u8g.print(pot_R , 2); u8g.print("   L:  "); u8g.print(pot_L , 2);

}

and second
void other_options()
{
  menu_redraw_required = 1; void_Menu_other_options();
  while(digitalRead(KEY_BACK) == HIGH)
  {
    if(digitalRead(KEY_PREV) == LOW){menu_pos = 1; menu_redraw_required = 1; void_Menu_other_options(); delay(200);}
    if(digitalRead(KEY_NEXT) == LOW){menu_pos = 0; menu_redraw_required = 1; void_Menu_other_options(); delay(200);}
  }
  menu_redraw_required = 1;
  u8g.disableCursor();
  in_mmenu = true;
}

void void_Menu_other_options()
{
  if ( menu_redraw_required != 0 ) {
   u8g.firstPage();
    do  {
     Menu_other_options();
   } while( u8g.nextPage() );
   menu_redraw_required = 0;
  }
}
void Menu_other_options()
{

  u8g.setFont(u8g_font_6x13);
  u8g.drawStr(40, 0, "Funkcje");
  u8g.drawStr(15, 15, "Zerowanie modulu");
  u8g.drawStr(15, 30, "Modul na max");
  if(menu_pos == 0){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(144); u8g.enableCursor(); u8g.setCursorPos(10,20);}
  if(menu_pos == 1){u8g.setCursorFont(u8g_font_cursor); u8g.setCursorStyle(144); u8g.enableCursor(); u8g.setCursorPos(10,35);}
  u8g.setPrintPos(5, 50); u8g.print("R:  "); u8g.print(pot_R , 2); u8g.print("   L:  "); u8g.print(pot_L , 2);

}