text:
Tx Rx Arduino uno
first of all let me thank you all , you have been of great help.
So, my problem is the next , i have note counter machine i need to read the data from the machine to the arduino , as bytes or ascii , just some readble data .
The machine is connected on the arduino via 2 pins , tx and rx and the data i am getting is not readble and kind of wierd , and one more question do i need some kind of serial shiled or no ?Because right now it is connected with just 2 wires . Thank you
#include <AltSoftSerial.h>

// AltSoftSerial always uses these pins:
//
// Board          Transmit  Receive   PWM Unusable
// -----          --------  -------   ------------
// Teensy 3.0 & 3.1  21        20         22
// Teensy 2.0         9        10       (none)
// Teensy++ 2.0      25         4       26, 27
// Arduino Uno        9         8         10
// Arduino Leonardo   5        13       (none)
// Arduino Mega      46        48       44, 45
// Wiring-S           5         6          4
// Sanguino          13        14         12

AltSoftSerial altSerial;

void setup() {
  Serial.begin(9600);
  while (!Serial) ; // wait for Arduino Serial Monitor to open
  Serial.println("AltSoftSerial Test Begin");
  altSerial.begin(9600);
}
byte rx_byte =0 ;
char text ;
char hex;
void loop() {
  if (altSerial.available()) {
    // get the byte from the software serial port

   rx_byte = altSerial.read();
    // send a byte to the software serial port
    //altSerial.println(text);
  Serial.print(rx_byte, HEX);

}
     //Serial.println("TUKA SUM");
      //text = altSerial.read();

    //hex=(text);

  //Serial.print(text);
    //Serial.write(text);
  // Serial.println(text);

What is the code? And what is the weird output?

Please provide a link to the note counter you are using.

Why are you using soft serial and not 'hardware' serial? What is the output? And are you sure 9600 is the correct speed?

AltSoftSerial Test Begin
00FE0F00000000000000000000000000000140B50000000000000000009C0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000083000830000B4AFB400002F90008000007F0042000091000E700E2FF00000F001E00FE0080000000000007DFC00F0000000008000FF

This is what i am getting , and link is http://souqmega.com/product/nc3500-ma-value-counting-machine/

and yeah i am sure because i can set the baud rate in the machine ,

A picture is of no use. Is there a manual or datasheet you can link to?

Is the connection to the machine UART or RS-232?

baud rate of what? the RX and TX pins are for external display

https://manualzz.com/doc/6360685/nc-3500-series-multi-currency-banknote-counter

Are you using the 9 pin or the 5 pin port?

try interchanging tx and rx pins it worked for me after interchanging those pins

I am using the 9 pin port , and from the tx and rx on the serial cable i am conecting them to the rx and tx on arduino , or 8 and 9 in the sketch , there is no shiled on the arduino for serial cable , just two wires .

You are still just printing human readable hexadecimal characters, just like in your earlier questions. And your output consists only of characters, that are used to represent hexadecimal values in human readable form. So what output were you expecting from it? As I see the code, you cannot get other output than this hex represetation.

The 9-pin port is designed for connecting to a printer. It uses the RS-232 protocol, not UART.
You cannot connect it directly to an Arduino - you must connect it via a MAX232 adaptor board.
Disconnect the cable immediately - the voltage levels of RS-232 are likely to do permanent damage to the Arduino.

Yeah i saw it somewhere , i disconeteced it , so in conclusion there is no way just two wires from serial cable to tx and rx on arduino ?

Nope. You need to transform the voltage levels from -10V/+10V to +5V/0V.

So without MAX232 adaptor board i can do the thing i want , Okey , thank you a  lot .


text:
ESP8266WebServer how to parse Json payload in post request that is bigger than the ram
I need to post a big json to the nodemcu server which would be bigger than the ram's size
I am using esp8266werserver and arduinojson libraries. I know how to use arduinojson to parse huge json response from other servers by parsing the response as a stream using response.getstream() . I can reuse a small static buffer in the stack to parse the whole json in a loop which performs really well.
But when I use nodemcu as a server, I can't find any similar method in the ESP8266WebServer to allow me to process json response as a stream. All I can only do is to read the string file in server.arg("plain") which may crash as the string may get bigger than the ram.
Is there a quick and dirty workaround? I look at the source in parsing.cpp there is a readBytesWithTimeout method that seems to be responsible to actually parsing the response stream. I am wondering if I may override this function to do what I need but I don't know how.
https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WebServer/src/Parsing.cpp

The ESP8266WebServer library can process only a HTML-Form POST request of application/x-www-form-urlencoded or mulripart/ content type.
You could sent the JSON as multipart 'upload' to save it to file, but it would require to build the multipart format of the POST body.
If you want to process POST with application/json content type, you could make a simple web server implemented with WiFiServer.

oh I didn't think about simply using WiFiserver. Seems like a nice workaround. Thanks so much for the suggestion.

But by the way what I will be missing if I use WiFiserver instead of the Esp8266webserver? Is the Esp8266webserver better optimised for the esp8266? Would like to know more about the trade off.

it depends how much of ESP8266WebServer functionality you use. ESP8266WebServer only wraps WiFiServer with HTTP and HTML-Form processing

Then seems like I should really look into WiFiserver instead thanks so much for your help Juraj

source: Stack Exchange

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

sort: votes


text:
expected ')' before executarAcao
here is the code:
#define pinSom 7
#define pinRele1 2
#define pinRele2 3
#define tempoMaximoDeUmaPalma 150 //milisegundos
#define tempoMaximoEntrePalmas 500 //milisegundos

int contaPalmas = 0;
long tempoEspera = 0;
long tempoEsperaEntrePalmas = 0;

void setup() {
  // put your setup code here, to run once:
    pinMode(pinSom, INPUT);
    pinMode(pinRele1, OUTPUT);
    pinMode(pinRele2, OUTPUT);
}

void loop() {{
  // verifica o estado do sensor de som (ele fica normalmente com
  int sensorSom = digitalRead(pinSom) ;

  //se o sensor detectou palmas
  if (tempoEspera == LOW) {

      //espera um tempo para não detectar a mesma palma mais de uma vez
    tempoEspera = tempoEsperaEntrePalmas = millis();
    contaPalmas++;
  }else if ((millis() - tempoEspera) >= tempoMaximoDeUmaPalma)
     tempoEspera = 0;
  }

    //caso exceda o tempo maximo entre palmas, zera o contador de palmas

    {

    if ( (contaPalmas != 0) && ((millis() - tempoEsperaEntrePalmas)
    (i get the error here) executarAcao();
    contaPalmas = 0;
    TempoEsperaEntrePalmas = millis();

 }
}
void executarAcao()
{
   switch (contaPalmas) {
    case 2:
      digitalWrite(pinRele1, !digitalRead(pinRele1));
      break;
   }

Your brackets are a mess.

Welcome to Arduino SE!! , I think you add more brackets on void loop() {{ line , please check again your code!!!

on SO such questions are closed as "typo error", because they are not worth an answer. answers are downvoted.

You're missing closing brackets in the line above your error.
It compiles now, but I have no idea whether it works as you intend.
Try forcing yourself to always open and close brackets when you begin one, and making sure to indent properly.
Also, Arduino code is case-sensitive.
#define pinSom 7
#define pinRele1 2
#define pinRele2 3
#define tempoMaximoDeUmaPalma 150 //milisegundos
#define tempoMaximoEntrePalmas 500 //milisegundos

int contaPalmas = 0;
long tempoEspera = 0;
long tempoEsperaEntrePalmas = 0;

void executarAcao()
{
  switch (contaPalmas) {
    case 2:
      digitalWrite(pinRele1, !digitalRead(pinRele1));
      break;
  }
}

void setup() {
  // put your setup code here, to run once:
  pinMode(pinSom, INPUT);
  pinMode(pinRele1, OUTPUT);
  pinMode(pinRele2, OUTPUT);
}

void loop() {
  // verifica o estado do sensor de som (ele fica normalmente com
  int sensorSom = digitalRead(pinSom);

  //se o sensor detectou palmas
  if (tempoEspera == LOW) {
      //espera um tempo para não detectar a mesma palma mais de uma vez
    tempoEspera = tempoEsperaEntrePalmas = millis();
    contaPalmas++;
  }
  else if ((millis() - tempoEspera) >= tempoMaximoDeUmaPalma) {
     tempoEspera = 0;
  }
    //caso exceda o tempo maximo entre palmas, zera o contador de palmas
  else {
    if ((contaPalmas != 0) && (millis() - tempoEsperaEntrePalmas)) {
      executarAcao();
      contaPalmas = 0;
      tempoEsperaEntrePalmas = millis();
    }
  }
}

This error means you did not close a pair of brackets, either {} or ().  The solution is to check through your code to make sure brackets are always in pairs.

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


text:
Problem with modbus communication between two arduinos when writing more than 27 registers
I have the following problem:
I want send 200 registers from a modbus master to a slave. Both are arduinos.
I can't send more than 27 registers. When I send more i get the Errorcode 255 which means timeout. I know that the modbus message is limited to 253 bytes (256 bytes - server address (1 byte) - CRC  (2 bytes)). Listed here: MODBUS APPLICATION PROTOCOL SPECIFICATION page.5
My setup:

I use two Arduino Mega 2560. One as a master and the other as the slave. If that works I want to use more than one slave. They are connected via Serial1 master TX1 (pin18) to slave RX1 (pin19) and master RX1 (pin19) to slave TX1 (pin18).
The modbus library I'm using is ModbusRtu.h from smarmengol.
Because i want to ultimately communicate with more than one slave device I use RS-485. To send the message as a broadcasat but thats not relevant now because first I want to send to one slave to test it out.

I know that the array is much bigger as the registers I want to send. Thats because I wanted to know when the the timeout happens. Sending 27 registers works fine and the slave recieves all of the 27. But when sending more than 27 registers I get the timeout and nothing will be send.
Master code
#define SERIAL_BUFFER_SIZE 256
#include "ModbusRtu.h"

#define Timeout 150
#define QUERYINTERVALL 50

/* Defined the buffersize as stated in
 * C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino\USBAPI.h
*/

modbus_t telegram;

// Test sending large array
uint16_t sendLargeArray[200] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
                                18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,
                                33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
                                48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62,
                                63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77,
                                78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
                                93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105,
                                106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117,
                                118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129,
                                130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141,
                                142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153,
                                154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165,
                                166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177,
                                178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189,
                                190, 191, 192, 193, 194, 195, 196, 197, 198, 199};

Modbus master;

void dataSend();

void setup()
{

 /**
 *  Modbus object declaration
 *  u8id : node id = 0 for master, = 1..247 for slave
 *  u8serno : serial port (use 0 for Serial)
 *  u8txenpin : 0 for RS-232 and USB-FTDI
 *               or any pin number > 1 for RS-485
 */
    master = Modbus(0, 1, 8); // this is master with RS-485 config
    master.begin(9600, SERIAL_8N2);
    master.setTimeOut(Timeout);
    Serial.begin(9600); // setup Serial for USB debugging
}

void loop()
{
    uint8_t error = master.getLastError(); //get errorcode
    uint8_t state = master.getState();     // get state from master 0 = idle 1 = waiting

    dataSend(); // function for sending array

    // Error Code
    Serial.print("Error code: ");
    Serial.print(error);
    Serial.println();

    // Print master state
    Serial.print("Master State: ");
    Serial.print(state);
    Serial.println();
}

void dataSend()
{
    uint8_t slaveId;
    uint8_t u8state;
    unsigned long u32wait;
    slaveId = 1;
    u32wait = millis() + QUERYINTERVALL;
    bool staywhile = true;

    // telegram for sending sendLargeArray
    telegram.u8id = 1;
    telegram.u8fct = 16;
    telegram.u16RegAdd = 0;
    telegram.u16CoilsNo = 28; // 27 or less works fine
    telegram.au16reg = sendLargeArray;
    u8state = 0;

    // Master broadcasts data
    while (staywhile)
    {
        switch (u8state)
        {
        case 0:
            if (millis() > u32wait)
                u8state++; // wait state
            break;
        case 1:
            master.query(telegram); // send query (only once)
            u8state++;
        case 2:
            master.poll(); // check incoming messages
            if (master.getState() == COM_IDLE)
            {
                u8state = 0;
                u32wait = millis() + QUERYINTERVALL;
                staywhile = false;
            }
            break;
        }
    }
}

Slave code
#define SERIAL_BUFFER_SIZE 256
#include "ModbusRtu.h"

/* Defined the buffersize as stated in
     * C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino\USBAPI.h
    */

// data array for modbus network sharing

uint16_t recieveLargeArray[200] = {};

 /**
  *  Modbus object declaration
  *  u8id : node id = 0 for master, = 1..247 for slave
  *  u8serno : serial port (use 0 for Serial)
  *  u8txenpin : 0 for RS-232 and USB-FTDI
  *               or any pin number > 1 for RS-485
 */
Modbus slave(1, 1, 8); // this is slave @1 and RS-485

void setup()
{
  Serial.begin(9600);
  slave.begin(9600, SERIAL_8N2); // baud-rate at 9600
}

void loop()
{
  uint8_t error = slave.getLastError();
  slave.poll(recieveLargeArray, 28); // receiving 27 or less registers works fine

  // print every 5th element of the recieved array
  // no spamming console that way
  Serial.print("Recieve: ");
  for (int i = 0; i < 200; i += 5)
  {
    Serial.print(recieveLargeArray[i]);
    Serial.print(",");
  }
  // Error Code
  Serial.println();
  Serial.print("Error code: ");
  Serial.print(error);
  Serial.println();

  memset(recieveLargeArray, 0, 200 * sizeof(uint16_t)); // recieveLargeArray = {}

}

Questions

Does anyone know why I cant send more than 27 registers?
Did anyone made a simillar project and can share the code?
Has anyone a fix for that?

Help is very appreciated.
Cheers ueberBrot
Link issuepage on ModbusRTU.h GitHub
Edit

Forgot to mention that I increased the buffer size inside the ModbusRTU.h library aswell. I did it like that #define MAX_BUFFER 256 as mentioned in this comment from Juraj
Changed the define location of #define SERIAL_BUFFER_SIZE 256 in both sketches to the top.

I did change the MAX_BUFFER inside ModbusRTU.h from 64 to 256. As you stated before in there its only the size for the used array. What I also did was move the #define SERIAL_BUFFER_SIZE 256 inside both my sketches to the top. That did nothing, After that I found a way to increase the RX and TX buffer size with the help of this post. I changed it from 64 to 256. maybe I could have changed those with a #define in my sketches aswell?.
Now I can send a max of 59 registers at once. Im not sure why I cant send more because the max should be 123 registers at once and the buffer is 256 bytes so  123 registers x 2 bytes = 246 is enough space in the buffer.

In ModbusRtu.h:
#define MAX_BUFFER 64 //!< maximum size for the communication buffer in bytes
27*2=54 bytes for registers and 10 for header and crc.
Change the MAX_BUFFER define. On Mega you have enough RAM.
btw: RS485 doesn't imply mandatory use of Modbus. You could use your own protocol.

Thank you for the answer @Juraj.
Oh sorry forget to mention that in the original post. After I increased the Arduino buffer size to 256 byte I did the same inside the ModbusRTU.h library #define MAX_BUFFER 256  . So thats not the problem.
Using my own protocol what do you mean by that? I dont have a clue how to do that so Im guessing its either not in my skillrange or I simply dont know where to begin. Can you explain or point me to an example? That I could use for my ultimate goal a master with many slaves?
Cheers ueberBrot

if it allows only 27 registers, then it didn't apply. what "Arduino buffer"?

In the file ***\Arduino\hardware\arduino\avr\cores\arduino\USBAPI.h the SERIAL BUFFER SIZE (Arduino buffer) is defined from line 77 to 86. If the buffer is not defined like I did in my sketches #define SERIAL_BUFFER_SIZE 256 it has two default values 16 or 64 byte dependening of the Arduino RAM. Or is this wrong?

not wrong, but not needed. The Serial buffer is really a 'buffer'. If full, write() waits a little until there is space (bytes are send out continuously). The buffer in ModbusRtu.h is not a real buffer, it is an array to build the complete message.

Ah ok thought it may be connected to my problem thats why I increased it. If the change I did inside the library did not apply how is that? Do you have a clue?

did you change the define inside ModbusRtu.h? in your sketch it is too late.


text:
Adding POE to Ethernet Board
If I was to use the Arduino A000024, would I be able to add a POE MODULE to the board to get a Ethernet board with POE to run my arduino project?

why not buy A100025 - Ethernet shield with POE?

Can't find a reliable reseller for that retired board.

If the pinout is what the Ethernet shield expects, then yes. The rows of holes at an odd angle are designed for a POE board similar to that. I can't vouch for whether the pinout is correct though.  It looks ok, but it depends on the dimensions of the board whether it fits the existing pinout.

I found the suggested POE module on another site that fits the pinning on this board, thank you for confirming this.


text:
How can I have code in a project that won't compile for Arduino?
I want to test the algorithms in my code without needing to send it to an actual Arduino board. I figured I could lay out my project like:
project/
    core.cpp      # core algorithms
    core.h        # header for core.cpp
    project.ino   # Arduino setup() loop() calling into core
    pc-main.cpp   # main(argv) calling into core

However, when I do this, the Arduino IDE wants to compile pc-main.cpp, which won't work since it uses stdio and all that. What can I do instead?
Is there a way to hide a file from the build, other than changing the extension which would inconvenience other editors and compilers? Is there a different standard approach to this kind of problem?

What I've thought of:

I could put pc-main.cpp in another directory and have the build for it refer to the files in the Arduino project directory, but that seems awkward and I'd like a more elegant solution.
I could symlink the core.* files into the Arduino project directory from elsewhere, but that would also be inelegant, and inconvenience Windows users should one want to compile the project.
I could put an #ifdef around the contents of pc-main.cpp, but I haven't found a suitable #define to check for, other than board-specific ones.

I don't want a solution which requires extra steps for each build; the whole point of trying to do this is fast and easy development.
I would also prefer one which does not bring in a whole additional build system, testing framework, or IDE; for example, I found arduino_ci and PlatformIO while researching this question. I'll switch to looking at such options if there isn't a good solution to the problem as I've stated it here.

[My question is arguably the same as Project structure to build for PC and Arduino at a high level, but the question and answer there are broad and about organizing modules and not how to make the build actually work.]

I would use conditional compilation, like this:
#ifndef(ARDUINO)
// Non-Arduino code.
#endif

Thanks. Is there official documentation that specifies this #define exists?

You can add the #define to your code and manually change it when you change environments. You can look up Arduino compiler predefined symbols. Or you can tweak the IDE's compiler command to include "-DSYMBOL_OF_MY_CHOICE" which would define your symbol during an IDE compile and presumably be undefined in your desktop environment.

To be clear, I found that ARDUINO is already defined and I didn't need to configure anything, so Edgar's code works exactly as written. I'm asking if there's documentation for it, as I think the answer would be even better with a link.

@KevinReid: I didn't find it in a doc (although it's mentioned here), but in a Makefile intended to emulate the Arduino IDE.


text:
How to upload a sketch to Arduino if it goes to deep sleep mode quickly
I have created sketch where Arduino goes to powerdown mode in about 1s after boot. Now I can not upload other sketch, because programmer does not get proper response. I tried to hold reset and release it at various stages during compile/upload, but it does not help. I suspect the programmer needs to communicate with Arduino for several seconds. Any advice how to erase the sketch without programmer, or how to ban the sleep mode? It is Pro Mini 168. Thanks

Hold the reset button while you start the upload. Wait until you upload first tries to connect to the Arduino, then release the reset.
If you can't get that to work, the next option is to load another Arduino with the ArduinoISP example sketch, connect the two as described in the comments, and use the 2nd Arduino to program yours.
Update:

Would another Arduino overcome this problem?

Ok, then it's time for plan B. Using a programmer (real, or simulated by another Arduino) doesn't depend on the 'failing' Arduino's bootloadloader but uses a direct (SPI) interface to program it. This article has more information.

Thanks for the response but I have tried to hold reset many times and Arduino never synchronized. I think it goes to sleep despite the data ready signal on programming interface. Would another Arduino overcome this problem? Sorry but I do not see any comments you refer to by "connect the two as described in the comments". Jan

Turn on Verbose output (Under File:preferences).
Press & hold the Reset button. After the compilation ends, you will see a message like:
"Compiled xxx of 32xxx bytes".
That's when the download starts - release reset.
It make take a few tries to get the timing of the release correct.
If you can't get the reset to take hold, then it's time to reburn the bootloader using a Programmer connected to the ICSP pins.


text:
Hot Swap Sensor
Is there a way to have a sensor be hot swappable, as in it can be disconnected and reconnected without locking up the Arduino? I have an I2C sensor that I want to be able to disconnect and reconnect without having to restart the board.

The i2c bus is not meant to have sensors disconnect and connect, but I think it can be done. Poll the sensor a few times per second and if it is reconnected, then initialize the sensor. Why do you want to do that? Is there an other way?

I am making a sensor that goes onto a filter loader and just wanted to make sure if the sensor got disconnected that it could be reconnected without issue or having to reset it. This is for a remote device from my office and I won't always be the one dealing with it.

Please see https://arduino.stackexchange.com/questions/31924/how-to-setup-an-i2c-bus-which-stays-valid-if-a-slave-is-powered-down-or-fails/31940#31940

The I2C bus is not blocking the operation, if the sensor isn't there. Also the Wire library will not block in this case. It will just return an error code, which you should handle in your code.
But this doesn't mean, that every library, which wraps the I2C workload for a specific sensor, is doing the same. Depending on the sensor and the used library you will have to check yourself, if it is blocking in any way. (This part is not better answerable without information on what sensor and what library will be used)
So: Yes, this is totally possible, but you will have to deal with the errors from disconnecting the sensor and handle them in your code. By polling the sensor in a regular fashion (like Jot mentioned in the comments) will give you the information, if there is a sensor with this address on the bus. The Wire.endTransmission() method will return 2 (received NACK on transmit of address), if no device with the specified address is reachable on the bus.
Depending on the used sensor, you might have to initialize the sensor correctly after every reconnect. Especially, if the disconnect happend during a transmission. Refer to the datasheet of the sensor to find out, what happens in this case with the sensor.
If you plan to use different sensors, you have to check for their specific addresses (since different types of sensor often have different hardwired addresses/address spans) and - if the sensors are controlled differently - determine, what sensor is actually connected. The least may be possible by reading their status registers, which can work for many sensor types.


text:
Turn infrared LED on and off in order to simulate an infrared signal
Note I am able to send and recieve IR signals. This question is only for purposes of learning.
When using the existing library #include <IRremote.h> it is very simple to read and transmit infrared signals. However I will like to send the signals myself with digitalWrite(pin, HIGH);
1) Receive an infrared signal from a remote control in order to clone it and send it later with Arduino.
For this to work I have purchased an infrared LED.
I connect the left leg of the IR LED to pin 11, the middle leg to the ground and the right leg to 5 volts.
Then I upload the following sketch to arduino:

#include <IRremote.h>

int receiverpin = 11; // left leg of IR receiver is connected to this pin

IRrecv irrecv(receiverpin);
decode_results results;

void setup() {
  pinMode(receiverpin, INPUT);
  Serial.begin(9600);
  irrecv.enableIRIn();
}

void loop() {
  if (irrecv.decode(&results))
  {
    Serial.println(results.value, HEX);
    irrecv.resume();
    delay(150);
  }
}

When I run that and press the power button of my samsung remote control this is what I capture through serial:
Encoding  : SAMSUNG
Code      : E0E040BF (32 bits)
Timing[67]:
 +4500, -4500     + 550, -1650     + 550, -1700     + 550, -1700
 + 550, - 600     + 500, - 550     + 550, - 550     + 550, - 600
 + 550, - 550     + 550, -1700     + 550, -1650     + 550, -1700
 + 550, - 550     + 550, - 550     + 550, - 600     + 550, - 550
 + 550, - 550     + 550, - 600     + 550, -1650     + 550, - 600
 + 550, - 550     + 550, - 550     + 550, - 550     + 550, - 600
 + 550, - 550     + 550, -1700     + 550, - 550     + 550, -1700
 + 500, -1700     + 550, -1700     + 550, -1650     + 550, -1750
 + 500, -1650     + 550
unsigned int  rawData[67] = {4500,4500, 550,1650, 550,1700, 550,1700, 550,600, 500,550, 550,550, 550,600, 550,550, 550,1700, 550,1650, 550,1700, 550,550, 550,550, 550,600, 550,550, 550,550, 550,600, 550,1650, 550,600, 550,550, 550,550, 550,550, 550,600, 550,550, 550,1700, 550,550, 550,1700, 500,1700, 550,1700, 550,1650, 550,1750, 500,1650, 550};  // SAMSUNG E0E040BF
unsigned int  data = 0xE0E040BF;

What is this supposed to mean. How can I conver this to 0s and 1s?
2) Sending cloned signal from arduino.
Now if I want to power on my TV with arduino I will need a Infrared LED. I will connect pin 3 to the long leg of my LED and ground to the short leg. Once I pefrom that connection I will run this sketch:
#include <IRremote.h>

IRsend irsend;

void setup() {}

void loop() {

  irsend.sendSAMSUNG(0xE0E040BF, 32); //Power Code
  delay(1000); // try again in 1 second

}

Note this code works and my TV powers on with my Arduino!
3) Now my question
It was very simple to read and transmit infrared signals using IRremote.h header.The only thing I had to do was capture 0xE0E040BF that I got when reading the infrared signal and use that hex code on part 2. From reading on the internet I have researched that sending an IR signal is just turning and IR LED on and off very fast (38khz). How can I tranlate what I read:
 rawData[67] = {4500,4500, 550,1650, 550,1700, 550,1700, 550,600, 500,550, 550,550, 550,600, 550,550, 550,1700, 550,1650, 550,1700, 550,550, 550,550, 550,600, 550,550, 550,550, 550,600, 550,1650, 550,600, 550,550, 550,550, 550,550, 550,600, 550,550, 550,1700, 550,550, 550,1700, 500,1700, 550,1700, 550,1650, 550,1750, 500,1650, 550};

To 0s and 1s and then send that hard coded for puposes of learning.
Acording to this link: http://www.remotecentral.com/cgi-bin/codes/samsung/tv_functions/
The infrared code to power on a samsung tv is:
0000 006d 0022 0003 00a9 00a8 0015 003f 0015 003f 0015 003f 0015 0015 0015
0015 0015 0015 0015 0015 0015 0015 0015 003f 0015 003f 0015 003f 0015 0015
0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 003f 0015 0015 0015
0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0040 0015 0015 0015 003f
0015 003f 0015 003f 0015 003f 0015 003f 0015 003f 0015 0702 00a9 00a8 0015
0015 0015 0e6e

I have converted that to binary and it comes to be:
000000000000000000000000011011010000000000100010000000000000001100000000101010010000000010101000000000000001010100000000001111110000000000010101000000000011111100000000000101010000000000111111000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000111111000000000001010100000000001111110000000000010101000000000011111100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000111111000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000010000000000000000010101000000000001010100000000000101010000000000111111000000000001010100000000001111110000000000010101000000000011111100000000000101010000000000111111000000000001010100000000001111110000000000010101000000000011111100000000000101010000011100000010000000001010100100000000101010000000000000010101000000000001010100000000000101010000111001101110

Now every time I see a 0 I will power off the LED and every time I see a 1 I will power on the LED waiting about 10 microseconds in order to have a frequency of 38khz This is how my sketch looks like:
int pinSend=3;
char data[1248] = "000000000000000000000000011011010000000000100010000000000000001100000000101010010000000010101000000000000001010100000000001111110000000000010101000000000011111100000000000101010000000000111111000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000111111000000000001010100000000001111110000000000010101000000000011111100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000111111000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000010000000000000000010101000000000001010100000000000101010000000000111111000000000001010100000000001111110000000000010101000000000011111100000000000101010000000000111111000000000001010100000000001111110000000000010101000000000011111100000000000101010000011100000010000000001010100100000000101010000000000000010101000000000001010100000000000101010000111001101110";
int waitTimeInMicroseconds = 5; // counter to try with different wait times in order to see what frequency works best

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

void loop() {

  Serial.print("Starting sending IR signal waiting ");
  Serial.print(waitTimeInMicroseconds);
  Serial.println(" microseconds");

  int len = sizeof(data);

  for(int i=0; i<len; i++)
  {
    if( data[i] == '0') // if 0 turn off LED
    {
      digitalWrite(pinSend,LOW);
    }
    else // else turn ON LED
    {
      digitalWrite(pinSend,HIGH);
    }

    delayMicroseconds(waitTimeInMicroseconds); // wait in microseconds
  }

  Serial.println("Done! Is TV on??????");
  delay(1000); // wait 1 second for next atempt

  waitTimeInMicroseconds++; // next time try with different wait time

}

When I run that code the TV does not turn on why? How can I hard code the 0s and 1s for purposes of learning?

Honestly, I almost always go to the web to find the exact codes for the different remote controls and devices I have.  Getting an approximate code is fine.  But if it is at the edge of being correct - who knows - maybe that will create times when the Ardunio appears not to work as well as the original remote control.

The embedded delay in your code waits 150ms each iteration.  But you are also executing code which takes its own time.  The error will accumulate as time goes on.  Causing any attempt at recreating the signal to be more off the longer the signal is.  It would be better to execute the sampling based on a hardware timer interrupt.

The receiver is more than just a photo diode.  The receiver demodulates the 38KHz signal.  To recreate the signal you need to turn the IR LED on and off at 38KHz and turn that signal on and off using the pattern you recorded at the output of the receiver.

To recreate the 38KHz signal, you would have to complete a loop of your code ever 13.158us.  That needs to include the time it takes to execute the code.  Likely the real driver does not bother with this.  Instead, code can configure the PWM hardware to generate a continuous 38KHz.  Then the code would only be tasked with modulating the 38KHz code.

Glad I came across your post.Hoe you can help me out:
how the hex data (0xE0E040BF) corresponds to the rawData? Is the raw data time of high and low? or rather difference?
Do you have a way to convert the hex to rawData ?
Thanks

@Pixelowsky, do not ask questions in comments. You wIll not get answers. Ask a new question instead.

Finally managed to figure it out without using any library. This is how I turn on my TV:
int pinSend=3;
int waitTimeInMicroseconds = 33; // counter to try with different wait times in order to see what frequency works best
unsigned int  rawData[67] = {4500,4500, 550,1650, 550,1700, 550,1700, 550,600, 500,550, 550,550, 550,600, 550,550, 550,1700, 550,1650, 550,1700, 550,550, 550,550, 550,600, 550,550, 550,550, 550,600, 550,1650, 550,600, 550,550, 550,550, 550,550, 550,600, 550,550, 550,1700, 550,550, 550,1700, 500,1700, 550,1700, 550,1650, 550,1750, 500,1650, 550};

int isOn =1;

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

void loop() {

    Serial.print("starting with ");
    Serial.println(waitTimeInMicroseconds);

    for(int jj=0; jj<16; jj++)
    {
    for(int i=0; i<67; i++)
    {
        if(isOn==0)    {
          isOn=1;

          int x=0;

          while(true)
          {
            digitalWrite(pinSend,HIGH);
            delayMicroseconds(waitTimeInMicroseconds); // wait in microseconds
            digitalWrite(pinSend,LOW);
            delayMicroseconds(waitTimeInMicroseconds); // wait in microseconds

            x=x+waitTimeInMicroseconds+waitTimeInMicroseconds;

            if(x > rawData[i])
            {
              break;
            }
          }

        }
        else{
          isOn=0;
          delayMicroseconds(rawData[i]);
        }

    }
    }

    delay(2500);
    //waitTimeInMicroseconds++;

}


text:
Eclipse Arduino Leonardo Pro Micro ATMega32U4 Programming Issue
Help Needed as I am little bit lost. I've procured a Pro Micro Board from sparkfun. Great little board and it work like clock work when using the standard Arduino Programming IDE.
Well Copied the code thru to the Eclipse Project, Hit compile and all seems well. But Trying to write the code to the device the following happens.

avrdude: Version 6.3-20171130
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch
     System wide configuration file is "C:/Users/vente/.arduinocdt/packages/arduino/tools/avrdude/6.3.0-arduino14/etc/avrdude.conf"

     Using Port                    : COM5
     Using Programmer              : avr109
     Overriding Baud Rate          : 57600
     AVR Part                      : ATmega32U4
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PA0
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
       lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : butterfly
     Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
Found programmer: Id = "F"; type = @
    Software Version = �.u; Hardware Version = �.
avrdude: butterfly_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: programmer did not respond to command: leave prog mode
avrdude: butterfly_recv(): programmer is not responding
avrdude: error: programmer did not respond to command: exit bootloader
avrdude done.  Thank you.

I've setup the Programming interface a as a Leonardo Board. AVR ISP.
For some reason It seems as if and it might be me that the usb does not reset? and go into programming mode.
Please Help

I am not familiar with that programming environment, but to enter the bootloader on those boards you have to open the serial port at 1200 baud then close it again. Normally the Arduino IDE does that for you. Does this system? Possibly not.

I assume you use Eclipse Sloeber plugin for Arduino. For serial upload over USB using bootloader choose programmer Default. All other programmers are for flashing over ICSP.

Okay I have installed version 2018-09 (4.9). The Toolset loaded is Arduino C++ Tools 9.5.3.201809121146. It was loaded with the help of the Yatta Plug-in interface. Under the Board  Configuration I Do not have the option to Select DEFAULT

So you don't use Sloeber Arduino Eclipse plugin

Just Re-installed  my Eclipse and found Mutiple Issues.The Path was to long under windows and this caused Sloeber not to install. I moved it and all seems to be fine now. Thanks

@MarthinusVenter, now I don't know. did my answer help or the problem was something else?


text:
How to set time for 15 seconds
When user used one password after close the servo the password will valid for 15 seconds then it will not work. Other 9 will be same process
Here is code I need just this to set
int locker = 13;
int lockerState = 0;
const int buzzer = 49;
String readString;

#include <Servo.h>
Servo myservo;
int pos = 0;

void setup() {
  Serial.begin(9600);
  pinMode(locker, OUTPUT);
  pinMode(buzzer, OUTPUT);
  myservo.attach(9);
}

void loop() {
  lockerState = digitalRead(locker);
  while (Serial.available()) {
    delay(3);
    char c = Serial.read();
    readString += c;
  }

  if (readString.length() >0) {
    Serial.println(readString);
    if ((readString == "2028") || (readString =="1234") || (readString =="1294") || (readString =="4795") || (readString =="5651") || (readString =="7616") || (readString =="5648") || (readString =="1487") || (readString =="7095") || (readString =="2554"))
    {
      digitalWrite(locker, HIGH);
      for (pos = 0; pos <= 180; pos += 1) {
      myservo.write(pos);
      delay(30);
      }
      delay(5000);
      digitalWrite(locker, LOW);
      /* for (pos = 180; pos >= 1; pos -= 1) {
      myservo.write(pos);
      delay(30);
      } */
      readString="";
    }
      /* else if (readString == "proceed") {
        digitalWrite(locker, HIGH);
        for (pos = 0; pos <= 180; pos += 1) {
        myservo.write(pos);
        delay(30);
        }
      digitalWrite(locker, LOW);
      readString="";
      } */
      if (readString == "decline") {
         digitalWrite(locker, HIGH);
         for (pos = 180; pos >= 0; pos -= 1) {
         myservo.write(pos);
         delay(30);
         }
      digitalWrite(locker, LOW);
      readString="";
      }

    else {
      tone(buzzer, 500);
      delay(1000);
      noTone(buzzer);
      delay(1000);
      readString="";
  }
 }
}

In programming, there are many cases where designing data structures is
more important than the code itself. Once you have a data structure that
makes sense, the code flows very naturally. I think this is one of those
cases, so let's start by looking at what data you have to store for each
of your passwords:

the password itself (let's call it the code)
whether it has ever been used and, if so, whether it has expired
if it has been used but has not expired yet: when it was used for the
first time

This can be saved in an object with the following data fields:
const char * const code;
enum { UNUSED, USED, EXPIRED } status;
uint32_t first_use;  // valid if status == USED

Now think about what kind of actions you want to perform on such a
password:

you want to be able to test whether it matches some user entry
you want check whether it can be used and, if so, take note that it is
being used

Based on these requirements, I propose the following class:
const uint32_t PASS_LIFE_TIME = 15000;

class Password {
public:
    Password(const char *c)
        : code(c), status(UNUSED) {}
    bool matches(const char *entry) {
        return strcmp(code, entry) == 0;
    }
    void update() {  // expire if it needs to be
        if (status == USED && millis() - first_use > PASS_LIFE_TIME) {
            status = EXPIRED;
        }
    }
    bool use() {  // returns true on success
        if (status == UNUSED) {
            status = USED;
            first_use = millis();
        }
        update();
        return status != EXPIRED;
    }
private:
    const char * const code;
    enum { UNUSED, USED, EXPIRED } status;
    uint32_t first_use;  // valid if status == USED
};

Now you need to store all the passwords in an array, and a couple of
functions to operate on the password collection as a whole:
const int PASS_COUNT = 10;

Password passwords[PASS_COUNT] = { "2028", "1234", "1294",
    "4795", "5651", "7616", "5648", "1487", "7095", "2554" };

void update_all_passwords()
{
    for (int i = 0; i < PASS_COUNT; i++)
        passwords[i].update();
}

// Returns true on success, and uses the matching password.
bool try_entry(const char * entry)
{
    for (int i = 0; i < PASS_COUNT; i++)
        if (passwords[i].matches(entry))
            return passwords[i].use();
    return false;  // no match found
}

The function update_all_passwords() is meant to be called on each
iteration of loop(). It may seem superfluous, as a password is updated
whenever you try to use it. However, without regular updating, a used
password could be reused 49.7 days later, because of the millis()
rollover.
Now, in your program, you just need to:

Put a call to update_all_passwords() at the beginning of loop()
Replace the big condition that tests for a valid password by
if (try_entry(readString.c_str()))

Good answer! I would add, that it is not a good practice to use delay(). I think it's worth mentioning, that the coding style from the BlinkWithoutDelay example is way better (which you already used in your code, but the OP didn't), and will help especially when adding more functions to the code.


text:
Not receiving data from NRF24L01
I'm trying to send data from one Arduino board to another using NRF24L01 connect to the two ends of the two Arduino boards. The Tx blinks in the transmitting end(Arduino board 1) but the receiving end(Arduino board 2) is not getting any value from it. Here is my code.
Transmitting end (Arduino board 1)
#include <SPI.h>
#include "RF24.h"

RF24 myRadio(0, 1);
byte addresses[][6] = {"0"};

struct package
{
    int id = 1;
    float longitude = 0.0;
    float latitude = 0.0;
    char text[100] = "Geographic coordinates";
};

typedef struct package Package;
Package data;

void setup()
{
    Serial.begin(115200);
    delay(1000);
    myRadio.begin();
    myRadio.setChannel(115);
    myRadio.setPALevel(RF24_PA_MAX);
    myRadio.setDataRate(RF24_250KBPS);
    myRadio.openWritingPipe(addresses[0]);
    delay(1000);
}

void loop()
{
    myRadio.write(&data, sizeof(data));

    Serial.print("\nPackage:");
    Serial.print(data.id);
    Serial.print("\n");
    Serial.println(data.longitude);
    Serial.println(data.latitude);
    Serial.println(data.text);
    data.id = data.id + 1;
    data.longitude = data.longitude + 0.1;
    data.latitude = data.latitude + 0.1;
    delay(1000);
}

Receiving end (Arduino board 2)
#include <SPI.h>
#include "RF24.h"

RF24 myRadio(7, 8);
struct package
{
    int id = 0;
    float longitude = 0.0;
    float latitude = 0.0;
    char text[100] = "empty";
};

byte addresses[][6] = {"0"};

typedef struct package Package;
Package data;

void setup()
{
    Serial.begin(115200);
    delay(1000);
    myRadio.begin();
    myRadio.setChannel(115);
    myRadio.setPALevel(RF24_PA_MAX);
    myRadio.setDataRate(RF24_250KBPS);
    myRadio.openReadingPipe(1, addresses[0]);
    myRadio.startListening();
    delay(1000);
}

void loop()
{

    if (myRadio.available())
    {
       while (myRadio.available())
       {
           myRadio.read(&data, sizeof(data));
       }
        Serial.print("\nPackage:");
        Serial.print(data.id);
        Serial.print("\n");
        Serial.println(data.longitude);
        Serial.println(data.latitude);
        Serial.println(data.text);
    }

}

This is how i connected the Arduino and NRF24L01

Any reason why im not getting the the data from the transmitting end?

try myRadio.readBytes(&data, sizeof(data)); What nRF24 library you use?

@Juraj RF24.h by TMRh20

it doesn't implement Stream so it doesn't have readBytes

@Juraj you mean like myRadio.available() >= sizeof(data) ?

it will not work. I deleted the comment. the struct is bigger then the receive buffer

it can transfer only 32 bytes payload. send and receive the data in 32 byte parts

So should i change the struct?. This worked few weeks ago and now it is not. i bought new Arduino and NRF24 module still no luck :(

with the same library and this struct? perhaps it worked, but it didn't transfer the whole char array

change while (myRadio.available()) to if (myRadio.available())

Check the reading and writing pipe addresses.
First, the default is 0xE7E7E7E7E7 for pipe 0 (RX_ADDR_P0) and 0xC2C2C2C2C2 for pipe 1 (RX_ADDR_P1), see the data sheet.  Check that the transmitter (TX) address is the same as the receiver
(RX) pipe address.
Secondly, you should not set the pipe address to 0x0 even if that's common between the TX and RX.  This note comes from the data sheet:

Addresses where the level shifts only one time (that is, 000FFFFFFF) can often be detected in
  noise and can give a false detection, which may give a raised Packet Error Rate. Addresses
  as a continuation of the preamble (hi-low toggling) also raises the Packet Error Rate

Actually the pipe address is "0" which is a string with implicit null terminator, which corresponds to 30 00 - which is still as bad. Also I don't know how the library fills up the missing 3 bytes from the address. In any case not knowing the real address can be troublesome. Better try something like "Link1" or something with 5 characters.


text:
Capturing interrupt on both edges when it's set on RISING or FALLING
I've been trying to capture rising edge of an IR sensor output. This sensor's Vcc connected to Arduino 5V and it has a digital output pin. I've observed the digital output pin on an Oscilloscope. It's not noisy.
When I attach a rising edge interrupt on digital pin 2. It somehow captures both rising and falling edges. This response is the same for when it's set for FALLING or CHANGE.
I've tried code at below both on Arduino Uno and
volatile bool caughtAnInterrupt = false;

void setup() {

  Serial.begin (19200);

  pinMode(2, INPUT);

  attachInterrupt(digitalPinToInterrupt(2), test, RISING);
}

void loop() {

  if (caughtAnInterrupt){

    Serial.println("Rising edge detected");

    caughtAnInterrupt = false;
  }
}

void test() {

  caughtAnInterrupt = true;
}

How much time between rising and falling edges, and what are you detecting, a square edge?

@MichaelT IR sensor outputs digital high when it has a object in front of it. So, it might be any time between rising and falling edges. As I specified in the answer, I found the solution. Probably I didn't observed signal properly on Oscilloscope and the signal had debouncing problem.

I've solved the issue with the reply by eventHandler to another post. Here it is;

The problem you are having is because the button glitches are
  producing many interrupts on each button press. You can find a good
  description and a way of solving it using hardware here.
Let me explain, when you press the button, the mechanical contact will
  have a transcient state in which it will fluctuate ON-OFF for a short
  period of time. The same effect might happen when you release the
  button.
One way of solving this problem is using a capacitor parallel to the
  load. Another "easier" way would be done by software. The idea is to
  set a fixed arbitrary time in which you don't allow new interrupts.
  You could use the millis() or micros() library to set this time. The
  code would look something like this.
unsigned long lastInterrupt;

void ngt()
{

  if(millis() - lastInterrupt > 10) // we set a 10ms no-interrupts window
    {

    state = !state;

    lastInterrupt = millis();

    }
}

This way you don't process new interrupts until 10ms have elapsed.
Note: adjust the time to your requirements.


text:
How to read sound sensor readings and light up sensor with water sensor if the readings is above threshold & when water is detected for 2 mins?
I am student that is new to Arduino and working on a project to trigger an alert if the sound level detected exceeds the threshold for a period of 2 mins. But I am stuck, would like to check how do I write a code to analog read sound sensor input and light up sensor if the readings is above datum for 2 mins? I had simple code but it triggers the light up immediately. :/
I have combined the coding together and this is the new code that worked with the help gotten:
    #define led 4 // led to D4
const int soundsensor= A0; //sound sensor to A0
const int threshold= 100; // to set the threshold value for sound sensor
int ssanalogread; //name of sound sensor analog read
bool wasOver;//add to globals
unsigned long firstDetect;

void setup() {
  Serial.begin(9600);
  pinMode(led,OUTPUT);
  pinMode(soundsensor,INPUT);// to get input from sound sensor

} // end void setup

void loop() {

     sound1();

} // close void loop

void sound1() {

  ssanalogread=analogRead(soundsensor); // reads analog data from sound sensor
  Serial.println(ssanalogread);

   if ((ssanalogread > threshold)){ //replace if else
      if(!wasOver){
       firstDetect = millis();
   }
   if(millis() - firstDetect > 1*10*1000){
      digitalWrite(led,HIGH); //turns led on if the sensor reads more than threshold
   } //end if
      wasOver = true;
   } // end first if
  else {
     wasOver = false;
     digitalWrite(led,LOW);
  } // end else

} //end loop

//this code works and is ok to run. can adjust the timing

What "sound sensor" are you using?

Hi i am using grove sound sensor: http://wiki.seeedstudio.com/Grove-Sound_Sensor/
and grove water sensor: http://wiki.seeedstudio.com/Grove-Water_Sensor/

You set a timestamp when the sound first exceeds the threshold and only set the output high when millis() - firstDetect > 2*60*1000
//add to globals
bool wasOver;
unsigned long firstDetect;

//replace if else
if ((ssanalogread > threshold)){
   if(!wasOver){
       firstDetect = millis();
   }
   if(millis() - firstDetect > 2*60*1000){
      digitalWrite(led,HIGH); //turns led on if the sensor reads more than threshold
   } //end if
   wasOver = true;
} else {
   wasOver = false;
   digitalWrite(led,LOW);
}

Hi Ratchet, thank you so much for your enlightenment! I have combine your coding together with mine (edited in original post), however there's an error message of : "exit status 1 Error compiling for board Arduino/Genuino Uno." :/ Not sure if i defined now() correctly...

@rachetfreak is confusing now() and millis().

@hmppp sorry I did indeed mix up now() and millis(). It's fixed now in the answer.

@rachetfreak and Majenko thanks both for the prompt assistance! i couldn't get the led to light up for this code after 2 mins. It was observed from the serial monitor that the data was about 270++. had adjusted my threshold to 200, however the light sensor still couldn't light up. I am using Grove base shield for this.

@rachetfreak, tried with 10s function, am able to get it uploaded and worked! thank you so much :)

This is actually a lot harder than you might at first think.
Your "sound sensor" is little more than a microphone and amplifier. It gives you an audio waveform - whereas what you are interested in is the peak power.
An audio waveform goes both positive and negative:

The "peak" of the waveform can both be positive (above the line) or negative (below the line).
To get that peak you have to rapidly sample over a short period and find both the maximum and minimum values, and get the difference between them.
However, the Arduino can't see negative values on the ADC - so you only get the upper portion of the waveform, which is less than ideal.  Really you should add a DC offset to the output of the sound sensor to bring the signal up to the middle of the ADC range (adding a 10kΩ + 10kΩ voltage divider across the input pin to +5V/GND would do the job).
If you don't add a DC offset then you can rapidly sample for a short period of time and work out the maximum value:
uint16_t getMaximum(uint8_t pin, uint32_t t) {
    uint16_t maximum = 0;
    uint32_t ts = millis();
    while (millis() - ts < t) {
        uint16_t sample = analogRead(pin);
        if (sample > maximum) {
            maximum = sample;
        }
    }
    return maximum;
}

Now to get the maximum over, say, a 10ms period, you can:
uint16_t maximum = getMaximum(A0, 10);

However, if you add a DC offset it gets a little more tricky, but the results will be better:
uint16_t getMaximum(uint8_t pin, uint32_t t) {
    int16_t maximum = 0;
    int16_t minimum = 0;
    uint32_t ts = millis()
    while (millis() - ts < t) {
        // The -512 here removes the DC offset from the reading. 512 is half
        // the ADC range.
        int16_t sample = analogRead(pin) - 512;
        if (sample > maximum) {
            maximum = sample;
        }
        if (sample < minimum) {
            minimum = sample;
        }
    }

    // We now have a positive value as the maximum and a negative
    // as the minimum - or zero if none went into the max or min
    // region of the waveform.  Subtract a negative from a positive
    // is like adding a positive to a positive.  But we only want
    // a positive result, so we'll get the absolute value.
    return abs(maximum - minimum);
}

Now that you actually have your peak-peak value of your waveform over a short period you can use it to work out when the sound goes above a threshold and when it goes below, and how long it's been above that threshold.  The basic method is:

Is the sound above the threshold?

Yes: Was it above the threshold before?
No: Set a timestamp and a flag to say it's above the threshold.
Yes: Has it been above > 2 minutes?

Yes: light the LED

No: Was it above the threshold before?
Yes: Has it been above > 2 minutes?

Yes: Extinguish the LED

The thing here is to know that you are looking for changes in the "above the threshold" state to start your timing.  A simple implementation may look like:
static uint32_t wentAbove = 0;
static bool isAbove = false;
const uint16_t threshold = 300;

uint16_t maxval = getMaximum(A0, 10);

if (maxval > threshold) {
    if (!isAbove) {
        isAbove = true;
        wentAbove = millis();
    } else {
        if (millis() - wentAbove > 120000) {
            digitalWrite(13, HIGH);
        }
    }
} else {
    if (isAbove) {
        isAbove = false;
        digitalWrite(13, LOW);
    }
}

Note: all code untested.

Hi Majenko, thank you for your detailed explanation. Sorry i am very new to programming and arduino and has some trouble understanding. Could you enlighten me what does uint32_t t in  uint16_t getMaximum(uint8_t pin, uint32_t t) do and how should i define getMaximum? :/

unsigned 32-bit integer. It's the same as "unsigned long" - but explicit.  You don't need to "define" these functions - I have defined them for you. Just copy and paste.

I tried both the codes the sample implementation give a error message that getMaximum is not declared. :/


text:
The ESP8266 connects to open WiFi hotspots, even If I supply a password
This question is more out of curiosity, then out of a need to solve something.
I was trying out some experiments with the ESP8266 Arduino core when I realized that I had programmed an SSID and password for the ESP8266, but the WiFi that I had set up was an open network.
I tried going through the documentation and then the Arduino core source code, but couldn't find if WiFi.begin(ssid,passphrase) a function does this on purposes, as in it was designed that way, or did it just happen to work this way.
Also, I would like to know if there is a way to stop the ESP from connecting to an open network when the passphrase is provided.

It's probably by chance - however it's impossible to know.
Connecting is done by wifi_station_connect(), which is a function provided by the (closed source) ESP8266 SDK. So we can never know what it's actually doing.
However, the sequence is probably something like:

-> Connect
<- Ok, give me a password
-> Here it is
<- Right, you're connected

Or, with no PSK:

-> Connect
<- Right, you're connected

Although you specify the password (which just gets stored in the configuration) if it never asks for it then it just doesn't use it.
Can you force it? Not without knowing what's going on in the mystery wifi_station_connect() function.  There is nothing much in the documentation for the SDK that even hints at a clue.


text:
What is the best serial communication method between an Arduino and a spectral sensor?
I have an Adafruit AS7262 visible spectral sensor. I want to receive the data of the sensor with an Arduino.
The sensor has two serial communication options: UART(asynchronous) or I2C(synchronous). I want to know which method is more suitable for the sensor to communicate with the Arduino microcontroller. I was thinking that UART is more suitable, because the sensor has his own master clock, in other words if I choose I2C then the Arduino needs to work as the "slave" and I dont think that is very suitable, because the Arduino has its own master clock also. For this reason I think that asynchronous method is more reliable, but I am not sure about this.

The I2C on this device is slave, not a master. Even though it has its own clock, it is designed to operate as a slave being read by a master.
You will have no issues using the I2C interface - in fact Adafruit uses it for their own software library.
Since there is already a I2C-based library available from the manufacturer I would use that, unless there is a good reason to use the UART instead.

Arduino will serve as the Master controller and will send the call to the slaves. AS7262 is a sensor device, Arduino will send the call commmand then receive the data from its sensors.  Sometime confusion arrises because developers are accustomed to the desktop computer as the Master, but in this case, Arduino receives data and engage a forward action like sending info to USB or WiFi connected computer or just do a feedback control to another digital or analog device.
You will find further reading on this subject at Arduino community here
Also


text:
getting error 'Serial' was not declared in this scope
I am adding Dust Sensor to my particle photon project at home,
I got this GitHub project that I want to test before implementing a final code.
I am not an expert in cpp, I wanted to modularise the dust sensor codebase to separate library so I created new dustSensor.cpp file and kept the code linked above.
but I keep getting error:
'Serial' was not declared in this scope
'Serial1' was not declared in this scope
'DEBUG' was not declared in this scope
'DEC' was not declared in this scope dustSensor.cpp:13:57:
I do have Serial.begin(57600) called in setup() function but still get the above error

add #include <Arduno.h> to cpp

you can find it with opened your Particle Project in the Desktop IDE and click on the Browse and Manage Libraries buttons and find the library you need. that's automatically include your libraries. see this docs.

I learned that I needed to include Arduino.h header file
apart from that I learned .ino files and .cpp files is that the .ino files transparently include particle.h for you.
The other difference is that .ino files generate forward declarations for you. This is necessary when you’ve implemented a function later in the file than when you’ve first used it. For example, if you pass the function to something like Particle.subscribe in setup() but you’ve implemented it farther down the file.

The technical name for that is a "forward reference". Historical note: the necessity to declare the function before a forward reference originated because early C compilers were written to read your source code only once, rather than once to find function and variable definitions and again to generate code once the components of it were known. Such a compiler was easier to write and ran faster (which was a bigger concern at the time than it is today).


text:
controll intigers from webserver on nodeMCU esp8266
I would like to controll neopixel leds from over wifi with my nodeMCU but i dont know how to controll values over wifi, through a web interface would be perferable over url, but that also works.
usinf arduinoIDE for all code.

did you see the WebServer example of the ESP8266WiFi library?

yes i di but that shows just on and off when it detects a webpage loading and not seting a value in a forfum in a forum

and ESP8266WebServer library?

what do you mean by that?

there is a ESP8266WebServer library in the esp8266 Arduino package

ive taken a look at the web server and advanced web server examples but saw nothing, i can look at the direct .h file if thats what you mean?


text:
How to build a valid HTTP Response. Recv failure: Connection reset by peer
I'm developing an Arduino server that should respond with a message when it receives a POST Request.
If I test my project with a HTTP Client (like insomnia or postman), I get an error:
Error: Failure when receiving data from the peer

I still get a response that I can read but with a final error.
That's my client request:
> POST /SOMETHING/ HTTP/1.1
> Host: [ARDUINO IP]
> User-Agent: insomnia/6.2.0
> Accept: */*
> Content-Length: 0

And this is my Arduino response considered as not valid:
< HTTP/1.1 200 OK
< Connection: close
< [MY MESSAGE]

* Recv failure: Connection reset by peer
* stopped the pause stream!
* Closing connection 2

As you can notice, I just added 2 strings
HTTP/1.1 200 OK
Connection: close

before the real message.
Am I missing something to create a valid response?
Thanks

HTTP requires an empty line after HTTP headers.
First line is status line. Then the header lines. The headers are terminated by an empty line. Then the response body follows. Line terminator for HTTP is \r\n. Arduino println() function uses \r\n.
The response with body should contain Content-type and Content-length header. Alternative to Content-lenght is "chunked" Transfer-Encoding.
ESP8266WebServer library handles HTTP for you.

Thanks, it works. I just don't know why it still doesn't work in insomnia or postman even if it works if I read the request from a browser. Insomnia keeps saying:
`< HTTP/1.1 200 OK
< Content-Type: text/html
< Connection: close

Received 9 B chunk
Recv failure: Connection reset by peer
stopped the pause stream!` ... looks like it receives the response but there's still the "recv failure" error.

you don't send content length, so the client doesn't know where the body ends. it waits for more data and you close the connection. browser tolerates it or has some orientation in the body structure (html tags?)

perferct. It works printing always the string.length() in Content-Length. Thanks


text:
Arduino esp8266 EEPROM lag
Trying to save my LED-State to EEPROM.
After every 5 seconds my EEPROM saves the value of white in this example (didn't put in RGB yet)
When the EEPROM gets commited and the value changes the LED is dark for a few milliseconds
what can I do?
int xInt = wVal.toInt();
white_val = xInt;
controlLed(whitePin, xInt);

Triggers LED:
void controlLed(int pin, int integer) {
  analogWrite(pin, integer);
  return;
}

Loop Saving Data every five seconds:
void loop() {
  static unsigned long startTemp = 0;
  unsigned long msTime = millis();

  if (msTime - startTemp >= 5000) {
    startTemp = msTime;
    writeEeprom(white_address, white_val);
  }
}

Writes Data to EEPROM:
void writeEeprom(int address, int value) {
  EEPROM.put(address, value);
  Serial.println("WRITTEN  TO EEPROM:");
  Serial.println(address);
  Serial.print("\n");
  Serial.println(value);
  Serial.print("\n");
  EEPROM.commit();

  EEPROM.get(address,value);
  Serial.println("READ  FROM EEPROM:");
  Serial.println(address);
  Serial.print("\n");
  Serial.println(value);
  Serial.print("\n");
  return;
}

What's the GPIO number of the pin you're using to control the LED?

const int whitePin = 14;
It's a esp8266 ESP-07

the first snippet is from setup()? which version of esp8226 Arduino core you use?

No the first snippet gets triggered when the value changes
`
if(text.startsWith("w")){
        String wVal=(text.substring(text.indexOf("w")+1,text.length()));
        int wInt = wVal.toInt();
        white_val = wInt;
        controlLed(whitePin, wInt);
        webSocket.sendTXT(num, "white changed", lenght);
       }

`
Latest Stable:
http://arduino.esp8266.com/stable/package_esp8266com_index.json
And Arduino 1.8.7
esp8266 has version 2.4.2


text:
OV2640 with 18 Pins - No XLCK System Clock
I'm trying to connect an OV2640 camera module to a microcontroller.
This camera module has only 18 pins as seen in this schema:
https://i.stack.imgur.com/wVBwV.jpg
Here an image of the module:
https://i.stack.imgur.com/tUVg0.jpg
These pins are on the module:

3.3V
GND
VSYNC
SCL
SDA
HREFF
D0 - D7
DCLK
PWDN
NC

Maybe I could set XLCK and PLCK via the DCLK pin but I don't know how.
I am pretty new to camera modules and searched the net a lot of times. Most examples are for the OV7670. This module has also 18 Pins but all are used quiet contrary to the OV2640.
Could anybody help me connect and get a signal?

http://www.arducam.com/camera-modules/2mp-ov2640/

@Juraj thanks for the link, i tried these examples. But it's a different kind, the arducam version has an XLCK.

Can you be specific about which microcontroller you want to use?

@MichaelT i tried it with an ESP8266, ESP32 and RaspberryPi 3 Model B+. I used this example: https://www.instructables.com/id/OV7670-Without-FIFO-Very-Simple-Framecapture-With-/ and https://www.instructables.com/id/How-to-Connect-OV7670-to-Arduino-Due/ http://embeddedprogrammer.blogspot.com/2012/07/hacking-ov7670-camera-module-sccb-cheat.html These examples are for ov7670 but i tried to adapt them.

In this specific OV2640 module, it's supposed to have a 12MHz oscillator in the board connected to XLCK pin (you can all time adjust the PLL trough SCCB interface as usual). Remove the plastic lens and see near the CMOS.
Regards

Thanks for your answer. Yes there is a oscillator right to the CMOS, i am a nooby when it comes to cameras with microcontroller. In all examples the XCLK is connected to a pin, i read that the XCLK could be "simulated" but i don't know how.

I also bought one of these to use with an esp32, not realizing that there was an on-board oscillator and no system clock pin. I just left the pin on the esp that's supposed to connect to XCLK hanging, and set the frequency to 12000000 in my code. It seems to work alright!


text:
Why my light meter's values are blank on Arduino Serial Monitor?
I tried to represent the values of TSL 2591 Adafruit light sensor on my Arduino Serial Monitor, but for some reason, I could not do that. The Arduino Serial Monitor just enters some blank values and scrolls down.
Here is the code:
uint16_t x = tsl.getLuminosity(TSL2591_VISIBLE);
y = float(tsl.getLuminosity(TSL2591_VISIBLE));
z = (y, DEC);
Serial.write((byte)z);

x, y, and z are floats initially.

Did you enabled the serial communication on arduino by using Serial.begin(9600)?

What's z = (y, DEC); supposed to do?

Yes, I enabled it. What if I change 9600 to another value? @svtag

I think it converts the values to decimals @Gerben

Use Serial.println(x); to print a number as text. Function write() sends the raw byte and Serial Monitor shows the character with that ASCII code, which is not valid or a not visible control character.

For the z = (y, DEC); from Wikipedia:

In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).

so z is always 10 (value of constant DEC), which is ASCII code for the new line character

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

authors: Асмир Абдимажитов


text:
How to write a script if water sensor comes into contact with water for more than 2 mins and LED lights up
I am a newbie to arduino and programming. I would like to come out with a code for water sensor to detect the presence of water for more than 2mins before lighting up the LED lightbulb. Currently using Arduino, Grove baseshield with grove water sensor http://wiki.seeedstudio.com/Grove-Water_Sensor/.
I have the simple base code but not sure how do i go about adding in the function to detect water for a longer period of time before the light lights up:
#define watersensor 8               //Grove water sensor to Arduino Digital Pin 8
#define led 4                      //Grove LED to Digital Pin 4

int isWater;
bool wasWater = false;
//bool isWater, wasWater = false;    // true => currently we are not seeing water
uint32_t waterstart_ms = 0;        // time first saw water

void setup() {
  pinMode(watersensor, INPUT);
  pinMode(led, OUTPUT);
}

void loop()
{
   // Is there water?
 isWater = digitalRead(watersensor);     // read sensor
 Serial.println(isWater);

   if( isWater ){
      if( wasWater ) {
      waterstart_ms = millis();  // First water: note the time
      }
        if( millis() - waterstart_ms >= 1*5*1000 ){// Water continues for 5s (trial first); time to light LED?
            digitalWrite(led, HIGH);
        }//end if
            wasWater = true;
   } // end first if
   else {
      wasWater = false; // No water; LED off
      digitalWrite(led, LOW);
   }
}

It's exactly the same as how you do it for sound - just using the presence of water instead of the maximum value of sound.

Should the LED be latched (stay on forever, once it's on), or go out if the sensor later detects no water? I'll assume the latter. Here's an (untested) state machine that should give you a good start. It keeps track of whether water was already seen, when it started, and whether it is seen now. There is some redundant switching of the LED; removing that (if desired) "is left as an exercise for the reader".
#define watersensor 8               //Grove water sensor to Arduino Digital Pin 8
#define led 4                      //Grove LED to Digital Pin 4

#define TWOMIN (2*60*1000L)

bool isWater, wasWater = false;    // true => currently/were seeing water
uint32_t WaterStart_ms = 0;        // time first saw water

void setup() {
  pinMode(watersensor, INPUT_PULLUP);  // pullup for testing w/a button
  pinMode(led, OUTPUT);
}

void loop()
{
  // Is there water?
  isWater = !digitalRead(watersensor);     // read sensor

  if ( isWater ) {
    if ( !wasWater ){
      // First water: note the time
      WaterStart_ms = millis();
      wasWater = true;
    }
    else {
      // Water continues; time to light LED?
      if ( (millis() - WaterStart_ms) >= TWOMIN )
        digitalWrite(led, HIGH);
    }
  }
  else {
    // No water; LED off
    wasWater = false;
    digitalWrite(led, LOW);
  }
  delay(300);
}

Update:
Added wasWater = true; at line 27. The delay(300) at line 40 isn't necessary. Ran correctly when I tested it with a button (also negative logic) for the sensor.

the light lights up randomly.

See if your sensor gives solid responses (try printing its output in loop() ). If it dithers around transitions, you may need to wait for some number of readings in a row that are opposite to the previous sensor state before you accept its new state as real.

Hi JRobert! Thanks for your guidance. I have made some minor amendments to the code. But the sensor only lights up without the presence of water. when i change the if ( !wasWater) to if (wasWater), the light lights up randomly.
Not sure where went wrong..
Had updated the new amended code in my question!


text:
How to use a precompiled library in a project with Arduino-IDE
I'm discovering the Arduino development and after quite some googling, I can't find an answer to the following question.
I'd like to distribute some code as mylib.h + precompiled mylib.o (this will be code ported from sources which I can't divulgate).
How is it possible to build a sketch using this precompiled mylib.o in the Arduino-IDE environment?
Do I simply have to put this mylib.o in a specific path and include the mylib.h in the sketch? If yes, which path? If no, what specific configuration steps do I have to follow?
Thanks in advance.

See https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification

library.properties file format
  [...]
  precompiled - (available from Arduino IDE 1.8.6/arduino-builder 1.4.0) (optional) set to true to allow the use of .a (archive) and .so (shared object) files. The .a/.so file must be located at src/{build.mcu} where {build.mcu} is the architecture name of the target the file was compiled for. Ex: cortex-m3 for the Arduino DUE. The static library should be linked as an ldflag.

So with the correct metadata and file layout the precompiled objects should be available.
You'll need to set the architectures property to indicate you're using esp8266 as your tag suggests.
More info on the library manager here https://github.com/arduino/Arduino/wiki/Library-Manager-FAQ including how to add to the public library list.


text:
How can I tell the resistance of an internal pull-up resistor?
I have a SparkFun ESP8266 Thing Dev board, to which I want to perform a digitalRead() on one of the GPIO ports. I'm using D15, and I'm configuring it for input like this
pinMode(15, INPUT_PULLUP);

It does seem to work as intended, and I am able to pull it down by connecting it to ground via a 4.7kΩ resistor.
But how do I know what the actual "correct" resistor would be? I can't find any specs for the internal pullup resistor online. On a related note, I first tried using D0, but it didn't seem to have an internal pullup resistor, since even using INPUT_PULLUP didn't turn it on.
Perhaps there are specs online and I'm just not able to find them, but is there any other way (measuring?) to find out which pins will work with INPUT_PULLUP and if so, what their internal resistance is?

What makes you believe that you need a resistor at all?

You may find this edifying though: https://majenko.co.uk/blog/measuring-arduino-internal-pull-resistors

Internal pullup resistor only gives the pin a definite input value (HIGH) if it is floating. If the pin is connected to ground then it will read LOW, regardless of whether a pullup resistor is used or not.

@gandalf61 Won't that depend on the ratio between the pullup and pulldown resistors? Of course if it's connected directly to ground, then it would definitely be low...

@Majenko Hmm... is it safe to connect a GPIO input directly to +5V or ground, without any resistor? Won't it draw an unnecessarily high current, and/or risk damaging something in the device?

D0 is io 16. it has internal pulldown. I know it from the esp8266 Arduino package online documentation

@Majenko I guess I got a bit worried about connecting anything directly to the pins since some seem to be used for various things, and some (at least the internal LED, D5) seem to be inverted (setting it to HIGH will turn off the LED, and LOW turns it on)... on the normal Arduino things seem more straightforward.

You can only do damage if the pin is set to output. When input there is nothing to damage. It is common to add a very small (100r or so) resistor in series with the output to protect it just in case.

@Juraj Hmm, by D0 I mean the pin labeled 0 on the board, and referred to as 0 and D0 in the pin overview image from SparkFun. Where exactly do you get 16 from? Either way, I can't seem to get that pin to work as expected, it might be because the docs say it's "Used in reset"....

right, io 0 is a boot configuration pin. it should have an external pull-up on board (NodeMcu and Wemos/Lolin have Dx labeled pins. you confused me with the D)

@MagnusW directly to +5V on an ESP8266, I'd limit that to +3.3V - as much as I've read that the GPIO are "5v tolerant" I'd stick to 3.3

io 0 and io 15 are with io 2 boot configuration pins of the esp8266. esp8266 dev boards have external pull-up on io 0 and io 2 and pull-down on io 15.

Thanks. Where can I find this information? The Hookup Guide I found doesn't really say much about pins 0, 4 and 15... and SparkFuns own examples seem to mostly use pin 12 as INPUT_PULLUP, which is the only one I got it to work with.

the best source is Espressif's site (esp8266_hardware_design_guidelines_en.pdf). but the information about boot pins is on many web pages about esp8266

Hmm, now I'm feeling a bit stupid... when I say pinMode(12, INPUT) - does the 12 refer to GPIO12 or to "pin 12", which in the Espressif Hardware Design Guidelines means GPIO13? It gets even more confusing when the SparkFun pin guideline refers to pin 12 as D12... Which one of all of these am I really interested in when calling pinMode()??

in Sparkfun Thing the labels and the pin numbers (even if prefixed with D) correspond to gpio numbers used by Espressif. (NodeMcu and Wemos/Lolin boards have Dx comstants and labels)

"The value of internal (built-in) pull-up resistor is between 30Kohm and 100Kohm."
Source: https://bbs.espressif.com/viewtopic.php?t=1079#p4097

did you read the accepted answer?


text:
Combining two code of two sensor in one program
I'm using two sensors, which is Galvanic Skin Response sensor and Heartrate sensor. The problem is that when I combined both of the codes, the only output that is showing up is from Heartrate only which is at A0. If I run them separately both codes works perfectly fine. My background in coding is basic and both codes came from the internet.
These are the codes:
    #define BLYNK_PRINT Serial
    #include <ESP8266_Lib.h>
    #include <BlynkSimpleShieldEsp8266.h>
    #include <SoftwareSerial.h>
    SoftwareSerial EspSerial(2, 3); // RX, TX

    #define samp_siz 4
    #define rise_threshold 4

    // Your ESP8266 baud rate:
    #define ESP8266_BAUD 9600

    char auth[] = "ba4e5bd1bd9549669a02ac378db9faf6";
    char ssid[] = "vivo";
    char pass[] = "takoyaki";

    /*char auth[] = "b3f01a592b78471f9f720b09d2ff8047";
    char ssid[] = "vivo";
    char pass[] = "takoyaki";
    */
    ESP8266 wifi(&EspSerial);

    BLYNK_CONNECTED()
    {
      Blynk.syncAll();
    }

    BlynkTimer timer;

    // Pulse Monitor Test Script

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

      // Set ESP8266 baud rate
      EspSerial.begin(ESP8266_BAUD);
      delay(10);

      Blynk.begin(auth, wifi, ssid, pass);

      pinMode(A0, INPUT);
      pinMode(A1, INPUT);

      //timer.setInterval(1000L, myTimerEvent);     //send the arduino's                         uptime
      timer.setInterval(350L, sensor);            //send gsr data every         0.35s
    }

    /*void myTimerEvent()
    {
      // You can send any value at any time.
      // Please don't send more that 10 values per second.
      Blynk.virtualWrite(V4, millis() / 1000);
    }
    */
    void sensor(){

      const int GSR=A1;
      int inputvalue=0;
      int gsr_average=0;
      long total=0;
      for(int j=0;j<10;j++)                       //Average the 10                 measurements to remove the glitch
          {
          inputvalue=analogRead(GSR);
          total += inputvalue;
          delay(5);
          }
       gsr_average = total/10;
       Serial.println(gsr_average);
       Blynk.virtualWrite(V6, gsr_average);
    }

    void heartrate ()
    {
        int sensorPin =A0;
        float reads[samp_siz], sum;
        long int now, ptr;
        float last, reader, start;
        float first, second, third, before, print_value;
        bool rising;
        int rise_count;
        int heartrate;
        int n;
        long int last_beat;

        for (int i = 0; i < samp_siz; i++)
          reads[i] = 0;
        sum = 0;
        ptr = 0;

        while(1)
        {
          // calculate an average of the sensor
          // during a 20 ms period (this will eliminate
          // the 50 Hz noise caused by electric light
          n = 0;
          start = millis();
          reader = 0.;
          do
                  {
            reader += analogRead (sensorPin);
            n++;
            now = millis();
          }
          while (now < start + 20);
          reader /= n;  // we got an average

          // Add the newest measurement to an array
          // and subtract the oldest measurement from the array
          // to maintain a sum of last measurements
          sum -= reads[ptr];
          sum += reader;
          reads[ptr] = reader;
          last = sum / samp_siz;
          // now last holds the average of the values in the array

          // check for a rising curve (= a heart beat)
          if (last > before)
          {
            rise_count++;
            if (!rising && rise_count > rise_threshold)
            {
              // Ok, we have detected a rising curve, which implies a         heartbeat.
              // Record the time since last beat, keep track of the two previous
      // times (first, second, third) to get a weighed average.
      // The rising flag prevents us from detecting the same rise more than once.
              rising = true;
              first = millis() - last_beat;
              last_beat = millis();

              // Calculate the weighed average of heartbeat rate
              // according to the three last beats
              print_value = 60000. / (0.4 * first + 0.3 * second + 0.3 *         third);

              heartrate = print_value;

              //Serial.print(print_value);
              Serial.print(heartrate);
              Serial.print('\n');
              Blynk.virtualWrite(V7, heartrate);

              third = second;
              second = first;

            }
          }
          else
          {
            // Ok, the curve is falling
            rising = false;
            rise_count = 0;
          }
          before = last;

          ptr++;
          ptr %= samp_siz;

        }
    }

    void loop()
    {
      Blynk.run();
      //timer.run();
      sensor();
      heartrate();
    }

