text:
Arduino Uno, ESP8266 HTTP request have no response
Firmware version
AT+GMR

AT version:0.21.0.0
SDK version:0.9.5

OK

Connection
ESP8266(ESP-01) <> Arduino Uno
GND  <> GND
3V3 <> 3.3V
EN(CH_PD) <> 3.3V
TX  <> D2
RX <>  D3

ps) I know I must not connect RX directly to Arduino's D3.
When I level down ESP8266's RX 5V to 3.3V, ESP8266 didn't work.
But when directly, It works well.
I supply power to Arduino Uno and ESP8266 by usb from PC.
Arduino Code
    #include <SoftwareSerial.h>
    #include <ESP8266.h>        //다운 후 libraries폴더에 저장한 라이브러리

    SoftwareSerial esp8266Serial = SoftwareSerial(2, 3);
    ESP8266 wifi = ESP8266(esp8266Serial);

    #define SSID "MYSSID"
    #define PWD "MYPWD"

    void setup() {
      Serial.begin(9600);
      esp8266Serial.begin(9600);  // ESP8266

      wifi.begin();
      wifi.setTimeout(1000);

      // test
      Serial.print("test: ");
      Serial.println(getStatus(wifi.test()));

      // restart
      Serial.print("restart: ");
      Serial.println(getStatus(wifi.restart()));
      Serial.print("quitAP: ");
      Serial.println(getStatus(wifi.quitAP()));

      // joinAP
      Serial.print("joinAP: ");
      Serial.println(getStatus(wifi.joinAP(SSID, PWD)));

      // getAP
      Serial.print("getAP: ");
      Serial.println(getStatus(wifi.getAP(SSID)));

      // getIP
      Serial.print("getIP: ");
      IPAddress ip;
      Serial.println(getStatus(wifi.getIP(ESP8266_WIFI_STATION, ip)));
      Serial.print("IP: ");
      Serial.println(ip);

      // connect with webserver

      Serial.print("connect: ");
      Serial.println(getStatus(wifi.connect(ESP8266_PROTOCOL_TCP, IPAddress(192, 168, 0, 52), 3000)));
      getConnectionStatue(wifi);

      // send to webserver
      Serial.print("send: ");

      Serial.println(getStatus(wifi.send("GET /?id=arduino HTTP/1.0\r\nHost: http://192.168.0.52:3000\r\n\r\n")));
    }

    void loop()
    {
      // read data
      unsigned int id;
      int length;
      int totalRead;
      char buffer[11] = {};
      if ((length = wifi.available()) > 0) {
        id = wifi.getId();
        totalRead = wifi.read(buffer, 1000);
        if (length > 0) {
          Serial.println((char*)buffer);
        }
      }
    }

    void getConnectionStatue(ESP8266 wifi) {
      // getConnectionStatus
      ESP8266ConnectionStatus connectionStatus;
      ESP8266Connection connections[5];
      unsigned int connectionCount;
      Serial.print("getConnectionStatus: ");
      Serial.print(getStatus(wifi.getConnectionStatus(connectionStatus,                                         connections, connectionCount)));
      Serial.print(" : ");
      Serial.println(connectionCount);
      for (int i = 0; i < connectionCount; i++) {
        Serial.print(" - Connection: ");
        Serial.print(connections[i].id);
        Serial.print(" - ");
        Serial.print(getProtocol(connections[i].protocol));
        Serial.print(" - ");
        Serial.print(connections[i].ip);
        Serial.print(":");
        Serial.print(connections[i].port);
        Serial.print(" - ");
        Serial.println(getRole(connections[i].role));
      }
    }

    String getStatus(bool status)
    {
      if (status)
        return "OK";

      return "KO";
    }

    String getStatus(ESP8266CommandStatus status)
    {
      switch (status) {
        case ESP8266_COMMAND_INVALID:
          return "INVALID";
          break;

        case ESP8266_COMMAND_TIMEOUT:
          return "TIMEOUT";
          break;

        case ESP8266_COMMAND_OK:
          return "OK";
          break;

        case ESP8266_COMMAND_NO_CHANGE:
          return "NO CHANGE";
          break;

        case ESP8266_COMMAND_ERROR:
          return "ERROR";
          break;

        case ESP8266_COMMAND_NO_LINK:
          return "NO LINK";
          break;

        case ESP8266_COMMAND_TOO_LONG:
          return "TOO LONG";
          break;

        case ESP8266_COMMAND_FAIL:
          return "FAIL";
          break;

        default:
          return "UNKNOWN COMMAND STATUS";
          break;
      }
    }

    String getRole(ESP8266Role role)
    {
      switch (role) {
        case ESP8266_ROLE_CLIENT:
          return "CLIENT";
          break;

        case ESP8266_ROLE_SERVER:
          return "SERVER";
          break;

        default:
          return "UNKNOWN ROLE";
          break;
      }
    }

    String getProtocol(ESP8266Protocol protocol)
    {
      switch (protocol) {
        case ESP8266_PROTOCOL_TCP:
          return "TCP";
          break;

        case ESP8266_PROTOCOL_UDP:
          return "UDP";
          break;

        default:
          return "UNKNOWN PROTOCOL";
          break;
      }
    }

Response
    test: OK
    restart: OK
    quitAP: OK
    joinAP: TIMEOUT
    getAP: OK
    getIP: OK
    IP: 192.168.0.55
    connect: OK
    getConnectionStatus: OK : 1
     - Connection: 0 - TCP - 192.168.0.52:3000 - CLIENT
    send: OK

There is no response
On server, the request ESP8266 sent didn't come.
I have no Idea...........
Addition
I send AT commands directly to ESP8266 by Arduino IDE
connection
ESP8266(ESP-01) <> Arduino Uno
GND  <> GND
3V3 <> 3.3V
EN(CH_PD) <> 3.3V
TX  <> TX
RX <>  TX

response
AT

OK
AT+CIPSTART="TCP","192.168.0.52",3000

CONNECT

OK
AT+CIPSEND=74

OK
> GET /?id=arduino HTTP/1.0\r\nHost:http://192.168.0.52:3000\r\n\r\n

busy s...

SEND OK
CLOSED

AT+CIPSTART="TCP","192.168.0.52",3000

CONNECT

OK
AT+CIPSEND=39

OK
> GET http://192.168.0.52/id?=arduino\r\n\r\nbusy s...

SEND OK
CLOSED

AT+CIPSTART="TCP","192.168.0.52",3000

CONNECT

OK
AT+CIPSEND=39

OK
> GET http://192.168.0.52/id?=arduino\r\n\r\n
busy s...

SEND OK

Sometime connection CLOSED after sending the request, sometime connection alive.

the 3.3 V pin on Arduino can't supply enough power to esp for wifi transmission

@Juraj then How can I supply power to esp? Connecting another 3.3V to ESP8266 will be enough?

sorry I don't know. I bought an esp on a 5 V adapter board with level shifters and the 5 V pin on Uno can supply the required power


text:
MFRC522 won't detect cards after the first loop
Edit: I have found out that it was something wrong with the cables. I have solved the problem. Thanks for everyone who tried to help.
I am working a project that should basically do:

Read the RFID card UID.
Get the selection from user using pushbuttons.
Restart the code for new cards.

The problem is, It reads the card and gets the input from pushbuttons. But after the first loop, It doesn't detect other cards (or the same card again). Here is my code: (I am using miguelbalboa's MFRC522 library and Arduino UNO)
#include <MFRC522Hack.h>
#include <MFRC522Extended.h>
#include <deprecated.h>
#include <MFRC522Debug.h>
#include <require_cpp11.h>
#include <MFRC522.h>

// protype 1 copy
#include <SPI.h>

// Define pin numbers for mfrc522
#define SS_PIN 10
#define RST_PIN 9
#define BLUE_BUT A0
#define RED_BUT A1

// Define pin numbers for lcd
const int RS = A0 , EN = A1 , D4 = A5 , D5 = A4 , D6 = A3 , D7 = A2;
int uids[] = {14805 ,25673};
int votedArray[] = {};
String uidNames[] = {"WHITE" , "BLUE"};
// Create LCD and MFRC522 instances
MFRC522 mfrc522(SS_PIN , RST_PIN);

unsigned long getCardID(int showCardData = 0){
  /* this function gets the uid of the rfid card
   and returns the uid in unsigned long format */
  /* this fn. should be called with argument 1
  if printing the card data to the serial monitor
  is needed. */

  unsigned long UID_unsigned;
   UID_unsigned =  mfrc522.uid.uidByte[0] << 24;
   UID_unsigned += mfrc522.uid.uidByte[1] << 16;
   UID_unsigned += mfrc522.uid.uidByte[2] <<  8;
   UID_unsigned += mfrc522.uid.uidByte[3];

  if(showCardData==1){
  Serial.println("UID Unsigned int");
  Serial.println(UID_unsigned);

  String UID_string =  (String)UID_unsigned;
  long UID_LONG=(long)UID_unsigned;

  Serial.println("UID Long :");
  Serial.println(UID_LONG);

  Serial.println("UID String :");
  Serial.println(UID_string); } // print card data to the serial monitor
int UID_int = (int) UID_unsigned;
 return UID_int;

 }

void showCardData(){
  /* this fn. calls getCardID function
  with argument 1 to print the data to
  the serial monitor (kind of shortcut)*/
  getCardID(1);
}

int findInList(int uid , int uidArray[]){
  /* this fn. returns the index of the uid in the array if found,
  returns -1 if not found*/
  int numOfElements = sizeof(uidArray)/sizeof(uidArray[0]); // calculate the num.of elem. in array
  for (int i = 0 ; i <= numOfElements ; i++) {
    if(uid == uidArray[i]){
      return i; // if element is found in the array, return true
    }
  }
  return -1;
}

String getCardName(int cardUID){
  int UIDIndex = findInList(cardUID , uids);

  if(UIDIndex == -1){
    return "ERROR";
    }

  else {
    String cardName = uidNames[UIDIndex];
    return cardName;
    }

}

void printCardName(int cardUID){
  String cardName = getCardName(cardUID);
  if(cardName == "ERROR"){
    Serial.print("ERROR! CARD UID: ");
    Serial.println(cardUID);
    }

  else {
    Serial.print("CARD NAME: ");
    Serial.println(cardName);
    }
}

void setup() {
  Serial.begin(9600); // Init. serial comm. with the PC
  SPI.begin(); // Init. SPI bus for MFRC522
  mfrc522.PCD_Init(); // Init. MFRC522 card
  pinMode(BLUE_BUT , INPUT);
  pinMode(RED_BUT , INPUT);
}

void loop() {

    // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent()){
  Serial.println("CARD NOT PRESENT");
    return;
 }

  // Verify if the NUID has been readed
  if ( ! mfrc522.PICC_ReadCardSerial()) {

    Serial.println("CARD NOT read");
    return;  }

  int cardUID = getCardID();

  Serial.println("CARD UID READ");
  printCardName(cardUID);

  Serial.println("SELECT WITH BUTTONS");

//getVote(cardUID);
  int blueState = LOW , redState = LOW ;
  while(1) {
   blueState = digitalRead(BLUE_BUT);
   redState = digitalRead(RED_BUT);

  if(blueState == HIGH){
    Serial.println("BLUE");

    break;
    }

  if(redState == HIGH){
    Serial.println("RED");
    mfrc522.PICC_HaltA();
mfrc522.PCD_StopCrypto1();
    break;
    }

  }

Serial.println("PROGRAM COMPLETE");

}

I have already tried adding
    mfrc522.PICC_HaltA();
    mfrc522.PCD_StopCrypto1();

but didn't help.
And here is the screenshot of the Serial Monitor after reading the first card and getting the button input.

I have checked the similar problems, but the solutions didn't help me.

It's obviously returning on one of the two ifs at the start of your loop. Your job is to work out which.

