text:
no matching function to call for SoftwareSerial::SoftwareSerial(int&,int&)? How to rectify this problem
#include <LiquidCrystal.h>

#include <SoftwareSerial.h>

float pulse = 0;

float temp = 0;

SoftwareSerial ser(9,10);

String apiKey = "U5AGYVQT5JRJPSDR";

//  Variables

int pulsePin = A0;                 // Pulse Sensor purple wire connected to analog pin 0

int blinkPin = 7           ;                // pin to blink led at each beat

int fadePin = 8;                  // pin to do fancy classy fading blink at each beat

int fadeRate = 0;                 // used to fade LED on with PWM on fadePin

LiquidCrystal lcd(13, 12, 6, 5, 4, 3);

// Volatile Variables, used in the interrupt service routine!

volatile int BPM;                   // int that holds raw Analog in 0. updated every 2mS

volatile int Signal;                // holds the incoming raw data

volatile int IBI = 600;             // int that holds the time interval between beats! Must be seeded!

volatile boolean Pulse = false;     // "True" when User's live heartbeat is detected. "False" when not
 a "live beat".

volatile boolean QS = false;        // becomes true when Arduoino finds a beat.

// Regards Serial OutPut  -- Set This Up to your needs

static boolean serialVisual = true;   // Set to 'false' by Default.  Re-set to 'true' to see Arduino
Serial Monitor ASCII Visual Pulse

volatile int rate[10];                      // array to hold last ten IBI values

volatile unsigned long sampleCounter = 0;          // used to determine pulse timing

volatile unsigned long lastBeatTime = 0;           // used to find IBI

volatile int P = 512;                      // used to find peak in pulse wave, seeded

volatile int T = 512;                     // used to find trough in pulse wave, seeded

volatile int thresh = 525;                // used to find instant moment of heart beat, seeded

volatile int amp = 100;                   // used to hold amplitude of pulse waveform, seeded

volatile boolean firstBeat = true;        // used to seed rate array so we startup with reasonable BPM

volatile boolean secondBeat = false;      // used to seed rate array so we startup with reasonable BPM

void setup()

{

  lcd.begin(16, 2);

  pinMode(blinkPin,OUTPUT);         // pin that will blink to your heartbeat!

  pinMode(fadePin,OUTPUT);          // pin that will fade to your heartbeat!

  Serial.begin(115200);             // we agree to talk fast!

  interruptSetup();                 // sets up to read Pulse Sensor signal every 2mS

                                    // IF YOU ARE POWERING The Pulse Sensor AT VOLTAGE LESS THAN THE BOARD VOLTAGE,

                                    // UN-COMMENT THE NEXT LINE AND APPLY THAT VOLTAGE TO THE A-REF PIN

                                    //   analogReference(EXTERNAL);

  lcd.clear();

  lcd.setCursor(0,0);

  lcd.print("Engineers Garage");

  ser.begin(9600);

  ser.println("AT");

  delay(1000);

  ser.println("AT+GMR");

  delay(1000);

  ser.println("AT+CWMODE=3");

  delay(1000);

  ser.println("AT+RST");

  delay(5000);

  ser.println("AT+CIPMUX=1");

  delay(1000);

  String cmd="AT+CWJAP="EngineersGarage","egP@$$w0rd?"";

  ser.println(cmd);

  delay(1000);

  ser.println("AT+CIFSR");

  delay(1000);

}

//  Where the Magic Happens

void loop()

{

   serialOutput();

  if (QS == true) // A Heartbeat Was Found

    {

      // BPM and IBI have been Determined

      // Quantified Self "QS" true when arduino finds a heartbeat

      fadeRate = 255; // Makes the LED Fade Effect Happen, Set 'fadeRate' Variable to 255 to fade LED
 with pulse

      serialOutputWhenBeatHappens(); // A Beat Happened, Output that to serial.

      QS = false; // reset the Quantified Self flag for next time

    }

  ledFadeToBeat(); // Makes the LED Fade Effect Happen

  delay(20); //  take a break

  read_temp();

  esp_8266();

}

void ledFadeToBeat()

{

   fadeRate -= 15;                         //  set LED fade value

   fadeRate = constrain(fadeRate,0,255);   //  keep LED fade value from going into negative numbers!

   analogWrite(fadePin,fadeRate);          //  fade LED

}

void interruptSetup()

{

  // Initializes Timer2 to throw an interrupt every 2mS.

  TCCR2A = 0x02;     // DISABLE PWM ON DIGITAL PINS 3 AND 11, AND GO INTO CTC MODE

  TCCR2B = 0x06;     // DON'T FORCE COMPARE, 256 PRESCALER

  OCR2A  = 0X7C;      // SET THE TOP OF THE COUNT TO 124 FOR 500Hz SAMPLE RATE

  TIMSK2 = 0x02;     // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A

  sei();             // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED

}

void serialOutput()

{   // Decide How To Output Serial.

 if (serialVisual == true)

  {

     arduinoSerialMonitorVisual('-', Signal);   // goes to function that makes Serial Monitor Visualizer

  }

 else

  {

      sendDataToSerial('S', Signal);     // goes to sendDataToSerial function

   }

}

void serialOutputWhenBeatHappens()

{

 if (serialVisual == true) //  Code to Make the Serial Monitor Visualizer Work

   {

     Serial.print("*** Heart-Beat Happened *** ");  //ASCII Art Madness

     Serial.print("BPM: ");

     Serial.println(BPM);

     lcd.clear();

     lcd.print("BPM: ");

     lcd.print(BPM);

   }

 else

   {

     sendDataToSerial('B',BPM);   // send heart rate with a 'B' prefix

     sendDataToSerial('Q',IBI);   // send time between beats with a 'Q' prefix

   }

}

void arduinoSerialMonitorVisual(char symbol, int data )

{

  const int sensorMin = 0;      // sensor minimum, discovered through experiment

  const int sensorMax = 1024;    // sensor maximum, discovered through experiment

  int sensorReading = data; // map the sensor range to a range of 12 options:

  int range = map(sensorReading, sensorMin, sensorMax, 0, 11);

  // do something different depending on the

  // range value:

  switch (range)

  {

    case 0:

      Serial.println("");     /////ASCII Art Madness

      break;

    case 1:

      Serial.println("---");

      break;

    case 2:

      Serial.println("------");

      break;

    case 3:

      Serial.println("---------");

      break;

    case 4:

      Serial.println("------------");

      break;

    case 5:

      Serial.println("--------------|-");

      break;

    case 6:

      Serial.println("--------------|---");

      break;

    case 7:

      Serial.println("--------------|-------");

      break;

    case 8:

      Serial.println("--------------|----------");

      break;

    case 9:

      Serial.println("--------------|----------------");

      break;

    case 10:

      Serial.println("--------------|-------------------");

      break;

    case 11:

      Serial.println("--------------|-----------------------");

      break;

  }

}

void sendDataToSerial(char symbol, int data )

{

   Serial.print(symbol);

   Serial.println(data);

}

ISR(TIMER2_COMPA_vect) //triggered when Timer2 counts to 124

{

  cli();                                      // disable interrupts while we do this

  Signal = analogRead(pulsePin);              // read the Pulse Sensor

  sampleCounter += 2;                         // keep track of the time in mS with this variable

  int N = sampleCounter - lastBeatTime;       // monitor the time since the last beat to avoid noise

                                              //  find the peak and trough of the pulse wave

  if(Signal < thresh && N > (IBI/5)*3) // avoid dichrotic noise by waiting 3/5 of last IBI

    {

      if (Signal < T) // T is the trough

      {

        T = Signal; // keep track of lowest point in pulse wave

      }

    }

  if(Signal > thresh && Signal > P)

    {          // thresh condition helps avoid noise

      P = Signal;                             // P is the peak

    }                                        // keep track of highest point in pulse wave

  //  NOW IT'S TIME TO LOOK FOR THE HEART BEAT

  // signal surges up in value every time there is a pulse

  if (N > 250)

  {                                   // avoid high frequency noise

    if ( (Signal > thresh) && (Pulse == false) && (N > (IBI/5)*3) )

      {

        Pulse = true;                               // set the Pulse flag when we think there is a pulse

        digitalWrite(blinkPin,HIGH);                // turn on pin 13 LED

        IBI = sampleCounter - lastBeatTime;         // measure time between beats in mS

        lastBeatTime = sampleCounter;               // keep track of time for next pulse

        if(secondBeat)

        {                        // if this is the second beat, if secondBeat == TRUE

          secondBeat = false;                  // clear secondBeat flag

          for(int i=0; i<=9; i++) // seed the running total to get a realisitic BPM at startup

          {

            rate[i] = IBI;

          }

        }

        if(firstBeat) // if it's the first time we found a beat, if firstBeat == TRUE

        {

          firstBeat = false;                   // clear firstBeat flag

          secondBeat = true;                   // set the second beat flag

          sei();                               // enable interrupts again

          return;                              // IBI value is unreliable so discard it

        }

      // keep a running total of the last 10 IBI values

      word runningTotal = 0;                  // clear the runningTotal variable

      for(int i=0; i<=8; i++)

        {                // shift data in the rate array

          rate[i] = rate[i+1];                  // and drop the oldest IBI value

          runningTotal += rate[i];              // add up the 9 oldest IBI values

        }

      rate[9] = IBI;                          // add the latest IBI to the rate array

      runningTotal += rate[9];                // add the latest IBI to runningTotal

      runningTotal /= 10;                     // average the last 10 IBI values

      BPM = 60000/runningTotal;               // how many beats can fit into a minute? that's BPM!

      QS = true;                              // set Quantified Self flag

      // QS FLAG IS NOT CLEARED INSIDE THIS ISR

      pulse = BPM;

    }

  }

  if (Signal < thresh && Pulse == true)

    {   // when the values are going down, the beat is over

      digitalWrite(blinkPin,LOW);            // turn off pin 13 LED

      Pulse = false;                         // reset the Pulse flag so we can do it again

      amp = P - T;                           // get amplitude of the pulse wave

      thresh = amp/2 + T;                    // set thresh at 50% of the amplitude

      P = thresh;                            // reset these for next time

      T = thresh;

    }

  if (N > 2500)

    {                           // if 2.5 seconds go by without a beat

      thresh = 512;                          // set thresh default

      P = 512;                               // set P default

      T = 512;                               // set T default

      lastBeatTime = sampleCounter;          // bring the lastBeatTime up to date

      firstBeat = true;                      // set these to avoid noise

      secondBeat = false;                    // when we get the heartbeat back

    }

  sei();                                   // enable interrupts when youre done!

}// end isr

void esp_8266()

