text:
Lighting up long led strip no longer works when my code grows
I have a 144 LED strip - Adafruit NeoPixel Digital RGB LED Strip 144 LED, link here:  https://www.adafruit.com/product/1507
If I create a simple project, eg turning pixels on off from the serial connection, then everything works fine.  But when I build a solution with an ethernet jack and acting as a http server and lots more code, as soon as I try to show the strip then random pixels light up in random colours.
I know the code is logically ok because if I run it to eg print a string to the serial port, "Turning pixels 0-71 green" the code works.
There are 762 lines of code and quite a few global variables defined.
When I compile I see:
Sketch uses 19180 bytes (59%) of program storage space. Maximum is 32256 bytes.
Global variables use 1462 bytes (71%) of dynamic memory, leaving 586 bytes for local variables. Maximum is 2048 bytes.

I did previously see build messages warning of instability due to size of global variables which I cut down and at least don't see the instability warning now.  Could it be that the code is using too many resources?  Any tips of reducing the code and / or use of global variables?
I am powering via the USB cable.  The unit is an Arduino Uno -the Arduino starter kit.  Could it be a power issue?
I have a 470ohm resistor on the data line into pin 6.  And a 1000uF capacitor between 5V+ and ground.  Anything else that could help?
I am using the Neopixel library to control the led strip: https://github.com/adafruit/Adafruit_NeoPixel

Chances are the Neopixel library can't allocate the memory it needs (432 bytes) for the RGB buffer for the LEDs. I don't know what library you're using though.

762 lines seems a lot for switching on a few lights.  Are there any strings that you can move with the PROGMEM macro, (or whatever it’s called)

Maybe some interrupts are interfering with the data transmission to the strip and are destroying the timing of the pulses. The strips can be very sensitive. Maybe you can try to turn of interrupts for the execution oft strip.show().

@chrisl How would I turn the interrupts off?