Thanks for your reply Majenko, you are right and I have checked it. I have found out that the first if statement (PICC_IsNewCardPresent()) causing it. But what can be the problem, why doesn't it detect the cards ?

I think the clue might be the word "new" in there - it won't detect the same card twice (second time it's not new, it's old), and maybe the other cards are the same ID or maybe broken? Who knows...  Do you get the same result regardless of which card you try first?

I don't think it is due to cards, because when I run the code without the "getVote" part, It works fine: reads the card UID, prints the name of the card. Something in that part should be affecting the reader. And yes, the result is same regardless of the order of the cards.

Which pins are RED_BUT and BLUE_BUT?

A0 (blue) and A1 (red)

I can see nothing there that would cause it. Can you share your entire sketch? There may be something you assume is unrelated yet is the cause.

I added the entire sketch to the main post.

Nothing immediately jumps out at me, though I really don't like your copious use of String objects around the place.

I assume, Buttons and RFID reader both connected to the 3.3v pin on arduino. Move buttons to the 5v, leave RFID on 3.3v alone.

source: Stack Exchange

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

sort: votes


text:
Why Arduino Mega 2560 throw error when i try to upload example
I'm try to connect my Arduino Mega 2560 to PC, but I think it's not easy as I imagine. I spent a lot's of time to install USB driver. Here is a screenshot:

When I try to upload blink example, Arduino IDE throw this error:
Sketch uses 656 bytes (0%) of program storage space. Maximum is 253952 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 8183 bytes for local variables. Maximum is 8192 bytes.
avrdude: ser_open(): can't set com-state for "\\.\COM10"
avrdude: ser_drain(): read error: The handle is invalid."

Please help to run one simple example.
I think this screen may help to understand my problem:

Did you reboot your PC after installing drivers?

I install driver for this site and everything is working well.
driver download:  wch.cn/download/CH341SER_EXE.html
I'm recommend to unplug arduino first and install driver, after that plug and enjoy.
Here is a video:
https://www.youtube.com/watch?v=FhmG5J-AHrg

So - you don't have a genuine Arduino then... Some cheap far-east inferior quality clone...

Tried everything but in the end these Chinese drivers works. Yes its not a genuine arduino. but its open source and anybody can make and manufacture it.

What you can try is:

Use another USB port
Reopen IDE
Reinsert the USB cable
Use a different USB cable
Prevent using a USB 'box' in between
Try a different 2560 (if you have)
Restart computer
Check if it can be found in the system drivers
Reinstall IDE (after deinstall it).

However, as the author already mentioned the real solution is needed for some non-genuine Arduinos:

Install the CH driver e.g. at wch.cn/download/CH341SER_EXE.html

I do everything(but not change other arduino) but does not meter, I think USB driver is not install correctly.

In that case the last option should fix it (maybe deinstall IDE first just for certainty)

ok, I'll try it one more time. but, I think best way to fix this issue is throw arduino into trash

nothing change, IDE can not connect to device.

You can also try another USB port and restarting the computer.

I'm installing this : http://www.wch.cn/download/CH341SER_EXE.html
and left only this problem: "Sketch uses 1462 bytes (0%) of program storage space. Maximum is 253952 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 8183 bytes for local variables. Maximum is 8192 bytes."

@AvtandilKavrelishvili You should put this as your answer ... some Chinese products do not use the same officially Arduino components and this driver is needed to install in addition.

Btw, the other message about the memory is not a problem, it just says you use 0% (or at least negigible) amount of flash memory and 9 bytes of dynamic memory ... so plenty left to be used.

I also got the same error. Then I un-plugged my connections and pressed the reset button. Then I uploaded the default blink example to my board. Then it's working fine. Then again I made a connection to the board and it shows the same error again. Now, I un-plugged the GND pin; it's working again. So, in my case there was some thing wrong with my connections.

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/


text:
Can the Leonardo Arduino be used as a USB HOST for CDC Com devices?
I am trying to connect a CDC communication device to the Leonardo USB port and have communication with it via the TTL com port. Basically I want to echo to the TTL port whatever is transmitted over USB and vice-versa.
ASCII data is transmitted out the USB from the CDC device into the USB port of the Leonardo Aurduino. The Arduino needs to xtransfer this info over to the UART pins D0 (RX) and D1 (TX) that are connected to the UART of another micro-controller. I should be able to test it by connecting an FTDI TTL-RS232 cable and see results and have comms in my terminal program.
I came across this sketch that appears to be basically what I want, but I think the "hosting" portion is not being set up:
void setup() {
  Serial.begin(9600);  // rx/tx pins
  Serial1.begin(9600); // USB port
  Serial1.write("2nd Version");
}

void loop() {
  // copy from virtual serial line to UART and vice-versa
  if (Serial.available()) {
    char c = (char)Serial.read();
    Serial1.write(c);
  }
  if (Serial1.available()) {
    char c = (char)Serial1.read();
    Serial.write(c);
  }
}

What am I missing? Note I am NOT trying to do HID but CDC. Basically I want to eliminate using a PC as a Host device and use the "bridge" between my CDC device and another micro-controller.

Interesting. I do know nothing about CDC. Can you show us a schematic showing the connectiions?

Nothing to it really....ASCII data is transmitted out the USB from CDC device into USB Port of the Leonardo Aurduino.  The Aurduino needs to xtransfer this info over to the UART pins D0(RX) and D1(TX)  that is connected to the UART of another microcontroller.  I should be able to test it by connecting an FTDI ttl-RS232 cable and see results and have comms in my terminal program

No, the Leonardo cannot be a USB Host. You may be able to use a USB Host Shield in conjunction with the Leonardo, though I have never tried it and cannot vouch for compatibility with the Leonardo.
USB is a host->device protocol, not a peer-to-peer protocol. You cannot just connect two devices together. Only a USB Host can communicate with a USB device.

Not even with an OTG cable?

No. The Leonardo cannot be a USB Host.


text:
Problem in Serial Communication between nodeMCU and arduino
I am trying to send some messages from nodeMCU to Arduino using Serial communication (aka UART). Following is the code on nodeMCU side:
#include <ESP8266WiFi.h>

const char* ssid = "my-ssid"; // SSID i.e. Service Set Identifier is the name of your WIFI
const char* password = "my-pasword"; // Your Wifi password, in case you have open network comment the whole statement.

int ledPin = 13; // GPIO13 or for NodeMCU you can directly write D7
WiFiServer server(80); // Creates a server that listens for incoming connections on the specified port, here in this case port is 80.

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

          pinMode(ledPin, OUTPUT);
          digitalWrite(ledPin, LOW);

          // Connect to WiFi network
          WiFi.begin(ssid, password);
          //Trying to connect to wifi
          while (WiFi.status() != WL_CONNECTED) {
            delay(500);
          }
          Serial.println("$Wifi Connected#");
          server.begin();
        }

        void loop() {
          // Check if a client has connected
          WiFiClient client = server.available();
          if (!client) {
            return;
          }

          // Wait until the client sends some data
          while(!client.available()){
            delay(1);
          }
          // Read the first line of the request
          String request = client.readStringUntil('\r');
          client.flush();

          int value = LOW;
          if (request.indexOf("/LED=ON") != -1)  {
            digitalWrite(ledPin, HIGH);
            Serial.println("$Led High#");
            value = HIGH;
          }
          if (request.indexOf("/LED=OFF") != -1)  {
            digitalWrite(ledPin, LOW);
            Serial.println("$Led Low#");
            value = LOW;
          }

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

          client.print("Led pin is now: ");

          if(value == HIGH) {
            client.print("On");
          } else {
            client.print("Off");
          }
          client.println("

");
          client.println("<button>Turn On </button>");
          client.println("<button>Turn Off </button>
");
          client.println("");
          delay(1);
        }

Following is the code on Arduino side:
String msgFromNodeMCU;
void setup() {
  pinMode(13,OUTPUT);
  Serial.begin(115200);
}

void loop() {
  msgFromNodeMCU=Serial.readString();
  Serial.println(msgFromNodeMCU);
}

which was working fine until I modified that code to:
String msgFromNodeMCU;

void setup() {
  pinMode(13,OUTPUT);
  Serial.begin(115200);
}

void loop() {
  msgFromNodeMCU=Serial.readString();
  delay(10);
  String wifi_connected="$Wifi Connected#";
  String led_High="$Led High#";
  String led_Low="$Led Low#";
    if (msgFromNodeMCU.equalsIgnoreCase(wifi_connected)) {
      Serial.println("Wifi Connected");
      delay(10);
    }
    if (msgFromNodeMCU.equalsIgnoreCase(led_High)) {
      digitalWrite(13,HIGH);
    }
    if (msgFromNodeMCU.equalsIgnoreCase(led_Low)) {
      digitalWrite(13,LOW);
    }
}

With this code, I see no "Wifi Connected" message on my Serial monitor and there is no response on pin 13. This implies msgFromNodeMCU is not heard. What can I do for msgFromNodeMCU to be heard? Any sort of help is highly appreciated. :D

You have two delay(), 10 seconds each. While interrupts still works when you delay(), communications input buffer are limited in size. If you don't collect the information timely, buffers will be overwriten, information will be lost. Replace delay with millis() as shown in the BlinkWithoutDelay sketch that comes with your IDE.

+Look Alterno Removing delay() or adding millis() was not helpful. It would be nice if as soon as any message comes to the Serial buffer, it interrupts the target device (arduino in this case). Is there a way to create such interrupt?

Serial will not interrupt you. You have to poll Serial frequently.

Serial is ESP or USB?

@Juraj  Serial is ESP. Not USB

My question was educational. you write "I see no 'Wifi Connected' message on my Serial monitor". how is Serial Monitor connected? I am sure it is USB.


text:
Arduino stop the loop
i have a problem with my code, i basically move a motor with the help of 3 relays, when a sensor does not detect the presence of an object part of a call, everything works perfectly, if it was after having called the function CHIAMATA() the arduino loop() stop unexplains, i certainly made a mistake, but i do not understand which.
thanks for your help
this is the code....
#include <swRTC.h>
#include <SoftwareSerial.h>
#include <String.h>

swRTC rtc; //create a new istance of the lib
SoftwareSerial mySerial(3, 2);

const int buttonPin = 19;
const int sensorPin = 9;
const int allarmPin =  13;

int buttonState = 0;
int sensorState = 0;
int relay1 = 8;
int relay2 = 7;
int relay3 = 6;
int var = 0;

// initialize the stepper library on pins 8 through 11:

void setup() {
    rtc.stopRTC(); //stop the RTC
    rtc.setTime(12,0,0); //set the time here
    rtc.setDate(4,6,2012); //set the date here
    rtc.startRTC(); //start the RTC
  Serial.begin(19200); //choose the serial speed here
  mySerial.begin(19200);
  pinMode(allarmPin, OUTPUT);
}

void loop() {

while(mySerial.available()!=0);{}delay(10);

    Serial.print(rtc.getHours(), DEC);
    Serial.print(":");
    Serial.print(rtc.getMinutes(), DEC);
    Serial.print(":");
   Serial.print(rtc.getSeconds(), DEC);
    Serial.println(" ");

//stato riserva croccantini
sensorState = digitalRead(sensorPin);

if (sensorState == HIGH) {
    // turn LED on:
    digitalWrite(allarmPin, HIGH);
    Serial.println("Croccantini esauriti");
    Serial.println("Spia allarme ACCESA");
    Serial.println("Tramoggia DISABILITATA");
    Serial.println("Imposto la chiamata");
    while(sensorState == HIGH) {CHIAMATA(); break;}
  } else {
    // turn LED off:
    digitalWrite(allarmPin, LOW);
    Serial.println("Croccantini OK");
  }
if (sensorState == LOW && rtc.getHours()== 12 && rtc.getMinutes()== 00 && rtc.getSeconds()== 5) {startmotor();}
  //start manuale carico/scarico
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);
  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
    if (buttonState == 1) {
      Serial.print("Pulsante alimentazione manuale ATTIVO");
    // turn on:
  // singlestartmotor();
  }

      }

void startmotor(){
//numero di cicli di carico da eseguire (5)
 while(var < 5){
 pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
    pinMode(relay3, OUTPUT);

 digitalWrite(relay3, LOW); //ABILITA TUTTO
 //AVANTI
 digitalWrite(relay1, LOW);
 digitalWrite(relay2, LOW);
 Serial.print("AVANTI");
 delay(1000); // wait 2 seconds

 digitalWrite(relay3, HIGH);//STOP TUTTO
 digitalWrite(relay1, HIGH);
 digitalWrite(relay2, HIGH);
 delay(1000); //ATTESA PER INVERSIONE MARCIA

 //INDIETRO
 digitalWrite(relay3, LOW);//ABILITA TUTTO
 digitalWrite(relay1, HIGH);
 digitalWrite(relay2, HIGH);
 Serial.print("INDIETRO");
 delay(1000); // wait 2 seconds

  digitalWrite(relay3, HIGH);//STOP TUTTO
  delay(5000); // wait 2 seconds

  var++;
}}

void CHIAMATA() {
 mySerial.println("ATD329xxxxx135;");//dial the number, xxxx ix the phone number.
 delay(100);
 Serial.print("Chiamata in corso..."); return loop();}

... return loop(); doesn't do what you think it does...

I've tried them all =P

Don't do return loop(); With that you enter into a never ending recursion. No system can resist that.
See: return loop(); means "evaluate loop() and return whatever it returns". Well, loop is void; it doesn't return anything.
Even worse is the recursion problem: you call loop(), which calls CHIAMATA, which calls loop ... never ending. You blow out the stack.
I don't look any further than that. Probably there are more errors.

that function refers to a library, it can not be wrong

@Cris - don't argue with us. Remove return loop(); from CHIAMATA.


text:
Arduino emits signal A (infrared) but another Arduino receives everything but A (IR-LED problem)
Situation: I was trying to make a simple Arduino program that mimics my TV-Remote ON-OFF button.
Diagnosis: It just won't work. So just to check I grabbed another Arduino (2) and added my IR-Sensor to that one and let it look for the signals sent by Arduino (1).
Conclusion: Even though I ran exactly the same program in a loop sending IR signals, Arduino (2) noticed each time another IR signal. The received signals didn't even look like the IR signal I sent.

The program I use to mimic my remote: Link to the Github. It is an example of a Lib
It could be the LED. Just a LED I picked up without being specific. Link to the Documentation of the LED

You should use an oscilloscope or logic analyzer to examine what you are actually sending from your program and compare that with what you think you are sending.

Sorry not enough rep to comment. Had to answer instead.
So if your schematic is correct then you just fried your LED. You need a series resistor between vcc and the LED.
If it's not accurate and you have the resistor in place, I'd check the LED anyway, it could be a dud. Apply voltage with a resistor and look at it with your cell/mobile phone digital camera, you should see it through the camera glow dimly.
If all is good then it might be the wavelength of the LED, which is 850nm. Most IR LED's I've used are 950nm, actually they all were.
Now I don't know what the specs of your receiver are but it might be out of its sensing (is that a word?) range, also it only has a 20° viewing angle, so check the alignment of transmitter and receiver.
I'm also confused by your statement that your getting signals that don't look like IR. This makes me wonder if your sensor is hooked up properly. It could be background IR or from another source. Look around the room or test elsewhere.

My answer assumes there is no issue with the sketch. Could you post your sketch. How did you verify that the Arduino/IR LED actually sent a signal?

I will upload my sketch when I get home. I did check if it glows with my phone, and it does. "How did you verify that the Arduino/IR LED actually sent a signal?" I used my phone for that and another arduino which has a IR reciever. (I know for sure that the reciever is working because I made lots of consistent recordings of my TV-remote. :)


text:
Sending and receiving data using 433 Mhz from Arduino to Arduino
Following this tutorial: https://tutorials-raspberrypi.com/let-raspberry-pis-communicate-with-each-other-per-433mhz-wireless-signals/ I was able to easily send code from one Raspberry Pi Zero to another using a RF 433 MHz Transmissor, Receiver pair using the Ninjablock's 433Utils library.
Now I'm trying to do the same between two Arduinos UNO. I'm following the explanations of the library itself: https://github.com/ninjablocks/433Utils, but until now without success.

Arduino_Sketches
Place the Sketches in your normal Arduino Sketches location. Install
  any required libraries:
1) Servo motor library (Should be included in the Arduino IDE)
2) Arduino rc_switch library