{

   // TCP connection AT+CIPSTART=4,"TCP","184.106.153.149",80

    String cmd = "AT+CIPSTART=4,"TCP","";

    cmd += "184.106.153.149"; // api.thingspeak.com

    cmd += "",80";

    ser.println(cmd);

    Serial.println(cmd);

    if(ser.find("Error"))

    {

      Serial.println("AT+CIPSTART error");

      return;

    }

  // prepare GET string GET https://api.thingspeak.com/update?api_key=LHAG4NSIYJ5UWS6U&field1=0rnrn

  String getStr = "GET /update?api_key=";

  getStr += apiKey;

  getStr +="&field1=";

  getStr +=String(temp);

  getStr +="&field2=";

  getStr +=String(pulse);

  getStr += "rnrn";

  // send data length

  cmd = "AT+CIPSEND=4,";

  cmd += String(getStr.length());

  ser.println(cmd);

  Serial.println(cmd);

  delay(1000);

  ser.print(getStr);

  Serial.println(getStr);

 //thingspeak needs 15 sec delay between updates

  delay(3000);

}

void read_temp()

{

  int temp_val =  analogRead(A1);

  float mv = (temp_val/1024.0)*5000;

  float cel = mv/10;

  temp = (cel*9)/5 + 32;

}

Align your code (select and press ctrl-k), and also make the minimal sketch that shows the program.

Sorry can you brief it clearly?