If you need the codes without those blynk's command just tell me in the comment section

the function heartrate() has an infinite loop, so the Uno is stuck there

so i cannot use the code as a function ? how do i need to edit it ?

The while(1) loop is the problem. Rewrite the function in a way, that it takes the reading, does somethings with it and then exits to the main loop to do something else

Since the code keeps record of the last measurements, you will have to make these variables static or global, so that they keep their value between different executions of the function. And btw: the start variable has to be an unsigned long, since that is the type, that the millis() function returns. The same goes for variable now.

Thank you so much for your help. I really do appreciate it sir. I'll do the edits soon and if i have questions I'll be here again

can you explain a little bit more about that while(1) loop ? im so lost

while(1){ ... } is an infinite loop - it never exits, therefore heartrate() can never end and return to loop. It just sits there taking readings - forever. Try calling only one of sensor() until it works. Then try calling only the other one, until it works, too. Once they each work correctly, only then try calling both of them. This is a classic "divide-and-conquer" debugging technique.

Ive done the tips like what you were suggesting and calling those sensors one by one and it works perfectly fine. What control structure is the most suitable for me to replace the while(1) ?

I have not tested the following code, so it will be up to you to do this and handle small errors. This is more about the coarse way to change the program. And you will have to understand, what the code really does, to be able to change it the way you need it.
First you will have to make some of the variables in the heartrate() function to global variables (by writing them near the top of the sketch outside of any function), so that they keep their values between the different executions of the function. I also changed some variable types, which match the type of the assigned values.
float reads[samp_siz], sum;
unsigned long now, start, ptr;
float last, before, reader;
unsigned long first, second, third;
bool rising;
int rise_count;
float print_value, heartrate;
unsigned long last_beat;