The Arduino rc_switch library is installed in my Arduino IDE.
What I would like to confirm is the following:
While with the Raspberry Pis I go to the folder 433Utils/RPi_utils and type the command sudo ./RFSniffer in one terminal and sudo ./codesend 1234 in another what I have to do with the Arduinos?
Upload the sketch RF_Sniffer.ino to one Arduino and the sketch Send_Demo.ino to the other and watch in the Serial Monitor the inputs/outputs appearing as magic?
That's unfortunately not working. :-(
May I install anything else? Modules and wiring is OK.

You should try the sanity check demos.  Do note that cheap 433 MHz receivers are notoriously noisy, but maybe you can see a difference in the LED.  You could also try sending from the Arduino to the pi.  Don't assume the wiring is correct until it works.

The transmitter and receiver that I use with the Arduinos are the same I used with success with RPis. By the way I've just sent from RPi (./codesend 1234) to the Arduino (using sketch RF_Sniffer.ino) with success. But not yet from Arduino to RPi. I read the code of Send_Demo.ino but I'm not sure what I should do. Just run the sketch and it will automatically transmit a code? Or similar to ./codesend 1234) should I write something (like 1234) in the Serial Monitor and hit the send button, so the sketch will transmit that way the code that would be catch by the RF_Sniffer?

Sounds like you need to study the code of whatever sketch you are trying.

That's what I'm doing and also asking for help. Maybe I find someone that could help by having experience on that.

The most important thing with making these work with a Uno is to supply enough power.  They simply will refuse to work if only powered by the USB connection.  Recommended to put 9-12 Volts into barrel connector.  How are you powering the Uno?

Hi @SDsolar With the RPis it worked connected also with the 3.3V pin! But now everything works well with the Arduinos too. As I said above I could already send from RPi and receive with the Arduino. Then I changed the send sketch to use with the Arduino and now I'm able to receive in the other Arduino.


text:
HM-10 only works when holding button
My HM-10 bluetooth module is behaving weird.
In order to have it operate normally, I have to keep holding the small black button on it. If I ever release the button, it just disconnects from my phone (if it was connected) and doesn't show on the bluetooth devices list anymore, and its red LED light becomes low, not bright as usual.
It operated normally before.
How can I fix this?
What would some possibles causes be for this weird behavior?
UPDATE: picture showing the button on lower right corner.

What button? I see no button on the HM-10...

@Majenko I uploaded a picture

That isn't on the HM-10, that's on the breakout board the HM-10 is soldered to. No idea what the button is supposed to do, since I don't see it on any of the breakouts on google...

I just had to connect the RX/TX jumpers. There was no real issue.
I though connecting the power jumpers was enough to just see HM-10 on my phone, since I didn't care about any data. Turns out if the RX/TX jumpers are not connect, the module behaves weird.

I'm sure everyone is glad you solved your problem, but this isn't really a valid answer - there are no apparent "RX/TX jumpers" in your picture.  To be a valid answer, this needs to be something which could make sense to someone else holding that module, and not only to you.

Accept your own answer to close this question.


text:
Is the Arduino Due compatible with a Dual VNH5019 Motor Driver Shield?
I'm planning on buying an Arduino Due and there is a shield I would like to attach to it. I have seen a lot of things saying that some shields are not compatible with Arduino Due... I was wondering if the Arduino Due is compatible with the Dual VNH5019 Motor Driver Shield.
This is where I'm buying it from if you need any extra information on the items:

The Arduino Due
The Dual VNH5019 Motor Driver Shield

Answers greatly appreciated! If you need any specifications let me know.

It is probably electrically compatible if wired point to point, though unclear if direct stacking as a shield would work.  The provided library is AVR-only, though it shouldn't be that difficult to write something that would work on a different processor.  The pins best suited for PWM may be in a different places, which could mean a choice between inefficient software or rewiring.

so its compatible, but the pins must be connected to the correct points?
so I cant just slap the shield on top?

That is unclear.  What was posted was a comment examining potential issues, not an answer.

ok so I went ahead and bought the arduino due and officially tested it out and the Arduino Due is compatible with the Dual VNH5019 Motor Driver Shield!
hope this helps!