I see now the code is already aligned (if you didn't do it, someone else did)

I don't see anything wrong in the SoftwareSerial declaration … can you recheck you are using the correct library? Check the constructor of the SoftwareSerial class you are using.

you are on esp8266. they changed the constructor an moved the parameters to begin()

I just copied the code from web ..should i add any other function or header file to this code

yes i'm using esp8266, can you explain what should i change in that code

can we use this code for nodemcu wifi module ?

the sketch is not for NodeMCU. it is for Uno with esp8266 wired to pins 9 and 10

The sketch in the question is not for NodeMCU. It is for Arduino with esp8266 wired on pins 9 and 10. But the error in title is a current error for esp8266 Arduino boards package 2.6.0. The EspSoftwareSerial bundled with the esp8266 Arduino boards package version 2.6.0 has a compatibility breaking change.
The problem was immediately reported and the EspSoftwareSerial maintainer added the legacy API back to EspSoftwareSerial. The fixed version will be available with esp8266 boards package 2.6.1, which will be available soon because of multiple problems with 2.6.0.

2.6.1 is released


text:
NodeMCU ESP8266 button wiring problem
Hello guys, this is my code and I am basically doing if-else statement.
int led = D2;
int but = D1;

void setup() {
  pinMode(led, OUTPUT);
  pinMode(but, INPUT);

}

void loop() {
  if (digitalRead(but) == HIGH){
    digitalWrite(led, HIGH);
  }else{
    digitalWrite(led, LOW);
  }

}

I have also attached the photo so that you can diagnose the situation.
The led show only glow if the button is pressed. But the led keeps glowing for longer time and I don't know why.
I think there is current leak somewhere in the circuit or the internal processing is slow.
Please help me guys.

The circuit seems like it's wrong.
When a button is pressed it wil fluctuate some before it going to be stable.
Try this:
"
bool state=digitalRead(but)
digitalWrite(led, state);
"
also similar problem: https://arduino.stackexchange.com/questions/3425/unstable-reading-from-pushbutton-on-digital-pin

Your button and pull-up configuration is not correct, so when the button is not being pressed, the pin D1 is floating, being pulled neither HIGH nor LOW.
Instead, use a pull-up resistor as shown. When the button is not pressed, D1 is connected to GND through a resistor. When the button is pressed, the 3.3V source has a direct path to D1.

simulate this circuit – Schematic created using CircuitLab

why pull-down? it is simpler to use the internal pullup

Because the asker has coded for a pull-up. Yes, it’s trivial to change.

source: Stack Exchange

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

sort: votes


text:
Arduino sketch not uploading to Arduino Nano
Port is detected and selected but sketch is not uploading to it.
I am getting error:
         avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\ACER\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9/etc/avrdude.conf"

         Using Port                    : COM5
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x2c
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x2c

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

In IDE in the Tools menu, select in submenu Processor the "Atmega 328P (Old Bootloader)" option.
The upload speed 115200 in your console output indicates the you try to upload for new bootloader. The fail to upload could indicate that your Nano has the old bootloader.

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


text:
Button isn't working properly
I am new in arduino trying to make race game. My problem is that my button (all buttons) is working sometimes and sometimes not. I am pretty sure that it's because of my code. Could you please help me with it?
Here is my code:
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int pausebetween = 1;
int spaceBetween = 1;
int maxElemnets = 4;
int obstacleArray[4][2];
int obstacles[4] = {3,3,2,3};
bool gameStart = false;
byte player[8] =
{
 B00000,
 B00000,
 B10100,
 B11110,
 B11111,
 B11110,
 B10100,
 B00000
};
byte obstacle[8] =
{
 B11111,
 B11111,
 B11111,
 B11111,
 B11111,
 B11111,
 B11111,
 B11111
};
byte enemy[8] =
{
 B00000,
 B00000,
 B00101,
 B01111,
 B00101,
 B00000,
 B00000
};
byte empty[8] =
{
 B00000,
 B00000,
 B00000,
 B00000,
 B00000,
 B00000,
 B00000
};
byte fire[8] =
{
 B00000,
 B00000,
 B00000,
 B11111,
 B00000,
 B00000,
 B00000
};
int mat[2][24] = {
  {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
  {1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}
  };
int up = 0;
int down = 0;
int reset=0;
int atack=0;
void setup() {
 pinMode(9, INPUT);
 pinMode(8, INPUT);
 pinMode(7, INPUT);
 pinMode(6, INPUT);
 Serial.begin(9600);
 lcd.createChar(0, player);
 lcd.createChar(1, empty);
 lcd.createChar(2, enemy);
 lcd.createChar(3, obstacle);
 lcd.createChar(4, fire);
 lcd.begin(16, 2);
}
void loop() {
  up  = digitalRead(9);
  down  = digitalRead(8);
  atack  = digitalRead(7);
  reset  = digitalRead(6);
  if(atack){
    for(int i = 0; i<2;i++){
        for(int j = 0; j<23; j++){
            if(mat[j][i]==1){
              mat[j+1][i]=4;
              Serial.println(mat[j+1][i]);
            }
        }
      }
  }
  if(reset){
    clearStage();
    gameStart = true;
  }
  if(gameStart){
    generateObstacles();
    redrawGame();
    moveObstacles();
  }
  delay(1000);

 }

void generateObstacles(){
  int obscount = random(1,4);
  int types[4][2] = {{1,3},{2,1},{1,1},{2,1}} ;
  int type = random(0,4);
  for(int i = 0; i< obscount; i++){
    mat[0][16+i] = types[type][0];
    mat[1][16+i] = types[type][1];
  }
  int spacecount = random(2,5);
  pausebetween = obscount + spacecount;
}
void redrawGame(){
   for(int j = 15; j >= 0; j--){
    for(int i = 0; i < 2; i++){
      lcd.setCursor(j,i);
      lcd.write(mat[i][j]);
    }
  }
}
void clearStage(){
  for(int i = 0; i<2;i++){
        for(int j = 0; j<23; j++){
            if(i!=1 && j!=1){
               mat[i][j] =1;
          }
        }
      }
}
void moveObstacles(){
   for(int i = 0; i<2;i++){
        for(int j = 0; j<23; j++){
           if(mat[i][j]!=0){
            mat[i][j] = mat[i][j+1];
          }else{
            mat[i][j-1]=1;
          }
          if(mat[i][j]==4){
            mat[i][j-1]=0;
            mat[i][j-2]=1;
           }
        }
      }
}

Scheme:

I have two suggestions.

Get rid of the delay(1000); in the loop and replace it with code from the BlinkWithoutDelay example that comes with the Arduino IDE: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay.
Debounce the buttons. There are several libraries on Github that simplify this, for example: https://playground.arduino.cc/Code/Bounce.

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


text:
ESP8266 Led is not working
My led is not blinking, I have no idea why it's not working.
I am running it on "generic esp8266 module" plate.
 /*Blink

  Turns an LED on for one second, then off for one second, repeatedly.

  Most Arduinos have an on-board LED you can control. On the UNO, MEGA and ZERO
  it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN is set to
  the correct LED pin independent of which board is used.
  If you want to know what pin the on-board LED is connected to on your Arduino
  model, check the Technical Specs of your board at:
  https://www.arduino.cc/en/Main/Products

  modified 8 May 2014
  by Scott Fitzgerald
  modified 2 Sep 2016
  by Arturo Guadalupi
  modified 8 Sep 2016
  by Colby Newman

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/Blink
*/

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(13, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

My scheme

Wifi module is working fine, but led is not working at all.

Another sketch
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <Servo.h>
// Initialize Wifi connection to the router
char ssid[] = "---";     // your network SSID (name)
char password[] = "---"; // your network key
int tempsensorPin = 0;
int lightsensorPin = 1;
bool searchState = false;
bool starting = false;
bool lightState = false;
Servo servo_test;
// Initialize Telegram BOT
#define BOTtoken "----"  // your Bot Token (Get from Botfather)

WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);

int Bot_mtbs = 1000; //mean time between scan messages
long Bot_lasttime;   //last time messages' scan has been done

void setup() {
  //servo_test.attach(8);
  Serial.begin(115200);

  // Set WiFi to station mode and disconnect from an AP if it was Previously
  // connected
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);

  // Attempt to connect to Wifi network:
  Serial.print("Connecting Wifi: ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);

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

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

void loop() {
 digitalWrite(13,lightState);
  if (millis() > Bot_lasttime + Bot_mtbs)  {
    int numNewMessages = bot.getUpdates(bot.last_message_received + 1);

    while(numNewMessages) {
      Serial.println("got response");
      for (int i=0; i<numNewMessages; i++) {
        String id = bot.messages[i].chat_id;
        String text = bot.messages[i].text;

       //bot.sendMessage(bot.messages[i].chat_id, bot.messages[i].text, "");
        if(searchState){
          searchState=false;
          bot.sendMessage(bot.messages[i].chat_id, "http://lmgtfy.com/?q="+text, "");
        }else{
          bot.sendMessage(bot.messages[i].chat_id, answerMe(text), "");
        }
      }
      numNewMessages = bot.getUpdates(bot.last_message_received + 1);
    }

    Bot_lasttime = millis();
  }
}
String answerMe(String request){
 int tempSensor = analogRead(tempsensorPin);
 int lightSensor = analogRead(lightsensorPin);
 float voltage = tempSensor * 5.0;
 voltage /= 1024.0;
 Serial.print(voltage); Serial.println(" volts");
   float temperatureC = (voltage - 0.5) * 20 ;
 Serial.print(temperatureC); Serial.println(" degrees C");
 float temperatureF = (temperatureC * 9.0 / 5.0) + 32.0;
 Serial.print(temperatureF); Serial.println(" degrees F");
 if(starting){
  if (request=="/temperatureF"){
    return "Current temperature is " + String(temperatureF) + " F";
  }
  if (request=="/temperatureC"){
    return "Current temperature is " + String(temperatureC) +" C";
  }
  if(request=="/lightIntensity"){
    return "Current light intensity is " + String(lightSensor);
  }
  if(request=="/lightON"){
    lightState=true;
    return "Current light state is true!";
  }
  if(request=="/lightOFF"){
    lightState=false;
    return "Current light state is false!";
  }
  if(request=="/lightDepend"){
    analogWrite(13,lightSensor);
    return "Here we go!";
  }
  if(request=="/google"){
    searchState=true;
    return "What you want to google?";
  }
  if(request=="close"){
    starting=false;
    servo_test.write(0);
    return "Bye bye!";
  }
}else if(request=="/open"){
    starting=true;
    servo_test.write(90);
    return "What's next?";
}else
    return "Open the box first!";

}

You are uploading ESP8266 code to the Arduino???

or his uploading Blink with pin 13 to esp8266 and expects the led on Arduino to blink

I think he's compiling for the ESP8266 (I am running it on "generic esp8266 module" plate.) but uploading it to the Arduino. Maybe. It's a common mistake that you select the ESP8266 as your target when it's a mere peripheral to the Arduino that you are actully programming.

the upload would fail, or not? 250+ kb? if I see it right RX is to RX and TX to TX

yep it's rx to rx and tx to tx and it works

So you're running code on the ESP8266 and expecting it to magically blink the LED on the Arduino?

@Juraj updated, i've changed tx to rx and tx to rx now led is blinking while code compile but upload fails warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

The esp8266 will not blink the LED on pin 13 or any other pin of the Uno. It has no access to pins of Uno. And your analogRead calls return some random values.
The RX to RX, TX to TX connection reduces the Uno to an "USB to Serial" adapter for the esp8266. You upload the Blink to esp8266. If the Blink sketch would have the original LED_BUILTIN pin number, then the LED on the esp8266 module would perhaps blink.
After you changed the connection RX to TX and TX to RX, you can't upload to esp8266 because the esp8266 is not anymore connected to PC over USB.
If you want to read and write the pins of Uno from esp8266, use ConfigurableFirmata sketch in Uno and FirmataMaster library in esp8266.
Other option is to write your own sketch for Uno and handle the communication between esp8266 and Uno over Serial.
Or you can use the esp8266 as network adapter with some firmware (AT firmware or WiFi Link) and port your sketch to Uno.

So it's impossible to make this light blink even if i change pin to 11? sorry for being dumb

you can blink any pin on Uno with a sketch in Uno. but for what you want to use the esp8266 module?

i am using it to connect to the telegram bot and by its commands getting different sensor outputs such as light sensor and temperature sensor, i also want to blink   light but it's not working, i spent like 2 days to solve this problem but its not working at all

you plan to send commands or you have a working sketch?

i have working sketch, but i can't make my led working on it other modules working well

updated pls check it out

your analogRead calls return some random values from esp8266 pins. If you want to read and write the pins of Uno from esp8266, use ConfigurableFirmata sketch in Uno and FirmataMaster library in esp8266. Answer updated.

Probably you are not uploading the code to ESP8266. Instead the code is getting uploaded to the Arduino. You should Ground the GPIO1 and connect ESP8266 Reset to Arduino Reset. Then go to the Sketch and see if you have changed the Board from ARduino to ESP8266.

how could a 250kb big esp sketch be successful uploaded to Uno?


text:
don't save on tab
Ok, I made some changes to the code and I wish they would see it.
At the moment the program has a bug, it is not saving the contents of the txt file to the table, can someone give some lights?
#include <LiquidCrystal.h>
#include <SPI.h>
#include <SD.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

// define some values used by the panel and buttons
int lcd_key     = 0;
int adc_key_in  = 0;
int x = 1;
String files, memo, memo1;
int sizef = 0;
int sizef1 = 0;
int sizef2 = 0;
int y=0;
int z=1;
int d=0;
int u=0;
int r=0;
int l=0;
int indice_objetos=0;

struct objeto_celeste_s {
  char nome[20];
  float ar;
  float dec;
  };
typedef struct objeto_celeste_s objeto_celeste;

void rightfunction (int rate){
 char cmd[] = {'P',2,16,36,rate,0,0,0};

  for(int i=0; i<(int)(sizeof(cmd)/sizeof(char)); i++)
    Serial1.print(cmd[i]);

}

void leftfunction (int rate){
 char cmd[] = {'P',2,16,37,rate,0,0,0};

  for(int i=0; i<(int)(sizeof(cmd)/sizeof(char)); i++)
    Serial1.print(cmd[i]);

}

void upfunction (int rate){
 char cmd[] = {'P',2,17,36,rate,0,0,0};

  for(int i=0; i<(int)(sizeof(cmd)/sizeof(char)); i++)
    Serial1.print(cmd[i]);
}

void downfunction (int rate){
 char cmd[] = {'P',2,17,37,rate,0,0,0};

  for(int i=0; i<(int)(sizeof(cmd)/sizeof(char)); i++)
    Serial1.print(cmd[i]);
}

File file;

#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5

char * list[]={"1.Modo Normal    ","2.Modo Teste    "};

// read the buttons
int read_LCD_buttons()
{

adc_key_in = analogRead(0);
if (adc_key_in > 1000) return btnNONE;
if (adc_key_in < 50)   return btnRIGHT;
if (adc_key_in < 250)  return btnUP;
if (adc_key_in < 400)  return btnDOWN;
if (adc_key_in < 450)  return btnLEFT;
if (adc_key_in < 650)  return btnSELECT;

return btnNONE;  // when all others fail, return this...
}

void setup() {

 Serial.begin(9600);
 Serial1.begin(9600);
 while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
 }
 Serial.println ("Welcome!");
 Serial.println ("Efectue o alinhamento do telescópio, depois carregue no botão UP.");
 lcd.begin (16,2);
 lcd.setCursor (0,0);
 lcd.print ("Efectue alinham.");
 lcd.setCursor (0,1);
 lcd.print ("E carregue UP");
 delay (1000);

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

void loop() {

lcd_key = read_LCD_buttons();  // read the buttons

 switch (lcd_key)  // depending on which button was pushed, we perform an action
 {
   case btnRIGHT:
     if (z==0){
      rightfunction (9);
      Serial.println ("Andar para a direita a uma velocidade de 9.");
      z=1;
      r=1;
      break;
     }

     if (r==1){
      rightfunction (0);
      Serial.println ("Parar de andar para a direita.");
      z=0;
      r==0;
      break;
     }

   case btnLEFT:
     if (z==0){
      leftfunction (9);
      Serial.println ("Andar para a esquerda a uma velocidade de 9");
      z=1;
      l=1;
      break;
     }

     if (l==1){
      leftfunction (0);
      Serial.println ("Parar de andar para a esquerda.");
      z=0;
      l=0;
      break;
     }

   case btnUP:
      if (z==0){
       upfunction (9);
       Serial.println ("Andar para cima a uma velocidade de 9");
       z=1;
       u=1;
       break;
     }

      if (u==1){
       upfunction (0);
       Serial.println ("Parar de andar para cima.");
       z=0;
       u=0;
       break;
     }

      if(x==1){
        x--;
        lcd.clear ();
        lcd.setCursor(0,0);
        lcd.print(">");
        lcd.println(list[0]);
        lcd.setCursor(0,1);
        lcd.print (" ");
        lcd.println(list[1]);
        break;
      }
   case btnDOWN:
      if (z==0){
       downfunction (9);
       Serial.println ("Andar para baixo a uma velocidade de 9.");
       z=1;
       d=1;
       break;
      }

      if (d==1){
       downfunction (0);
       Serial.println ("Parar de andar para baixo.");
       z=0;
       d=0;
       break;
      }

      if(x==0){
        x++;
        lcd.clear ();
        lcd.setCursor(0,0);
        lcd.print(">");
        lcd.println(list[1]);
        lcd.setCursor(0,1);
        lcd.println("                ");
        break;
      }

   case btnSELECT:
    if (x==2){
      Serial.println ("Bem-vindo ao Modo Manual.");
      lcd.clear ();
      lcd.print ("Modo Manual");
      lcd.setCursor (0,1);
      lcd.print ("Reset p/mod GoTo");
      Serial.println ("Pressione os botões UP, DOWN, RIGHT ou LEFT no arduíno para controlar o telescópio.");
      z=0;
      break;
    }

    if (x==0){
    lcd.clear ();
    lcd.print ("Modo Normal");
    Serial.println ("Selecionou o modo normal!");
    delay (1000);
    if (SD.exists("objectos.txt")) {
    Serial.println("O ficheiro 'objetos' foi encontrado!");
    lcd.clear ();
    lcd.setCursor (0,0);
    lcd.print ("Modo Normal");
    delay (1000);

    file = SD.open("objectos.txt", FILE_READ);
    if (file) {
    while (file.available()) {
     String line = file.readStringUntil('\n');
     sizef++;
    }
    } else {//se houver erro a abrir o ficheiro
     Serial.println("Erro a abrir o ficheiro 'objectos.txt'.");
    }
     Serial.print ("Contados ");
     Serial.print (sizef);
     Serial.println (" objetos no ficheiro objectos.txt.");

     objeto_celeste *tab =(objeto_celeste *)malloc((sizef) * sizeof(objeto_celeste));

     if (tab==NULL){
      lcd.clear ();
      lcd.print ("Erro a alocar memoria");
      Serial.println ("Erro a alocar memória");
      while (1){ };

     }else{

      Serial.print ("Memória alocada para ");
      Serial.print (sizef);
      Serial.println (" objectos.");
      lcd.setCursor (0,1);
      lcd.print ("Alocados ");
      lcd.print (sizef);
      lcd.print (" obj");
      }

      file.close();

    char * line1 =(char*) malloc(sizeof(String));

    file = SD.open("objectos.txt", FILE_READ);

    if (file) {
     Serial.println ("Carregando informação para a memória:");

     while (file.available()) {

     char c = file.read ();

     if (c=='\n'){

     char * justafun = strtok (line1," "); //divide em tokens

     while (justafun !=NULL){

      switch (indice_objetos) {
          case 1:
            tab[sizef2].ar = atof(justafun); //to float

            indice_objetos++;
            break;
          case 2:
            tab[sizef2].dec = atof(justafun);

            sizef2++;
            indice_objetos=0;
            break;
          case 0:
            strcpy(tab[sizef2].nome, justafun); //this one is a string
            indice_objetos++;
            break;
      }
      justafun = strtok (NULL, " ");
      }

      if (line1==NULL){
      Serial.print ("Falhou na linha ");
      Serial.println (sizef2);

     }else{
       line1="";
    }
   }else{
     sprintf(line1, "%s%c", line1, char(c));
     }
    }
   }
  file.close ();

  delay (1500);

  if (Serial1.available()) {
   int inByte = 'V';
   Serial1.write (inByte);
   int inByte1 = 'e';
   Serial1.write (inByte1);
  }

delay (1000);

Serial.println ("Tabela ordenada alfabeticamente:");

 x=2;
 delay (1000);
 lcd.clear ();
 Serial.println ("Modo GoTo. Para entrar em Modo Manual pressione o botão select.");
 lcd.print ("Modo GoTo");
 lcd.setCursor (0,1);
 lcd.print ("Slct p/Modo Man.");

 }else {

    Serial.println ("O ficheiro 'objetos' não existe.");
    lcd.clear ();
    lcd.print ("Erro nao encontrado");
    delay (2000);
    while(1) { };
  }
 }

    if (x==1){
      lcd.clear ();
      lcd.print ("Modo Teste");
      Serial.println ("Selecionou o modo teste!");
      delay (2000);

      if (SD.exists("teste.txt")) {
      Serial.println("O ficheiro 'teste.txt' foi encontrado!");
      lcd.clear ();
      lcd.setCursor (0,0);
      lcd.print ("Modo Teste");
      lcd.setCursor (0,1);
      lcd.print ("Ficheiro encontrado");
      delay (2000);

      file = SD.open("teste.txt", FILE_READ);

      if (file) {
      while (file.available()) {//ler o ficheiro
      String line = file.readStringUntil('\n');
      sizef++;
     }

      files = "Contados " + String (sizef) + " objetos no ficheiro teste.txt.";
      Serial.println (files);
      objeto_celeste *tab = (objeto_celeste *)malloc((sizef) * sizeof(objeto_celeste));
      memo = "Alocados " + String (sizef) + " obj  ";
      memo1= "Memória alocada para " + String (sizef) + " objetos.";

      if (tab==NULL){
        lcd.clear ();
        lcd.print ("Erro alocar memoria");
        Serial.println ("Erro a alocar memória");
        while (1){ };

      }else{

        Serial.println (memo1);
        lcd.setCursor (0,1);
        lcd.print (memo);
      }

      file.close();

     } else {//se houver erro a abrir o ficheiro
      Serial.println("Erro a abrir o ficheiro 'teste.txt'.");
     }

    }else {
      Serial.println ("O ficheiro 'teste.txt' não foi encontrado.");
      lcd.clear ();
      lcd.print ("Erro nao encontrado");
      delay (2000);
      while(1) { };
    }
   }
     break;

   case btnNONE:
      break;
 }
 delay (200);
}

This is the content of txt.
P.S. I know the "Ar" section is wrong, it's just for test purposes.
Syrius 6.45 -16.42
Deneb 20.41 +45.16
Capella 5.16 +45.59
Rigel 5.14 -8.12
Vega 18.36 +38.47
Alnitak 05.40 -01.56

Possible duplicate of https://arduino.stackexchange.com/questions/51957/program-dont-read-memory-well

Hi, this is too long for a comment in other post.

And the code is not the same...

Why do you except the contents of your textfile to be saved into the array tab? You read one character at a time but aren't doing anything else with it than using it in an if-statement. You have to actually put your information into your data array

Consider that you always can edit your question. Code or other long things should not be placed in code, but the question should be edited. For me it seems, that you have the same problem as last time. If not, please be more specific

else{sprintf(line1, "%s%c", line1, char(c));

You should edit the code in your question to be a minimal, complete, verifiable example of the problem. Very likely you'll discover the problem in the process of creating it, and if not, you'll create a question which might be of use to someone else in the future, which is what this site is about.

@1manonearth: This line is not in the code of your question. Edit it, so that it reflects the code you are actually using

I have edited. Can u see?

Maybe I have found your problem:
Before reading the file you are allocating memory with malloc() and creating a pointer line1 to it. malloc() takes the number of bytes to allocate as a parameter. Here you use sizeof(String), which would give you the size of a new String object. But the point of the String object is, that is dynamically allocates the memory for the string of characters. So the created buffer line1 is most likely to small for your text. You have to allocate the buffer with the maximum number of characters of all lines.
But you should consider, that using malloc() or any other dynamic memory allocation is dangerous on microcontrollers, which don't have much RAM. If you are doing it to often you get heap fragmentation, essentially making swiss cheese of your heap. If possible you should use a statically declared array or at least allocate memory only once during the lifecycle of your program.

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


text:
ArduCAM OV2640 and microSD card module -- SPI problems
So what I'm trying to do is use the ArduCAM OV2640 (2MP Mini) to take a timelapse. Of course the first thing I have to do it to get it to take a picture and write it to an SD card. The thing is, the camera works fine by itself, however when I hook up the SD card something happens where the SPI no longer works (I have a general understanding of how SPI works -- not a highly technical understanding though).
So my main question is if it's possible for a device using SPI to 'use up' the entire SPI bus so that other peripheral devices can't interact with the microcontroller?
And if so, is there any software or way to visualize this? Like something that monitors the SPI bus?
And as for how to actually fix the problem, would it be practical to use a shield with a built in SD card module? Or use a logic gate to determine which device to allow access?
I really don't have the greatest understanding of this, so any help would be appreciated.
EDIT:
I'm using this camera module with this sd card module. As for my wireup, the camera follows as below:
The common pins between the SD card module and camera are VCC,GND,MISO (pin 12) , MOSI (pin 11), and SCK (pin 13). I have an individual CS pin for each.

What exactly are the used modules and your wireup? You could maybe have the same problem as described in https://arduino.stackexchange.com/questions/43707/multiple-spi-device/43709.

I'll take a look at the link you referenced, and I have updated my post with wireups/modules. Also, should I be using resistors?

In this case, I don't think that a device is "using SPI to 'use up' the entire SPI bus so that other peripheral devices can't interact with the microcontroller". I think that your problem probably lies with how your SD card is connecting via the SPI bus.
The problem is that a lot of Serial Peripheral Interface (SPI) devices, particularly the cheaper ones, don't properly put the MISO pin into high-impedance when SS is pulled high.
I had almost exactly this situation with one of my projects. I eventually resolved it by placing a tri-state buffer in the MISO line for each of the SPI devices.
In that case, I used a 74HC125 (4-channel tri-state buffer).
This is the page on Better SPI Bus Design in 3 steps that finally got me on the right track. I think the explanations are reasonably clear (at least compared with many other sites I found!).

This is very common with SD cards. I always use a separate SPI bus for SD cards (and of course an MCU with multiple SPI buses).

@Majenko I thought arduino only had 1 spi bus?

@LukeThistlethwaite Many Arduino branded boards have only one SPI bus. There are a myriad of other options though, some with many SPI busses (one I use regularly has 4 busses).

@Majenko My bad, I just thought that you were referencing an arduino board since, after all, this is arduino.stackexchange.com

@LukeThistlethwaite There are Arduino boards with multiple SPI busses.Generally the ARM based boards like the Arduino Due.

@LukeThistlethwaite Personally, though, I always use chipKIT boards (PIC32) since I am a PIC32 engineer.


text:
use arduino IDE for USB isp programmer
A few years ago I programmed AVR ATmega8 with AVR studio by USB isp programmer.
I was using C language. Now I would like to use arduino(C++) langauge and my external USB isp programmer. Is it possible?

What kind of programmer? What is the Model?

The Arduino IDE compiles and outputs standard Intel HEX format files that are compatible with (nearly?) all programmers. If you enable detailed logging in the preferences panel you can find out which directory the IDE is building your code in and if the IDE does not include specific support for your programmer you can then locate the .hex file and upload it using the tool you are familiar with. The projects are typically built in a build.* subdirectory under %TEMP% (or /tmp on unix).

If you want to use arduino IDE to program the atmega328 you don't need a USB ISP programmer. The only thing you have to do is load the arduino bootloader on the atmega328 in order to program it through the arduino IDE. In the ide you can program the board with c++. But if you want to program the atmega328 through you're USB ISP programmer (assuming it is capable of programming the Atmega 328) you have to use other IDE in which you can program in c++ and produce an hex file that can be burned on the chip through you're  programmer on the atmega328.

The programmers supported by the Arduino IDE are listed under Tools | Programmer. In order to upload your sketch using the programmer either Shift-click the upload button, select File | Upload Using Programmer, or press CtrlShiftU.


text:
Turning all LEDs on (FAST.LED)
In Fast.Led lib for arduino there is a code to turn off all leds
FastLED.clear ();

Is there also a shortcut to turn all LEDs ON, and with a specific color

What leds/driver are you using?

Arduino nano, FastLed lib and WS2812B leds

I think you could use showColor

You can use fill_solid.
For example
fill_solid( leds, NUM_LEDS, CRGB(50,0,200));

Or
fill_solid( leds, NUM_LEDS, CRGB::Red);

Works fine. While FastLED.showColor() will not behave properly if you add delay after it,


text:
Parallel Chaining of APA102 LED matrices
I have four APA102 LED matrices (those flexible ones) and I want to connect them together to make a display for showing images. Now my problem is this:
Consider the coordinate system with four quadrants. I put one matrix in each of the quadrant and my target is to have a one single display as mentioned above. I connect like this: The input of matrix 1 is connected to Arduino, the output of matrix 1 to input of matrix 2, output of matrix 2 to input of matrix 3 (or can be input of 4 also ) and then finally output of 3 (or output of 4th matrix) is connected to input of 4th matrix (or input of 3rd matrix accordingly).
The problem with this is that although this might seem a big display from a distance with 4 matrices working in sync but actually its 4 matrices daisy chained and split into 2 rows. This would split my image if I were to display.
Question: Is it possible to parallel chain these APA102 matrices and thereby form one continuous display which can be controlled by FASTLED library?? I might be somehow able to address an individual LED in this type of weird pattern, but while displaying images, I am lost. Can't figure out how to do that? Realised that I need to have parallel chaining.....which I have no idea of.
Any help, guidance would be great!
Thanks

It's a problem that can easily be fixed in software. Some libraries support this kind of paneling out of the box.

@Gerben Thanks bro! I managed to do a very simple yet effective solution: I split the bitmap data depending on the total number of columns of those flexible matrix (continuous serpentine):P ...

How about write up an answer and share it with us?


text:
Sending LCD commands to a slave micro
I need to split up code which I've already developed for one micro into two different Arduinos connected by serial. The "remote" micro is directly connected to a 20x4 character LCD and the main micro will be sending it a command set to print, move cursor, etc.
My plan was to make functions that used existing code such as
lcd.print("This or that");
to replace the lcd library on the main micro and send command bytes and data bytes up to the remote micro. Seems pretty straightforward.
Then I discovered that apparently lcd.print cannot be a function name. Fine, so I changed it to lcd_print(). So far, so good. But in the existing library, lcd.print accepts strings, bytes, just about anything any length. For example:
lcd_print("any string of any length");
lcd_print(a_2d_array [x] [y]);
lcd_print(this_byte);
lcd_print(this_integer);
Now it's getting over my head. I know I can painstakingly turn a single function into many different functions, but wouldn't it be nice to replicate the functionality of the Arduino LCD library with a single command:
lcd.print();
Then all I have to do is create the function and keep the existing code and send the bytes up to the slave micro. Wouldn't that be nice! I appreciate any thoughts. Thanks.

Just inherit Print class and implement virtual size_t write(uint8_t); and you can use all kinds of print/println that Print implements. See Print Class @arduino.cc.
It implements these methods for you:
size_t print(const __FlashStringHelper *);
size_t print(const String &);
size_t print(const char[]);
size_t print(char);
size_t print(unsigned char, int = DEC);
size_t print(int, int = DEC);
size_t print(unsigned int, int = DEC);
size_t print(long, int = DEC);
size_t print(unsigned long, int = DEC);
size_t print(double, int = 2);
size_t print(const Printable&);

size_t println(const __FlashStringHelper *);
size_t println(const String &s);
size_t println(const char[]);
size_t println(char);
size_t println(unsigned char, int = DEC);
size_t println(int, int = DEC);
size_t println(unsigned int, int = DEC);
size_t println(long, int = DEC);
size_t println(unsigned long, int = DEC);
size_t println(double, int = 2);
size_t println(const Printable&);
size_t println(void);

However you have to implement 2D array print if you really need this, I don't see why do you need it but whatever (you can print each line separately). It just saves you time with implementing everything else.
And for std::ostream like approach I like this (works with anything inherited from Print class):
template <class T> inline Print & operator<<(Print & p, const T & val) {
  p.print(val);
  return p;
}

// ...

void loop() {
  float variableA = 221.23;
  String variableB = "Some string";
  Serial << F("flash string to save some ram: ") << variableA << F(" / ") << variableB << "\n";
}

Then you can implement some commands interface.

Dear KIV: Thank you for your response! I'm afraid I don't know how to "inherit Print class". It's beyond my current programming experience. I often see the "uint8_t" in code I've looked at and puzzled over what it does. I'll try to do some research but would appreciate a jump start!

Dear KIV: Thank you.
Assuming I add this code, would it be in setup?
class lcdclass: public Print
{
public:
virtual size_t write(uint8_t);
};
Given the old lcd command sans library: Will the old command work?
lcd.print(some_crazy_set_of_data);
if I write a function:
void lcd.print()?
Don't know how to pass the many different formats of possible parameters to this function. Maybe cause it's inherited, but please advisee.

That answers it, KIV! Thanks. You're right. Now I have to decide if it's gonna be easier to retain all the lcd.xxx commands in the current code and write new functions, or go through the code line by line and revise it to send serials up to the remote micro. Despite the attraction of the print class it sounds more attractive to me to just revise the code because some of the commands are 2d, some are 1d, etc. and you're absolutely right, eventually it's going to be sent down serial as one byte followed by another!!!

At the remote micro end, it's going to reassemble those bytes into lcd.xxx commands anyway! As the remote is going to use the existing lcd library.

You can find an implementation of this in the Cosa VLCD library. It implements the Cosa LCD interface but uses I2C/TWI as an adapter. The library contains both the application interface and the TWI slave implementation. https://github.com/mikaelpatel/Cosa/blob/master/libraries/VLCD/VLCD.hh


text:
Good voltage and resistor value for string of LEDs
I building multiple parallel strings of 4 LEDs in series.
Since the four LEDs in series have a combined forward voltage of 12.56V at 20mA, and it's powered by 2 AA batteries, I have added a voltage booster.
Now my question is, since I can both choose the output voltage of the boost converter, and the resistor added to each string of 4 LEDs, what would be a reasonable value for both?
I could set the voltage to exactly 12.56V and not use a resistor, but that would probably lead to uneven current spread between the sets of 4 LEDs, as their forward voltage can differ slightly due to manufacturing differences.
On the other hand, I don't want to set the voltage too high, and wast a lot of power.
So what would be an acceptable voltage drop over a current limiting resistor?

I think the The answer depends the on what you mean exactly by a "lot of power" (to work out the LED resistor value) and how bright (very bright in daylight, ok to be visible in dark only?) you want the LED to be.

@qwerty10: Brightness is dependent on current, which has been fixed at 20mA. The only power consideration (for this question) is power loss in the ballast resistor.

@Ignacio Vazquez-Abrams I didnt notice it said 20ma. But I do now. I guess it could be 19.5ma rounded up to 20ma.

Since the relation between voltage and power is quadratic, the obvious answer is "as little as possible".
Allowing for 3% variance in VF gives us just under 13V, so that is a reasonable starting point. Solving for R gives 22ohms, a E24 value. This will result in a 8.8mW loss, which even a 0201 resistor can handle.

Thank you for your explanation. I was already leaning towards 22 ohm as a somewhat wild guess. 0201 is still a bit too small for me, but I plan on ditching the 0805 for 0603 pretty soon. 0805 is quite big if your want to create small PCBs.

I could set the voltage to exactly 12.56V and not use a resistor, but that would probably lead to uneven current spread between the sets of 4 leds, as their forward voltage can differ slightly due to manufacturing differences.

While that is a completely true statement, by having multiple LEDs in a chain you effectively average out the forward voltages. The more LEDs you have in your chain the more "average" each chain gets.
It's still not good to rely on the forward voltage to set the current, since it also varies with temperature (as the LEDs heat up the current will rise, leading to more heat and therefore more current, until you get thermal runaway).
As Ignacio says, the less the better when it comes to the resistance, and has recommended 22Ω and 13V, which I would recommend too.
Another option is to use a low-side constant current sink on each chain. This will guarantee that the current is exactly what you want (within reason) with no thermal drift in either the LEDs or the resistor.
You can find some example circuits here: http://www.radio-electronics.com/info/circuits/transistor/active-constant-current-source.php
Or you can use constant-current sink LED driver chips, which also often gives you the advantage of being able to control each chain of LEDs individually - either on/off, or PWM.

Using a boost converter and a resistor to limit current seems rather inefficient. The resistor is used to approximate a constant current source, but it would be far more efficient to use a switch mode supply to generate a constant current.
There are dedicated LED controllers which do this, although usually used with higher power LED e.g. CREE LED.
It may be possible to modify the feedback circuit in the boost converter to regulate the current, monitored with a small series resistor.

The issue is that there are multiple parallel strings, which would mean that a) ballast resistors would be required regardless, and b) failure of a single string will cascade to the other strings.


text:
How to compile a sketch using arduino-builder?
How do you compile a sketch with a custom library path using arduino-builder? The docs are a little light.
I have my source code organized like this:
lib
    SomeLib
        somelib.h
        somelib.cpp
src
    otherfile.h
    main.ino

I've installed Arduino 1.8.1 into /usr/share/arduino.
I'm trying to compile this for an Arduino Uno from my project root directory with:
arduino-builder -compile -hardware /usr/share/arduino/hardware -tools /usr/share/arduino/hardware/tools -libraries lib -fqbn arduino:avr:uno -build-path .build src/main.ino

But it returns this error:
fork/exec {runtime.tools.ctags.path}/ctags: no such file or directory

What's causing this error?

You need to specify the path to the tools-builder folder, which is where ctags is. Try this:
arduino-builder \
  -compile \
  -hardware /usr/share/arduino/hardware \
  -tools /usr/share/arduino/hardware/tools \
  -tools /usr/share/arduino/tools-builder \
  -libraries lib \
  -fqbn arduino:avr:uno \
  -build-path .build \
  src/main.ino

Is there a way to upload the compiled program to the Arduino using arduino-builder or some other cli tool?

This seems to do the trick for me:  avrdude -V -F -C /etc/avrdude.conf -p atmega328p -P /dev/ttyACM0 -c arduino -b 115200 -U flash:w:sketch.hex


text:
Custom boards list
Is there a simple way to create or modify my boards list? I find having a full library listing confusing. I have about 6 boards I program regularly, but using the listings from the board manager gives me about 60 things to look through, which gets tedious fast.
Here is a list of MCUs I frequently use:

Teensy2.0
Adafruit Trinket 16Mhz
Adafruit Trinket Pro 16MHz
Adafruit Circuit Playground
Adafruit feather Huzzah
Arduino Uno R3

How can I make a boards list that only includes the boards I own?

Throwing out the unneeded boards from the boards.txt files will do what you want.

where is that? in the arduino directory?  Im on linux, I will look for it.

Avr boards are in arduino install/hardware. Boardmanager installs are at  ~/.arduino15/packages on linux.


text:
How can I tell what programmer to use?
I have a bunch of different dev boards for different projects. What I have been getting very confused about is what board needs what programmer from the Tools > Programmer menu.
I wish the selection had the option to be partially automated for the board selection. But it's evidently not. Part of my problem is that if you choose the wrong programmer, some boards seem to work. Others read but won't write, or will write to some spaces, but not others. Or, you might get other cryptic errors that sound a lot like failed hardware. Have a look at this message for an example:

OK, so let's say I have some random dev board. How can I know what programmer I should use? Assume the manufacturer's documentation mentions nothing about it...

I'm voting to close this question as off-topic because the question arrises from a fundamental misunderstanding - as explained below, the programmer selection is not applicable in the ordinary case, and where needed would depend on the physical programmer purchased, not the target board.

I'm voting to leave open because this is a common cause of confusion for beginners and is very much on topic for Arduino Stack Exchange.

Generally the Tools > Programmer selection is only used for Tools > Burn Bootloader and Sketch > Upload Using Programmer and is not used for standard uploads. So for standard uploads you can set it to anything you like because it will have no effect.
The most notable exception is the Adafruit Trinket, which does require you to select Tools > Programmer > USBTinyISP even though you are uploading through the USB socket on the Trinket board without a separate ISP programmer.
You will also find some 3rd party hardware packages that are not written for boards with an Arduino style serial bootloader and so treat a standard upload as an "Upload Using Programmer" for the sake of convenience. Examples are MicroCore and the "Barebones ATmega Chips (no bootloader)" hardware package. In this case the correct Programmer menu selection is dependent on which model of ISP programmer you are using.
So regarding the question "How can I tell what programmer to use?": If you're doing a standard upload, start by assuming it doesn't matter. If that doesn't work, read the documentation!
If you're doing a Tools > Burn Bootloader or Sketch > Upload Using Programmer (or holding shift while pressing the "Upload" button) then you should select the model of the ISP programmer you're using.

The clock and the timing signals and the voltage levels do not always match. And perhaps something is connected to the pins already which makes it harder for the programmer.
I use mostly the cheap USBasp version 2 (the text "version 2" is often written on the PCB). They are based on the USBasp from Thomas Fischl.
Sometimes there is a timing conflict. Sometimes that can be corrected with options for avrdude or with the avrdude.conf file, sometimes I have to grab an older or newer USBasp programmer.
What do you mean by choosing the wrong programmer? If there is a programmer connected to the computer, then select that type of programmer. Do you have a programmer?

The programmer is on the dev board For example: An Arduino Uno R3 uses the "AVRISP MKII" from the menu. The Adafruit trinket uses "USBTiny". And yes, I think it is confusing that I might have to select a programmer for a development board that doesn't share the same name. Maybe I just need to write all the variations down, and look it up when I start having trouble.

What dev board ? The Arduino Uno uses the usb connector and can upload a sketch when it has a bootloader. How does the programmer come into that ?

If you pick the wrong one, it does work.

If you don't have a programmer, the selection in the menu for the programmer does not matter. You can upload a sketch via het usb cable to the Arduino Uno. You only need to select the Arduino board and the serial port.

Thats not concurrent with what I am experiencing.

The selection of the programmer is only used with 'upload with programmer' or when burning the bootloader. If you experience something else, then something is very wrong. I have never heard that it influenced the normal upload. If you make a fresh install of the newest Arduino IDE on an other computer without extra cores (for example by Adafruit), then it should work in a normal way.


text:
Arduino Time Library and RTC Libraries
I am using RTClib.h and TimeLib.h with an Uno.
Have been struggling for days in understanding the various RTC libraries available and how to use them with the Arduino Time Library.
Question 1.
If I do not want to create a new now() object each time through the loop, how do I sync the Time Library to the RTC every x seconds?  Any time I try to use the RTClib function now.hour now.minute etc it requires me to use DateTime now = RTC.now() creating the now() object.
Is there an equivalent function in RTCLib as setSyncProvider(RTC.get) in DS1307RTC library?
Is there an equivalent to setSyncInterval(5000)
Question 2.
Which RTCLib should I call out? There are several used in examples:
<RTClib.h>
"RTClib"   using quotes
<RTCLib.h> with capital L
and sometimes also calling out one of these:
RTC_DS1307 RTC
or
RTC_DS1307 rtc
or
RTC_DS3231 rtc
Question 3
a. Are tmElements_t tm part of the DS1307RTC library?
b. Are these tm.Hour tm.Minute from the RTC?
c. Is there an equivalent in the RTClib.h ?
And finally I have posted some code below just to show my usage:
#include "RTClib.h"
#include <Wire.h>
#include <TimeLib.h>

RTC_DS1307 RTC;

void setup() {

Serial.begin(9600);
Wire.begin();  //sets up the I2C
RTC.begin();   //initializes the I2C to the RTC

if (! RTC.begin()) {
    Serial.println("Couldn't find RTC");
}

//  Set the RTC Time to 5:10:30 Nov 3 2020
      RTC.adjust(DateTime(2020,11,3,5,10,30));

//Set Arduino Time Library different than RTC time to see which is which
setTime(9, 27, 05, 14, 07, 2015);

}

 void loop() {

/*
// How do I sync Time Library to RTC after x seconds?
  setSyncProvider(RTC.get); // This is in the DS1307RTC.h Library
  setSyncInterval(5000);   //  Are there such functions in RTClib ?
*/

DateTime now = RTC.now();   // Pulls RTC time into now().  Does not sync with Time Library
                            // Do not want to do this every loop.

//Print RTC Time
Serial.println();
Serial.print("RTC now.hour        ");
Serial.println(now.hour());
Serial.print("RTC now.minute      ");
Serial.println(now.minute());
Serial.print("RTC now.second:     ");
Serial.println(now.second());
Serial.println();
Serial.println();

//Print Arduino TimeLib Time
Serial.print("Time Lib Hour:       ");
Serial.print(hour());
Serial.println();
Serial.print("Time Lib Min:        ");
Serial.print(minute());
Serial.println();
Serial.print("Time Lib Sec:        ");
Serial.print(second());
Serial.println();
Serial.println();

delay(1000);

 }

Updated 5 Nov 2020
I think I almost  understand.
Please let me know if this code is doing what I think it is doing, specifically:
In Setup:
Set the RTC to 5:10:30.
Set Time Library to 9:27:05 with setTime().
Set Time Library to RTC time with DateTime now (over writing   9:27:05)?
Set Time Library variables to RTC using tm.Hour = now.Hour, etc.
In Loop:
Every 5 seconds update hour(), minute() second() with RTC time.
Every loop update tm.hour with hour(), etc.
I know it is still not right since the serial prints show tm.Hour,tm.Minute alternating each loop as shown at the bottom.
#include "RTClib.h"
#include <Wire.h>
#include <TimeLib.h>

RTC_DS1307 RTC;

time_t time_provider()
{
    return RTC.now().unixtime();
}

tmElements_t tm;  //part of Time Library

void setup() {
    //setSyncProvider(time_provider);
    Serial.begin(9600);
    Wire.begin();  //sets up the I2C
    RTC.begin();   //initializes the I2C to the RTC

    if (! RTC.begin()) {
        Serial.println("Couldn't find RTC");
    }

    //  Set the RTC Time to 5:10:30 Nov 3 2020
    RTC.adjust(DateTime(2020,11,3,5,10,30));

    //Set Arduino Time Library different than RTC time 9:27:05
    setTime(9, 27, 05, 14, 07, 2015);

    //Setting Time Library to RTC time
    DateTime now = RTC.now();
    tm.Hour = now.hour();
    tm.Minute = now.minute();
    tm.Second = now.second();
}

void loop() {
    setSyncProvider(RTC.now);
    setSyncInterval(5000);

    //Time Library time updates to RTC every 5 seconds
    tm.Hour = hour();
    tm.Minute = minute();
    tm.Second = second();

    Serial.print("tm.Hour:    ");
    Serial.print(tm.Hour);
    Serial.println();
    Serial.print("tm.Minute:  ");
    Serial.print(tm.Minute);
    Serial.println();
    Serial.print("tm.Seconds: ");
    Serial.print(tm.Second);
    Serial.println();
    Serial.println();
    delay(1000);
}

Serial Prints:
tm.Hour:    5
tm.Minute:  34
tm.Seconds: 56

tm.Hour:    18
tm.Minute:  0
tm.Seconds: 0

tm.Hour:    5
tm.Minute:  34
tm.Seconds: 56

tm.Hour:    18
tm.Minute:  0
tm.Seconds: 0

tm.Hour:    5
tm.Minute:  34
tm.Seconds: 56

tm.Hour:    18
tm.Minute:  0
tm.Seconds: 0

Let me first give some background about these libraries.
The Time library uses millis() for timekeeping. Since this can be
subject to significant drift, it provides a means to periodically sync
to an external time provider. Hence the functions setSyncProvider()
and setSyncInterval().
RTClib is meant to interface an RTC. It does not provide timekeeping on
its own: you get the current time by querying an RTC through it's
now() method.
These two libraries can nicely complement each other, as RTClib can be
used as a time provider for the Time library:
// Provide the RTC time to the Time library.
time_t time_provider() {
    return RTC.now().unixtime();
}

void setup() {
    // ...
    setSyncProvider(time_provider);
}

If I do not want to create a new now() object [...]

It is actually called a DateTime object.

Is there an equivalent [to tmElements_t] in the RTClib

Yes, the DateTime class. Note that, unlike the
tmElements_t structure, the data fields of DateTime are not public,
and you have to use accessors to get them: year(), month(),
day()...
Alternative timekeeping method
Since you are using an Arduino Uno, there is a third method of
timekeeping you may want to consider. Instead of querying the RTC on
every loop iteration (RTClib) or interpolating the RTC readings with
millis() (Time library), you may route a 1 Hz output of the RTC
to an interrupt pin, and count the seconds in the ISR. The avr-libc
timing code is designed to provide timekeeping in this
fashion. It all boils down to:
// Initialize the system time from the RTC.
set_system_time(RTC.now().secondstime());

// Keep the time in sync using the 1 Hz output of the RTC.
pinMode(pin1Hz, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(pin1Hz), system_tick, FALLING);

For more details, see the example sketch interrupts1Hz.ino
provided with RTClib.

Edit 1: Answering a comment

which pin does [the Arduino interrupt pin] connect to on the RTC?

It depends on the RTC you are using. I will assume it's a DS1307, as
implied by the code in your question. Take a look at the datasheet
of the RTC. On page 6, there is a table titled “Pin description”. From
this table:

pin: 7
name: SQW/OUT
function: Square Wave/Output Driver. When enabled, the SQWE bit
set to 1, the SQW/OUT pin outputs one of four square-wave frequencies
(1Hz, 4kHz, 8kHz, 32kHz). The SQW/OUT pin is open drain and requires
an external pullup resistor. SQW/OUT operates with either
VCC or VBAT applied. The pullup voltage can be
up to 5.5V regardless of the voltage on VCC. If not used,
this pin can be left floating.

If you are using an RTC module, you will have to figure out where this
pin is exposed on the module's connector.
In any case, you will have to enable the 1 Hz square wave output with
RTC.writeSqwPinMode(DS1307_SquareWave1HZ);

Edit 2: Commenting on the update to the question:

// Set the RTC Time to 5:10:30 Nov 3 2020
RTC.adjust(DateTime(2020,11,3,5,10,30));

Correct.

// Set Arduino Time Library different than RTC time 9:27:05
setTime(9, 27, 05, 14, 07, 2015);

Correct. Date is 2015-07-14.

// Setting Time Library to RTC time
DateTime now = RTC.now();
tm.Hour = now.hour();
tm.Minute = now.minute();
tm.Second = now.second();

No. This is only partially initializing the tm variable. It has no
effect on the idea the Time library has of the current time. Note that
the date fields of tm have not been initialized at this point, and
could well be invalid (like month 23, day 125).

setSyncProvider(RTC.now);

This is incorrect, and should have generated a compiler warning.
setSyncProvider() expects a function that returns the current time as
Unix time (a simple integer, of type time_t). You are providing a
function that returns the current time in broken down form (year,
month...), with type DateTime. The Time library will not understand
that and may yield garbage like, say, 18:00:00.
The time returned by RTC.now() can be converted to Unix time with the
unixtime() method. That's why I gave you the time_provider()
function.
Also, you are not supposed to call setSyncProvider() and
setSyncInterval() on every loop iteration. Do it once and for all in
setup().

// Time Library time updates to RTC every 5 seconds
tm.Hour = hour();
tm.Minute = minute();
tm.Second = second();

Again, this is only updating the variable tm. It has no effect on what
the Time library believes is the current time.

Is there an equivalent function in RTCLib as setSyncProvider(RTC.get) in DS1307RTC library?
Is there an equivalent to setSyncInterval(5000)

Those are TimeLib functions. There's no "equivalent to" since you are using TimeLib.
The first one just expects a pointer to a function that returns a time_t. What is in that function is up to you.

Which RTCLib should I call out? There are several used in examples:

The capitalisation should match the name of the header file. Windows doesn't care, and OS X usually doesn't care, but can be configured to. Linux does care and needs it to match. If you want your code to be portable then you must keep the capitalisation the same as the file.

and sometimes also calling out one of these:

You need to create an object that matches your physical RTC.

a. Are tmElements_t tm part of the DS1307RTC library?

No. They are part of TimeLib.

b. Are these tm.Hour tm.Minute from the RTC?

They are whatever gets assigned to them by a function that is called. They are just variables. They can contain anything.

c. Is there an equivalent in the RTClib.h ?

No. But then you don't need there to be if you're using TimeLib.
So: you need to

Create a function that gets the time from the RTC through whatever library you want to use (RTCLib for example) and calculates the number of seconds since 00:00:00 01/01/1970, which it then returns as a time_t.
Pass that to TimeLib's setSyncProvider()
Set a sync frequency with setSyncInterval().

-I have read much about these libraries and still confused.  Thanks for your help.  Couple follow ups:  1. Does function now.hour() get time from RTC?  2.  Does hour() get time from Time Library? 3. Does setSyncProvider() set  hour() to the RTC ?

now is the time from the RTC at the moment you assign the now object. .hour() is just the hour contained inside that object. hour() is the time from the TimeLib library, yes. setSyncProvider() doesn't send anything to the RTC, it gets the time from the RTC on a regular basis and updates the TimeLib with the current time.

@Edgar Bonet - Using interrupt pin looks very nice and clean. If Pin 2 is used on Arduino for the interrupt, which pin does Pin 2 connect to  on the RTC?  I assume it is in addition to the SCL and SDA pins (?).

"setSyncProvider() doesn't send anything to the RTC, it gets the time from the RTC on a regular basis and updates the TimeLib with the current time."    Yes, so If hour() is the time from the TimeLib Library then setSyncProvider() makes hour() equal to RTC hour?

It's a little more complex than that. TimeLib uses millis() to keep track of the time. It regularly updates its internal idea of what the time is depending on setSyncInterval(). when you ask for hour(), if more time has passed since it last got the real time that you specified in setSyncInterval() it will go and get the time from the RTC. Otherwise it will just tell you what it thinks the time is according to its own internal calculations.

I updated my post with help provided. Almost have it understood.

Why does output alternate values for tm.hour, etc?  See bottom of updated question. thanks

Because you're constantly changing the sync provider and interval. You set those once and once only in setup, and never again.

Thanks that worked.    Looking at my updated code, to make sure I am not deceiving myself, are the outputs of  tm.Hour tm.Minute. tm.Second  Time Library values which are updated from the RTC  every 5 seconds ?  And am I not creating an Object every loop?

That looks right, yes. Though you don't need the tmElements_t struct at all since all you're dealing with is simple numbers. tmElements_t is just a convenient way of bundling them all together if you want to pass it to another function. Just Serial.print(hour());

thanks for all of your help.  I will post the final code as an answer for anyone else needing to learn this.


text:
Speaker & Piezo when beeping both cause CapacitiveSense to sense
I am using this speaker:  CUI part number CSS-I4B20-SMT-TR as an alarm on a clock using atmega328 chip and Arduino IDE with the tone function. Works great.
I am also using Arduino CapacitiveSensor.h library.  Also works great.
Problem:  Want to touch the clock to put it in snooze when the alarm starts.  But when the speaker beeps, the speaker affects the Touch Sensor so it puts itself in snooze after one beep!
EMI is not the issue.  Tested with a second speaker beeping, running from a different Arduino.  Brought speaker close to the Touch Sense circuit and it DID NOT trigger. Can something be added/changed to prevent the beep pulses from affecting the rest of the circuit?

Change Speaker to Piezo Buzzer which does not have a coil.  I thought that was the answer until I read about the Piezo being a risk to the atmega328 from sending  voltage into the circuit and/or possibly drawing too much current.  I would think this could be solved using a resistor, transistor and diode.
This was tried. Piezo in circuit also was sensed when beeping.

Any thoughts would be greatly appreciated, or Options I have not thought of. Thanks.

Update:  Changed to Murata piezo sounder with circuit shown below.  Still triggers Touch Sensor when beeping.
Question:  Is there a circuit change that could reduce the effect of the speaker on the rest of the circuit?

a connect a piezo directly (200 Ohm). did you try to replace the speaker with piezo in that circuit? and I why do you use an A pin for tone()?

Yes, did test a piezo in the circuit and it does work.  I then was concerned that the piezo could somehow damage the chip, but am not sure, not familiar with risks of using a piezo.  As far as using the Analog pin, I already used the PWM pins, and the tone function does work on the analog pin.  Are there advantages to using the tone function on a PWM pin?  If so, I can change things around to make a PWM pin available. thanks

See update above.  Piezo also causes EMI problem

Turns out it is NOT and EMI problem.  Speaker is affecting the circuit which the TouchSense circuit detects.  See updated problem statement.

are they still on pins next to each other?

One speaker is on a breadboard run by an Arduino. The speaker I am concerned with is on a PCB with the touch sense circuit run by an ATMEGA328PB chip.  I held the speaker on the breadboard while beeping right next to the PCB touch sense circuit and it did not sense the beeping speaker.

A reasonable amount of EMI happens to be on the cable and not through the air, so bringing the devices close to each other is not sufficient to test for EMI.

Yes true, and in the PCB traces.  I was surprised the Piezo speaker did not work. I hoped  eliminating the speaker coil would fix it. The CapacitiveSensor circuit is very sensitive. Is there any way to suppress the EMI from the speaker?

Well I solved it with software!  I have the CapacitiveSensor only active between beeps. Works great!


text:
Scan Bluetooth devices using HC-05
Basically, I want to connect the HC-05 to a specific mobile Bluetooth(whose address is known) and when the connection is established I want to turn on a LED on the breadboard.
I am totally clueless how to write the code. Can you please help me with it as it is a part of my project.
I know the various AT commands and have scanned the Bluetooth address with AT+INQ command.

You know how to configure the HC-05 with AT commands (as you wrote). What is the problem with just letting the Arduino send these commands over the Serial? Be more specific in what the actual problem is.

I want to connect the HC-05 to a specific mobile Bluetooth and when the connection is established I want to turn on a LED on the breadboard.
So I want help with its coding.

If you don't have a clue how to start: Start with an empty sketch with setup()? and loop() function. In the setup() function initialize the connection. Send the AT commands over Serial. Do Serial.begin() with the correct baudrate (the same as when you scanned with AT+INQ command). Send all necessary AT commands like Serial.print() or Serial.write(). Check with Serial.read() for the modules answer. If you get an understandable answer, you have a functioning serial connection to the module. Try it and come back, when you have a specific problem, that you cannot solve.

If you are using an Arduino board with HC-05 for AT commands over serial, you can follow the below flow :

Setup HC-05
Check for available nearby devices AT+IRQ
Check the response to check is the desired device is enlisted in the nearby devices
If device is enlisted, use AT+BIND=<Bluetooth address> to connect to the other device
Check the response of the AT+STATE? command until you receive “CONNECTED” (you can go for a while loop here)
Once the connection is successfully established here, you can send a confirmation now as per your requirement.

The above scenario is applicable only when you are sure with the Bluetooth address of the device you want to connect to. If the scenario is something different, comment and let us know with the actual requirement.

I want to connect the HC-05 to a specific mobile Bluetooth(whose address is known) and when the connection is established I want to turn on a LED on the breadboard.
So I want help with its coding.

Then in that case the above procedure might help you to the fullest.

Thanks a lot. It helped me a lot and even I m almost done with the coding part.

Your welcome Shivam Thakur. I just want to remind you that if you find any answer that helped you with your problem, just mark it as Accepted so that the one who helped could earn reputation score & also, it could help others.


text:
How to check for valid Serial data, then break?
I'm having trouble completing this code for my university final project. I feel like I'm almost there, but I can't seem to find the final buttons to press. I'm using the Arduino Pro Micro.
I have one static pressure transducer connected to the hardware serial pins, RX1 and TX0. I have one differential pressure transducer connected to digital pins 10 (Rx) and 16 (TX), on which I have implemented SoftwareSerial. I'm reading the output data from each of these transducers. Which means technically I don't need to connect the TX pins, because I'm not writing anything to them. They are already programmed to give a continuous serial data stream.
With lots of great help from StackExchange and the Arduino Forums, I'm able to write code to check for a start-marker and end-marker from the two serial ports. I'm storing each character in an array for each of the transducers.
Here is the code I'm using for the static pressure transducer:
const byte numChars = 16;
char paroChars[numChars];     //array to store received data
boolean newParoData = false;

void setup(){
  Serial.begin(9600);     //with computer
  Serial1.begin(9600);     //with Paro transducer
}

void loop(){
  readParo();      //read from Paro and store values in paroChars
  if(newParoData == true){
    Serial.println(paroChars);      //print Paro data with a new line for each value
    newParoData = false;
  }
}

void readParo(){      //reads each character from Paro and stores it in array
  static boolean receiveInProgress = false;
  static byte index = 0;
  char startMarker = '*';
  char endMarker = '\n';
  char pd;
  while(Serial1.available() && newParoData == false){
    pd = Serial1.read();
    if(receiveInProgress == true){
      if(pd != endMarker){
        paroChars[index] = pd;
        index++;
        if(index >= numChars){
          index = numChars - 1;
        }
      }else{
        paroChars[index] = '\0';      //terminate string
        receiveInProgress = false;
        index = 0;
        newParoData = true;
      }
    }else if(pd == startMarker){
      receiveInProgress = true;
    }
  }
}

I do get the correct output on the Serial Monitor from the static pressure transducer when I upload this program to the Arduino:
000114.2927
000114.2928
000114.2927
000114.2929

Similar code goes for the differential pressure transducer:
#include <SoftwareSerial.h>
#define honeywell_RX 10
#define honeywell_TX 16

SoftwareSerial honeySerial(honeywell_RX, honeywell_TX);

const byte numChars = 16;
char honeyChars[numChars];     //array to store received data
boolean newHoneyData = false;

void setup(){
  Serial.begin(9600);     //with computer
  honeySerial.begin(9600);      //with Honeywell transducer
}

void loop(){
  readHoney();      //read from Honeywell and store values in honeyChars
  if(newHoneyData == true){
    Serial.println(honeyChars);    //print Honeywell data with a new line for each value
    newHoneyData = false;
  }
}

void readHoney(){     //read each character from Honeywell and store it in array
  static boolean honeyReceiveInProgress = false;
  static byte index = 0;
  char honeyStartMarker = '?';
  char honeyEndMarker = '?';
  char hd;
  while(honeySerial.available() && newHoneyData == false){
    hd = honeySerial.read();
    if(honeyReceiveInProgress == true){
      if(hd != honeyEndMarker){
        honeyChars[index] = hd;
        index++;
        if(index >= numChars){
          index = numChars - 1;
        }
      }else{
        honeyChars[index] = '\0';      //terminate string
        honeyReceiveInProgress = false;
        index = 0;
        newHoneyData = true;
      }
    }else if(hd == honeyStartMarker){
      honeyReceiveInProgress = true;
    }
  }
}

And this is the output I get on the Serial Monitor for the differential pressure transducer, which is also correct:
01CP=0.0000
01CP=0.0001
01CP=-0.0001
01CP=0.0000

My problem is combining these two programs. Basically, I want to be able to read from the Hardware Serial port first, make sure that the data is valid, store it, then exit the function. After that, read from the SoftwareSerial port, make sure the data is valid, store it, and exit the function. After this I would print both arrays to the Serial Monitor. I don't know how to read from the Serial ports only until the array is filled up with valid characters, then exit. If I combine these two programs, the output is distorted, meaning the values are either bunched together, or there are random characters showing.
I found that these two pressure transducers operate at different frequencies. The static transducer gives serial output at 10Hz, while the differential transducer is about 2Hz. I'm not sure if that factors into the problem.
Basically, I want to get one reading like 000114.2927, then another like 01CP=0.0001, then print both of these to the Serial Monitor. I can't figure out how and where to break out of reading from the serial ports.
Thanks!

read from the Hardware Serial,validate, store, exit function .... read from the Software Serial, validate, store, exit function .... this may cause data loss ...... in loop() check for new data from both devices ... store data and raise flag if data is available ... process data if available

What exactly is the problem? You didn't include the combined code, so we cannot help you with this. Go the way, that is described in the answers of your other questions. Read every value from the serials, but only send every 5th value for one of it. The other can be send everytime a complete value was received


text:
Read one value from continuous data stream at a lower frequency
I am working on a university final project and have run into a problem with programming Arduino, after a 3 year hiatus. I have a pressure transducer that is sending pressure data at 10Hz. I have successfully programmed my Arduino Pro Micro to read the data as it is coming in. I'm using the SoftwareSerial library to set digital pins 8 and 9 to RX and TX, respectively. As the pressure transducer is continuously streaming data values, I read each character, store them in an array, and print them to the Serial Monitor. I'm using a start and end-marker to recognize each incoming character and put them into the array. The raw data output from the transducer is in the form:
*000114.2927
*000114.2926
*000114.2927

And this is the code I am using.
#include <SoftwareSerial.h>
#define paroRX 8
#define paroTX 9

SoftwareSerial paroSerial(paroRX, paroTX);

const byte numChars = 16;
char paroChars[numChars];     //array to store received data
char paroToSend[numChars];      //array to transmit
boolean newParoData = false;

void setup(){
  Serial.begin(9600);     //with transmitter radio
  paroSerial.begin(9600);
}

void loop(){
  paroSerial.listen();
  readParo();      //read from Paro and store values in paroChars
  if(newParoData == true){
    for(int i=0; i<16; i++){
      paroToSend[i] = paroChars[i];
    }
    Serial.print(paroToSend); Serial.print('\n');     //transmit Paro data with a new line for each value
    newParoData = false;
  }
}

void readParo(){
  static boolean receiveInProgress = false;
  static byte index = 0;
  char startMarker = '*';
  char endMarker = '\n';
  char pd;
  while(paroSerial.available() && newParoData == false){
    pd = paroSerial.read();
    if(receiveInProgress == true){
      if(pd != endMarker){
        paroChars[index] = pd;
        index++;
        if(index >= numChars){
          index = numChars - 1;
        }
      }else{
        paroChars[index] = '\0';      //terminate string
        receiveInProgress = false;
        index = 0;
        newParoData = true;
      }
    }else if(pd == startMarker){
      receiveInProgress = true;
    }
  }
}

And this is the output that I get, which is correct. I don't really want that * in front anyways.
000114.2927
000114.2928
000114.2927
000114.2929

But all of this happens at 10Hz, which means I get a constant stream of readings on the Serial Monitor. I want to slow this down to 1Hz, or just one reading per second. The obvious solution that occurred to me was to put a delay in the loop. So I tried to implement this with delay(1000) and using the millis() function as well, but I get strange readings like:
000114.2927
***000114
**2928
***.000114
000114.2928

How can I read at 1Hz from the 10Hz data stream? I want to just store one data value from the stream per second in the form of 000114.2927, then ignore the rest while the Arduino does something else.
Thanks!

How can I read at 1Hz from the 10Hz data stream? ... discard 9 readings

You're thinking backwards. You don't want to read slower (which is what delay does), you want to only send every 10th entry.
That is, count the lines as they come in. When you hit 10 you print one and reset your count.
In other words:
static int count = 0;

if(newParoData == true){

  count ++;
  if (count == 10) {
      count = 0;

      // (Why copy the line just to send the copy...?)
      for(int i=0; i<16; i++){
        paroToSend[i] = paroChars[i];
      }
      Serial.print(paroToSend); Serial.print('\n');     //transmit Paro data with a new line for each value
  }
  newParoData = false;
}

I would use Stream class timed functions. Serial is implementation of Stream. The property timeout (setTimeout) sets how long will the blocking functions wait for the next byte/character. Default timeuot is 1000 ms.
Timed functions of Stream are find, parseInt, parseFloat, readBytes, readBytesUntil, readString and readStringUntil. (Non blocking read functions are available, read and peek.)

Majenko’s answer is spot on: you just have to count the sentences you
read and repeat one every ten sentences. And you don't need two copies
of the sentence you are reading: one is enough. But I would add that you
don't even need a single copy: you can just echo back the characters you
read, without ever storing them, until you hit a '*':
void loop()
{
    static uint8_t sentence_count;
    if (paroSerial.available()) {
        char c = paroSerial.read();
        if (c == '*') {
            // Increment the sentence count modulo 10.
            if (++sentence_count == 10)
                sentence_count = 0;
        } else if (sentence_count == 0) {
            // This is one sentence we have to repeat.
            Serial.write(c);
        }
    }
}

As a side note, if your program doesn't read input from the computer,
and if it doesn't send anything to the transducer, then you may consider
getting rid of SoftwareSerial and using only the hardware serial port:

the receiver part of the port for reading the data from the transducer
the emitter part to send the data to the computer.

Yes, it is perfectly fine to use the receiver and the transmitter for
different links. The only caveat is that you will have to use the same
port configuration on both sides: if the transducer talks at
9600 bps, then the whole port will have to run at 9600 bps.

Thanks everyone for the helpful responses. I'm asking my question because I actually have two pressure transducers hooked up to my Arduino via the SoftwareSerial implementation, and I need to send the pressure data from one after the other. So far, I've only had luck sending data from one at a time. I read that the Arduino Pro Micro cannot receive from more than one Serial port simultaneously when SoftwareSerial is used, so I was thinking if I could strictly read one data value from the first transducer, then read another one from the second transducer. Maybe I should start a new topic?

@bf109k4: Or you can use the hardware serial receiver and only one software serial.


text:
How to connect a Pressure Sensor-MPX10DP to an Arduino?
I'm very new to Arduino, I'm trying to connect an air pressure Sensor without success.
I followed this tutorial:
Arduino Air Pressure Measurement
The values I'm getting are very weird and the variations when I blow in the sensor are not more than about +/- 0.2.
So, the tutorial does use the same model, is that why? I need something else?
Any help will be very appreciated.

The MPX10DP does not have an amplifier inside. The output is the output of the internal wheatstone bridge. It is not even compensated for temperature.
This is the manufacturers page about the MPX10 series: nxp.com MPX10 series.
You need an instrumentation amplifier and perhaps a temperature compensation. The INA125 is an instrumentation amplifier. It was used in the past with the Arduino a lot. Nowadays, most sensors are digital, and the bare sensors with wheatstone bridge output are not used that often anymore.
When you connect both sensor outputs to two Arduino inputs (without amplifier), then the difference is 35mV for 10kPa. The resolution is in theory 5V / 1024. The overall accuracy for two analog inputs perhaps 9 bits, then you can measure the 10kPa in 3.5 steps (about 2 or 3 kPa resolution).
If you seriously want to use this specific sensor, and don't want to use extra hardware, then you might have a look at my question about the differential mode and gain that is possible with the Arduino Mega 2560 and Leonardo.
Or you could buy a pressure sensor with 0...5V output, that can be connected to the Arduino analog input. The tutorial you mentioned uses the MPX5010. That sensor has a amplifier inside and is temperature compensated. They are reliable and ratiometric with the 5V, therefor super easy to use. With a lot of averaging in the code, you can get a high (relative) accuracy.


text:
I2C collision detection
I have put together a system that uses multiple Arduinos and a couple of 20x4 LCD displays to monitor my PV sun tracker and a weather station.  I am using I2C to link them all together.  One of the LCDs has been modified to have a different address (0x3b) so as to not conflict with the first one (0x3f).  So far, so good.   The sun tracker shows its display on the yellow one and the weather station shows its data on the blue one.
In order to connect this together I am using the Mayhew I2C&Power devices, so one power source energizes the entire system.  I send 12 Volts on the wire, then at each node I use a 12v to 5v converter to provide power for the I2C&Power board and the Nanos.  (The anemometer on the WX needs 12V to operate so that's a plus)
Each Arduino has a unique I2C address - there is no master in the system.
I have learned to set the screen updates to be quick (take readings and do any calculations before writing to the LCD in one swell foop), and to stagger the display update timings (the WX info updates every 65050 ms (full display update) and the PV info updates every 67050 ms (4 characters) and 605550 ms (full display refresh).  I chose these (arbitrarily random) values to make it less likely that they would try to update at the same time, because when both systems try to update their respective displays at the same time it causes some very interesting results - basically wiping out one or both displays.  It works most of the time but eventually one or the other screen will get wiped out.
Question:  Is there any way to implement collision detection on the I2C bus to prevent transmitting while other devices are communicating?  Something like CSMA/CD (Carrier Sense Multiple Access with Collision Detection) on Ethernet..

What are the physical distances involved with your interconnections?

Less than 50 feet for the longest one.  If the I2C&Power over Ethernet cable doesn't do the trick (They claim 300 feet - but the time delays could become an issue) then I will need to put a Pi out there to put up a value somewhere, like the way people Tweet parameters.

I did find this little gadget that provides interrupts so I could have dual I2C buses feeding into a single device without having them actually collide:  http://www.ebay.com/itm/401208338113

Collision detection on I2C is fully supported (See I2C Multi-Master). It works basically by attempting to transmit something and reading what is being transmitted at the same time. If what is read matches what is transmitted then the transmission worked. If it didn't match then there was a collision.
It is usually performed on a per-bit basis:

If a 0 then pull the data line LOW. If a 1 then let the resistor pull the data line HIGH.
Read the data line. If you want a 1 and get a 0 then some other device is pulling the data line low for a 0.
If the value was wrong then stop your transmission and back off by a random amount. Retry again. (note: both ends may retry, so you need good random numbers).

There is no support in the Wire library for collision detection, though, so you will have to implement it yourself. Section 22.4 of the datasheet gives you more information about how to implement it.

Thank you, @Majenko.  I'll follow up on this one for sure.  I am not using any pull-ups at all right now, (though I suspect some of my devices on the line, like the RTC, might have their own).  But this is very intriguing.

The Wire library turns on the internal pullups on the I2C pins for you. It really shouldn't, since they are too big (by about 10x). You should use external ones at about 3.3kΩ.

Upon more experimentation I have discovered that my I2C bus (extended by Mayhew I2C&Power modules) only works so well because of the presence of the RTC module.  It can be anywhere on the bus - at the display or out at the sensors with the Nano.  If I remove it, the bus quits working.  So I presume it is doing the job for me.

I will be multi-master, per se.  But will designate a primary system that can have one byte to say which system is currently allowed to transmit.  After determining that the bus is not busy I will read that one byte  and if zero then will put my node number in and then read it back to confirm.  Then open the connection then set it back to zero when I am done.  If nonzero I will know either a part failed in the middle of a write operation or the bus-busy failed.  So will wait and try again.  If the problem persists then I will write a FF to signal the primary to do a poll for missing nodes.

That link to the datasheet is quite interesting.  It is clear that there needs to be a software solution.  I like the idea of opening and writing a byte then checking to see if it went through.  The other nodes will have to honor that and wait their turn.  I'll be sending short messages from all of them, so a too-long delay in releasing the channel will mean a node failed to clear the byte.