The sensor pin should be #defined at the top of the program (by convention). Then you should put this code:
for (int i = 0; i < samp_siz; i++)
    reads[i] = 0;
sum = 0;
ptr = 0;

into the setup() function.
Now we can look at the while(1) loop. On Arduino a value of 0 is treated as the boolean false and every other value as true. So this is the same as writing while(true). The while() structure loops as long, as the expression inside the brackets evaluates to true. Since this is always the case here, it will loop forever. At this point you can just erase this line (and the corresponding closing bracket }).
After these changes the function will only take 1 reading (averaged over 20ms), then check, if a heartbeat was detected, and finally exiting to the loop() function. Since not every reading is a heartbeat, you will get more output from the sensor() function (which outputs on every execution) than from the heartbeat() function. And now, due to your functions being non-blocking, you will get very fast output. You might want to slow that down, by using a delay() or (better) the millis() function (like in the BlinkWithoutDelay example of the Arduino IDE).
Note, that this code exhibits some bad coding styles. You can get much of good code on the web, but also much of bad code. I see wrong types for variables, the usage of totally unnecessary variables and usage of the millis() function, which doesn't handle the rollover. This doesn't mean, that the code does not work. But you can get weird and difficult to debug errors through them.


text:
programming relays wit millis code
Trainset info,
Turnout 1 = relay 1 - makes turnout track go left
          = relay 2 - makes turnout track go right