There are builtin functions for that: noInterrupts() and interrupts() (hope I have correct spelling). You should only do this to ensure that short timing sensitive code is executing without interruption. Functions like millis() and it`s siblings will not work correctly in this time, because they rely in Interrupts. Shifting the data out to the strip should be short enough to not disturb most other code.

@chrisl by using F() for static strings and reducing the code size I am now able to light the pixels ok.  I guess it must have been low static memory being the problem.  But all the comments are useful if I see problems again.


text:
LMT01 temperature sensor code does not run - need help
Apr 06, 2018, 09:52 pm
I hope this is appropriate.  I posted this question on the Arduino/Sensor site, got 42 views, but no reply.
I had no success getting help with any earlier post on this subject, so I am starting over with new code by Kevan Darrah. He is a good  programmer, so the code should work, but it doesn't.  I did a lot of reading and I understand how it should work, so let me spend few words explaining what I learned and maybe someone can take it from there. The LMT01 output is 0.6V to 1.6V pulses 10 usec wide, I verified this using a scope, the total number of theses pulses is proportional to the temperature. This repeats every 100 msec.  This signal is input to pin D2, but that is a digital pin: High=5V, Low= 0V, but Arduino IDE does something sneaky when you use the special function "attachInterrupt(pin,ISR,Falling)" - It redirects the signal internally to pin A0N of the positive side of an Analog Comparator, and attaches to AN1 internally a stable reference voltage of 1.1V. Now the 0.6V to 1.6V pulses are exactly centered on the comparator so it puts out a perfect 1's and 0's for easy counting.
So to repeat myself only Pin2 is attached with the LMT01 to the Arduino. Why doesn't this  &!#^-thing work, it compiled and uploaded correctly.  If I had  a debugger on this software, moving one line at a time I could fix it myself.  Code follows:
 //Sample Code for LMT01 Temperature Sensor
//LMT01ELPGQ1
//Kevin Darrah

//TempPins
#define pulsePin 2 //D2 on arduino D5 on esp8266 **This is the output from the LMT01

//globals for the LMT01 temp sensor
volatile unsigned int pulseCount = 0;//pulses out of the sensor
float temperatureC = 0, temperatureF = 0;//converted temperatures
float tempHIGH, tempLOW = 1000;

//functions
void pulseDetect();//interrupt function
float getTemperature();//call this to get temperature from the LMT01 - returns a float for the temperature in (C)

void setup() {
  Serial.begin(115200);
  pinMode(pulsePin, INPUT);//output from LMT01 sensor circuit

}

void loop() {
  temperatureC = getTemperature();// call getTemperature() to return temp in C
  if (temperatureC != 1000) {//returns 1000 if anything went wrong
    temperatureF = temperatureC * 9.000 / 5.000 + 32;
    if (temperatureF > tempHIGH)
      tempHIGH = temperatureF;
    if (temperatureF < tempLOW)
      tempLOW = temperatureF;
    Serial.print(temperatureC);
    Serial.print("C  ");
    Serial.print(temperatureF);
    Serial.print("F  HIGH=");
    Serial.print(tempHIGH);
    Serial.print("F  LOW=");
    Serial.print(tempLOW);
    Serial.print("F  DIFF=");
    Serial.print(tempHIGH - tempLOW);
    Serial.print("F  ");
    Serial.print(pulseCount);
    Serial.println("pulses  ");
    for (int i = 0; i < random(50, 200); i++)
      delay(1);
  }

}

float getTemperature() {// *********  GET TEMPERATURE FUNCTION *** returns the temperature C
  attachInterrupt(digitalPinToInterrupt(pulsePin), pulseDetect, FALLING);//using interrupt pin tp trigger on falling edge

  unsigned long conversionStartTime = millis();//keeps track of timing

  while (millis() - conversionStartTime < 10) { //looking for silence, in case we go to read temperature mid-measurement, ride it out till next one
   // yield();//for the ESP8266 to keep other tasks happy
    if (pulseCount > 0) {
      pulseCount = 0;
      conversionStartTime = millis();
    }
  }

  pulseCount = 0;//reset pulse count
  while (millis() - conversionStartTime < 150) {//wait for first pulse
   // yield();//for the ESP8266 to keep other tasks happy
    if (pulseCount > 0)
      break;
  }
  if (pulseCount == 0)
    return 1000;//FAIL - never got a pulse

  conversionStartTime = millis();//conversion done, so reset time
  unsigned int oldPulseCount = pulseCount;//just to help keep track of timings when pulse pin goes idle
  unsigned long pulseTime = millis();
  while (millis() - conversionStartTime < 60) { //measure pulses
   // yield();//for the ESP8266 to keep other tasks happy

    if (pulseCount != oldPulseCount) {//new pulse, so update timer
      oldPulseCount = pulseCount;
      pulseTime = millis();
    }
    else if (millis() - pulseTime > 5) {//no pulses for a while, must be done.
      break;
    }
  }
  //^^^ Stays stuck here counting pulese for 60ms

  if (pulseCount < 5) { //this is just noise, false trigger... I mean only 5 pulses, that can't be right
    return 1000;//FAIL
  }

  detachInterrupt(digitalPinToInterrupt(pulsePin));//done with the interrupt
  temperatureC = 256.000 * pulseCount / 4096.000 - 50;//conversion
  //see 7.3.2 Output Transfer Function in Datasheet

  return temperatureC;//throw the temp back
}

//change this function to look like this if using the ESP8266
//void ICACHE_RAM_ATTR pulseDetect()

void pulseDetect() {// *********  PULSE COUNTER INTERRUPT FUNCTION
  pulseCount++;
}

start by reducing your code to just count pulses and print out the value of pulseCount every second or so  .... you are also making an assumption that all the Arduino processors behave the same way internally ............. your question is too wordy ... you wrote a bunch of text that has nothing to do with the problem ... makes people lose interest before they get to the problem description .... everything before The LMT01 output is 0.6V to 1.6V pulses 10 usec wide is just fluff

does not work is a description that provides no information about the failure

This is added 15 months after the OP but there is very little information on this sensor.
You have not included your schematics which would be useful. For this setup TI gives you four options: transistor level shifting, isolation, multiple devices to one MCU pin, and common ground with high-side signal. Kevin Darrah uses the transistor level shifting method in his videos. Please refer to the TI datasheet for connections, pages 3 and 21 are relevant in setting that up. There is also this sample code supplied with a video that shows setup using the comparator.
NOTE: Ensure you do not have your sensor reverse biased or it will not work and may wreck it. Diodes are a good idea here.
Try commenting this out:
if (pulseCount < 5) { //this is just noise, false trigger... I mean only 5 pulses, that can't be right
return 1000;//FAIL

}
I found this sensor gives very low pulse readings if you have something setup incorrectly which will come out around -50C and this line may be causing it to read a fail. If that is the case you will need to rewrite the getTemperature() function, possibly using the comparator method supplied by TI which will require you to rewire, see their training code which includes a video. TI notes the first couple of readings may be incorrect. In my code I have my function perform several throwaway tests before spitting out a reading.
TL;DR If you use the TI comparator method, you can use the digital pins for power instead of the +5VDC like they do but use a diode (needed also for multiple sensors) to isolate the sensor to prevent reverse bias. If you do this you can shut the sensor off by switching it to INPUT but be aware, OUTPUT mode goes to ground by default which can cause reverse bias and fry your sensor. Use digitalWrite(pin,HIGH) prior to switching to OUTPUT to change default behaviour to +5V rather than GND (true, the diode should protect you here but adding this line is necessary anyway so do it in this order, safety first). I needed multiple sensors in my build so this is what I found, I used the Arduino-based comparator method quite successfully.
I don't have the necessary components to connect with transistor level shifting and actually test this at the moment but you could try this code if you want. I trimmed it down, eliminated most of the ESP8266 stuff you weren't using anyway and modified the getTemperature function to resemble what I have working right now.
//Sample Code for LMT01 Temperature Sensor
//LMT01ELPGQ1
//Kevin Darrah
// Ben Nesbitt, 2019

// For LMT01 if using transistor method of connection

//TempPins
#define pulsePin 2 //D2 on arduino  **This is the output from the LMT01

//globals for the LMT01 temp sensor
volatile unsigned int pulseCount = 0;//pulses out of the sensor
float tempC = 0;//converted temperatures
float tempHigh = 151;
float tempLow = 151;
unsigned long timeMillis = millis();

//functions
void pulseDetect();//interrupt function

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

  pinMode(pulsePin, INPUT);//output from LMT01 sensor circuit

}

void loop() {
  timeMillis = millis();
  tempC = getTemp(pulsePin);// return temp in C

  Serial.print(tempC); Serial.print("C  ");
  Serial.print(pulseCount); Serial.println("pulses  ");

  while (millis() - timeMillis < 5000) {} // Change this for how often you want to sample the temperature.

}

float getTemp(int pin)
{
  attachInterrupt(digitalPinToInterrupt(pin), pulseDetect, FALLING);//using interrupt pin tp trigger on falling edge
  float temperature = 0;
  unsigned long timeMillis = millis();//keeps track of timing
  int counterRef = 0; // Pulse count reference

  while (millis() - timeMillis < 10) { //looking for silence, in case we go to read temperature mid-measurement, ride it out till next one
    if (pulseCount > 0) {
      pulseCount = 0;
      timeMillis = millis();
    }
  }

  pulseCount = 0;//reset pulse count
  for (int i = 0; i < 3; i++)
  {
    while(pulseCount < 1) {}  //* TI recommends aborting the first one or two tests as inaccurate

    if(pulseCount != 0){
      //Wait for counting to be complete
      counterRef = 0;
      while(pulseCount != counterRef)
      {
        counterRef = pulseCount;
        timeMillis = millis();
        while (timeMillis == millis()){}
      }
      if (i < 2)
      {
        pulseCount = 0;
      }
      else
      {
         temperature = 0.0625 * pulseCount -50; // Pulses to temperature conversion
      }
    }
  }

  detachInterrupt(digitalPinToInterrupt(pin));//done with the interrupt

  //see 7.3.2 Output Transfer Function in Datasheet

  return temperature;
}

void pulseDetect() {// *********  PULSE COUNTER INTERRUPT FUNCTION
  pulseCount++;
}

source: Stack Exchange

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

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

sort: votes


text:
How do I get a nonzero output from my HX711 and load cell?
I am trying to set up a load cell using the HX711 amplifier. Whenever I upload my sketch, my serial monitor only will read zeros regardless of load applied to the sensor (no signal appears to be sending from my load cell).
Here is my wiring, with the Arduino Uno connected to a COM port. I am using an Arduino Uno, HX711, and Sparkfun's TAL220 Straight Bar 10kg load cell.

Here is the calibration sketch I am using (from the HX711 hookup guide):
#include <HX711.h>

#define DOUT 9
#define CLK 8

HX711 scale(DOUT, CLK);

float calibration_factor = 282650; //-7050 worked for my 440lb max scale setup

void setup() {
  Serial.begin(9600);
  Serial.println("HX711 calibration sketch");
  Serial.println("Remove all weight from scale");
  Serial.println("After readings begin, place known weight on scale");
  Serial.println("Press + or a to increase calibration factor");
  Serial.println("Press - or z to decrease calibration factor");

  scale.set_scale();
  scale.tare(); //Reset the scale to 0

  long zero_factor = scale.read_average(); //Get a baseline reading
  Serial.print("Zero factor: "); //This can be used to remove the need to tare the scale. Useful in permanent scale projects.
  Serial.println(zero_factor);
}

void loop() {

  scale.set_scale(calibration_factor); //Adjust to this calibration factor

  Serial.print("Reading: ");
  Serial.print(scale.get_units(), 1);
  Serial.print(" kgs"); //Change this to kg and re-adjust the calibration factor if you follow SI units like a sane person
  Serial.print(" calibration_factor: ");
  Serial.print(calibration_factor);
  Serial.println();

  if(Serial.available())
  {
    char temp = Serial.read();
    if(temp == '+' || temp == 'a')
      calibration_factor += 10;
    else if(temp == '-' || temp == 'z')
      calibration_factor -= 10;
  }
}

And here is a typical output from the serial monitor (I previously had this load cell functioning correctly, which is why my calibration factor is so different).

Observations:

Whenever I upload the sketch and open the serial monitor, the TX LED on my Arduino Uno will light up flashing, but the RX LED stays off.
Removing the scale.tare() step will output a constant nonzero value, but the load cell is unaffected by any loading:

I have tried adding an external power supply to the hookup assembly (I don't know if this is even necessary, but I know the load cell requires excitation to function, so I thought I'd give it a try). So far it has not changed the output in any way.
I have also tried adjusting the calibration factor, which only offsets the constant value outputted.
I have re-soldered the connecting wires to the load cell and replaced the remaining wires, as well as tried multiple Uno Boards and a new USB cord. I have also gone over my wiring and had my labmate check it too (though I will definitely not rule out it being some small wiring/hardware mistake on my part, as I am still very new to Arduino).

Thank you for any suggestions!

you do not appear to have any code that reads the load cell

This is a calibration sketch, I also have a separate sketch that reads the load cell once the calibration is complete - is this what you mean?

so if i use a calibration factor of 8388607 and t reads zero then my hx711 is broken? i tried it and it reads -0.5kg

The zero factor 8388607 showed up in a similar question on another forum and is associated with the range of the HX711 amplifier. This indicated that my amplifier was broken; I have since replaced it and am now receiving a signal from the load cell.

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


text:
Comparing custom variable type definitions
In a library I am using with an OBD adapter, they define a public function to get the state of the OBD connection using some strange (and, in my opinion, useless) custom defined variable type:
// states
typedef enum {
    OBD_DISCONNECTED = 0,
    OBD_CONNECTING = 1,
    OBD_CONNECTED = 2,
    OBD_FAILED = 3
} OBD_STATES;

...

// get connection state
virtual OBD_STATES getState() {
      return m_state;
}

How can I get the state into a variable such as boolean isConnected or int state so it can interact with the rest of my code? I have tried the following with no luck:
boolean isConnected = obd.getState() == OBD_CONNECTED;
if(isConnected) { ... }

int state = (int) obd.getState();
if(state == 2) { ...}

In response to your answer: why don't you think it is convenient? As you already noticed, you can use the enum values directly in your sketch.
Anyway, it is better to use a switch statement:
Serial.write("ODB State: ");
switch (odb.getState()) {
  case ODB_DISCONNECTED:
    Serial.write("Disconnected");
    break;

  case OBD_CONNECTING:
    Serial.write("Connecting");
    break;

  case OBD_CONNECTED:
    Serial.write("Connected");
    break;

  case OBD_FAILED:
    Serial.write("Failed");
    break;

  default:
    // Error case
    break;
}
Serial.write("\n");

This way, whenever the enum is changed (e.g. added items), you automatically fall into the error state, so you know you have to adapter the code.

I realize now it is actually pretty convenient. I was just used to java where I typically return some sort of integer and then provide static constants from the constructor class to compare it against.

Java has enum type too

I found the answer to my problem, but it is not very convenient.
Serial.write("ODB State: ");
OBD_STATES state = obd.getState();
if(state == OBD_DISCONNECTED) Serial.write("Disconnected");
if(state == OBD_CONNECTING) Serial.write("Connecting");
if(state == OBD_CONNECTED) Serial.write("Connected");
if(state == OBD_FAILED) Serial.write("Failed");
Serial.write("\n");


text:
How to control a DSP-G1 programmatically/electronically?
I want to generate music/sounds for a video game I am making with my son (using an Arduino Mega and a 240x320 LCD graphical display). I have a basic understanding of the MIDI protocol. I've been a computer programmer for over 30 years. I read the MIDI implementation in the DSP-G1 manual, but I don't understand how to go from this to sending the right signals from the dev board to the chip pins.
Everything I find is about connecting a physical MIDI device. Can anyone possibly provide or point me to information on how to control the DSP-G1 programmatically/electronically? I think I need some hardware or software to serialize MIDI protocol bytes into a sequence of voltage changes, but all my searching leads me to info about a physical device.

You've got the wrong side of the circuit, you want a midi out circuit.

@ChrisStratton No, he wants to know how to replace this circuit when not using the electrical MIDI protocol.

@CL. that would be off topic for an Arduino site and also wouldn't really make any sense, since an Arduino could readily be made to drive that with a transistor.  Much better to plug into the gear by the existing connector than to modify it.

The purpose of the MIDI output circuit is to convert the TTL signal into a 5 mA current.
The purpose of the MIDI input circuit is to convert the current back into a TTL signal.
If the Arduino and the DSP-G1 are part of the same circuit (and share the ground), you can omit these conversions, and connect the Arduino's TX directly to the LPC810's RX, without any other components needed. (The LPC810 requires a 3.3 V power supply, but its RX pin is 5 V tolerant.)
MIDI was designed to work with most microcontrollers, so it uses standard UART signals at 31250 baud. The only configuration you need is:
Serial.begin(31250);

Yes, you understand what I am trying to do. Sometimes a simple thing is harder to find than a more complex one.  So to confirm my understanding, I need to use the Serial methods, in particular Serial.begin(31250), followed by a series of Serial.write() calls to send a stream of bytes the same as I would write to a file, per the MIDI file format, e.g., https://www.csie.ntu.edu.tw/~r92092/ref/midi/

And it seems this will automatically go to TX0 (pin 1) on an UNO. Any need to do anything with pinMode()? What if I wanted to use TX1 on a MEGA?   Thanks for your help!

And I would have no need of the optocoupler, correct?

What is sent over a MIDI cable is not a MIDI file, but only the actual MIDI events/messages. There are no timestamps; bytes are sent in real time. See the actual MIDI specification.

Serial goes to the first UART; the others are Serial1, Serial2, etc.

I'm supposed to avoid comments like "thanks" so... ahem... I appreciate your reply. It makes so much sense in hindsight that the chip would act on my MIDI commands in real time -- I wouldn't expect it to do buffering, so what else could it do? And, yes, I went back to https://www.arduino.cc/reference/en/language/functions/communication/serial/ and it does tell about Serial1, etc.; I must have skimmed over that part before. Good stuff to know. Your guidance has given me enough confidence to part with $25 and try this thing out!


text:
Most compact way to power 5V Arduino boards?
So I have quite a few ideas for wearable devices using Arduino boards (mainly the Nano and the Micro clones). With that in mind, I want to determine what the best way to power an Arduino is, with compactness in mind (and cost too, of course). One single button cell battery does not supply enough power to the Arduino to power it properly. I can use these 2x button cell battery holders (6v) but they mainly ship only from China and, for some reason, are relatively expensive ($15 for 6 of them).
Does anyone know of a better and cheaper way of powering these Arduino boards, with wear-ability in mind?
Thanks! :)

The best solutions are probably not to run at 5v.  In the ATmega you have a processor which at appropriate clock can match the range of several battery chemistries, choosing one or two cells appropriately.

I made a torch locator which looks like this:

That was powered by a single button cell. The actual processor is an ATtiny85. As you can see it isn't much bigger or heavier than the coin cell.
You can run the Atmega328P (and the ATtiny) at 3V (as from that battery) provided you slow them down to 8 MHz. That is quite easy to achieve, and then you don't need an external crystal as the Atmega328P has an inbuilt oscillator which can drive it at that frequency (as does the ATtiny).
I have a page about power saving which might help you with your design.
A possible alternative is a single LiPo cell (nominally 3.7V) which, if you get a small one, should be quite light.


text:
Arduino - Raspberry Pi serial communication
I need to connect a Raspberry Pi and an Arduino Uno through serial communication and decided to follow this guide, which mentions the use of a voltage divider.
I understand the connection to the Raspberry Pi GPIO requires 3.3V but I also plan to power the Raspberry Pi from the Ardunio's 5v output pin.
What's the safest approach to achieve this and the recommended current? Thanks.

Are you talking about powering the PI via its 5v pin, or powering the it from the Arduino 5v pin?  Yes you need a voltage divider, you might get away with a resistor network, but a proper one would be better.

I mean powering the pi from the Ardunio's 5v output pin. The real question here is how I'm supposed to establish connections between pi-arduino when the gpio pins require 3.3v and I need to power the pi with 5v

Depending on what pi it is you need 2.5A, which an Arduino can not provide.  You need to connect the gnd pins to provide a common ground to allow them to communicate.  The Arduino will send 5v signals into the voltage divider and these will be dropped to 3.3v for the pi, and then the process will be reversed.  AliExpress or eBay will have loads for sale, they cost about $0.5 each.

Thanks alot. You've made a couple of things clear to me. If I have a 5V, 2.5A power source to be connected to a pi pin and I also need to connect the 3.3v from the voltage divider to a pin, is it safe to have two voltage sources into the pi?

Yo should connect the 5v 2.5A PSU via the power input micros USB socket on the Pi rather than the 5V pin.  I don't know for certain, but the chances are that the socket is better protected against over/under voltage, reverse polarity, etc.  If you use the power in pins of the GPIO connector (if there are any) then you need to be 100% certain you are correct otherwise you will fry your Pi, and fried Pi smells bad.  If you use the power socket the 3.3V will also be provided by the circuitry and all will be good.

You CAN NOT reliably power any model Pi from the Arduino 5V output.
You can interconnect the Arduino serial to the Pi using a voltage divider or (preferably) a level converter, as suggested in the linked article. (I might add that the linked article contains a number of errors which will not work on recent Pi models).

Better still you can use a USB connection, to provide serial communication to the Arduino, AND you can power the Arduino from the Pi (I often do this).


text:
Storing random and different values of millis() while inside a loop?
Is it possible to store a value of time while you're inside a loop? Entertain the condition:
if (condition && value > 0)
{
timeTrans = millis() + 2000;
timeTrans - millis() = value;
}

basically i want it to begin counting down from 2 to 0 no matter what time it is at, but the problem is if it's inside the loop tineTrans will update as millis counts up, and value will always be 2000 and will never count down to 0. And the condition stated in the if function cannot be called in void setup(), so there's no hope in that direction. I'd post my code but it's a little long, if it will help find a solution i will post it and point around to what i'm working on.
Also, the condition is met randomly. I do not know when, or at what time/millis() it will be met at.
I also tried using for loops as well but it counts wayyyy too fast for it to be viable, and obviously i cant delay it while its inside a void loop(). Is there any other way i can go about with this?
I've been looking at the beginners guides and here's where i'm at right now, this is about as clear and concise as this question is going to get
is there any way to make "time-2000" a constant variable in this example?
unsigned long time, timeNow, timePast, timeStart, value;
unsigned long period;

void setup() {
  Serial.begin(9600);
  timeStart = 0;

}

void loop() {
  time = millis();
  if (time > 3000) //Using time bigger than 3 sec as a condition substitute to trigger my event
  period = time-2000; //Since in my example, we'll know at what time the condition was triggered (once it's triggered), I set the "period" to that.
    if ((time - timeStart) > period) //aaaaannndd the attempt
      timePast = period;

  Serial.print("Time: "); //debugging
  Serial.print(time);
  Serial.print(" please work ");
  Serial.println(timePast);

that "time-2000" just needs to be turned into a constant somehow. After that, i'll be golden. Anybody know a way around this?

“this is about as clear and concise as this question is going to get” Then it's hopeless. You must make the question clearer if you want to have any chance of getting a good answer. Start by telling us what you are trying to accomplish.


text:
put_index = (put_index + 1) % 100;
Can someone interpret the code in the Title line for me?  Specifically the function of the "%" sign?  It is a line having to do with a 100 element circular buffer.

More a simple coding question.  Not really a question about the Arduino.

which programming language?

use http://symbolhound.com/ for research

The % is the modulo operator in C/C++, which basically means:

Divide the value to the left of the % by the value to the right of it
Discard the quotient and keep only the remainder.

For instance, 10 % 5 = 0, because 10/5 = 2 with no remainder. Whereas 11 % 5 = 1, because the remainder of the division is 1.
In your case, the modulo operator is likely being used to keep the value of put_index less than 100 at all times. If it became 100 because of the operation put_index = put_index + 1, then the modulo operation would make the 100 into 0, so put_index will keep incrementing 0–99 repeatedly.

In C the % symbol is the modulo operator : https://en.m.wikipedia.org/wiki/Modulo_operation


text:
If I run a function in loop() or setup(), and the function doesn't work after some time, is there a way to escape the function and return to the code?
The hardware is an Arduino Uno, using the Arduino IDE.
As a simplest working example, say I have this code
(partially from Edgar Bonet's answer):
// Simulate an initialization that can hang. Connect pin 8 to ground if
// you want the function to ever return.
void initialize()
{
    pinMode(8, INPUT_PULLUP);
    while (digitalRead(8) == HIGH)
    ;  // wait
}

setup()
{
    initialize();             //Function I want to run

    Serial.begin(9600);       //Baud rate
    Serial.println("TEST 1"); //Test message
}

loop()
{
    Serial.println("TEST 2"); //Test message
    delay(1000);
}

if the initialize() function does not complete after some time, such as 2 secs.,
is there a way to ignore that function and continue with the rest of the code?

Not really.  But you could use a watchdog timer to give up and start over; and you can detect that this happened and maybe skip that function.  Or you can use a scheduler and have tasks take turns rather than run sequentially.  Generally though, even if you use one of these things, you should make your functions deterministically conclude and explicitly handle the situations that might cause operations to get stuck.

An infinite busy loop, like you have coded, is not a great idea.  Is there a reason you didn't try for(int l = 0; l < 20 && (digitalRead(8) == HIGH); ++l){Sleep(100);}?  Not a brilliant solution, but pretty fool proof.

@CodeGorilla That initialize function was only there to try make the question more specific, since this question was "put on hold as too broad". The actual function I use comes from a library I didn't write, and I wanted to avoid changing it since it was a bit hard to follow and had several inter-related dependent files.

In general, the right thing to do in such a situation is to fix the
initialize() function so that it always returns. If there is a timeout
to be handled, it should be handled within that function. This is likely
to be the easiest and cleanest solution.
However, if for whatever reason that is not feasible (maybe it comes
from a library that is too opaque to edit), then the idea suggested by
Michel Keijzers is a viable alternative:

[...] set up a timer interrupt and start it just before you initialize
  the device/component you want to initialize. When the timer interrupt
  triggers and the device is not initialized, behave the same like a
  timeout has occurred.

The issue with this is that you would want the ISR (interrupt service
routine) to return to the point where initialize() was called. This is
not trivial, but it can be done. Actually, and contrary to what my own
comment says, it can be handled without resorting to assembly hacks, by
using the setjmp “non-local goto” feature of the avr-libc. Here is a
proof of concept:
#include <setjmp.h>

jmp_buf env;

// Simulate an initialization that can hang. Connect pin 8 to ground if
// you want the function to ever return.
void initialize()
{
    pinMode(8, INPUT_PULLUP);
    while (digitalRead(8) == HIGH)
        ;  // wait
}

// This fires when the initialization times out.
ISR(TIMER1_OVF_vect)
{
    TIMSK1 = 0;       // disable timer interrupt
    longjmp(env, 1);  // go to where setjmp() was called
}

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

    // Configure Timer 1 to fire an interrupt in about 4 seconds.
    TCCR1A = 0;           // reset timer
    TCCR1B = 0;
    TCNT1  = 0;
    TIFR1  = _BV(TOV1);   // clear interrupt flag
    TIMSK1 = _BV(TOIE1);  // enable timer overflow interrupt
    TCCR1B = _BV(CS10)    // clock at F_CPU / 1024
           | _BV(CS12);   // ditto

    // Attempt initialization.
    if (setjmp(env) == 0) {

        // This is the normal program flow.
        Serial.println("Attempting initialization.");
        initialize();
        TIMSK1 = 0;  // disable timer interrupt
        Serial.println("Initialization succeeded.");
    } else {

        // We get here through longjmp() in case of timeout.
        Serial.println("Initialization aborted on timeout.");
    }

    Serial.println("Moving on to the rest of the program.");
}

void loop(){}

If pin 8 is grounded, the initialization succeeds and the program prints
Attempting initialization.
Initialization succeeded.
Moving on to the rest of the program.

If pin 8 is left floating, the initialization hangs and the program
prints
Attempting initialization.
Initialization aborted on timeout.
Moving on to the rest of the program.

with a 4 second pause between the first and second lines.

I'm not sure if you should want this in the first place. Initialization normally should contain the necessary parts to start with.
If there is a device/component you want to initialize that is not able to initialize (because it is not present, or broken), check first if there is an intiialization function with a timeout and when the timeout is reached, set a boolean to denote the device has not been initialized.
If there is not a timeout function, you could try to set up a timer interrupt and start it just before you initialize the device/component you want to initialize. When the timer interrupt triggers and the device is not initialized, behave the same like a timeout has occurred.

About your timer interrupt suggestion: Ideally, the ISR should return to the caller of initialize(), but that would be quite tricky, and would probably have to handled in assembly. If you can manage to add to your answer some example code implementing the idea, it would be really great.

@EdgarBonet If it is problematic to have an ISR during initialize, why not create the initialization part that might fail in the loop() function and after initialization is finished use a while(true) to stay in that loop.

@EdgarBonet Btw, I never tried an ISR during initialization myself.

@EdgarBonet having an ISR "return to the caller" of a blocked function is approximately what a scheduler does.  What would be more realistic here is to have the ISR set a "timed out" flag and have whatever operation is spinning in a while() give up on seeing that.  Checking elapsed time via millis() is comparable, only instead of a boolean flag it's a numeric value updated by the Arduino core's timer ISR handler.


text:
Can only upload certain programs to standalone Arduino
I can't upload a program that uses digitalRead, analogRead, and Serial.print on my standalone Arduino, because I get this error:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xbf

However, I have no trouble uploading the blink program to it, which only uses digitalWrite, so it has to do something with the methods mentioned at the start of this post.
You can see the diagram below.

I added a connection between digital pin 9 and ground with an led

I uploaded the blink program, changed the dgital pin to 9 in the program, uploaded it and connected an led from digital pin 9 to ground. Then I can see the led is blinking every 1 second.

change the blink rate to 1/2 second

It can do that. Now it turns on/off every 500 ms.

ok, this is pretty weird. ... i originally thought that maybe you missed the download fail with the blink program, and the Arduino already had a blink program loaded. ... i have to think on this one

Please post (edit your question) the code that does not upload.

I do not see any decoupling capacitors between Vcc and AVcc and ground, which are absolutely required.

Also, remove the Aref connection to 5V. Aref should only have a 0.1uF cap to Gnd.
Won't affect programming, but could damage the internal ADC mux or other ADC circuits.


text:
How to add a pedestrian button code to a traffic light with ultrasonic sensor?
So I have a project to create a 2 set of traffic lights which would detect a car coming and stopping on the ultrasonic sensor and my code would allow the traffic lights to loop and let the car through. But now I also have to add a pedestrian code in for the pedestrians to press the button, the traffic lights to loop back to red and give 30 seconds of crossing time.
I did the ultrasonic sensor traffic lights code already and some of it seems confusing but somehow works quite well. I'm not familiar with the buttons and looping the traffic lights correctly back to red so I need help to add a pedestrian crossing code to this code:
// Variables for Station 1 Traffic Light Components
const int Red1LED = 9;
const int Yellow1LED = 2;
const int Green1LED = 3;
const int GreenArrow = 4;
#define trigPin 12
#define echoPin 13
// Setup Variables for Station 2 Traffic Light Components
const int Red2LED = 5;
const int Yellow2LED = 6;
const int Green2LED = 7;
const int GreenArrow2 = 8;

void setup() {

  pinMode(Red1LED, OUTPUT);
  pinMode(Yellow1LED, OUTPUT);
  pinMode(Green1LED, OUTPUT);
  pinMode(GreenArrow, OUTPUT);
  pinMode(Red2LED, OUTPUT);
  pinMode(Yellow2LED, OUTPUT);
  pinMode(Green2LED, OUTPUT);
  pinMode(GreenArrow2, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(trigPin, OUTPUT);
 Serial.begin(9600);
  // Set Initial state of all red LED to HIGH
  digitalWrite (Red1LED, HIGH);
  digitalWrite (Red2LED, HIGH);
}

void loop() {
  // put your main code here, to run repeatedly:
 long duration, distance;
  digitalWrite(trigPin, LOW);  // Added this line
  delayMicroseconds(2); // Added this line
  digitalWrite(trigPin, HIGH);
//  delayMicroseconds(1000); - Removed this line
  //delayMicroseconds(10); // Added this line
  //digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  Serial.println(distance);
  if (distance < 20) {  // This is where the LED On/Off happens
     delay(1000);  //  1 Seconds of Red
  digitalWrite(Green1LED, LOW);  //  Sets Red1 OFF Green ON
  digitalWrite(Yellow1LED, HIGH);
  delay(1000);  // 1 Seconds of Green
  digitalWrite(Yellow1LED, LOW);  //  Sets Green1 OFF Yellow ON
  digitalWrite(Red1LED, HIGH);
  delay(1000);  // 1 Seconds of Yellow
   // Station 2 Timing
  delay(1000);  //  1 Second of Red
  digitalWrite(Red2LED, LOW);
  digitalWrite(GreenArrow2, HIGH);  //  Sets Red2 OFF Green ON
  delay(1000);  // 1 Second of Green
  digitalWrite(GreenArrow2, LOW);
  digitalWrite(Green2LED, HIGH);  //  Sets Green ARROW OFF Yellow ON
  delay(1000);  // 1 Second of Yellow
  digitalWrite(Green2LED, LOW);
  digitalWrite(Yellow2LED, HIGH); // Sets Green 2 OFF YELLOW OFF
  delay(1000);
  digitalWrite(Yellow2LED, LOW);
  digitalWrite(Red2LED, HIGH);

   digitalWrite(Red1LED, LOW);
  digitalWrite(GreenArrow, HIGH);
  delay(1000);
  digitalWrite(GreenArrow, LOW);  //  Sets Yellow1 OFF Red ON
  digitalWrite( Green1LED, HIGH);
}
  else {
   digitalWrite(Red1LED, LOW); // When the Red condition is met, the Green LED should turn off
  digitalWrite(Red2LED, HIGH);
  digitalWrite(GreenArrow, LOW);
  digitalWrite(Green1LED, HIGH);
  digitalWrite(Yellow1LED, LOW);
  digitalWrite(Yellow2LED, LOW);
  digitalWrite(Green2LED, LOW);
  digitalWrite(GreenArrow2, LOW);

  }
}

I NEED HELP ASAP PLEASE. Due tomorrow by 12 am. It is extension so I am not that worried if I don't get help by the deadline but if I still do after the deadline I can still learn so don't hesitate to post.

Thank you for making it clear that this is course work.
You are asking for help to do the extension, but by your own words you don't understand how the core code works.  I have to be honest I can't be bothered to read the code, it looks horrible.  If I was your teacher I would quit, because I have failed to teach you one of the most fundamental aspects of coding.  "You write it once but it gets read many times", it is ALWAYS worth spending a few minutes making the code look pretty!  (If you teacher can't be bothered to read it, you aren't going to get 100%!)

Comments - commenting out code is not the best use for // explaining why you are doing what you are doing is.
Its good that you have defined variables to identify you pins, but you have two identical sets of variables, so you could have used an array, a structure or an array of structures.  (These might be more advanced than where you are at the moment, sorry if that's the case).
Breaking you code down into bite sized pieces make it more readable.  That start of your loop contains some code that could be in a function called getDistance()
Turning the lights on and off in the way you are doing it is open to errors.  You could turn the red light on and the green light on.  If you made a class to represent the lights then you could have a function that turned off all of the lights and only turned on the one you wanted.  You wouldn't need to store the state.

Example code (not tested or compiled)
class Lights
{
  public:
    enum eLight {Red, Amber, Green, GreenArrow, GreenPedestrian, RedPedestrian, eMaxLight};
    Lights(int[] pins)
    {
      for (int l = 0; l < eMaxLight; ++l)
        pinMode (pins[l], OUTPUT);
    }
    ~Lights()
    {}
    void setLight (eLight newLight)
    {
       for (int l = 0; l < eMaxLight; ++l)
         digitalWrite(m_Light[l], LOW);
       digitalWrite(m_Light[newLight], HIGH);
    }
}

You probably want to look at a state machine.  List all the possible LEGAL combinations and then create a enum with each of those states in and then write a function that moves from a state to the next legal state, you will need conditionals for has the button been pressed.  This should give you a working system with a pedestrian button that hopefully you understand.

Thanks for answering but the code you have given me includes pedestrian lights. I would rather just press the button and have all the lights turn off. How does the code work and what does each line do because I'm very confused. And what is a enum? My code was rather simple because it is all we know. We just started learning arduino and our teacher has been away for quite awhile now. And compared to other students in my class this was the shortest code so I guess you can't expect better for beginners. I just have to learn coding all together to be honest.

An enum is a way of representing a discrete set of values with words in your code.  (A better description is here https://msdn.microsoft.com/en-us/library/2dzy4k6e.aspx).  So a pedestrian presses the button on pin 'x' and the traffic lights go off?  or do you mean the lights go red.  That should be "easy" to achieve.  Delete the pedestrian values from the enum.  Attach a button and get it to trigger an interrupt (see Arduino website).  The interrupt handler will set the value of a volatile bool to true.  Your main code will have to check this value regularly, and change the lights.


text:
Interrupt fires a random number of multiple times for one pulse
This is my first time posting on this forum. I have tried to format this question properly, but let me know if I need to correct anything. I searched to see if someone else had a similar problem, but let me know if someone has already answered this question.
Overview: I am sending pulses to my Arduino, but sometimes one single pulse is interpreted as anywhere from 2 to 30 pulses. But after looking at the pulse on an oscilloscope (see Fig. 1) I am not sure why. When I use a really long wire the ratio of false pulses to legit pulses is about 1 to 1. I shortened the length of the wire and improved the situation, so that only 1 in about every 2,000 pulses is registered as a false pulse.
For one test, I added a capacitor to the short wire situation, but that increased the rise time and made the problem worse. I am currently using attachinterrupt and have tested the situation with using both a rising and falling edge. Right now, I mainly want to understand how interrupts work on the Arduino in light of my current problem, although I welcome general advice.

When I set the interrupt to the falling edge, why does the Arduino still sometimes count 1 pulse as several? The falling edge in the photo, which is for the really long wire case, lasts about 40 microseconds and appears to have a clean break. The pulse remains low for about 80 milliseconds. Could the falling interrupt trigger during the rise time based off the oscillatory behavior shown in Fig. 1? I smoothed out the signal by adding in a 1 nF capacitor, but the Arduino still counted false pulses. So could the rise time period have anything to do with it? I also have a 10k Ohm pullup resistor connected to the Arduino's 5 V for the pulse path.

I have the relevant code attached below. I have much more code as well, but it deals with saving pulseCounts to the SD Card and uploading electricity consumption files through the cell network.
Cheers.
//Global Variables
unsigned long pulse_time = 0;
unsigned long last_pulse_time = 0;
byte code = 1; //code let's me see if a false pulse was reported for each
//SD file

void setup() {
  attachInterrupt(digitalPinToInterrupt(3), onPulse, RISING);
}

void onPulse() {
  pulse_time = millis();
  if ((pulse_time - last_pulse_time) > 50 ) {
    Serial.println("Good Pulse");
    pulseCount++;
    last_pulse_time = pulse_time;
  } else {
    Serial.println("Bad Pulse");
    pulseCount++;
    code = 2;
  }
}

That is not a nice pulse. You can fix it with a rc filter and a transistor. The transistor can be triggered at a lower voltage. Looking at the scope picture, about 1.5 to 2V would be a good trigger voltage (because the 0V is much stronger than the 5V level). You may not use the Serial.println in a interrupt function because they use interrupts themself. Because of the Serial.println, you can not make any conclusions with this sketch.

Thanks, I ran the test again leaving out the Serial.println statements and instead printed the statements in loop(), but I still get false pulses. I believe I have tried a RC filter. I always have a 10 kOhm resistor tied to the 5 V line, but then I added a 1 nF capacitor between the pulse line and ground. The signal from that is much smoother, but it increases the rise time, so I still have false pulses. I could add a transistor, but before adding hardware I am more curious about why it is counting multiple pulses. Is there a way to determine if it is rise time or the oscillations?

How is the signal generated? Is it just pulled low by the external source? I'd try a lower value pull-up resistor? Also, a Schmitt trigger could help to prevent the effect of a (very) slow rise.

I have a pulse meter that generates a pulse for every unit of electricity consumed.  Yes, the pulse line is default high (5 V) and is then pulled low for the duration of the pulse to 0 V before returning high.  I have done a test with a 1 kOhm resistor, and it decreased the rise time to about 4 milliseconds as compared to about 25 milliseconds in the short wire case.  The signal looks smooth, but I have been warned that there may be unintended consequences for making a pull up resistor below 10 kOhms.  Is there a reason I should be hesitant about lowering the pull-up resistor value?

Firstly, unless the processor pin is a Schmitt trigger, increasing capacitance will only make the problem worse by allowing any noise to be interpreted as multiple high-low transitions.  For a CMOS logic input the area around the transition point of 1/2 VDD typical is actually an area of linear operation, not digital.
A Schmitt trigger introduces hysteresis such that when the signal is interpreted as a high level, it must go low by more than the hysteresis to be interpreted as a low level again.  This is accomplished with a bit of positive feedback added to a buffer where the output transition from low to high then pulls the input that much higher or a transition from high to low pulls the input that much lower:

The red line represents the typical CMOS threshold and the green lines represent the thresholds defined by the hysteresis of the Schmitt trigger.  The hysteresis defines the noise immunity of the input.  Most processors have pins that are equipped with a Schmitt trigger or and external device like a 74HC14 can be used.
Another way to deal with this type of noise is to lock out any transitions within the expected pulse-to-pulse transitions:  Once triggered, no more transitions are allowed until the lock out time expires.

ATmega inputs are Schmitt triggers.

Okay, from this article link  it mentions that for a 5 V arduino, VIH = 3.0 V.  Does that mean that if I set the Interrupt to RISING, that it should only trigger when the pin voltage starts below VIH and then becomes higher than VIH?  Is VIH the correct term for a CMOS threshold and does VIH = 3.0 V on my ATMEGA328 chip?  The oscillatory behavior on the oscilloscope seems to occur when the voltage is more than 4 V.

For that part at 5V the maximum low voltage (VIL) is 1V and the minimum high voltage (VIH) is 3V.  When an interrupt is set to trigger on a rising edge, then that means the input must go from low to high to generate an interrupt but even a short noise pulse of a few micro seconds from high to low to high again can generate a new interrupt.  I see from your scope capture that there is a lot of ripple on the input which means that there is probably a lot of ripple on your 5V... if your 5V goes higher while your input stays the same, this looks to the processor like the input is going lower.


text:
Which container to use?
So for my project, I am measuring heartbeat of a person in a span of 10s. However, as the number of heartbeats may differ for each person, is it wise to use a vector?

What are you measuring? The time between each and every beat, or the number of beats in that 10 second period?

@Majenko I am measuring the time when each pulse occurs within a span of 10s. I will then use this information and find out the BPM in the end.

Why store information about every heartbeat, if you only need an average. Just store the number of heartbeats, and the timestamp of the last one. Combined with the timestamp of the first heartbeat, gives you enough information to calculate the average. Or do you want to measure irregularities?

No, you don't want a vector, for a number of reasons:

There is no "vector" unless you add extra (unsupported) code.
Vectors use dynamic memory. Arduinos don't work well with dynamic memory.
It's pointless anyway.

Just allocate an array big enough to contain enough timestamps. In a 10 second period, if you get more than 100 beats, the person you are measuring the heart rate of is most likely in a noticeably "unfortunate" state. That's 600bpm. That's entering panicked mouse territory.
Even with that extreme number of beats an array of 100 32-bit values is only 400 bytes.

alright thanks a lot. Just wondering too, is there going to be a difference if I allocate a vector with a size of 100 vs an array with a size of 100? Also, can you explain when you mention arduinos dont work well with dynamic memory? Is it due to not having enough memory?

Yes, it's due to not having much memory. It's easy for heap fragmentation to occur, as evidenced when people over-use String variables and their program crashes randomly.  Vectors are pointless. Don't even consider them. Erase them from your mind. They are a concept not compatible with little microcontrollers.

Alright, thats a pity since in c++ we almost always use vectors instead of arrays. So the only container for arduino are arrays?

Not the "only", but the only "sensible" one.

I am curious about your opinion on malloc(), alloc() and free() as well.

On a small MCU they should be avoided at all cost. As should new.  alloca() is OK since it does stack allocation.


text:
Synchronizing http GET and POST request
My project aims to send HTTP GET request to web page(using Arduino UNO and ESP8266-01) then receive response, extract wanted values from response and react with(for example turn on LED1,LED3) then resend led's status to another web page to be inserted in mysql database using HTTP POST in order to make sure that Arduino received the command and executed successfully (in an infinitive loop).
Each request HTTP GET or HTTP POST works fine alone, but when trying to do that in a sequence HTTP GET then HTTP POST inside the loop I got bad result shown in serial monitor like unknown strange characters.
Here is my loop :
void loop() {
  if (millis() - lastTimeMillis > 40000) {
    lastTimeMillis = millis();
    ESP8266.println("AT+CIPMUX=1");
    delay(1000);
    printResponse();
    ESP8266.println("AT+CIPSTART=4,\"TCP\",\"" + server + "\",80");
    delay(1000);
    printResponse();
    String cmd = "GET /ard/sensor.php HTTP/1.1\r\nHost: localhost";
    ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
    delay(1000);
    ESP8266.println(cmd);
    delay(1000);
    ESP8266.println("");
  }
    if (ESP8266.available()){
    Serial.write(ESP8266.read());
    }
  Value1=(digitalRead (LED_PIN1));
  Value2=(digitalRead (LED_PIN2));
  Value3=(digitalRead (LED_PIN3));
  Value4=(digitalRead (LED_PIN4));
 data = "Value1=" + Value1 + "&Value2=" + Value2 + "&Value3=" + Value3  + "&Value4=" + Value4;
  httppost();
}

And here is

httppost()

void httppost () {

    ESP8266.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");
    if( ESP8266.find("OK")) {
    Serial.println("TCP connection ready");
    }
    String postRequest =
    "POST " + uri + " HTTP/1.0\r\n" +
    "Host: " + server + "\r\n" +
    "Accept: *" + "/" + "*\r\n" +
    "Content-Length: " + data.length() + "\r\n" +
    "Content-Type: application/x-www-form-urlencoded\r\n" +
    "\r\n" + data;
    String sendCmd = "AT+CIPSEND=";
    ESP8266.print(sendCmd);
    ESP8266.println(postRequest.length() );
    delay(5000);
    if(ESP8266.find(">")) { Serial.println("Sending.."); ESP8266.print(postRequest);
    if( ESP8266.find("SEND OK")) { Serial.println("Packet sent");
    while (ESP8266.available()) {
    String tmpResp = ESP8266.readString();
    Serial.println(tmpResp);
    }
    ESP8266.println("AT+CIPCLOSE");
    }
    }
}

When uploading this code it seems like only HTTP POST works fine in a loop while HTTP GET having a trouble. So how to make them both work fine in a loop?
Thanks in advance

do you like AT commands? I do not. Use a library https://github.com/bportaluri/WiFiEsp or program the esp8266 with esp8266 Arduino core package https://github.com/esp8266/Arduino#installing-with-boards-manager

Why does one use AT+CIPSEND=4,<N> and the other AT+CIPSEND=<N>?

@Gerben This is the first time I deal with Arduino, may you explain more please ?

Try removing the 4,, or try adding it to both.


text:
how can I send a variable to println?
this is my method
void mensaje_sms()
{
  string numero = "777777";  // this is my variable
  SIM900.print("AT+CMGF=1\r");
  delay(100);
      SIM900.println("AT+CMGS=\"591"numero"\"");
//IM900.println("AT+CMGS=\"59177777777\""); //only in this way does it work
      delay(100);
      SIM900.println("SEND NUMERO VARIABLE RODO");
      delay(100);
      SIM900.println((char)26);
      delay(100);
      SIM900.println();
      delay(5000);
      Serial.println("SMS sent successfully");
    }

how can I send a variable to println?

What variable? What do you want to happen?

this is my variable int numero = 777777; I need to put that in the println

Change:
SIM900.println("AT+CMGS=\"591"numero"\"");

to
SIM900.print("AT+CMGS=\"591");
SIM900.print(numero);
SIM900.println("\"");

Note that only the final call is to println() (which just prints a carriage-return character at the end.)


text:
Can a cheap RF module be used for two way communication
Can a cheap RF(transmitter and receiver) module be used for two way communication, not at the same time of course but for example arduino A sends string to be printed on lcd the arduino B receives it and prints it on lcd, then after some time arduino B sends a temperature data back to arduino A, then arduino prints the temperature data on the serial monitor. All of this while arduino A is connected to a transmitter and arduino B is connected a receiver.

Yes you can, but you'd need both modules on both Arduinos. So two sending modules, and two receiving modules.

Each device that will ever transmit anything will need a transmitter. Each device that will ever receive anything, needs a receiver. The devices you show in your question are separate receivers and transmitters, so on Arduino A and Arduino B, you will need both a receiver and a transmitter in order to have real, two-way communication between them.
Some RF devices are "Transceivers" which have both a receiver and a transmitter in the same module. Some of these can operate "full-duplex", meaning they can receive at the same time they are transmitting other data (Typically each direction is on a different frequency, but not necessarily.) Most cheap ones are half-duplex, meaning the module can only receive or transmit at any one time.
ADDITIONAL INFORMATION ABOUT RADIOHEAD
Your comment mentioned the RadioHead library. I was able to find the documentation on the library and see that it supports a wide range of radio chipsets and modules. The cheap ones you note are simple ones that use OOK (on-off-keying) or ASK (amplitude-shift-keying) and don't actually have a protocol. The receiver simply provide a HIGH or LOW output if it detects a signal on it's designated receive frequency. The transmitter simply oscillates at the transmit frequency when it's input pin sees a HIGH value, and stops when it sees a LOW value.
The RadioHead RH_ASK class deals with these simple transmitters. The documentation is at http://www.airspayce.com/mikem/arduino/RadioHead/classRH__ASK.html#details
This page notes the way to connect both a transmitter and receiver thus:
Connecting to Arduino

Most transmitters can be connected to Arduino like this:

Arduino                         Transmitter
 GND------------------------------GND
 D12------------------------------Data
 5V-------------------------------VCC

Most receivers can be connected to Arduino like this:

Arduino                         Receiver
 GND------------------------------GND
 D11------------------------------Data
 5V-------------------------------VCC
                                  SHUT (not connected)
                                  WAKEB (not connected)
                                  GND |
                                  ANT |- connect to your antenna syetem

i have searched everywhere for a diagram of some sort of how to connect both transmitter and receiver to one arduino, i cant find any, do you have some advise? i am asking this because the "RadioHead" library expects data from pin 12, and i don't know if any other pin would work? thanks.

This sounds different enough to become a new question itself. That is, the RadioHead library and dealing with separate transmitter and receiver modules.

Sure it can.  A transmitter is only a transmitter while it's actively transmitting.  And you can have as many receivers as you like.

wait... so does this mean when a receiver is not receiving it can transmit? and when a transmitter is not transmitting it can receive?

No, it means you can have two people in a room. Each has a mouth, and each has ears. Only one should talk at once, but both people's ears are working all the time. The person talking knows he's talking though so ignores whatever comes in through his ears.

not those ones, those look to be separate transmitter and receiver modules.  But something like the nrf24 is a transceiver, meaning it can do both   like this   https://www.amazon.com/dp/B00O9O868G/ref=sspa_dk_detail_1?psc=1

I'll second Chad G's recommendation of the NRF24L01 unit, cheep/readily available(Ebay) and very effective. I am using these to remote control my projects, range depends on who you talk to but have seen statements ranging from 100 to 1000mts. This item is well supported in the Arduino community.


text:
How do I isolate numbers in text?
I need to separate numbers from the text where my string of numbers will always be of length 8:
string text = "77953505HELLO THIS IS A MESSAGE"; //my string of numbers will always be of length 8

My result
string number = "77953505"; //my string of numbers will always be of length 8
string message = "HELLO THIS IS A MESSAGE";

What operation should I use?
this is the job I'm doing
void setup() {
  Serial.begin(9600);
}

void loop() {
  if (Serial.available() > 0) {

    String Texto = String(Serial.read());

    String number = Texto.substring(0, 7);
    String message = Texto.substring(8);

    Serial.write(number);
    Serial.write(message);
  }
}

help me!

read() reads one char. https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

please, helpme  whith a example

i new in the world of arduino

it has little to do with Arduino. It is programming in C++. Read the blog.

Depends, and probably better to use C strings:

If you know the number is always the same amount of characters, use the C function strncpy.
You can also split on a delimiter (char), with strtok, but in your case this is not possible since you don't know the delimiter character.
If the number has a variable length, start copying character by character through the string, until you find a character that gives false for the isdigit condition and copy the remainder (with strncpy) to the other string.

Update after the question's edit
Since the number of text to be copied is know, strncpy can be used with the following prototype:
char *strncpy(char *dest, const char *src, size_t n)

In your case put the text in a normal text string:
char text[80]; /* Assuming max length of text */

Copy it where needed:
strcpy(text, "77953505HELLO THIS IS A MESSAGE");

Note: it can be done in once like this:
char text[] = "77953505HELLO THIS IS A MESSAGE";

Than you can copy the items by:
char number[9]; // Add 1 for \0
char message[81]; // Assuming max length of message;

strncpy(number, text, 8);
strncpy(message, &(text[8]), strlen(text) - 8);

(Note not checked with compiler).
Improvements: use instead of 8 a define e.g.
#define NUMBER_LENGTH 8

char number[NUMBER_LENGTH + 1];

strncpy(number, text, NUMBER_LENGTH);
strncpy(message, &(text[8]), strlen(text) - NUMBER_LENGTH);

You can do similar for MESSAGE LENGTH
#define MESSAGE_LENGTH 80

Also, another improvement is not to copy the message, but just set the pointer to the correct place:
char* message = &(text[8]);

message will point to "HELLO THIS IS A MESSAGE"
like below
"77953505HELLO THIS IS A MESSAGE"
|        |
+-- text |
         +-- message

In an Arduino 80 bytes can be a lot of memory, using two buffers cost 160 bytes, and this way you save at least one buffer.

i edited my question

So in this case you can use strncat; I will edit my answer

I changed strncat by strncpy and added some improvements.

look at my edition

what output you get? I don't see a problem so far.

For a fixed length substring the simple arduino-ish way would be to use String.substring(left_pos, right_pos)
String number = text.substring(0, 7);
String message = test.substring(8); // right_pos is optional

This is not necessarily the best option depending on how you intend to use the resulting substring.  Memory is allocated and the content is copied. Requiring at least double the memory (plus some overhead). If memory is tight you may not want to create a String but use char* instead.

look at my edition


text:
Use PWM to play notes on ATMega328
I have old speaker which I want to use to play sound. I chose to use PWM mode on ATMega328 (which is in turn on Arduino Uno R3 board) in order to do it.
For signal on the speaker I chose rectangular wave because it does not require any additional setup. To generate this signal I chose timer1 because it is easy to change PWM frequency just by changing ICR1 value. For duty cycle I chose 50%. So my program looks as follows:
#define     CLK_FREQ 16000000   //clock frequency on ATMega328
#define     PRSCLR   1024       //chosen prescaler of timer1

//duration of one note
unsigned int halfDur = 200;
//number of notes in the melody
const int notesSize = 32;
//frequencies of notes in the melody:
unsigned int notes[notesSize] = { 220, 277, 329, 277, 220, 277, 329, 277,
                                  207, 277, 329, 277, 207, 277, 329, 277,
                                  184, 277, 369, 277, 184, 277, 369, 277,
                                  220, 293, 369, 293, 220, 293, 369, 293 };
//method to play one note
void PlayFreq( unsigned int freq );

void setup()
{
    //PB1 pin in OUTPUT mode
    DDRB |= ( 1 << DDB1 );

    TCCR1A = 0b0;
    //non-inverting mode of PWM
    TCCR1A |= ( 1 << COM1A1 ) | ( 1 << COM1B1 );
    //Fast mode PWM with ICR1 as TOP:
    TCCR1A |= ( 1 << WGM11 );
    TCCR1B = 0b0;
    TCCR1B |= ( 1 << WGM12 ) | ( 1 << WGM13 );
    //prescaler = 1024
    TCCR1B |= ( 1 << CS12 ) | ( 1 << CS10 );
}

void loop()
{
    for ( int i = 0; i < notesSize; i++ )
    {
        PlayFreq( notes[i] );
        delay( halfDur );
    }
}

void PlayFreq( unsigned int freq )
{
    //claclulate TOP according to note frequency
    ICR1 = CLK_FREQ / PRSCLR / freq - 1;
    //50% duty cycle
    OCR1A = ICR1 / 2;
}

Problem is only several first notes are playing and then there is no sound, then again I hear some notes then there is no sound and so on. It seems that tempo is OK. It just skips some notes. What it could be?

Why not use the built-in tone() function?

@Majenko, I will try it now. Thx.

Yes, it works perfectly. But what's wrong with my code?

Just a couple of remarks, unrelated to your problem: 1. There is a macro named F_CPU which is already defined and holds the clock frequency. No need to define CLK_FREQ yourself. 2. You would get a better frequency resolution by setting the prescaler to 64. Actually, if your frequencies are always higher than 31 Hz, you could even set the prescaler to 8.

@EdgarBonet, Thank you for your remarks. Useful.


text:
AnalogWrite not working in if statement
Arduino Uno with ATMega328P Processor.analogWrite is not working properly in if statement. It changes the brightness of the LED as if there wasn't any if statement at all.
There are 2 potentiometers to create an intervall in which to program increases of the LED brightness, starting at 40% of the maximum. When it's lower than the minimum value, the LED is turned off.
int ledPin = 6;
int sensorPot = 1; // it's a potentiometer for now
int maxPot = 7; // potentiometer
int minPot = 3; // potentiometer
int fortypercent = 255*0.4;
int brightness = 0;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(sensorPot, INPUT);
  pinMode(maxPot, INPUT);
  pinMode(minPot, INPUT);
  Serial.begin(9600);
}

void loop() {
  int start = analogRead(minPot);
  int maxVal = analogRead(maxPot);
  int sensor = analogRead(sensorPot);
  Serial.println(sensor/4);
  Serial.println(start/4);
  Serial.println(maxVal);
  if(sensor/4 > start/4) {
    analogWrite(ledPin,sensor/4);
  } else if(sensor = baslangic) {
    analogWrite(ledPin,LOW);
  } else if ((start < sensor < maxVal)) {
    brightness = sensor/4 - fortypercent;
    analogWrite(ledPin,brightness);
  } else if (sensor = maxVal) {
    analogWrite(ledPin , 255);
  }
}

Can't execute how? What happens?

Of course it can. What problem are you having? What output do you expect from this program? What output do you have instead?

Sorry, edited question

Please, be more specific, like “If I set the pot XXX to position XXX I expect the program to do XXX and instead ot does XXX”.

I updated my question

ORIGINAL RESPONSE, BASED ON DIFFERENT CODE
You are comparing sensorValue to see if it's ever less than minValue.
However, you have mapped sensorValue to range from 0 to 255, and minValue is set at 0. How can anything from 0-255 be less than zero?
NEW RESPONSE, BASED ON UPDATED CODE
One of your if statements: else if(sensor = baslangic) is not comparing, but assigning baslangic to sensor. To compare, use ==.
Your other if statement: else if ((start < sensor < maxval)) is wrong. C++ doesn't work this way. Maybe you want: if ((start<sensor) && (sensor<maxval))?
Instead, your statement evaluates like if ( (start<sensor) < (maxval) ), which means you are comparing the TRUE or FALSE of (start<sensor) to the int that is maxval.

I am analog reading minValue.

Indeed. So, what is connected to pin A3 (minPot) and what values from analogRead() is it providing? Use debug statements. I will retract this answer, since I misread the question.

Sorry for asking not well explained questions... Newbie here... Updated the question


text:
How to implement the Arduino Extended Database library in a custom class?
I am struggling to implement a custom class that uses the Arduino Extended Database Library (EDB.h). The purpose of my custom class is to manage my application's internal database.
While searching for a solution I found this, which seems very relevant: the code and goal are the same as mine.
But my problem with that Q&A is that I am not able to implement the given solution as I don't fully understand the way it should be written.
For the sake of trying to give the best support for explanation, I upladed the code below. Feel free to explain me how to modify it.
Thank you.
EDIT: Following duplicate comments, I'll try to be more precise in my question.

Indeed, I even posted the link.
If I did it's for a specific reason: I do not understand the solution.
May be you could help ? Thx Juraj

I think it is explained good there

Juraj, sure it must be good if one have the knowledge, which I haven't.
In clear: do you understand that I do not understand the given explanation ?
If its good enough for you, and you understand it, may be you could  please give me more details on how to implement it ? Thanks

simplified: you can't give a class member function, where function is required.

@Juraj That's not entirely correct.

@CodeGorilla, I know. can you explain it better than in the answer to the referred question?

It is difficult to answer this question because I'm not sure what you have managed to achieve.  Sorry if some of it seems a bit basic.
Look at Majenko's answer to the question.  If you want to use this EDB class then you need to define two functions:
  void configWriter( unsigned long address, byte data );
  byte configReader( unsigned long address );

You need to be able to access the single instance of these functions from anywhere in the code, so the need to have global scope.  When they are global you can assign them to pointers by using the function name and no brackets/parenthesis.  i.e.
aPtr = configWriter;

So the call to create the EDB instance would be:
 configDB = new EDB( configWriter, configReader );

Now you could create the EDB instance using a class member function.  To do this you have to make the function a static member, which means it has no access to the class's data. (in its simplest terms static means there is only one of the things it is referring to) i.e.
class myEDB
{
  public:
    static void configWriter( unsigned long address, byte data );
    static byte configReader( unsigned long address );
...
};
configDB = new EDB( myEDB::configWriter, myEDB::configReader );

Essentially its the same thing, but the code is compartmentalised better and you end up with neater code.
However, if you are only ever going to have one instance of the myEDB class then you can have a static member variable that hold the value of this.  You set this value in the class constructor.
class myEDB
{
  public:
    static void configWriter( unsigned long address, byte data );
    static byte configReader( unsigned long address );
    myEDB() {pInstance = this;}
  private:
    static myEDB* pInstance = nullptr;
...
};
configDB = new EDB( myEDB::configWriter, myEDB::configReader );

When configReader or configWriter is called it checks to see if the member pInstance has a non null value, if it doesn't then it creates a new instance.  The then use this pInstance to access the functions and variables for the instance of the class.  (This is the design pattern for a single instance class or singleton).
SO what should YOU do?
Start simply, define two global functions that do what you need as per the top of this answer.  If you get stuck, if you need more info feel free to ask or comment.

Hello and Thank you again Code Gorilla. I posted my code following your explanation, and the resulting compilation errors. Can you help me to understand these errors, and modify the code accordingly ?


text:
Receive data from Arduino board to Android application
I'm trying to receive data and print it on a label of my application, but I can not get it. Actually, I have 0 experience with Arduino. It's the first time I see this. I read this tutorial to receive data from an Arduino. In my Arduino I have this code:
#include <SoftwareSerial.h>
const int RX_PIN = 2;
const int TX_PIN = 3;
SoftwareSerial blueTooth(RX_PIN, TX_PIN);
char commandChar;

void setup () {
  Serial.begin(57600);
  Serial.println("Let's start!");
  blueTooth.begin(9600);
  blueTooth.println("Hello, world?");
}

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

My Android code is this:
public class MainActivity extends AppCompatActivity {
FrameLayout frame;
GifImageView imagen;
TextView mensaje,debug;
Button boton;
private TextToSpeech talk;
public static StringBuilder sb;
private static final String TAG = "conexionBluetooth";
ConnectedThread mConnectedThread;
BluetoothAdapter blueAdapter;
BluetoothDevice mDevice;
BluetoothSocket mSocket;
Handler handler;

final int MENSAJE_RECIBIDO = 1;
final UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static String MAC = "00:21:13:02:EA:07";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getSupportActionBar().hide();
    setContentView(R.layout.activity_main);
    talk = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int i) {
            if(i == TextToSpeech.SUCCESS){
                talk.setLanguage(Locale.US);
                mensajeInicio();
            }
        }
    });
    debug = (TextView) findViewById(R.id.debug);
    mensaje = (TextView) findViewById(R.id.mensajeApp);
    frame = (FrameLayout) findViewById(R.id.androidIc);
    imagen = (GifImageView) findViewById(R.id.imageBluethoot);
    imagen.setVisibility(View.INVISIBLE);
    frame.setVisibility(View.VISIBLE);
    boton = (Button) findViewById(R.id.botonInicio);
    Animation flotarArriba = new TranslateAnimation(
            TranslateAnimation.ABSOLUTE, 0f,
            TranslateAnimation.ABSOLUTE, 0f,
            TranslateAnimation.RELATIVE_TO_PARENT, 0f,
            TranslateAnimation.RELATIVE_TO_PARENT, 0.05f
    );
    flotarArriba.setDuration(1000);
    flotarArriba.setRepeatCount(-1);
    flotarArriba.setRepeatMode(Animation.REVERSE);
    flotarArriba.setInterpolator(new LinearInterpolator());
    mensaje.setAnimation(flotarArriba);
    boton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            boton.setEnabled(false);
            mConnectedThread.write("0");
            Toast.makeText(getApplicationContext(),"Data send to arduino",Toast.LENGTH_LONG).show();
        }
    });
    handler = new Handler(){
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MENSAJE_RECIBIDO:
                    byte[] readBuf = (byte[]) msg.obj;
                    String strIncom = new String(readBuf, 0, msg.arg1);
                    sb.append(strIncom);
                    int endOfLineIndex = sb.indexOf("\r\n");
                    if (endOfLineIndex > 0) {
                        String sbprint = sb.substring(0, endOfLineIndex);
                        sb.delete(0, sb.length());
                        debug.setText(sbprint);
                        boton.setEnabled(true);
                    }
                    //Log.d(TAG, "...String:"+ sb.toString() +  "Byte:" + msg.arg1 + "...");
                    break;
            }
    }};
    configBluetooth();
    comprobarEstadoBluetooth();
}

@Override
public void onResume() {
    super.onResume();
    Log.d(TAG, "...onResume - try connect...");

    BluetoothDevice device = blueAdapter.getRemoteDevice(MAC);

    try{
        mSocket = crearSocket(device);
    } catch (IOException e) {
        Toast.makeText(getApplicationContext(),"ERROR!! No se ha logrado crear el enchufe! " + e.getMessage(),Toast.LENGTH_LONG).show();
        finish();
    }

    blueAdapter.cancelDiscovery();

    Log.d(TAG, "...Connecting...");
    try{
        mSocket.connect();
        Log.d(TAG,"Connection OK!!");
    } catch (IOException e) {
        try{
            mSocket.close();
        } catch (IOException e1) {
            Toast.makeText(getApplicationContext(),"Error fatal en el metodo onResume. Incapaz de cerrar conexion: " + e1.getMessage(),Toast.LENGTH_LONG).show();
            finish();
        }
    }
    mConnectedThread = new ConnectedThread(mSocket);
    mConnectedThread.start();
}

@Override
public void onPause() {
    super.onPause();
    Log.d(TAG, "...In onPause()...");
    try {
        mSocket.close();
    } catch (IOException e) {
        Toast.makeText(getApplicationContext(),"Error fatal en el metodo onPause. Incapaz de cerrar conexion: " + e.getMessage(),Toast.LENGTH_LONG).show();
    }
}

private void enable() throws IOException {
        boton.setText(getString(R.string.finalizar));
        mensaje.setText(getString(R.string.mensajeActivo));
        frame.setVisibility(View.INVISIBLE);
        imagen.setVisibility(View.VISIBLE);
        mensaje2();
        boton.setText(getString(R.string.iniciar));
        mensaje.setText(getString(R.string.pontelos));
        frame.setVisibility(View.VISIBLE);
        imagen.setVisibility(View.INVISIBLE);
        mensaje1();

}

private void mensajeInicio(){talk.speak(getString(R.string.app_name) + getString(R.string.textApp) + getString(R.string.pontelos),TextToSpeech.QUEUE_FLUSH,null);}
private void mensaje1(){talk.speak(getString(R.string.pontelos),TextToSpeech.QUEUE_FLUSH,null);}
private void mensaje2(){talk.speak(getString(R.string.mensajeActivo),TextToSpeech.QUEUE_FLUSH,null);}

private void configBluetooth(){
    Toast.makeText(getApplicationContext(),"Metodo llamado",Toast.LENGTH_LONG).show();
    blueAdapter = BluetoothAdapter.getDefaultAdapter();
    if(blueAdapter != null){
        Set<BluetoothDevice> pairedDevices = blueAdapter.getBondedDevices();
        if(pairedDevices.size() > 0){
            for(BluetoothDevice device: pairedDevices){
                if(device.getName().equals("HC-06")) {
                    mDevice = device;
                    Toast.makeText(getApplicationContext(), "Nombre del dispositivo: " + mDevice.getName() +
                            "\nDireccion MAC: " + mDevice.getAddress() + ".", Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}

private void comprobarEstadoBluetooth(){
    if(blueAdapter == null){
        Toast.makeText(getApplicationContext(),"ERROR!!! No hay soporte Bluetooth!",Toast.LENGTH_LONG).show();
        finish();
    }else{
        if(blueAdapter.isEnabled()){
            Toast.makeText(getApplicationContext(),"Bluetooth encendido. . .",Toast.LENGTH_LONG).show();
        }else{
            Intent activarBTH = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(activarBTH, 1);
        }
    }
}

private BluetoothSocket crearSocket(BluetoothDevice device) throws IOException {
    if(Build.VERSION.SDK_INT >= 15){
        try{
            final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
            return (BluetoothSocket) m.invoke(device, uuid);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    return device.createRfcommSocketToServiceRecord(uuid);
}

private class ConnectedThread extends Thread {
    private final InputStream mInStream;
    private final OutputStream mOutStream;

    public ConnectedThread(BluetoothSocket socket) {
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mInStream = tmpIn;
        mOutStream = tmpOut;
    }

    public void run() {
        byte[] buffer = new byte[256];  // buffer store for the stream
        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                // Read from the InputStream
                bytes = mInStream.read(buffer);        // Get number of bytes and message in "buffer"
                handler.obtainMessage(MENSAJE_RECIBIDO, bytes, -1, buffer).sendToTarget();     // Send to message queue Handler
                handler.handleMessage(new Message());
            } catch (IOException e) {
                break;
            }
        }
    }

    /* Call this from the main activity to send data to the remote device */
    public void write(String message) {
        Log.d(TAG, "...Data to send: " + message + "...");
        byte[] msgBuffer = message.getBytes();
        try {
            mOutStream.write(msgBuffer);
        } catch (IOException e) {
            Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
        }
    }
}
}

I notice the following behaviors:

The application does not crash when it is executed.
When I start the application, the bluetooth module of the Arduino flashes differently. (I guess it's because my app connectswith the board).
Inside the Log Cat, it can be seen that the connection has been made correctly. . .

What could be missing here to print the data received from the Arduino? I do not know if it's me, or the handler method never runs. (public void handleMessage (Message msg))
Also note that in the serial monitor of the Arduino, the value that I command when pressing the button of the application is never printed...
UPDATE
Investigating on the internet about the module of my Bluetooth (HC-06) I found that;

If the light of the module is constantly flashing, it is not paired
with the phone.
If the module light stays on, then it is already connected.

My concern is that when I open my application, to blink constantly, it blinks much slower. . . Could it be that I've never been able to connect?

If you are not connected to the HC-06 and try to work with the socket, the monitor of your Android applications would at least show an error. Habe you checked, if you get an IOException when opening the streams? Your exeption handler is empty

And have you tried this with a bluetooth serial terminal app in your phone? So you can rule out a Problem with the arduino code vor wiring.

Hello,I  follow your advice:
In effect, if I am not connected to the bluetooth (or if I connect, and the bluetooth module is badly connected) the application releases an error. Download what you suggested (Bluetooth termial), I could verify that I am connecting with the module HC-06. But I can not receive data at the end ... @chrisl

Then maybe you use the wrong baudrate. My HC-06 is configured for 9600 baud by standard, but in the web you see several, which use other baudrates by default. Try to use other baudrates (for example 57600 I think). Also you can configure the module for different baudrates by using AT commands

Oh right! I changed that too @chrisl ! Serial and bluetooth begin at 9600 now! I forgot to add that in my answer

I don't think your code is correct:
void loop () {
 if (blueTooth.available())
    Serial.write(blueTooth.read());
  if (blueTooth.available())         <----
    blueTooth.write(Serial.read());
}

Shouldn't you be monitoring Serial.available on this line?

Oh, well, I made the change that you say but nothing happends :/

I could solve it already !!!! It turns out that the bluetooth module was badly connected to the arduino !!!! I can already receive data! thank you very much for your comments, especially chrisl, for your suggestion to use the bluetooth serial monitor app! :)
I had connected the VCC to 5V ... that was what was bothering me, I read on the web that if you have it in 5V, as a self defense, the RX pin is completely blocked. The VCC must be connected to 3.3V.
EDIT: I forgot something very important! had to change the baud of bluetooth to 9600 like Serial! this part was very important too.


text:
Add a watermark to text message in an Arduino
I'm trying to add a watermark to the text in the Arduino and there are several levels of watermarks (fragile, semi-fragile, robust). What is the difference between these levels in terms of algorithms used?

I don't understand what you are trying to accomplish. Can you explain what your "text in the Arduino" is?

The term watermarking is usually used in the context of images. I can't make sense of the idea of watermarking text.

"Robustness", in the context of digital watermarking, specifies the ability to detect the watermark after some signal processing modification (for images, this might be translation, rotation, scaling, compression, etc.) Some digital watermarking techniques are robust against some operations but not against others. The classifications are:

Robust: The watermark should be able to survive against any and all
modification. This is often used in copyright protection, for
example.
Fragile: This kind of watermark is designed to be destroyed by any
modification to the original. This allows any manipulation, even
slight changes, to be detected. Fragile watermarks are generally used
to enable authentication and integrity verification.
Semi-fragile: The watermark should be "robust" against certain,
defined, modifications, but "fragile" against others. In other words,
the watermark should survive intact under the operations you want to
allow, but be destroyed by anything else. Again, these are used to
enable authentication.

For more information, you might find the 2005 paper A Review Study on Digital Watermarking by L. Jian and H. Xiangjian (in the journal Information and Communication Technologies) useful.

Watermarking is used to detect changes against the original source. In images this is done by changing some pixels, almost invisible to see, but enough to check the source or see if changes have been made.
For text this is not possible normally, since changing the text will visible change the output (when you print it).
Instead a so called CRC (cyclic Redundancy Code) is used and stored separately. E.g. a certain text has a specific CRC code. When the code is changed, the CRC code should be changed too. But if someone only changes the text, you can check the text against the (unchanged/encrypted) CRC code to see it has been mangled with.


text:
Ultrasonic Sensor receiving Side
I'm doing my project regarding 40khz ultrasonic sensor which will be used to get accurate distance measurements. I have a separate transmitter and receiver. I want to get the time between the moment my transmitter transmitted the waves and the time my receiver received it. However, I couldn't actually make it work. Does any of you give me a code that would help me transmit and receive the 40khz waves and get the time in between so I could use it to compute for the distance?Thank you in advance. I would greatly appreciate it!

What is your exact hardware? Most commercial US sensors I know have their own measuring implemented on board.

@mystery what about the HC-SR04?

I know that one quite well. It should serve OPs wish for example code https://github.com/sparkfun/HC-SR04_UltrasonicSensor/blob/master/Firmware/HC-SR04_UltrasonicSensorExample/HC-SR04_UltrasonicSensorExample.ino

I'm using arduino uno, and separate ultrasonic transmitter and receiver. I'm not using any commercially available ultrasonic sensor

This is the most basic ultrasound pulse and receive code. I wrote it to work with the HC-SR04 modules; so hopefully it will work fro you too as those also sound at 40khz.
The main functionality comes from the pulseIn() funciton.
#define TRIGPIN 9
#define ECHOPIN 10

void setup() {
  Serial.begin(9600);
  pinMode(TRIGPIN, OUTPUT);
  pinMode(ECHOPIN, INPUT);
}

void loop() {
  digitalWrite(TRIGPIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGPIN, LOW);

  uint16_t duration = pulseIn(ECHOPIN, HIGH, 4000);
  int distance = (duration*.0343)/2;
  Serial.println(distance);
}

Note that you will need to adjust the 4000 (μs) to whatever timeout in you want (or emit entirely if you don't want it).

Hi Sir! Sadly, I'm not using any commercially available ultrasonic sensor like HC-SR04. I have separate transmitter and receiver transducer Sir.

@JeniferRicalde That is fine, can you provide a link to these? The code will still work assuming the transmitter and receiver are simply digital outputs (i.e. send HIGH to transmit sound on the transmitter and the receiver outputs HIGH when it receives).

Sir, will it be ok if I ask for your email?I wish to send the code. I cannot attach it in here

Why not? Just insert into the question like I have in my answer the .ino file.  Or make a link with https://pastebin.com/

I'm sending 8 pulses of 40khz waves then the receiver will measure the voltage peak of the wave it received so that it may know the time interval.however, i'm not quite sure if my code is right

here's the link:
https://pastebin.com/4chsLQ6R

I used, Mr. Kerry Wong's code

@JeniferRicalde I am sorry but since you have just copied someone's code it is especially difficult to debug without being able to try things out (since I don't have that setup). However there are two things: you can use the delay() function to delay in milliseconds and use delayMicroseconds() for micros - there is no need to write your own delayMilliseconds() function because delay() already works. And secondly, I recommend you use the Serial lib to print the readings from the receiver to help debugging.

I don't have 'a code', but what you can do is using a timer set to 40 kHz and send the pulses you need. .
If nothing else needs to be done (nor in the future) you can use a delay function.
Also check the pulseIn function from Arduino, you can use this convenience function for the checking the result.


text:
ToF VL53L1X sensor integrate with arduino
I have this latest version VL53L1X time of flight laser distance sensor: http://www.st.com/en/imaging-and-photonics-solutions/vl53l1x.html
I study about this sensor, It says that sensor only Access with API(Application program Interface) how do I Integrate that API code in arduino or
how do I use Wire library to Integrate this sensor.

I can see how to communicate with the device in the datasheet, but they don't seem to tell you what to communicate. Very helpful. And software for their boards is registration-walled. So stuff that.  I'd pick an easier to use sensor.

Also asked at: http://forum.arduino.cc/index.php?topic=539443 If you're going to do that then please be considerate enough to add links to the other places you cross posted. This will let us avoid wasting time due to duplicate effort and also help others who have the same questions and find your post to discover all the relevant information.

There's actually a library created by Pololu that is quite straightforward to use so you don't need to worry about any of that. I think it covers all available functionality.
https://github.com/pololu/vl53l0x-arduino
I was also a bit confused by the API comment and the datasheet.
I misread the device name so the above is not relevant.
In theory I think to use the API you can just #include the C code they provide into your sketch like a normal library. You can download the API code from the manufacturer ST here.
You'll need to give your name and email but it's free.
It's in C but you can probably understand it if you're familiar with Arduino/C++.
Before compiling you would also need to implement some I2C functions for which they provide prototypes (in the vl53l1_platform.c file). However, I think there are some additional steps when using C files that you will need to take to get this to compile, unfortunately I am not familiar with this so can't help - if anyone does then they can probably write a more complete answer.
The alternative is to write your own functions that replicate the functionality that is described in the API.
I would do this by looking at the basic process flow in the API User Manual, taking each function and working through the API files to see what it does.
The main thing you're looking for is the registers that you need to write (via I2C) in order to trigger a range measurement starting, and then the registers that you need to read to find out the result.
I would note that there are multiple levels of #defines for some of the register values and there is a lot of code that deals with managing the status of the device, so this might take a while.

Good find there. That should make life easier for them. I could find nothing to detail the registers on the ST site...

I try this VL53L0X library and change few functions but this library doesn't support in latest VL53L1X.


text:
Camera on mkr1000 or nodemcu 0.9
My question is: it is possible to connect camera on an Arduino/Genuino mkr1000 or to a NodeMCU 0.9?
If yes which one?
As far as I now ArduCam OV2640 has ported a library for ESP8266 (that is the chip inside the nodemcu)? Where can I find it and how does I plug the camera to the board?
Reading the camera user guide I've found that:

The ArduCAM mini can be used in any platforms like Arduino, [...] as long as they have SPI and I2C interface

Does one of these 2 board have both SPI and I2C interfaces
EDIT: Here I list my personal search with possible interesting results:

Here is a guide of arducam on ESP8266 module ESP-12E (My nodemcu is ESP-12)
Here another guide for ESP8266-12E

I hope that can be useful the wiring scheme to ESP8266-12E
     ArduCAM mini   ->    ESP8266-12E
         CS         ->        D0
        MOSI        ->        D7
        MISC        ->        D6
         SCK        ->        D5
         GND        ->       GND
         VCC        ->       3V3
         SDA        ->        D2
         SCL        ->        D1

Why the downvote?

Because you didn't do any research yourself. The linked MKR1000 site mentions it and figuring it out for the NodeMCU isn't hard either.

@gre_gor I've added also other research. I asked only if it was possible on my board. Everywhere I find only sketches and examples for ESP8266-12E. I cannot be sure if it works or not so I am asking here.
The question was if any cam is working there, my idea was the arducam that I linked. I make the question because it seems possible that the cam works but I've no certainty.
Sorry if I don't know what are those 2 interfaces but from wikipedia I don't understand much.
Tell me what do you want from me to prove that I made researches, I've linked all the stuff that can be useful.

There are a couple of levels of names in your question, so here are how they fit together:
ESP8266 - This is the bare chip found in the wide range of "esp8266"-based boards/modules/etc. The chip itself has no flash storage, no clock/oscillator, and no voltage regulation.
The I/O pins on the ESP8266 bare chip have labels like GPIO0, GPIO1, etc.

Chip outlined in Red is the ESP8266 alone.
So, to be of much use, the chips are often found on other modules along with flash memory, an oscillator, perhaps voltage regulation, a PCB antenna for the wifi portion, etc.
A popular "brand" of such module is the AI-Thinker modules, with names like

ESP-01
ESP-07
ESP-12
ESP-12E
ESP-12F

The different modules have different PCB sizes, but most notably, different numbers of pins from the actual ESP8266 chip brought out to the module's pins.
These often also call the I/O pins names like GPIO0, GPIO1, etc.

These ESP-xx modules, in turn, are often incorporated into larger modules that then add a USB-serial chip, LEDs, etc. One popular line are the NodeMCU series.
These modules provide different names for the I/O pins. NodeMCU in particular uses D0, D1, etc. and these don't correspond to the same numeric suffix as the bare chip. This chart gives the mappings for NodeMCU modules.

ANSWER
Thus, in the web page you linked about the ArduCAM and ESP8266, you can see a chart on the Hardware Connection of the the ArduCAM pins, and equivalent pins for both the NodeMCU-style pin names, and also the AI-Thinker and bare chip pin names.
The ESP-12 and ESP-12E both have the exact same ESP8266 chip inside, and the same amount of flash memory. There is no difference between them as far as connecting to the ArduCAM is concerned. The ESP-12E has a few more pins brought out to the headers than the ESP-12.
So, as long as you have D0, D1, D2, D5, D6, and D7 on a NodeMCU, OR GPIO4, GPIO5, GPIO12, GPIO13, GPIO14, and GPIO16 on the AI-Thinker module, then you can hook up the ArduCAM, as these are all the pins described in the hookup table.

Thank you for the explanation and the answer. This is far better than what I expected!