text:
Sensors go crazy on external power
For few days, I am trying to figure out, why my sensors do not work on external power. I bought NodeMCU along with couple different sensors etc. I was happily working with them, connecting them one by one to the 3.3v pin in the NodeMCU board, programming each of them. Everything was working as expected. After I have finished, I decided it's time to use them all at once, but I knew, that for that to work, I need to provide them with enough power, as USB probably won't be enough (plus, when I'm done, I don't plan to use USB to power the system anyway). I have a module that converts 230v AC into 5v DC, and then I am stepping it down to 3.3v in order to power the sensors. After checking with multimeter, the voltages are ok, and so is the current.
My problem is, that the sensors give completely random data (most of the time they don't give any information, but once in a while they send something like 1000 times the normal value). Below you can see the schematic that I use. Can you please help me figure this out?
Edit: I would just like to add - I did try to run NodeMCU solely on the Ext. Power - the circuit looked exactly as below, I just connected positive output of 3.3v power source, to the 3.3v connector on NodeMCU. The board was working (I was able to control the onboard LED via WiFI), but the sensor did not. I then reconnected the sensor from external power, to NodeMcu 3.3v, and it (the sensor) worked... I have no idea why.

simulate this circuit – Schematic created using CircuitLab

Did you connect both ground (Arduino, ext. power) together permanently or only for testing voltage difference?

I did connect them (NodeMCU GND <-> Ext. Power GND) permanently, to test if the sensors will start working. They still were behaving randomly, so I removed that connection.

@ojek https://hackingmajenkoblog.wordpress.com/2016/12/06/the-importance-of-sharing-grounds/

@Majenko: Thanks. I did read about common ground before. That's why I decided to power the whole system only by "Ext. Power 3.3v" (so no USB). And it still behaves the same way - sensor Vin/GND connected to NodeMCU works, but when I connect them to Ext. Power it stops working.

Line noise, maybe? Do you have an osc? Can you give us more information on the power supply side of the story?

I have fiddled with it a little more. Turns out, that the resistor I was putting in the circuit was the cause of failure - the sensor did not have enough power.
Now this is very weird to me, as the sensor is rated at 190uA max, and it is not working on this current. Only after I removed the resistor (so the current was around 800mA) it started operating as it should have.

Sorry I don't have reputation for a comment but this might be of help.
You didn't specify if the sensor was a breakout board. If it is then the board may already have the resistor in place, which is why removing it worked.
Now if you had the resistor in place when it was also connected to the nodeMCU, then perhaps power from it was high enough to still generate a stable operating condition (not familiar with nodeMCU) but more likely you have a power supply issue.

Is it a module and does it have resistor on board.
was the 27k resistor only in circuit on external power.

If the answer was yes to the above that is probably the issue.
If they are not the cause, my next check would be your external power. It could need calibration, power spikes/ripples etc but the easiest thing to do is put in a smoothing capacitor in circuit after your power supply.
Probably about 20-30% of my sensor issues are resolved by this. Another 60% are solved by fixing my screw ups and assumptions.

Ugh I just realized you were talking about the current the sensor draws. I had a brain dump (assumptions will be the death of me). You need to just get rid of the resistor. The sensor, if voltage is right will only draw what it needs. I'm guessing you didn't have it in circuit before you went to external power.

I feel really bad for an answer that made such a bad assumption. My apologies. Let me know if you work out the cause.


text:
Powering arduino sensors - what resistor should I use?
Recently I have asked a question, why my sensors do not work on external power supply (link). I have found out, that I was limiting the current too much with the resistors. I have tried using two sensors:

DHT22, rated at 1.5mA max (picture of my module)
BH1750, rated at 190uA max (picture of my module)

My logic is, if they are rated at that current, I should put a resistor in the Vin, to restrict the current to given value. But it turned out that I was wrong, because they started working only after I removed my resistors.
My questions is - should I put a resistor in there? If yes, then how do I know what resistance should I have, if the data sheet values are misleading?

You should have NO resistor.
The datasheet states the current values the device will pull from the supply. Supplies DO NOT PUSH CURRENT.
Remove all resistors.
As long as the voltage is correct and the supply can provide at least as much current as all devices combined want to use then it will work.

And I was wondering, why every electrical component had clearly specified the operating voltage, but the current was somewhere below in the details section. That would explain things. Thank you!

99% of components and devices require a specific voltage to operate, and the current varies depending on what it is doing at the time. The main exception is LEDs which have to have a specific current instead of a specific voltage.


text:
Is there a way to define an alias for a hardware Serial
I'm porting some code from Arduino Uno over to a Mega and I want to replace a SoftwareSerial defined in the previous code with one of the built-in UARTs.
Rather than go through and replace all references to the serial port, I'd prefer to create an alias for Serial1. The alias can be a constant.
In my old code, I setup the Software Serial as follows:
//SoftwareSerial HMI(HMIRX, HMITX); // Define software serial for the HMI adapter (RX, TX)

I"m not even sure where to start.

it is simple
#define HMI Serial1

Alternatively: HardwareSerial &HMI = Serial1;


text:
Arduino with Figaro TGS sensor
I am going to use few Figaro TGS sensors, which including TGS2600, 2602 and 2620 with my Arduino. I referred to the datasheet and found that these sensors need more than one voltage source. May I know the correct way to connect them to my arduino? (Arduino Mega or Uno probably)...(beginner here)

Please update your question with links http://www.figarosensor.com/products/entry/tgs2600.html , http://www.figarosensor.com/products/entry/tgs2602.html , http://www.figarosensor.com/products/entry/tgs2620.html and write the voltages that each one needs. What have you read in the datasheet that makes you think that more than one voltage is needed ? I can not find that in the datasheets.

It needs 5V for the heater and 5V for the detector circuit. What makes you think that is two different voltages? Does 5 not equal 5 in your universe?

Opps...I made a stupid mistake...So for http://www.figarosensor.com/products/2602pdf.pdf (TGS2602 datasheet), sensor pin 3 and 4 simply connected to the voltage source and pin 1 and 2 simply to the ground (pin 2 with load resistor)...am I right?

Yes, correct. The sensor requires an accurate 5V. That means when you use only a USB cable to power the Arduino and the sensor, the voltage can vary a lot and the result will be unreliable.

Maybe I can use a 5V voltage regulator

I think I will use a 9V barrel jack adapter as my power supply...for more stable readings from my sensor

By the way, I found some information online states that if using 9V barrel jack adapter as my power supply, the use of 5V pin on arduino might overheating the voltage regulator built in...Any suggestion on better way as my power supply? ( I think 9V battery does not provide enough current for the sensors)


text:
My sketch is not working as intended
I am a beginner with Arduino. I am doing something to cool down my room temperature using an exhaust fan and cooler through relays. I am trying to reduce the temperature initially using an exhaust fan and wait for 10 minutes to see if the temperature reduced to a set range. If not, the exhaust fan is turned off and the rest of the cooling is done by the cooler.
At the beginning of the program all goes well: it turns on the exhaust fan and waits 10 minutes and if it's not dropping, it transfers the job to the cooler. But after one cycle, when the temperature increases, the cooler is turned on directly, without the exhaust fan urning on, or waiting for 10 minutes and things. I tried a lot but I can't understand what is happening. Please suggest something to solve the problem.
#include <dht.h>

dht DHT;

#define DHT1_PIN 7 // dht11 connected to pin 7

int exhaustpin = 4; // set pin for exhaust fan relay
int coolerpin = 5; // set pin for cooler relay
boolean exhaust;
void setup(){
   Serial.begin(9600);
    pinMode(exhaustpin, OUTPUT);
  pinMode(coolerpin, OUTPUT);
  digitalWrite(exhaustpin,HIGH );
  digitalWrite(coolerpin,HIGH );
  exhaust= LOW;

}
void loop()
{

    DHT.read11(DHT1_PIN);
  Serial.print(" MY Room Temperature = ");
  Serial.println(DHT.temperature);
  Serial.print("MY Room Humidity = ");
  Serial.println(DHT.humidity);
 delay(500);
  int  roomtemp =DHT.temperature;
  static unsigned long interval;
  long interval;
  if (exhaust== LOW){
  if ((roomtemp>=30)&&(digitalRead(coolerpin)==HIGH )){
    digitalWrite(exhaustpin,LOW ); // if temperature increses above 30 the exhaust starts to work
     interval = millis();
  }
  }
   if (digitalRead(exhaustpin)==LOW){
     exhaust= !exhaust;
 if ((millis()-interval) >= 600000){
    digitalWrite(coolerpin,LOW );
    digitalWrite(exhaustpin,HIGH );   // after the starting of exhaust fan it wait for 10 minutes ,then it turn
                                      // on the cooler and turns off the exhaust fan
       }
   }
  if (roomtemp<28){
    digitalWrite(coolerpin,HIGH );
     digitalWrite(exhaustpin,HIGH );
     exhaust= !exhaust;
   // i am trying here to start cooling the room with my exhaust fan
   // then wait 10 minutes ,if it is still not less than 28 degrees turn on the cooler to do the cooling
   // and turn off the exhaust fan
   }
  }

FYI you may want to fix indentation, it will help a lot with making the flow of the program clear. I edited your post with that.

Code doesn't compile.

I doubt this code works at all. The DHT object is not initialized...

The DTH11 working part is fine.All other functions are going as planed but except the Time schedule

What should happen when the temperature drops after the cooler run to 28 and then again grows over 30? Try the fan again? Please show all the sketch after correction.

yes my intention is as you said

  if (digitalRead(exhaustpin) == LOW) {
    static unsigned long interval = millis();
    if ((millis() - interval) >= 600000) {
      digitalWrite(coolerpin, LOW);
      digitalWrite(exhaustpin, HIGH);
      // after the starting of exhaust fan it wait for 10 minutes, then it turns on
      // the cooler and turns off the exhaust fan
    }
  }

interval is only ever set once. So 10 minutes after it is first set it will remain over 10 minutes.
The simplest fix is to set interval to millis() when you set exhaustpin to low:
if ((roomtemp>=30)&&(digitalRead(coolerpin)==HIGH)) {
  digitalWrite(exhaustpin,LOW );
  // if temperature increses above 30 the exhaust starts to work
  interval = millis();
}

i tried your help but now the cooler pin is not turning on after the 10 minute on the first time

interval has to be a global. You can't create it every time you enter the if clause...

can you be more specific i can't get my head behind it.

Put unsigned long interval = 0; on the line before loop() and then when you want to assign it, leave out the unsigned long and just say interval = millis()

still the problem is not solved , the interval is not working now


text:
Arduino program to Blink L LED when input matches a set pattern
I have written a code that is supposed to blink the LED on PB5 pin, when a sequence of input matches a 4 digit password input from a keypad.But the program doesn't appears to be working as expected.
keypadGetKeyPressed() returns a char output of the keypad
and I want to blink led on PB5 /13 PIN
lcd.h has used PORTB is it because of that
        #include <avr/io.h>
        #include <util/delay.h>

        #include "lcd.h"
        #include "keypad.h"

        #include <string.h>

        int main(void) {

            // Password
            char password[4]="5678";

            char keyPressed, oldKeyPressed = 0;
            lcdInit();
            keypadSetupPins();

            lcdWriteCommand(DISPLAY_ON | BLINK | UNDERLINE);
            lcdWriteCommand(CLEAR_DISPLAY);

            char p1 = '1';
            char p2 = '2';
            char p3 = '3';
            char p4 = '4';
            char p5 = '5';

            //Sets the digital pin Pb5 or 13 as Output
            DDRB |= (1<<PB5);
            //Sets LED initially as ON, put ~ before the ( to set it off initially
        //  DDRB |= (1<<PB5);

            // to count matched character
            int count=0;
            char message[]="Logged In";
            while (1) {

                keyPressed = keypadGetKeyPressed();
                if(keyPressed==password[count]){
                    count+=1;
                }
                else{
                    //if next char doesn't match reset counter
                    count= (keyPressed==password[0])?1:0;
                }
                if(count==4){
                    //Call the required function to toggle LED
                     count=0;

                     PORTB |= ~(1<<PB5);
                    _delay_ms(1000);
                    // Turn led off by setting corresponding bit low in the PORTB register.
                    PORTB |= ~(1<<PB5);

                    _delay_ms(500);
                    lcdWriteString(message);

                }

                if (keyPressed != 0 && (keyPressed != oldKeyPressed))

                {
                    lcdWriteChar(keyPressed);
                }

                oldKeyPressed = keyPressed;

                _delay_ms(20);

                if (keyPressed == p1 ) {

                    lcdWriteString("done");
                }

            }

        }

keypad.h file
            #ifndef KEYPAD_H_
            #define KEYPAD_H_

            #include <avr/io.h>

            #define NUM_COLS    3
            #define NUM_ROWS    4

            #define COL_DIR     DDRB
            #define COL_PORT    PORTB
            #define COL_1_PIN 2
            #define COL_2_PIN   3
            #define COL_3_PIN   4

            //NB it is important that the row pins all trigger the same
            //Pin change interrupt - see p70 of the datasheet
            #define ROW_DIR     DDRC
            #define ROW_INPUT   PINC
            #define ROW_PORT    PORTC  //for pullups

            #define ROW_1_PIN   0
            #define ROW_2_PIN   1
            #define ROW_3_PIN   2
            #define ROW_4_PIN   3

            /*
             * Set up the keypad pin directions, enable the pin change interrupt
             * and drive the column pins low.
             */
            void keypadSetupPins(void);

            /*
             * Scan the keypad to determine which key is pressed.
             * Returns 0 if no key pressed and returns ascii code if key pressed.
             * Sets all the cols to low when done.
             */
            char keypadGetKeyPressed(void);

            #endif /* KEYPAD_H_ */

keypad.c file
         * Set up the keypad pin directions, pull up resistors
         * and drive the column pins low.
         */
        void keypadSetupPins(void)
        {
            //Set column pins as output pins
            COL_DIR |= ( (1<<COL_1_PIN) | (1<<COL_2_PIN) | (1<<COL_3_PIN) );

            //Set rows pins to be inputs
            ROW_DIR &= ~( (1<<ROW_1_PIN) | (1<<ROW_2_PIN) | (1<<ROW_3_PIN) | (1<<ROW_4_PIN) );

            //Enable Pullups on row pins
            ROW_PORT |= ( (1<<ROW_1_PIN) | (1<<ROW_2_PIN) | (1<<ROW_3_PIN) | (1<<ROW_4_PIN) );

            //Send out three 0's on COLs
            COL_PORT &= ~( (1<<COL_1_PIN) | (1<<COL_2_PIN) | (1<<COL_3_PIN) );

        }

        /*
         * Scan the keypad to determine which key is pressed.
         * Returns 0 if no key pressed and returns ascii code if key pressed.
         * Sets all the cols to low when done.
         */
        void passwordString(char string[])
        {
            int i = 0;

        }

        char keypadGetKeyPressed(void)
        {
            char retVal = 0;
            uint8_t rowPins;

            //Send 011 on the cols
            //Send out 0 on col 1

            COL_PORT &= ~(1<<COL_1_PIN);
            //Send out 11 on cols 2 and 3
            COL_PORT |= ( (1<<COL_2_PIN) | (1<<COL_3_PIN) );

            //CRUCIAL - delay to allow values to propagate to the rows
            _delay_us(1);

            //Read PIN reg and copy into var
            rowPins = ROW_INPUT;

                //Test row 1
                if( !(rowPins & (1<<ROW_1_PIN)) ) //if the ROW_1_PIN in the ROW_INPUT reg is NOT high
                {
                //there is a 0 on row 1 pin => Key 1 is pressed
                retVal = '1';
                }

                //Test row 2
                if( !(rowPins & (1<<ROW_2_PIN)) ) //if the ROW_2_PIN in the ROW_INPUT reg is NOT high
                {
                //there is a 0 on row 1 pin => Key 4 is pressed
                retVal = '4';
                }

                //Test row 3
                if( !(rowPins & (1<<ROW_3_PIN)) ) //if the ROW_1_PIN in the ROW_INPUT reg is NOT high
                {
                    //there is a 0 on row 1 pin => Key 7 is pressed
                    retVal = '7';
                }

                //Test row 4
                if( !(rowPins & (1<<ROW_4_PIN)) ) //if the ROW_1_PIN in the ROW_INPUT reg is NOT high
                {
                    //there is a 0 on row 1 pin => Key 7 is pressed
                    retVal = '*';
                }

            COL_PORT &= ~(1<<COL_2_PIN);
            //Send out 011 on cols 2 and 3
            COL_PORT |= ( (1<<COL_1_PIN) | (1<<COL_3_PIN) );

            //CRUCIAL - delay to allow values to propagate to the rows
            _delay_us(1);

            //Read PIN reg and copy into var
            rowPins = ROW_INPUT;

                //Test row 1
                if( !(rowPins & (1<<ROW_1_PIN)) ) //if the ROW_1_PIN in the ROW_INPUT reg is NOT high
                {
                    //there is a 0 on row 1 pin => Key 1 is pressed
                    retVal = '2';
                }

                //Test row 2
                if( !(rowPins & (1<<ROW_2_PIN)) ) //if the ROW_2_PIN in the ROW_INPUT reg is NOT high
                {
                    //there is a 0 on row 1 pin => Key 4 is pressed
                    retVal = '5';
                }

                //Test row 3
                if( !(rowPins & (1<<ROW_3_PIN)) ) //if the ROW_1_PIN in the ROW_INPUT reg is NOT high
                {
                    //there is a 0 on row 1 pin => Key 7 is pressed
                    retVal = '8';
                }

                //Test row 4
                if( !(rowPins & (1<<ROW_4_PIN)) ) //if the ROW_1_PIN in the ROW_INPUT reg is NOT high
                {
                    //there is a 0 on row 1 pin => Key 7 is pressed
                    retVal = '0';
                }

            COL_PORT &= ~(1<<COL_3_PIN);
            //Send out 011 on cols 2 and 3
            COL_PORT |= ( (1<<COL_1_PIN) | (1<<COL_2_PIN) );

            //CRUCIAL - delay to allow values to propagate to the rows
            _delay_us(1);

            //Read PIN reg and copy into var
            rowPins = ROW_INPUT;

                //Test row 1
                if( !(rowPins & (1<<ROW_1_PIN)) ) //if the ROW_1_PIN in the ROW_INPUT reg is NOT high
                {
                    //there is a 0 on row 1 pin => Key 1 is pressed
                    retVal = '3';
                }

                //Test row 2
                if( !(rowPins & (1<<ROW_2_PIN)) ) //if the ROW_2_PIN in the ROW_INPUT reg is NOT high
                {
                    //there is a 0 on row 1 pin => Key 4 is pressed
                    retVal = '6';
                }

                //Test row 3
                if( !(rowPins & (1<<ROW_3_PIN)) ) //if the ROW_1_PIN in the ROW_INPUT reg is NOT high
                {
                    //there is a 0 on row 1 pin => Key 7 is pressed
                    retVal = '9';
                }

                //Test row 4
                if( !(rowPins & (1<<ROW_4_PIN)) ) //if the ROW_1_PIN in the ROW_INPUT reg is NOT high
                {
                    //there is a 0 on row 1 pin => Key 7 is pressed
                    retVal = '#';
                }

                return retVal;
          }

lcd.h file
            #ifndef LCD_H_
            #define  LCD_H_

            #include <avr/io.h>
            #include <util/delay.h>

            //If nibble mode is enabled it is assumed that D4->D7 on the LCD
            //are connected to pins 0->3 of the data port.
            #define USE_NIBBLE_MODE    0  //0 for false, 1 for true
            #define LINE_MODE          0 //0 for ONE line mode, 1 for TWO line mode

            #define LCD_CONTROL_PORT   PORTB
            #define LCD_CONTROL_DIR    DDRB
            #define RS_PIN             PORTB0
            #define E_PIN              PORTB1

            #define LCD_DATA_PORT      PORTD
            #define LCD_DATA_DIR       DDRD

            #define CLEAR_DISPLAY       0x01
            #define DISPLAY_CURSOR_HOME 0x02
            #define DISPLAY_ON          0x0C
            #define DISPLAY_OFF         0x08
            #define UNDERLINE           0x02    //OR this with DISPLAY_ON
            #define BLINK               0x01    //OR this with DISPLAY_ON
            #define ONE_LINE_MODE       0x34
            #define TWO_LINE_MODE       0x38
            #define SET_ADDRESS         0x80    //You must OR the appropriate address with this
            #define DISPLAY_SHIFT_LEFT  0x18
            #define DISPLAY_SHIFT_RIGHT 0x1C
            #define CURSOR_SHIFT_LEFT   0x10
            #define CURSOR_SHIFT_RIGHT  0x14

            void lcdInit(void);

            void lcdWriteCommand(uint8_t command);

            void lcdWriteChar(char ch);

            void lcdWriteString(char string[]);

            #endif  /* LCD_H */

lcd.c file
            #include "lcd.h"

            /***********************************************************
             * This function sets th direction of the pins that are
             * connected to the LCD.
             * The code makes use of the #defined names in lcd.h so that
             * if the pins connected to the LCD change only lcd.h needs
             * to be changed and not the code in this file.
             *
             * This function is complete.
             **********************************************************/
            void lcdInit(void)
            {
                //set direction of control pins to be outputs
                LCD_CONTROL_DIR |= (1<<RS_PIN);
                LCD_CONTROL_DIR |= (1<<E_PIN);

                //Set direction of data port pins to be outputs
                LCD_DATA_DIR |= 0xFF;
            }

            /****************************************************
             * Sends a a single command to the LCD
             * Takes care of the register selection,
             * placing data on the data pins and toggle of E pin
             *****************************************************/
            void lcdWriteCommand(uint8_t command)
            {
                PORTB &= ~(1<<RS_PIN);

                PORTD = command;

                PORTB |= (1<<E_PIN);

                _delay_us(2); //lcd boot delay

                PORTB &= ~(1<<E_PIN);

                _delay_ms(2);
            }

            /****************************************************
             * Sends a a single ascii char to the LCD
             * Takes care of the register selection,
             * placing data on the data pins and toggle of E pin
             *****************************************************/
            void lcdWriteChar(char ch)
            {
                PORTB |= (1<<RS_PIN);

                PORTD = ch;

                PORTB |= (1<<E_PIN);

                _delay_us(2); //lcd boot delay

                PORTB &= ~(1<<E_PIN);

                _delay_ms(2);
            }

            /****************************************************
             * Writes a string to the LCD
             * Steps through the string passed as a parameter and
             * calls lcdWriteChar() to send each character of the
             * string
             *****************************************************/
            void lcdWriteString(char string[])
            {
                int i = 0;

                while (string[i] != '\0')
                {
                    lcdWriteChar(string[i]);
                    i++;
                }
            }

Please define "not work as expected". What does it do?

the program does not blink on input sequence match with the password  and does no display the message to the lcd screen

Does not look like your key debouncing is very robust.  Likely you are sensing numbers like "5555566677777777888".

my approach is based on the code in https://repl.it/NAeo/0  and I need it for small input sequences like say 200 inputs

@ShubhamJohar. The code your are based on is PC-centric, where OS take care of physical devices, debouncing and buffering. With Arduino you have none of these: you have to debounce your keys yourself. See library Bounce2.

Why you are not using a standard LCD library?

I am supposed to use only pure C for this work

The following proposed code:

corrects the worst of the logic problems
eliminates unused/unnecessary local variables
performs the desired function
keeps data declarations local to where they are used
expects the keypad input function to perform the majority of the key debouncing.

and now the proposed code:
    #include <avr/io.h>
    #include <util/delay.h>

    #include "lcd.h"
    #include "keypad.h"

    #include <string.h>

    int main(void)
    {
        // Password
        char password[5]="5678";  // 5 to allow for trailing NUL byte

        char oldKeyPressed = 0;

        lcdInit();
        keypadSetupPins();

        lcdWriteCommand(DISPLAY_ON | BLINK | UNDERLINE);
        lcdWriteCommand(CLEAR_DISPLAY);

        //Sets the digital pin Pb5 or 13 as Output
        DDRB |= (1<<PB5);
        //Sets LED initially as ON, put ~ before the ( to set it off initially
        //  DDRB |= (1<<PB5);

        size_t count = 0;

        for( size_t i=0; i< strlen( password ); i++ )
        {
            char keyPressed = keypadGetKeyPressed();

            if(keyPressed==password[count])
            {
                count+=1;
            }

            else
            {
                count = 0;
            }

            if( count == strlen( password ) )
            {
                char message[] = "Logged In";

                //Call the required function to toggle LED
                PORTB |= ~(1<<PB5);
                _delay_ms(1000);
                // Turn led off by setting corresponding bit low in the PORTB register.
                PORTB &= ~(1<<PB5);

                _delay_ms(500);
                lcdWriteString(message);
            }

            // this code block should (probably) only be for debug
            if (keyPressed != 0 && (keyPressed != oldKeyPressed))
            {
                lcdWriteChar(keyPressed);
            }

            // debounce the keypad
            oldKeyPressed = keyPressed;
            _delay_ms(20);

            // method of exiting the program before fully logged in
            if (keyPressed ==  '1' )  // so '1' cannot be part of the password
            {
                lcdWriteString("done");
                break;
            }
        }
    }


text:
Minimum number of Pins to use for multiplexing LEDs
whats the minimum number of pins to use when multiplexing 6 LEDs?
is there some kind of formula that can be applied to n LEDs?
Or in other words, how many LEDs can an Arduino Uno control without the help of a separate IC?

It depends on the style of multiplexing.
For basic Row-Column multiplexing you have N=RC - the number of LEDs is the number of rows multiplied by the number of columns. The LEDs, of course, don't have to be arranged physically in rows and columns, those are purely logical wiring concepts.
For Charlieplexing (used by the LOL shield) it's slightly more complex. The formula is: N = n² - n, where n is the number of pins, and N is the number of LEDs they can drive.
Charlieplexing can multiplex far more LEDs than traditional R/C multiplexing, but is harder to program for and wire up.

So concretely (to answer precisely OP), 5 pins (3+2) are needed with multiplexing (not a big gain, given extra code complexity), and 3 pins for charlieplexing.


text:
Display values from a function on GLCD
I am new to Arduino and I'm trying my first Pro Mini. I was able to find DS1302 code from github that runs perfectly. My problem is trying to add some LM35 code to also display temperature data as well as the time data.
The code doesn't seem to run the Celsius and Fahrenheit functions. I have attached my code. Any help will be appreciated.
//Required library - http://www.rinkydinkelectronics.com/library.php?id=5
//Blog Post - http://overskill.alexshu.com/ds1302-real-time-clock-w-arduino/

#include "U8glib.h"
#include <DS1302.h>
#include <PreciseLM35.h>
//int float pinLM35 = A0;
const int pinLM35 = A0;
PreciseLM35 lm35(pinLM35, DEFAULT);

DS1302 rtc(2, 3, 4);
U8GLIB_ST7920_128X64 u8g(13, 11, 12, U8G_PIN_NONE);

void setup(void) {
  rtc.halt(false);
  rtc.writeProtect(false);

  // The following lines can be commented out to use the values already stored in the DS1302
  // Once you flash the Arduino with the correct time.

  //rtc.setDOW(FRIDAY); // Set Day-of-Week to FRIDAY
  //rtc.setTime(12, 0, 0); // Set the time to 12:00:00 (24hr format)
  //rtc.setDate(6, 8, 2010); // Set the date to August 6th, 2010

  // assign default color value
  if (u8g.getMode() == U8G_MODE_R3G3B2)
    u8g.setColorIndex(255); // white
  else if (u8g.getMode() == U8G_MODE_GRAY2BIT)
    u8g.setColorIndex(3); // max intensity
  else if (u8g.getMode() == U8G_MODE_BW)
    u8g.setColorIndex(1); // pixel on
}

void draw(void) {
  u8g.setFont(u8g_font_04b_03);
  u8g.drawStr( 2,5, "******************************");
  u8g.drawStr( 13,10, "Arduino Pro Mini Control ");
  u8g.drawStr( 24,20, (rtc.getTimeStr()));
  u8g.drawStr( 1,20, "TIME: ");
  u8g.drawStr(70,20,  "Temp (C): ");
  u8g.drawStr (80,20, (lm35.readCelsius()));
  u8g.drawStr( 25,30, rtc.getDOWStr());
  u8g.drawStr(70,30, "Temp (F): ");
  u8g.drawStr(3,30, "DAY: ");
  u8g.drawStr(80,30, (lm35.readFahrenheit()));
  u8g.drawStr( 24,40, rtc.getDateStr());
  u8g.drawStr(1,40, "DATE: ");
  u8g.drawStr(70,40, "AREF : ");
  u8g.drawStr(80,40, (lm35.readPreciseAref()));
  u8g.drawStr( 15,55, "DS1302 Real Time Clock");
  u8g.drawStr( 2,65, "********************************");
}

void loop(void) {
  // picture loop
  u8g.firstPage();
  do {
    draw();
  } while(u8g.nextPage()); //u8g.nextPage()
  // rebuild the picture after some delay
  delay(500);
}

Have you tried sending the output of the functions to the serial monitor and seeing if its a problem with the display library or the functions?

I used this code:  u8g.setPrintPos(110,20);

Use an DS3231 RTC instead. It include a temperature sensor with digital output. No need to read an analog value and it means less component in your PCB.

I used this code:  u8g.setPrintPos(110,20); and then               u8g.Print(temps.TempInCelcuis);and its working great. Thanks for the helpful suggestions.


text:
How to call 5 different functions in a loop based on serial input?
I have 5 types of such functions with different input parameters.
blink(int a,char* b, int c);
fade(int a,int b,int c);
split(int a,int d);

and so on from serial input what i want is to call this three functions in any combinations that can be later executed in a loop. For example  my serial input is this ..
[blink(a,b,c),fade(a,b,c),blink(a,b,c),fade(a,b,c),split(a,d),blink(a,b,c)]

The  Code should also be saved  in memory so that when a person reset Arduino. The order of functions execute without waiting for serial input.The order of functions would get change only when person enter serial data to arduino.
I have no clue where to begin please help me out.

It's obvious that you are a beginner, but you have good ideas and some capacity to think beyond the obvious. You lack training but not imagination. Keep trying.

This sounds very much like a school assignment?

@MikaelPatel. At least is a very good school assignment and I think is a good oportunity to show a good communication strategy. I upvoted it because I feel is a valuable lesson on how to solve things.

@MikaelPatel That's My school assignment Dot matrix demo  for which i am making an custom app to add multiple transations  with arduino

This answer isn't going to give you the code to solve your problem, it is just ideas that you can look at and see what suits you best.
You should be able to find an example on how to read from a serial connection, I'm sure there is at least one example in the IDE.
You need to work out how to encode your data, having it in nice human friendly format (like you have above) is great if you are processing it on a PC but on a processor that is slow and have very limited memory using A,B,C... as the function names might be more practical.  It will be smaller to store and quicker to compare.
You want to store the input so it can be read back later.  There are a number of ways you can do this but they all need a non-volatile storage medium.  You could use an SD card, obviously you'd need an SD reader and the type of reader you get will affect the code you need, but these can be problematic.  You can also use EEPROM chips that, you can get little I2C interfaced modules, they have less space than an SD card, but are generally faster (they also have a shorter lifespan, but don't worry I don't you'll ware one out).  You can also use the EEPROM that is in the Arduino itself (I've never done this).
It is best to build you program up in small parts, get the reading from serial working, then calling functions, then saving and loading.  That way you only have to debug a small bunch of issues at once.  If you wanted you could abstract the storage device away from the code by writing a base class that has virtual save and load functions.  You could then inherit from this class for the EEPROM or the SD card and changing wouldn't affect the rest of the code.
Like I said at the start I appreciate this answer hasn't given you a step by step guide on how to solve your problem, but hopefully it has given you a few pointers on what you could do and you can research the options from there.  Remember when you get stuck on one particular aspect just post a minimal example of what you have tried and explain what you expect it to be doing and people will be more than willing to help.

This answer isn't going to give you the code to solve your problem either, it is just tricks that you can look at and see what suits you best.
[I'm assuming your serial input is all readable text (no binary data).]
Made serial input fixed format: Every function name is 3 letter long, all parameters the same length, and if possible, all function the same number of parameter. That's make parsing things easy, later you can upgrade to variable length parameters.
Know you can write two small functions that read Serial and returns a single element:
String getFunction();
int    getArgument();

Each function will take care of commas and other delimiters. Also, getArgument will convert values as text to binary values.
You loop will look like (pseude-code, don't compile).
void loop() {
  String fn = getFunction();

  if (fn.equals("blink")) {
    doBlink();
  }
  if  (fn.equals("fade")) {
    doFade();
  }
 ....
 }
 void doBlink() {
    int val1 = readArgument();
    int val2 = readArgument();
    int val3 = readArgument();
    // Do some blink.
    }
 void doFade() {
    // same thing.
    }
  }

Now, if you want to transmit char data (strings, texts), put them at the as last parameter. You will need a third function to read a variable length string until end of the line (or some marker you choose).


text:
SendCommand(Key) function is not working properly using digitalWrite()
I finally figured out to get the unique value from the Car's Head panel input and send the command to the JVC radio as per the input.
Everything seems to be working fine, just the problem is the SendCommand(Key) function is not working properly as expected. It works sometimes, like sometimes I have to click the button twice or thrice to make it work, sometimes it works in the first time and some times it works twice even if i pressed it once...
But every times it shows that the key is there using Serial.println(Key) function... and it has been sent to the function SendCommand(Key) but still it doesn't works every time...
So just want to know that is there anything wrong in the code...
#include <SoftwareSerial.h>

SoftwareSerial mySerial(7, 5); // RX, TX
String readString;

//JVC Controls
#define VOLUP       0x04
#define VOLDOWN     0x05
#define SOURCE      0x08
#define EQUALIZER   0x0D
#define MUTE        0x0E
#define TRACKFORW   0x12
#define TRACKBACK   0x13
#define FOLDERFORW  0x14
#define FOLDERBACK  0x15
#define UNKNOWN1    0x37
#define UNKNOWN2    0x58

// Connect optocoupler input through a 1k resistor to this pin
#define OUTPUTPIN   8 // D8
// On-board LED, useful for debugging
#define LEDPIN     13 // D13
// Pulse width in µs
#define PULSEWIDTH 527
// Address that the radio responds to
#define ADDRESS 0x47
void setup()
{
  Serial.begin(57600);
  //Serial.setTimeout(2000);
  mySerial.begin(9600);
  pinMode(OUTPUTPIN, OUTPUT);    // Set the proper pin as output
}

unsigned char GetInput(int number, int prevNumber)
{
  if(number == 143)
    return TRACKBACK;
    else if(number == 140)
    return TRACKFORW;
    else if(number == 142)
    return FOLDERBACK;
    else if(number == 139)
    return FOLDERFORW;
    else if(number == 1)
    return VOLUP;
    else if(number == 255)
    return VOLDOWN;
    else if(number == 60)
    return MUTE;
    else if(prevNumber == 52 && (number == 32 || number == 37 || number == 38))
    return SOURCE;

    return 0;
}

 int prevNumber=0;
void loop() {

  while (mySerial.available()) {
    delay(10);
    int number = mySerial.read();
    mySerial.flush();
      unsigned char Key = GetInput(number, prevNumber);  // If any buttons are being pressed the GetInput() function will return the appropriate command code
      if (Key) {  // If no buttons are being pressed the function will have returned 0 and no command will be sent
        Serial.println(Key);
        SendCommand(Key);
    }
    prevNumber = number;

}
}

// Send a value (7 bits, LSB is sent first, value can be an address or command)
void SendValue(unsigned char value) {
  unsigned char i, tmp = 1;
  for (i = 0; i < sizeof(value) * 8 - 1; i++) {
    if (value & tmp)  // Do a bitwise AND on the value and tmp
      SendOne();
    else
      SendZero();
    tmp = tmp << 1; // Bitshift left by 1
  }
}
// Send a command to the radio, including the header, start bit, address and stop bits
void SendCommand(unsigned char value) {
  unsigned char i;
  Preamble();                         // Send signals to precede a command to the radio
  for (i = 0; i < 3; i++) {           // Repeat address, command and stop bits three times so radio will pick them up properly
    SendValue(ADDRESS);               // Send the address
    SendValue((unsigned char)value);  // Send the command
    Postamble();                      // Send signals to follow a command to the radio
  }
}
// Signals to transmit a '0' bit
void SendZero() {
  digitalWrite(OUTPUTPIN, HIGH);      // Output HIGH for 1 pulse width
  digitalWrite(LEDPIN, HIGH);         // Turn on on-board LED
  delayMicroseconds(PULSEWIDTH);
  digitalWrite(OUTPUTPIN, LOW);       // Output LOW for 1 pulse width
  digitalWrite(LEDPIN, LOW);          // Turn off on-board LED
  delayMicroseconds(PULSEWIDTH);
}
// Signals to transmit a '1' bit
void SendOne() {
  digitalWrite(OUTPUTPIN, HIGH);      // Output HIGH for 1 pulse width
  digitalWrite(LEDPIN, HIGH);         // Turn on on-board LED
  delayMicroseconds(PULSEWIDTH);
  digitalWrite(OUTPUTPIN, LOW);       // Output LOW for 3 pulse widths
  digitalWrite(LEDPIN, LOW);          // Turn off on-board LED
  delayMicroseconds(PULSEWIDTH * 3);
}
// Signals to precede a command to the radio
void Preamble() {
  // HEADER: always LOW (1 pulse width), HIGH (16 pulse widths), LOW (8 pulse widths)
  digitalWrite(OUTPUTPIN, LOW);       // Make sure output is LOW for 1 pulse width, so the header starts with a rising edge
  digitalWrite(LEDPIN, LOW);          // Turn off on-board LED
  delayMicroseconds(PULSEWIDTH * 1);
  digitalWrite(OUTPUTPIN, HIGH);      // Start of header, output HIGH for 16 pulse widths
  digitalWrite(LEDPIN, HIGH);         // Turn on on-board LED
  delayMicroseconds(PULSEWIDTH * 16);
  digitalWrite(OUTPUTPIN, LOW);       // Second part of header, output LOW 8 pulse widths
  digitalWrite(LEDPIN, LOW);          // Turn off on-board LED
  delayMicroseconds(PULSEWIDTH * 8);
  // START BIT: always 1
  SendOne();
}
// Signals to follow a command to the radio
void Postamble() {
  // STOP BITS: always 1
  SendOne();
  SendOne();
}

Won't you timings be off because you are doing two digtalWrite before delaying for the number of pulse widths.  Does that matter?

Hi... thanks for helping... but the thing is I dont understand this coding.. I am using it for my car... so it will be helpful if you can help me with the exact code... then I will run it and then let you know...

If you want to use the code you are going to need to understand it.  You are calling delayMicroseconds(PULSEWIDTH * 16); which means you are waiting for a very specific amount of time eg 8432 microseconds.  I assume your receiver will need a delay of 8432us not 8479us because you have called the function digitalWrite() twice before delaying.  So the question is do you need to reduce the delay by X microseconds because of the calls to digitalWrite()?  (I don't know what X is)

Then what should i do... ? Should i remove the function delayMicroseconds or reduce the value in that or add delayMicroseconds after each digitalWrite function... ?

You need to read the requirements of the receiver and see what you should do.


text:
Help setting up Dust sensor with Arduino Mega
So I wired Sharp Dust Sensor with Arduino Mega with below fritzing:

the connector cable only connects to the dust sensor as you can seee the image below:

however looking at other example projects the same dust sensor has wiring inverted. I followed the hookup and the code as given here: https://www.elecrow.com/wiki/index.php?title=Dust_Sensor-_GP2Y1010AU0F
but I get the result without having to connect the green wire to A0 and Yellow wire connected to D2
Raw Signal Value (0-1023): 346.00 - Voltage: 1.69 - Dust Density: 0.19
Raw Signal Value (0-1023): 394.00 - Voltage: 1.92 - Dust Density: 0.23
Raw Signal Value (0-1023): 398.00 - Voltage: 1.94 - Dust Density: 0.23
Raw Signal Value (0-1023): 408.00 - Voltage: 1.99 - Dust Density: 0.24
Raw Signal Value (0-1023): 433.00 - Voltage: 2.11 - Dust Density: 0.26
Raw Signal Value (0-1023): 468.00 - Voltage: 2.29 - Dust Density: 0.29

if I connect the yellow to A0 And green to D2  then I get below result.
Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
Raw Signal Value (0-1023): 1020.00 - Voltage: 4.98 - Dust Density: 0.75
Raw Signal Value (0-1023): 1020.00 - Voltage: 4.98 - Dust Density: 0.75
Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
Raw Signal Value (0-1023): 1022.00 - Voltage: 4.99 - Dust Density: 0.75
Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
Raw Signal Value (0-1023): 1020.00 - Voltage: 4.98 - Dust Density: 0.75
Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
Raw Signal Value (0-1023): 1022.00 - Voltage: 4.99 - Dust Density: 0.75
Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
Raw Signal Value (0-1023): 1023.00 - Voltage: 5.00 - Dust Density: 0.75
Raw Signal Value (0-1023): 1005.00 - Voltage: 4.91 - Dust Density: 0.73
Raw Signal Value (0-1023): 952.00 - Voltage: 4.65 - Dust Density: 0.69
Raw Signal Value (0-1023): 712.00 - Voltage: 3.48 - Dust Density: 0.49
Raw Signal Value (0-1023): 631.00 - Voltage: 3.08 - Dust Density: 0.42
Raw Signal Value (0-1023): 559.00 - Voltage: 2.73 - Dust Density: 0.36
Raw Signal Value (0-1023): 504.00 - Voltage: 2.46 - Dust Density: 0.32
Raw Signal Value (0-1023): 463.00 - Voltage: 2.26 - Dust Density: 0.28
Raw Signal Value (0-1023): 431.00 - Voltage: 2.10 - Dust Density: 0.26
Raw Signal Value (0-1023): 409.00 - Voltage: 2.00 - Dust Density: 0.24
Raw Signal Value (0-1023): 430.00 - Voltage: 2.10 - Dust Density: 0.26
Raw Signal Value (0-1023): 413.00 - Voltage: 2.02 - Dust Density: 0.24
Raw Signal Value (0-1023): 377.00 - Voltage: 1.84 - Dust Density: 0.21
Raw Signal Value (0-1023): 453.00 - Voltage: 2.21 - Dust Density: 0.28
Raw Signal Value (0-1023): 368.00 - Voltage: 1.80 - Dust Density: 0.21
Raw Signal Value (0-1023): 367.00 - Voltage: 1.79 - Dust Density: 0.20
Raw Signal Value (0-1023): 364.00 - Voltage: 1.78 - Dust Density: 0.20
Raw Signal Value (0-1023): 361.00 - Voltage: 1.76 - Dust Density: 0.20
Raw Signal Value (0-1023): 357.00 - Voltage: 1.74 - Dust Density: 0.20
Raw Signal Value (0-1023): 356.00 - Voltage: 1.74 - Dust Density: 0.20
Raw Signal Value (0-1023): 358.00 - Voltage: 1.75 - Dust Density: 0.20
Raw Signal Value (0-1023): 357.00 - Voltage: 1.74 - Dust Density: 0.20
Raw Signal Value (0-1023): 345.00 - Voltage: 1.68 - Dust Density: 0.19
Raw Signal Value (0-1023): 309.00 - Voltage: 1.51 - Dust Density: 0.16
Raw Signal Value (0-1023): 375.00 - Voltage: 1.83 - Dust Density: 0.21
Raw Signal Value (0-1023): 395.00 - Voltage: 1.93 - Dust Density: 0.23
Raw Signal Value (0-1023): 421.00 - Voltage: 2.06 - Dust Density: 0.25
Raw Signal Value (0-1023): 441.00 - Voltage: 2.15 - Dust Density: 0.27
Raw Signal Value (0-1023): 343.00 - Voltage: 1.67 - Dust Density: 0.18
Raw Signal Value (0-1023): 352.00 - Voltage: 1.72 - Dust Density: 0.19
Raw Signal Value (0-1023): 341.00 - Voltage: 1.67 - Dust Density: 0.18
Raw Signal Value (0-1023): 339.00 - Voltage: 1.66 - Dust Density: 0.18
Raw Signal Value (0-1023): 342.00 - Voltage: 1.67 - Dust Density: 0.18
Raw Signal Value (0-1023): 307.00 - Voltage: 1.50 - Dust Density: 0.15
Raw Signal Value (0-1023): 335.00 - Voltage: 1.64 - Dust Density: 0.18
Raw Signal Value (0-1023): 343.00 - Voltage: 1.67 - Dust Density: 0.18
Raw Signal Value (0-1023): 348.00 - Voltage: 1.70 - Dust Density: 0.19
Raw Signal Value (0-1023): 351.00 - Voltage: 1.71 - Dust Density: 0.19
Raw Signal Value (0-1023): 355.00 - Voltage: 1.73 - Dust Density: 0.19
Raw Signal Value (0-1023): 359.00 - Voltage: 1.75 - Dust Density: 0.20
Raw Signal Value (0-1023): 456.00 - Voltage: 2.23 - Dust Density: 0.28
Raw Signal Value (0-1023): 477.00 - Voltage: 2.33 - Dust Density: 0.30
Raw Signal Value (0-1023): 392.00 - Voltage: 1.91 - Dust Density: 0.23
Raw Signal Value (0-1023): 443.00 - Voltage: 2.16 - Dust Density: 0.27
Raw Signal Value (0-1023): 419.00 - Voltage: 2.05 - Dust Density: 0.25
Raw Signal Value (0-1023): 379.00 - Voltage: 1.85 - Dust Density: 0.21
Raw Signal Value (0-1023): 292.00 - Voltage: 1.43 - Dust Density: 0.14
Raw Signal Value (0-1023): 341.00 - Voltage: 1.67 - Dust Density: 0.18
Raw Signal Value (0-1023): 311.00 - Voltage: 1.52 - Dust Density: 0.16
Raw Signal Value (0-1023): 307.00 - Voltage: 1.50 - Dust Density: 0.15
Raw Signal Value (0-1023): 284.00 - Voltage: 1.39 - Dust Density: 0.14
Raw Signal Value (0-1023): 322.00 - Voltage: 1.57 - Dust Density: 0.17
Raw Signal Value (0-1023): 309.00 - Voltage: 1.51 - Dust Density: 0.16
Raw Signal Value (0-1023): 331.00 - Voltage: 1.62 - Dust Density: 0.17
Raw Signal Value (0-1023): 326.00 - Voltage: 1.59 - Dust Density: 0.17
Raw Signal Value (0-1023): 304.00 - Voltage: 1.48 - Dust Density: 0.15
Raw Signal Value (0-1023): 340.00 - Voltage: 1.66 - Dust Density: 0.18
Raw Signal Value (0-1023): 385.00 - Voltage: 1.88 - Dust Density: 0.22
Raw Signal Value (0-1023): 399.00 - Voltage: 1.95 - Dust Density: 0.23
Raw Signal Value (0-1023): 420.00 - Voltage: 2.05 - Dust Density: 0.25
Raw Signal Value (0-1023): 448.00 - Voltage: 2.19 - Dust Density: 0.27
Raw Signal Value (0-1023): 479.00 - Voltage: 2.34 - Dust Density: 0.30
Raw Signal Value (0-1023): 424.00 - Voltage: 2.07 - Dust Density: 0.25
Raw Signal Value (0-1023): 438.00 - Voltage: 2.14 - Dust Density: 0.26
Raw Signal Value (0-1023): 438.00 - Voltage: 2.14 - Dust Density: 0.26
Raw Signal Value (0-1023): 330.00 - Voltage: 1.61 - Dust Density: 0.17
Raw Signal Value (0-1023): 352.00 - Voltage: 1.72 - Dust Density: 0.19
Raw Signal Value (0-1023): 350.00 - Voltage: 1.71 - Dust Density: 0.19
Raw Signal Value (0-1023): 343.00 - Voltage: 1.67 - Dust Density: 0.18
Raw Signal Value (0-1023): 314.00 - Voltage: 1.53 - Dust Density: 0.16
Raw Signal Value (0-1023): 305.00 - Voltage: 1.49 - Dust Density: 0.15
Raw Signal Value (0-1023): 306.00 - Voltage: 1.49 - Dust Density: 0.15
Raw Signal Value (0-1023): 317.00 - Voltage: 1.55 - Dust Density: 0.16
Raw Signal Value (0-1023): 341.00 - Voltage: 1.67 - Dust Density: 0.18
Raw Signal Value (0-1023): 361.00 - Voltage: 1.76 - Dust Density: 0.20
Raw Signal Value (0-1023): 384.00 - Voltage: 1.88 - Dust Density: 0.22
Raw Signal Value (0-1023): 417.00 - Voltage: 2.04 - Dust Density: 0.25
Raw Signal Value (0-1023): 435.00 - Voltage: 2.12 - Dust Density: 0.26
Raw Signal Value (0-1023): 446.00 - Voltage: 2.18 - Dust Density: 0.27
Raw Signal Value (0-1023): 310.00 - Voltage: 1.51 - Dust Density: 0.16
Raw Signal Value (0-1023): 462.00 - Voltage: 2.26 - Dust Density: 0.28
Raw Signal Value (0-1023): 432.00 - Voltage: 2.11 - Dust Density: 0.26
Raw Signal Value (0-1023): 391.00 - Voltage: 1.91 - Dust Density: 0.22
Raw Signal Value (0-1023): 339.00 - Voltage: 1.66 - Dust Density: 0.18
Raw Signal Value (0-1023): 324.00 - Voltage: 1.58 - Dust Density: 0.17
Raw Signal Value (0-1023): 306.00 - Voltage: 1.49 - Dust Density: 0.15
Raw Signal Value (0-1023): 294.00 - Voltage: 1.44 - Dust Density: 0.14
Raw Signal Value (0-1023): 283.00 - Voltage: 1.38 - Dust Density: 0.13
Raw Signal Value (0-1023): 274.00 - Voltage: 1.34 - Dust Density: 0.13

If I connect the green wire to A0 and Yellow wire to D2 I get below result
Raw Signal Value (0-1023): 0.00 - Voltage: 0.00 - Dust Density: -0.10
Raw Signal Value (0-1023): 0.00 - Voltage: 0.00 - Dust Density: -0.10
Raw Signal Value (0-1023): 0.00 - Voltage: 0.00 - Dust Density: -0.10
Raw Signal Value (0-1023): 0.00 - Voltage: 0.00 - Dust Density: -0.10
Raw Signal Value (0-1023): 0.00 - Voltage: 0.00 - Dust Density: -0.10
Raw Signal Value (0-1023): 0.00 - Voltage: 0.00 - Dust Density: -0.10

I am not really sure whether I am getting the correct result or not, and have I hooked up correctly.

The outline diagram shows the connection order:

As you can see from the image in the second row pin 1 is closest to the edge of the unit. In your image that is red.  So following those down and matching them to the "Terminal Configuration":

V-LED = Red (Connect to 5V via resistor)
LED-GND = Black (GND)
LED = Yellow (D2)
S-GND = White (GND)
Vo = Green (A0)
Vcc = Blue (Connect direct to 5V)

connecting this way gives this result:
Raw Signal Value (0-1023): 0.00 - Voltage: 0.00 - Dust Density: -0.10
Raw Signal Value (0-1023): 0.00 - Voltage: 0.00 - Dust Density: -0.10

The way you wired it before may have killed the IR LED through over-current...

is IR LED replaceable manually by soldering ?

If you can get to it, possibly. Unlikely though for a novice.


text:
The exact time for functions or CPU cycles for any function
I'm trying to read input data from the parallel port of a PC and send it to another device. For this purpose the input data is saved, when it's available and is sent if a flag is set.
The whole procedure should be done in less than 10 ms. I need to know the running time. How can I compute the CPU cycles for ReadParallel and WriteParallel functions (digitalRead, digitalWrite, bitRead,bitWrite) in my code or any other instructions?
Here is the code for the Arduino Uno:
#define InterruptInputPin 2 // For checking if the input data is available
#define InterruptSensorPin 3 // For checking when to send data

#define IN0 A0
#define IN1 A1
#define IN2 A2
#define IN3 A3

#define OUT0 5
#define OUT1 6
#define OUT2 7
#define OUT3 8

volatile int ParallelInput; // The input data

//*************************************
void ReadParallel() //Reads input and saves it in parallelInput.
{
  if (digitalRead(IN0) == HIGH)
    bitWrite(ParallelInput,0,1);
    else
      bitWrite(ParallelInput,0,0);

  if (digitalRead(IN1) == HIGH)
    bitWrite(ParallelInput,1,1);
    else
      bitWrite(ParallelInput,1,0);

  if (digitalRead(IN2) == HIGH)
    bitWrite(ParallelInput,2,1);
    else
      bitWrite(ParallelInput,2,0);

  if (digitalRead(IN3) == HIGH)
    bitWrite(ParallelInput,3,1);
    else
      bitWrite(ParallelInput,3,0);

}
//***************************************

void WriteParallel() //Writes ParallelInput to output.
{
  detachInterrupt(digitalPinToInterrupt(InterruptInputPin));
  digitalWrite(OUT0,bitRead(ParallelInput,0));
  digitalWrite(OUT1,bitRead(ParallelInput,1));
  digitalWrite(OUT2,bitRead(ParallelInput,2));
  digitalWrite(OUT3,bitRead(ParallelInput,3));
  attachInterrupt(digitalPinToInterrupt(InterruptInputPin),ReadParallel,RISING);

}

void setup() {

  pinMode(IN0,INPUT);
  pinMode(IN1,INPUT);
  pinMode(IN2,INPUT);
  pinMode(IN3,INPUT);

  pinMode(OUT0,OUTPUT);
  pinMode(OUT1,OUTPUT);
  pinMode(OUT2,OUTPUT);
  pinMode(OUT3,OUTPUT);
  attachInterrupt(digitalPinToInterrupt(InterruptInputPin),ReadParallel,RISING);

attachInterrupt(digitalPinToInterrupt(InterruptSensorPin),WriteParallel,RISING);

}

void loop() {

}

Note that, in this particular instance, you can get much faster I/O (like 100 × faster or so) by using direct port access. For example: void ReadParallel() { ParallelInput = PORTC & 0x0f; } should compile to not much more than 6 instructions. Or even 4 if you declare ParallelInput as a byte rather than an int.

Method summary
(section added on 2018-01-28)
There are several methods available for timing code. I am adding this
preliminary section to my answer in order to provide comparative data on
several methods. The methods covered in the table below are those
proposed as answers to both this question and a duplicate question of
this. As this question has been tagged “arduino-uno”, all
this data assumes an AVR-based board clocked at 16 MHz.
Method comparison:
| method         | resolution    | max. time       | typ. overhead  |
|----------------|---------------|-----------------|----------------|
| `millis()`     | 1 – 2 ms      | 49.7 days       | 0.69 – 1.3 µs  |
| `micros()`     | 4 µs          | 71.6 min        | 2.8 – 2.9 µs   |
| Timer 1        | 0.0625 µs     | 4.096 ms        | 0.25 – 0.5 µs  |
| pin toggling   | scope-limited | ∞               | 0.125 µs       |
| cycle counting | 0.0625 µs     | boredom-limited | 0              |
| looping        | N.A.          | N.A.            | 0.25 µs        |

The methods are characterized by the following criteria:

Resolution is the granularity of the measurement, the smaller the
better.
Maximum measurable time: any method that does timing arithmetics
on the Arduino is prone to overflows if measuring too long times. Note
that a timer rolling over to zero during the measurement is not a
problem, as long as the period being measured is less than
the rollover period.
Typical measurement overhead: the code used to measure the timings
takes itself a finite time to execute, thus one ends up measuring the
execution time of the “instrumented” code, which is slightly larger
than the time taken by the code one is trying to profile. This
overhead should in principle be subtracted from the result, but it is
often not known exactly, as it depends on how the compiler optimizes
both the instrumented and the non-instrumented code.

The methods listed in the table are:

millis(), which may be the most obvious choice, as it is so well
known. Its low resolution, however, makes it ill-suited for timing
code execution. It should be noted that the millis() counter is
incremented every 1024 µs. Most of the time it is incremented by
1 but, every 43 ms (roughly) it is incremented by 2 in order to
avoid creeping drift. This is why its resolution is stated as
“1 – 2 ms” in the table.
micros(), as proposed in ratchet freak's answer, is usually
a good choice, the main caveat being the 4 µs resolution, when
one could naively expect 1 µs. It also has a significant
overhead.
Timer 1, which is discussed in the second part of this answer, is
my favorite: it has single cycle resolution and low overhead. However,
it is incompatible with other uses of the timer (PWM, Servo
library...). It is also limited to measuring small delays.
Pin toggling, as proposed by 4ilo, and by myself in the third
part of this answer, is ideal if you have an oscilloscope handy. Any
half-decent scope should provide single-cycle resolution. It is also
minimally invasive on the code being measured and has minimal
overhead.
Cycle counting, as proposed in Majenko's answer, is arguably
the “perfect” method: it is cycle-accurate, does not modify the code
and has zero overhead. However, for anything beyond a handful
instructions, it quickly becomes tedious. And it requires some
understanding of the AVR assembly.
Looping, as proposed in Michel Keijzers' answer, is not a
measurement technique per se. It is meant to be used in conjunction
with another technique in order to improve the resolution and dilute
the overhead. However, lopping carries it's own overhead, which is
typically 4 CPU cycles per iteration, assuming a 16-bit loop
counter.

Using Timer 1
(original answer of 2017-10-23)
One technique I often use is to make Timer 1 count at the full CPU speed
and use it to time the code I want to profile. For example:
volatile uint8_t pin = 2;
volatile uint8_t value = HIGH;

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

    // Set Timer 1 to normal mode at F_CPU.
    TCCR1A = 0;
    TCCR1B = 1;

    // Time digitalWrite().
    cli();
    uint16_t start = TCNT1;
    digitalWrite(pin, value);
    uint16_t finish = TCNT1;
    sei();
    uint16_t overhead = 8;
    uint16_t cycles = finish - start - overhead;
    Serial.print("digitalWrite() took ");
    Serial.print(cycles);
    Serial.println(" CPU cycles.");
}

void loop(){}

Note the volatile variables used to prevent the compiler from
optimizing them as constants.
Note also that when you profile some code you are inevitably slowing it
down, because of the time taken by the profiling operations themselves.
This is what the overhead variable above accounts for. In order to
know the exact overhead, I start with a guess, compile and disassemble,
and then count the number of clock cycles spent in profiling that will
be counted by the timer. Then I adjust the overhead value, compile and
disassemble again, and make sure the overhead has not changed. This is
also when you have to ask yourself what exactly you want to count. Here
I am counting the time needed to execute call digitalWrite, but not
the time needed to get the arguments in the proper registers, as I am
artificially slowing this down by making them volatile.
This method is good for anything that takes more than roughly a dozen,
and less that 65,536 clock cycles. Less than that, clock counting would
be simpler, since you still have to clock-count the overhead. More than
that, the count would overflow, and you could instead just use
micros(), and live with its inherent inaccuracy.

Toggling a pin
(section added on 2017-10-23)
If you have a scope, there is another method that is minimally
invasive on your code: toggle a pin just before and just after the thing
you want to time. E.g., assuming you have previously
pinMode(13, OUTPUT):
// Set pin 13 HIGH.
PORTB |= _BV(PB5);

// The thing we want to time.
...

// Set pin 13 LOW.
PORTB &= ~_BV(PB5);

This will create a pulse that you can measure on the scope. Note that
using direct port access, like here, the overhead is only two CPU cycles,
or 125 ns. Also, direct port access won't use any CPU register, so
chances are the compiler will not generate less efficient code than when
not including the timing part.

And without a 'scope, I/O pin timing can be done with some DMMs. If it can measure pulse frequency and duty-cycle, you can calculate the interval (puse-width). Tekpower TP4000ZC is one such DMM and an inexpensive one, at that.

Thanks for answer. I haven't worked with registers and direct port access,  can you send me a document or link for more details?

@Mehran: The link I already sent you about direct port manipulation is a good introduction. You may then want to take a look at the description of the avr-libc macros commonly used for that task (mostly _BV() which is the avr-libc's equivalent of Arduino's bit()). Then, the ultimate reference is the microcontroller's datasheet.

There's two methods:

Profiling.
Clock counting.

The first method involves recording timestamps at different points in your program and calculating the time difference between them. That's the simplest, but not always the most accurate.
The second method is far harder and involves disassembling the program after you have compiled it (or obtaining the assembly language from part way through the compilation sequence) and examining all the assembly instructions, looking them up in the instruction list, and totalling how many clock cycles are used for each instruction. That gets very complex, especially when you have loops. However it will tell you precisely how many clock cycles, and thus how long, a block of code will take to execute (not including interrupts, which always throw a big spanned in the works).

To efficiently measure the time a block of code takes, run it for like 1,000 or 1,000,000 times and divide the time by the amount of iterations.
In some cases initialization/variables can be cached but in principle the times are quite accurate. You can easily check this by doing the test for e.g. 1,000 and 2,000 times and see that the time difference also is a factor 2.
For the time counter, use an unsigned long type to accommodate more than 65,535 (ms/us whatever the unit is used).

Keep in mind that managing the loop carries some overhead, typically about 4 CPU cycles per iteration for a 16-bit loop counter. You will have to subtract this from your result if you want sub-µs accuracy.