Turnout 2 = relay 3 - makes turnout track go left
          = relay 4 - makes turnout track go right
 Signal 1 = relay 5 - makes signal go green - train 1 starts driving
          = relay 6 - makes signal go red - train 1 stops for signal
 Signal 2 = relay 7 - makes signal go green - train 2 starts driving
          = relay 8 - makes signal go red - train 2 stops for signal

I have a arduino - uno and a 8 relay board.
I want to run a program (loop) for 1/2 hour / 1800 seconds.
Switching time should be 2 seconds (relay ON)
Can somebody help me with a millis code please.
Loop times should be:
relay 1 = (2),1250,(2),546 - total 1800 seconds
relay 2 = 620,(2),630,(2),546 - total 1800 seconds
relay 3 = 10,(2)1260,(2),526 - total 1800 seconds
relay 4 = 630,(2),640,(2),512 - total time 1800 seconds
relay 5 = 20,(2),1270,(2),505 - total time 1800 seconds
relay 6 = 600,(2),750,(2),446 - total time 1800 seconds
relay 7 = 640,(2),640,(2),516 - total time 1800 seconds
relay 8 = 1240,(2),450,(2),106 - total time 1800 seconds

Regards, Martinus van Walsum
xxxxxxxx@xxxxxxxx.com

Start at the top of your question and read outloud. Only stop to take a breath after the end of a sentence. (when a period is inserted) Did you have a difficulty saying all that without stopping? Probably. You question is very hard to read. If you want help then please make it easier for someone to figure out what you want. Did you notice that my comment uses punctuation? If we were allowed line breaks in the comments, I would also use that. It all helps with understanding. But even if you used proper punctuation, your question is still not clear. Get rid of the train speak.

@Rudy, only newlines were lost without code block

What was your specific problem with writing the code? Have you read the BlinkWithoutDelay example, which shows, how this coding style works? Have you read some of the many tutorials for this on the web? Currently I don't know, how I could help you, without having to write the whole code myself.

Btw: Putting your email address directly on a public website will only get you tons of spam.

Do you realize that Turnout 1 will be switching both left and right (at the same time) at the 1250 mark? And that Turnout 2 will be switching both left and right at the 1260 mark? And so on.

This is functional. I would do more by making a function to be called with the time and state information. It would reduce the number of if statements. But this is simple to understand. I started with Blink without delay.
I did two relays. For the others, copy and paste, then change the relay numbers and times.
/*
  Blink without Delay
  http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
*/

const int On =  1;
const int Off =  0;

// constants won't change. Used here to set a pin number:
const int ledPin =  LED_BUILTIN;// the number of the LED pin
const int relay1 =  5;
const int relay2 =  6;

// Variables will change:
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated

int    secondCount = 0;

// constants won't change:
const long interval = 1000;           // interval at which to blink (milliseconds)

#define onTime  2           //relay on time

#define relay1_on1 0
#define relay1_on2 (relay1_on1+onTime+1250)

#define relay2_on1 62
#define relay2_on2 (relay2_on1+onTime+630)

void setup() {
  // set the digital pin as output:
  digitalWrite(relay1, Off);
  digitalWrite(relay2, Off);
  pinMode(ledPin, OUTPUT);
  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
}

void loop() {
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the difference
  // between the current time and last time you blinked the LED is bigger than
  // the interval at which you want to blink the LED.
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    //------------------------------
    // Relay 1
    if (secondCount == relay1_on1) {
      digitalWrite(relay1, On);
    }
    if (secondCount == (relay1_on1 + 2)) {
      digitalWrite(relay1, Off);
    }

    if (secondCount == relay1_on2) {
      digitalWrite(relay1, On);
    }
    if (secondCount == (relay1_on2 + 2)) {
      digitalWrite(relay1, Off);
    }

    //------------------------------
    // Relay 2
    if (secondCount == relay2_on1) {
      digitalWrite(relay2, On);
    }
    if (secondCount == (relay2_on1 + 2)) {
      digitalWrite(relay2, Off);
    }

    if (secondCount == relay2_on2) {
      digitalWrite(relay2, On);
    }
    if (secondCount == (relay2_on2 + 2)) {
      digitalWrite(relay2, Off);
    }

    //------------------------------
    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);

    secondCount++;
    if (secondCount == 180) {
      secondCount = 0;
    }
  }

}


text:
Can't make ultrasonic sensor work with motor controller
I just started using Arduino Uno, I can't get the ultrasonic to work ,with motor controller board, the output value is always zero.
Just to make sure I'm talking about the correct stuff:
I used this guide to try to make it work (look at the picture how did I connect the parts).
And this is my code:
#define trigPin A4//Attach Trig to port 8
#define echoPin A5//Attach Echo to port 7
#include <AFMotor.h>
//SMARS Demo 2 with Line sensor

AF_DCMotor R_motor(2); // defines Right motor pin
AF_DCMotor L_motor(1); // defines Left motor pin

int lmotorpin1 = 3;
int lmotorpin2 = 5;
int rmotorpin1 = 6;
int rmotorpin2 = 9;
int distancecm = 0;
//const int trigPin = 18;
//const int echoPin = 19;

// defines variables
long duration;
int distance;
void setup() {

  Serial.begin(9600); // sets up Serial library at 9600 bps

  //changes the following values to make the robot drive as straight as possible
  L_motor.setSpeed(200); // sets L motor speed
  R_motor.setSpeed(140); // sets R motor speed

  R_motor.run(RELEASE); //turns L motor on
  L_motor.run(RELEASE); //turns R motor on

  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
}

void loop() {
      Serial.println(trigPin);
    Serial.println(echoPin);
  distancecm = mdistance();
  if (distance < 5) {
    L_motor.run(BACKWARD); //moves motor L Forward
    R_motor.run(FORWARD); //moves motor L Forward
//    delay(1000);
//    L_motor.run(FORWARD); //moves motor L Forward
//    R_motor.run(FORWARD); //moves motor L Forward
//    delay(1000);
  }
  else {
    L_motor.run(FORWARD); //moves motor L Forward
    R_motor.run(FORWARD); //moves motor L Forward
  }
}

int mdistance()
{
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  Serial.print("Duration: ");
  Serial.println(duration);
  // Calculating the distance
  distance = duration * 0.034 / 2;
  // Prints the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.println(distance);
}

As you can see I tried different pin numbers but it always 0 ....
what do you think can be wrong?
The motors work.
Motor Controller: KEYES L293D Motor Control Shield
Sensor: Ultrasonic Ranger V2.0

and the motors work? do you have the shield?

what sensor are you using?

I added the info in the main post at the end

the way the description of your problem reads is the ranger does not work with the motor controller, but it works without the motor controller ..... is that what is happening?

I didn't check it without the motor controller.

Pin numbers 0 and 1 are reserved for the Serial monitor which you're using on the board.
The function int mdistance() should return an integer.
You also didn't seem to set the motor pins as OUTPUT.

This seems to be more of a comment than actual solution to the OP's problem

Where is pins 0 and 1? I don't see why this is a problem because the motors are working.. The problem is the ultrasonic sensor.. Please explain yourself.

the motor number is not a pin number