text:
Is it possible to convert RCA(video only) to Arduino Uno then to a computer?
I have an old wireless RCA output camera. I was wondering if I can convert its analog input to a digital one and have it saved on a file in my laptop?

yes, get a USB video digitizer with an RCA input ... plug into your laptop

Not possible with the Arduino Uno. The composite video signal has an analog bandwidth of ~5MHz, and a 16MHz Arduino with its 12-bit ADC has a max sample freq of circa 77kHz. You cannot sample the signal fast enough and you also can't send it to the computer fast enough due to the incredibly slow serial interface. You'll a need a faster chip (high-speed ADC and DMA..). See https://www.sciencedirect.com/topics/engineering/composite-video-signal, http://zone.ni.com/reference/en-XX/help/373389B-01/nivms/signals_cvbs/ https://forum.arduino.cc/index.php?topic=6549.0

Is it possible? Technically, yes - after all the ZX Spectrum had the Videoface. Only good for still images though (sampled the image in sections across many many frames - 0.26 seconds per image, so about 6 frames needed to get an image depending on region), and 4-bit graphics (fed though a few comparators). Would it be worth doing it? No. Unless you only wanted the experience of doing it. Would the results be usable? No. Absolutely not. Would I do it? No. I'd get a USB video capture dongle.

Thank you! Still got lots of things to learn.


text:
Change From One State Machine To Another
I have a project where I need to state from leds turning on and off to another one that will have all the leds turned on and send data and I was wondering how should I do that, this the code I have:
#include <CapacitiveSensor.h>

CapacitiveSensor cs_11_10 = CapacitiveSensor(11,10);

int state_s1 = 0;
int state_s2 = 0;
int state_s3 = 0;
int state_s4 = 0;
int state_prev_s1 =0;
int pin_s1 = 12;
int val_s1 = 0;

const unsigned int ledPins[]={2,3,4,5,6,7,8,9};
const unsigned int lenledPins=9;

unsigned long t_s1 = 0;
unsigned long t_0_s1 = 0;
unsigned long t_s3 = 0;
unsigned long t_0_s3 = 0;
unsigned long t_0_s4 = 0;
unsigned long t_s4 = 0;
unsigned long t_s2_4 = 0;
unsigned long tiempo = 250;

unsigned long bounce_delay_s1 = 5;

long total = 0;

void setup()
{
  pinMode(pin_s1, INPUT_PULLUP);
  Serial.begin(9600);

  for(int i=0; i<(9); i++)
  {
    pinMode(ledPins[i], OUTPUT);
  }

  cs_11_10.set_CS_AutocaL_Millis(0xFFFFFFFF);
  Serial.begin(9600);

}

void loop()
{

  MBoton();          //MAQUINA DE ESTADO

 MaquinaGeneral();

  if(state_s2 == 1)
  {
    led();
  }

  if(state_s1 != state_prev_s1)
  {
    Serial.print("state =");
    Serial.println(state_s3);
  }

  if(state_s4 == 6)
  {
    for(int i=0; i<lenledPins; i++)
    {
      digitalWrite(ledPins[i],HIGH);
    }
  }

  Serial.print("");

}

void MaquinaGeneral()
{
  switch(state_s2)
  {
    case 0:
    if(state_s1 == 4)
    {
      state_s2 = 1;
    }
    break;

    case 1:

    break;
  }
}

void MBoton()
{
  state_prev_s1 = state_s1;
  switch(state_s1)
  {
    case 0:         //RESET
    state_s1 = 1;
    break;

    case 1:        //START
    val_s1 = digitalRead(pin_s1);
    if(val_s1 == LOW)
     {
      state_s1 = 2;
     }
    break;

    case 2:         // GO!
    t_0_s1 = millis();
    state_s1 = 3;
    break;

    case 3:         //WAIT
    t_s1 = millis();
    if(t_s1 - t_0_s1 >= bounce_delay_s1)
    {
      state_s1 = 5;
    }
    break;

    case 5:         //ARMED
    val_s1 = digitalRead(pin_s1);
    if(val_s1 == HIGH)
     {
      state_s1 = 4;
     }
    break;

    case 4:       //TRIGGERED
    state_s1 = 0;
    break;

  }
}

void led()
{

  switch(state_s3)
  {
    case 0:         //OFF
    for(int i=0; i<lenledPins; i=i+2)
    {
      digitalWrite(ledPins[i],LOW);
    }
    for(int i=1; i<lenledPins; i=i+2)
    {
      digitalWrite(ledPins[i],HIGH);
    }

    t_0_s3 = millis();
    state_s3 = 1;
    break;

    case 1:         //WAIT
    t_s3 = millis();
    if(t_s3 - t_0_s3 >= tiempo)
    {
      state_s3 = 2;
    }
    break;

    case 2:         // ON
     for(int i=0; i<lenledPins; i=i+2)
    {
      digitalWrite(ledPins[i],HIGH);
    }

     for(int i=1; i<lenledPins; i=i+2)
    {
      digitalWrite(ledPins[i],LOW);
    }

    t_0_s3 = millis();
    state_s3 = 3;
    break;

    case 3:         //WAIT
    t_s3 = millis();
    if(t_s3 - t_0_s3 >= tiempo)
    {
     state_s3 = 0;
    }
    break;

  }

  }

void Capacitor()
 {

  switch(state_s4)
  {

    case 0:         //RESET
    state_s4 = 1;
    break;

    case 1:        //START
    total = cs_11_10.capacitiveSensor(10);
    if(total >= 1000)
     {
      state_s4 = 2;
     }
    break;

    case 2:         // GO!
    t_0_s4 = millis();
    state_s4 = 3;
    break;

    case 3:         //WAIT
    total = cs_11_10.capacitiveSensor(10);
    if(total < 1000)
     {
      state_s4 = 0;
     }

    t_s4 = millis();

    if(t_s4 - t_0_s4 >= 2000)
    {
      state_s4 = 5;
    }

    break;

    case 5:         //ARMED & WAIT
    t_s2_4 = millis();
    total = cs_11_10.capacitiveSensor(10);
    if(total < 1000)
     {
      state_s4 = 4;
     }

     if(t_s2_4-t_s4 >= 1000)
     {
      state_s4= 6;
     }
    break;

    case 4:       //TRIGGERED
    state_s4 = 0;
    break;

    case 6:     // ARMED 2
    Serial.println("Entro al estado 6");
    total = cs_11_10.capacitiveSensor(10);
    break;

}
}

A quick scan of your code would suggest you have too much going on.  That  or not enough comments to explain your decision to use multiple state machines.  I would start over with only 1 state machine and stick with only 1 state machine.

I don't quite understand, what your problem is with doing so. You have written all these state machines. So  you can just add states for exactly what you want (a state that would leave the LEDs on and would send data). Though I think st2000 is right in that you should check thoroughly if using only 1 state machine would be sufficient. That would be way easier to code.

Also use an enumeration type for the states, instead of 'magic numbers' 1, 2, 3 etc.

I highly recommend you design state machines with a state-diagram showing events, transitions, and actions. They are a whole lot easier to read & understand than any state-machine code I've ever seen or written. When you have a diagram you believe does what you want, then start coding it. Remember to check your state-machine code against the diagram, to be confident your code does what the diagram says it should. The state-diagram should be your working reference. When you debug, debug/fix it on the diagram first, then use that to fix the code. You'll get a working state machine much sooner.

If you think you need two finite state machines, where only one of them
is running at any given time, then it is trivial to combine them
together: draw them side by side, and add the required transitions
between them. The set of states of the combined FSM will be the union of
the states of the initial FSMs. For example, if you have:

FSM 1 states: STATE_A, STATE_B, STATE_C
FSM 2 stages: STATE_D, STATE_E
global states: FSM_1_RUNNING, FSM_2_RUNNING

Then the combined FSM will have the states STATE_A, STATE_B,
STATE_C, STATE_D and STATE_E, and all the transitions of both
initial FSMs.

Similar to what others have commented, this is not the best implementation of a Finite State Machine (FSM). You should establish clear states and define what happens during all transitions of your system.
Follow Edgar's advice on using enumerators for your states.
Nick Gammon's guide will surely be of great help: https://www.gammon.com.au/statemachine

source: Stack Exchange

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

sort: votes


text:
Sending sine wave from MATLAB and reading on Arduino Uno
I am working on timing issues associated with sampling data at high rates and storing it on an SD card (ADC delays, clock drifts and file I/O time). For this experiment, I thought of sending a sinusoidal wave to an analog pin on the Arduino Uno, and have the board read the samples. Can I eliminate the need for a function generator and instead use the Matlab Support Package for Arduino to send the sinusoid to the Arduino? (I guess this would mean two programs simultaneously, a Matlab program for generation of a sinusoid and an Arduino sketch for reading and writing.)
I'm new to Matlab, so any help would be greatly appreciated.

So do you have a problem implementing the arduino sketch or the matlab code? How are you going to output the analog signal? Please show us what you have tried so far.

I would like to know if running two such programs at the same time is possible. Also, I am going to write the output on an SD card, hence the Arduino sketch will just have analogRead() and file.print() functions. I'm not sure how to go about with the Matlab code, (again only if running two programs is possible).

No, it's not possible. Only 1 program at a time. Use a second Arduino. An please mind, that the Arduino Uno does not have a real DAC. If you use analogWrite() it will output a PWM wave, not an actual analog voltage.

No, you can't. The Arduino Uno has no analog outputs to start with and,
as you guessed, it cannot run two programs at the same time.
Maybe you should search for a solution of the initial problem instead.
You should be aware that you cannot get consistent timings with
analogRead(). You will have to read the datasheet of the ATmega328p,
especially the section dedicated to the ADC. Then you will configure the
ADC yourself, at the register level. It has a feature called
“auto-trigger” which is intended to provide perfectly consistent
timings. This is what you are looking for.

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


text:
Arduino simple resistors in series
Silly question but how would a circuit be set up with Arduino where two different resistors are in series but one has an unknown value (i.e. is just a piece of metal for example) and so how would we be able to find the current through each, collage through each and thus find the value of the resistance of the unknown wire.

If you know the voltage at either end of the chain, and the voltage at the middle node, as well as the value of one resistance, then you can calculate everything else.

series resistances have the same current flowing through them ... there is no "current through each" ... it is similar to water flowing through two pipes connected together

Just a math exercise really.
Say you had a 5V source, two Resistors R1 and R2, and an Arduino.
5V - R1 - R2 - Gnd, with R1/R2 junction feeding the Arduino.
R1 is unknown.
Vout is what the Arduino sees. Vout = 5VxR2/(R1+R2)
Vout (R1+R2) = 5VxR2
R1+R2 = 5VxR2/Vout
R1 = 5VxR2/Vout - R2
Vout = ~ 0.00488mV x Analog In reading. (5V/1024)
If you select R2 of say 5K ohm, and you determine Vout to be 3V (analogRead returns 615), then you can calculate R1:
(5V x 5000)/3V- 5000 = 3333 ohm.
Checking with Vout = 5VxR2/(R1+R2), 5V x 5000/(3333 + 5000) = 3.000V

While CrossRoads' answer got the math sorted out that is likely not the kind of measurement you are aiming for if the unknown resistor has a rather low resistance (i.e. is just a piece of metal). Assume the same circuit: 5V - R1 - R2 - GND.
Consider R1 to be a strand of copper wire of ribbon cable, AWG 26, i.e. with a diameter of 0.4 mm (0.016 inch) and a cross section of 0.13 mm², and a length of 3 inches (7.62 mm), being that "piece of metal". Its resistance will be 0.001 Ohms. To have any meaningful readings you'd want to have the other resistor (R2) in the same range otherwise the output voltage of the voltage divider will just be close to VCC (or GND if R1 and R2 are reversed). So assuming R2 to be 0.001 Ohms too, the total resistance of both resistors in series is therefore 0.002 Ohms. Connecting these to a 5V power supply (i.e. a voltage source) we find using Ohm's Law a current of 2500 A - which of course an ordinary Arduino wall plug will not provide. The power supply will either limit the current or its output voltage will be reduced or both - either way not a desirable situation in a measurement setup. Another approach of direct measurement is to apply a known current to the unknown resistor and measure the voltage across it. For any reasonable current that voltage will be rather small (i.e. 1 mV at 1 A) and would need to be amplified before being measured with an Arduino's ADC.
In short, measuring low resistances is difficult and might require a dedicated setup such as a Wheatstone bridge. Best answers are likely to be found at Electrical Engineering but need additional input on measurement range and required accuracy.


text:
How is better to store html / java script / in code or in flash on esp32
I have an esp32 which is running a web page together with a java script and using socket I update some values on the web page. I am doing this very fast (like each 50ms). Now I am serving all the html/java script code stored in a string variable but I am wondering which is the best? To store this html in spiff or in code ? and why?
Thank you very much

SRAM is typically an order of magnitude faster than NVRAM.

why do you need to update a web page every 50 ms?

I am displaying rpm of an engine which is read through obd port and I want see it as "real time" as possible

Best is to store static files in SPIFFS and serve them with Expires header set, to let the browser cache the html, css, js files and pictures files.
How to build the Expires header:
unsigned long expires = now() + SECS_PER_YEAR;
bp.printf(F("Expires: %s, "), dayShortStr(weekday(expires))); // two printfs because ShortStr functions share the buffer
bp.printf(F("%d %s %d 00:00:00 GMT"), day(expires), monthShortStr(month(expires)), year(expires));

And use AJAX method to show data on the page. Make the request with XMLHttpRequest object:
function getData(cmd) {
  var xhr = new XMLHttpRequest();
  xhr.onerror = function(e) {
    alert(xhr.status + " " + xhr.statusText);
  }
  xhr.onload = function(e) {
    showValues(xhr.responseText);
  };
  xhr.open("GET", "http://" + host + ":" + restPort + "/" + cmd, true);
  xhr.send();
}

showValues would be your function to fill the data into page
In ESP32 build the response as JSON for simple handling of the data in JavaScript.
Here is the WebServer in my project. It uses the basic Arduino Server class, not the esp WebServer. It has #ifdefs for SD or SPIFFS. The static files of my project including the js file are here.

It depends on your definition of "better".
Directly inlined in your code will probably be faster - it will be subject to the caching mechanisms of the execution pipeline, whereas SPIFFS will have to make specific SPI calls to read the data from the flash chip at the time it's required.  However SPIFFS will be easier to maintain since you are just working with files.
I would probably choose SPIFFS for larger files like graphics or big chunks of Javascript. Things that the client can download once and then cache (as long as your web server supports that kind of functionality - not sure what facilities the default ESP32 web server code has). The rest, the more dynamic things that change often, have as inline string literals.


text:
HC-05 Bluetooth fails AT+LINK
I'm trying to get a HC-05 connected as master to a Bluetooth ELM327 OBD scanner.
The HC-05 is accepting AT commands, no problem. This is the sequence I use:

AT+RMAAD    (Clear any paired devices)
AT+ORGL     (Set factory defaults)
AT+ROLE=1   (Set role to master)
AT+RESET    (reset needed after role change)

AT+CMODE=0  (allows connection to any device)
AT+INQM=0,5,9   (set inquiry to search for up to 5 devices for 9 seconds)
AT+INIT     (Inits BT)
AT+INQ      (searches for BT devices)

AT+PAIR=1D,A5,68988A,9  (Pairs to the address of the ELM327, timeout in 9 secs)
AT+BIND=1D,A5,68988A    (Binds the address)
AT+CMODE=1      (HC-05 will now only connect with the paired device)
AT+LINK=1D,A5,68988A    (Connect to device)

Everything is fine, until the last step: AT+LINK.
What happens is:
>at+link=1D,A5,68988A
FAIL
+INQ:1D:A5:68988A,1F00,7FFF
OK

So it fails the AT+LINK, then for some reason, it starts inquiry mode.
I saw a guide which had CMODE=1/0 swapped. I have tried both, anyway, doesn't make any difference to the result. I should be in full AT command mode, I connected 3.3v to pin 34. The password for the ELM327 is 1234, and the default password for the HC-05 is 1234.
If I skip the link stage, then re-power the HC-05 in comms mode, then the ELM327 flashes its green LED which means its transmitting. The HC-05 flashes rapidly, then slowly, then rapidly, then slowly, and so on. But I get nothing in the serial monitor, not even garbled text.
This is the OBD reader I have
This is the HC-05 I have
So I don't know what the problem is, I have connected the HC-05 to my phone as a slave, and can send messages to and from it though the serial monitor. So its working. And the ELM327 is working fine when connected to my phone. So both are working fine.
So my guess is, either I'm missing something, like, maybe the outgoing password/pin is set with a different AT Command other than AT+PSWD? Or, maybe this particular HC-05 for some reason isn't capable of master mode? Or maybe the ELM327 I have for some reason will never accept a connection from something other than an android phone?
I just wondered if anyone has some experience with this, and can advise, before I go off and buy another HC-05 and another ELM327. Thanks in advance for any help.
Just for more information, I'm using an ESP32, which I know has bluetooth and I wanted to use it, but I couldn't find how to enter it's AT Commands (at least, not easily), it was just easier to buy a HC-05. So since the ESP32 has 3.3v outputs I don't use a voltage divider. I use the 5V out for the VCC on the HC-05, and I use the 3.3v out to go directly to pin 34. Here's the sketch I use to enter AT Commands:
#include "HardwareSerial.h"
#define RXD2 16                //Arduino pin connected to Tx of HC-05
#define TXD2 17                //Arduino pin connected to Rx of HC-05

HardwareSerial BTSerial(2);

char c=' ';
boolean NL = true;

void setup()
{
  // initialize the 2 serial ports:
  Serial.begin(38400);  //For the arduino to communicate with the PC
  Serial.print("Sketch:   ");   Serial.println(__FILE__);
  Serial.print("Uploaded: ");   Serial.println(__DATE__);
  Serial.println(" ");

  BTSerial.begin(38400, SERIAL_8N1, RXD2, TXD2); //-> HC-05 AT mode baud rate is 38400
  Serial.println("BTserial started at 38400");
  Serial.println(" ");
}

void loop() {

  // Read from the Bluetooth module and send to the Arduino Serial Monitor
  if (BTSerial.available()) {
    c = BTSerial.read();
    Serial.write(c);
   }

  // Read from the Serial Monitor and send to the Bluetooth module
  if (Serial.available()) {
    c = Serial.read();
    BTSerial.write(c);

    // Echo the user input to the main window. The ">" character indicates the user entered text.
    if (NL) { Serial.print(">");  NL = false; }
    Serial.write(c);
    if (c==10) { NL = true; }
  }
}

I have exactly the same problem. Did you find a solution?
I tried to enter the AT-mode by pushing small button and request the status of the device (AT+STATE?). Device status changed from inquaring to connecting. But the module cannot establish a connection with ELM327

Sorry, I didn't find a solution, I emailed the company who made the module, and they said sometimes there are compatibility issues. They couldn't tell me which one would work, theres a few different ones out there. What I ended up doing is using wires, connecting TX/RX on the arduino to the RX/TX on the ELM327, and it works fine.

AT+CMODE=1 (HC-05 will now only connect with the paired device) // tha's wrong, the CMODE that only allow to conect with a device is CMODE=0


text:
OLED shield for wemos d1 mini pro not staying on
I recently bought a wemos d1 mini pro to toy with wifi and bought a oled shield with it. I've been looking on youtube and github for software and I finally found the software and got it to load onto the board. however, the shield is only on for a fraction of a second and I don't know why.
here is the code
#include "SPI.h"
#include "Wire.h"
#include "Adafruit_GFX.h"
#include "Adafruit_SSD1306.h"

#define OLED_RESET 0  // GPIO0
Adafruit_SSD1306 display(OLED_RESET);

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

display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
// init done

display.display();
delay(2000);

// Clear the buffer.
display.clearDisplay();

// text display tests
display.setTextSize(2);
display.setTextColor(WHITE);
display.setCursor(0,10);
display.println("Hello");
display.println("World");

display.display();
delay(10000);
display.clearDisplay();
}

void loop() {

}

here is what it says when uploading
Build options changed, rebuilding all
Sketch uses 278084 bytes (26%) of program storage space. Maximum is 1044464
bytes.
Global variables use 27432 bytes (33%) of dynamic memory, leaving 54488
bytes for local variables. Maximum is 81920 bytes.
esptool.py v2.6
2.6
esptool.py v2.6
Serial port COM5
Connecting....
Chip is ESP8266EX
Features: WiFi
MAC: b4:e6:2d:53:19:6b
Uploading stub...
Running stub...
Stub running...
Changing baud rate to 460800
Changed.
Configuring flash size...
Auto-detected Flash size: 16MB
Flash params set to 0x0290
Compressed 282240 bytes to 204639...

Writing at 0x00000000... (7 %)
Writing at 0x00004000... (15 %)
Writing at 0x00008000... (23 %)
Writing at 0x0000c000... (30 %)
Writing at 0x00010000... (38 %)
Writing at 0x00014000... (46 %)
Writing at 0x00018000... (53 %)
Writing at 0x0001c000... (61 %)
Writing at 0x00020000... (69 %)
Writing at 0x00024000... (76 %)
Writing at 0x00028000... (84 %)
Writing at 0x0002c000... (92 %)
Writing at 0x00030000... (100 %)
Wrote 282240 bytes (204639 compressed) at 0x00000000 in 4.8 seconds
(effective 467.5 kbit/s)...
Hash of data verified.

Leaving...
Hard resetting via RTS pin...

and this is the monitor
0⸮~?⸮4⸮!⸮⸮⸮⸮OCAG⸮⸮

thank you for your time

How is it all being powered?

through a usb from my computer

you set io 0 as reset. to which D pin on the board did you wire the reset pin of the display? D0 (io 16) or D3 (io 0)?

did you try to remove the last two lines of setup()?

I assume I wired the reset pin to the reset pin on the wemos mini pro due having soldered all 16 male pins on the oled shield going into all 16 female pins on the top half of the wemos mini pro. I did remove the cleardisplay() line but not the second to last. I'll try that tomorrow morning

sorry. It is a shield so you don't wire it. I found the schematics

i tried removing the last 2 lines from the setup code but it did nothing. I also have a dc power shield which i just tried and it doesn't help

I fixed the problem. I was the one who did the soldering so i decided to make the soldering better and now it works. thank you juraj for your time


text:
Having an issue accessing values from a pointer
Context
This may be more of a C++ question than an arduino specific question, but it's dealing with arduino c++ so I thought I'd start here.
I'm building a class to abstract some simple melody playing that I want for a project. I got everything working in a procedural way, so I started moving everything out to a header and cpp file (still new-ish territory for me).
The general concept is that I want to call a public method on my class to allow my code to play a specific melody. I defined an enum for each melody available and in my playMelody() method I'm using a couple of pointers and a switch statement to get the specific frequencies and durations I need to play the specific melody. These frequency and duration values are stored in private arrays in the class.
Here's the header:
// MelodyPlayer.h

enum MELODY
{
    SHAVE_AND_A_HAIRCUT = 0,
    IDLE,
    READY,
    PROCESSING,
    COMPLETE,
};

class MelodyPlayer
{
    uint8_t speakerPin;

    int melody_shaveAndAHairCut[9];
    int durations_shaveAndAHairCut[9];
    int *activeMelody;
    int *activeDurations;

    void _playMelody();

public:
    MelodyPlayer(uint8_t speakerPin);
    void playMelody(MELODY name);
};

MelodyPlayer::MelodyPlayer(uint8_t pin)
{
    speakerPin = pin;

    int melody_shaveAndAHairCut[] = {
        NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4, 0};

    int durations_shaveAndAHairCut[] = {
        4, 8, 8, 4, 4, 4, 4, 4, 4};
}

void MelodyPlayer::playMelody(MELODY name)
{
    switch (name)
    {
    case SHAVE_AND_A_HAIRCUT:
        Serial.println("Shave and a hair cut");
        activeMelody = melody_shaveAndAHairCut;
        activeDurations = durations_shaveAndAHairCut;
        break;
    }

    _playMelody();
}

And here's the implementation:
// MelodyPlayer.cpp

void MelodyPlayer::_playMelody()
{
    Serial.println("Playing Melody");
    // * pulled from the toneMelody arduino example
    for (int thisNote = 0; thisNote < 8; thisNote++)
    {

        int activeDuration = activeDurations[thisNote];
        int noteDuration = 1000 / activeDurations[thisNote];
        int noteFrequency = activeMelody[thisNote];

        Serial.println(thisNote);
        Serial.println(activeDuration);
        Serial.println(noteDuration);
        Serial.println(noteFrequency);

        tone(speakerPin, noteFrequency, noteDuration);

        int pauseBetweenNotes = noteDuration * 1.30;
        delay(pauseBetweenNotes);

        noTone(speakerPin);
    }
}

And I call it in my .ino file like this:
MelodyPlayer player = MelodyPlayer(SPEAKER);
player.playMelody(SHAVE_AND_A_HAIR_CUT);

The problem
I'll upload the sketch and everything fires. The problem I'm running into is that when I get to the private _playMelody() method the values I get for activeDuration, noteDuration and noteFrequency are all ultra wrong:

I imagine I'm doing something wrong with the setting and getting of the values via the pointer variable I set in the switch statement, but I'm not sure where I'm going wrong.
You can see/pull down the actual code from the abstracting-to-class branch of my repo if you want to dig in.
I've done a similar dynamic-selection-via-pointer in a proof of concept before, but it was procedurally written, not classed. I can't seem to figure out where the difference is :|
Any ideas?

Your melody and duration arrays that contain the actual data are local to the constructor. Further to that, they aren't used, so the compiler will optimize them away.

As Majenko mentioned in the comment, you created new local arrays in the constructor, but never put anything in the member arrays of the classes. They have the same name, but are not the same variable. Responsible for creating the new variable is the keyword int. However, you cannot simply assign array values by just omitting the int. Therer are multiple possibilities:

You can fill the array for each index: durations_shaveAndAHairCut[0] = 1;
You can copy your local array to the member variable with memcpy: memcpy((void*)this->durations_shaveAndAHairCut, (void*)durations_shaveAndAHairCut, 9*sizeof(int));
You can declare the arrays static in the class declaration and initialize it outside of the constructor in MelodyPlayer.cpp:
int MelodyPlayer::durations_shaveAndAHairCut[] = {
    4, 8, 8, 4, 4, 4, 4, 4, 4};

I prefer the last option.

Awesome! Thanks for the help! I went with the last option. It definitely feels like the most simple and straight forward solution.


text:
Arduino Stepper motor control programming problem
I want to control the speed and position of stepper motor by a 4*4 keypad and monochrome graphic lcd interfaced with arduino. some open sources gave me good hint points to start controlling the distance and the speed of the stepper motor .
 I have made some modifications on the code in order to use it in both controlling the speed of motor and distance. I expect from the code either to:
1- change the position from 1 line to another and change the value at each parameter and see it on the graphic screen.
2- To change the page of the graphic lcd and modify each parameter separately in each page.
[I tried to code the first option but I faced the problem of changing the line to the next parameter without changing the written value, and that was a bit hard to me.]
The code contains of functions that changes the pressed keypad signal to a readable number to be able to draw it in the lcd, then these functions are called by case statements.
I have modified the code to have a number string for each parameter separated from the other one.
When I modified the loop code (as cleared below), I have seen that when I press 'A' or 'B' for the first time, one of the parameters screen is shown on the screen and the loop of this parameter is activated, and I can not change the parameter by pressing the other button.
 This is because of the While loop [While(1)] which frames me in one of the buttons loops forever.
When I remove this loop, the case statements are no longer valid, I just see the change in the screen but I can not add or remove any number.
So that I tried to change it this loop with other options like: while( keypressed == 'A') or [do -- while(0)] or if statements, but no results on the screen.
this is the part of the code.
void loop()
{

char keypressed = customKeypad.getKey();  // Get value of keypad button if pressed

if (keypressed != NO_KEY)     // If keypad button pressed check which key it was
{
    if (keypressed == 'A')
    {
        Serial.println("A");
        draw3();
        while(1)
        {
            char key1 = customKeypad.getKey();
            if (key1 !=NO_KEY)
            {
                switch (key1)
                {
                    case '1':
                        checknumber(1);
                        break;
                    case '2':
                        checknumber(2);
                        break;
                    case '3':
                        checknumber(3);
                        break;
                    case '4':
                        checknumber(4);
                        break;
                    case '5':
                        checknumber(5);
                        break;
                    case '6':
                        checknumber(6);
                        break;
                    case '7':
                        checknumber(7);
                        break;
                    case '8':
                        checknumber(8);
                        break;
                    case '9':
                        checknumber(9);
                        break;
                    case '0':
                        checknumber(0);
                        break;
                    case '*':
                        deletenumber();
                        break;
                    case'#':
                        calculatedistance();
                        break;
                    }
                }
            }
        }
        if (keypressed == 'B')
        {
            draw4();
            Serial.println('B');
            while(1)
            {
                char key1 = customKeypad.getKey();
                if (key1 !=NO_KEY)
                {
                    switch (key1)
                    {
                        case '1':
                            checknumber(1);
                            break;
                        case '2':
                            checknumber2(2);
                            break;
                        case '3':
                            checknumber2(3);
                          break;
                        case '4':
                            checknumber2(4);
                            break;
                        case '5':
                            checknumber2(5);
                            break;
                        case '6':
                            checknumber2(6);
                            break;
                        case '7':
                            checknumber2(7);
                            break;
                        case '8':
                            checknumber2(8);
                            break;
                        case '9':
                            checknumber2(9);
                            break;
                        case '0':
                            checknumber2(0);
                            break;
                        case '*':
                            deletenumber2();
                            break;
                        case'#':
                           stepperspeed();
                           break;
                        }
                    }
                }
            }
        }
    }

this looks like an exact same question that has been asked very recently .... are you asking this question again? ... is this a school assignment?

note: because of their simplicity, the switch blocks would actually be more readable if you single-lined the case statements ... like so case '1':   checknumber(1);   break; ... line up the command lines into neat columns

Seems like you have three tasks: 1. reading the keypad 2. writing the lcd 3. controlling the stepper. Which of those is the problem? Asking for help in all of them is too broad to answer in my opinion.

I just changed the location of the question from robotics to arduino to be more feasible. I already discovered that I already have more than 1 issue to talk about because as you say there is more than 1 task.
If I solved the first part between the LCD and the keypad, I think that the rest of controlling the stepper will not be a problem, as designing a graphic layout is the most harsh part in the coding. anyway I have changed the method. if you are interested, check my 2nd question and I will be grateful if you helped me to answer it.


text:
Send serial data at custom voltage using PWM
The Raspberry Pi has 3.3 V logic level and the Arduino has a 5V logic level.  It is warned against connecting the Arduino TX to the Pi RX:

Pi is 3.3v and the Arduino is 5v. Connect the two and you might conjure up some magic blue smoke

I was wondering if without a logic level converter chip like the CD4050, you could use the PWM functionality of the Arduino plus a low-pass-filter to effectively produce 3.3 V TX signals that would be safe for the Pi RX to receive?
I have an Arduino Uno with an ATMega8 according to the schematic.  It seems it is possible to change the frequency of the PWM pins to up to 32 kHz.  I assume it's possible to use the PWM with a low-pass-filter to effect a 3.3 V and as it runs at 32 kHz this frequency would then be more than enough to support 9600 baud rate.  Is this correct?  I'm finding it hard to search for "Arduino send serial using PWM".  The SoftwareSerial library requires any Digital IO pins so this sounds like it might not allow for using the PWM pins?  I've also read SoftwareSerial library can use the Analog Input pins for output i.e. TX?

Why the down vote?

A simple voltage divider between the Arduino TX and the Pi RX should work to protect the Pi.
And thanks to Juraj's comment, it appears that the Pi's 3.3V high will be enough to trigger the Arduino and it won't need to be boosted up to nearer 5 V.

https://arduino.stackexchange.com/questions/66170/how-does-the-dual-5v-and-3-3v-output-on-the-uno-r3-work-exactly/66180#66180

I assume it's possible to the change the value of the voltage the PWM is producing

This is not possible. PWM cannot output an analog voltage. Instead, it rapidly switches between 5 V and 0 V.

Thanks for your answer Edgar.  Could put a capacitor on it to effect a smoothing to approximate 3.3 V?

A resistor in series followed by a capacitor to ground. But that would be no simpler than a voltage divider with two resistors.

True.  I wonder why people suggest a more complex route of using the logic level converter.


text:
Communication using two HC05 modules
I'm working on a project that consists of sending data from flex sensors from a master Arduino to a slave arduino that uses that data to control servo-motors. I am trying to start slow and just control an LED using a button.
I have gone through all AT commands, have set both a master and a slave and binded the addresses but when I try to light the LED on it for some reason doesn't work. My serial monitor keeps printing the letter "d" over and over again and I don't know what this is. Code is below:
int val=0; //Master code
#define button 3
void setup() {
Serial.begin(38400);
pinMode(button,HIGH);
}
void loop(){
val=digitalRead(HIGH);
if(val==HIGH){
Serial.write(100);
delay(500);
}
delay(50);
}
}

#define led2
int pos=0;
int val;

void setup(){
Serial.begin(38400);
pinMode(led,OUTPUT);
}
void loop(){
if(Serial.available()>0){
val=Serial.read();
if(val==100 && pos==0)
{
digitalWrite(led,HIGH);
pos=1;
}
else if(val==100 && pos==1)
{
digitalWrite(led,LOW);
pos=0;
}
}
}

If anyone can help i'd appreciate

that is what you are sending ... look at lower case d on this page  ... http://www.asciitable.com/mobile/

How can I convert that value 100 to the actual decimal value? I want to send a number not an ASCII code

Currently you are sending a number. The serial monitor is just interpreting it as ASCII (since that is what the serial monitor is supposed to do). Other serial terminal programs can also shoe you the byte data, where you could see the value 100. If you want to see it in serial monitor, you have to send ASCII encoded data with Serial.print()


text:
(Advice) Home Automation Project (Domotic mobile home)
I have a project that I hope to accomplish in the near future.
I want to transform a mobile home into automation mobile home.
The elements that make up my project are the following:

My idea is to supply the home with a solar installation, disregarding their potential (we can discuss the autonomy of the system later, uses and consumptions).
The idea is to keep an Arduino always running in order to monitorize the home and provide remote administration.(like geolocation, camera and sensors control,power management for hardware ...)
The laptop can be out of the system (when I take it with me). It could be connected to a secondary monitor.
The docker provide an easy way to charge the laptop, connect devices and provide a WOL utility.
The Arduino could have differents components like Ethernet, own battery, gps... And It could switch on/off the camera and sensors.
The laptop could be powered on/off by WOL and administrate remotely.
The camera could have a microSD to save media and it can be manipulated with Arduino by a remote connection.
Arduino could get info about sensors too(as proximity).
I have some doubts:

Instead of using WOL , we could use Arduino to wake up the laptop?
It's possible to connect the laptop and the arduino by wlan or ethernet interface? or we need to wire it (usb...)?

Thanks for the attention, I await your answer.

no because you only show a network connection between the arduino and the laptop .... 2. yes and no

https://arduino.stackexchange.com/tour

@jsotola Well technically arduino can send WOL packet to the laptop.

Cool ! What have you done do far, and which bit of it are you having difficulty with?

Dou you really want to use an Arduino for this? At least the Atmega based arduinos are not capable of handling any "media".  Why not using a raspberry Pi or similar. I think that would make much more sense

If i can use Arduino than other powerful devices better ,  in order to save battery.

The Arduino is not built or powerful enough to handle things like cameras and high-speed 4g connections for remote administration. I would suggest using something like a Raspberry PI 3 as it would be much better suited to the job.
I would recommend asking this question again on the raspberry pi exchange.

But I only would use it for power on/off devices, move the point of view of the camera , and detect activation of sensors like proximity (Boolean) and thinks like that. Not processing video or these heavy tasks. I suppose the ip camera has the capacity to record video and so on. And if the PC is on the system could do other heavy tasks. I thought that with Arduino was enough for these uses.

It would be fine for the uses you just stated but configuring the arduino and the PC to work together would be quite difficult. (Like how would you get the recorded video to the computer?) Also, your computer would need to always be there so if you wanted to use your laptop in your house and moniter the sensors, there would be a problem. I think a single one board computer like a PI would be easier and more effective.

Okei thanks, I will study use PI.

If you want to save battery, you can also use a smaller Pi board, like the Raspberry Pi Zero W. Though it has no LAN, but WLAN.

Yep, under clocking the raspberry pi is also an option but you can discuss those details on the pi stack exchange/forum


text:
Using Serial.write() to send a uint32_t send one byte x4 or send 4 bytes x1
In the IRremote library, IR signals are decoded and held in results.value.  My project uses the NEC protocol which is 32 bits, so the IR code will always be 4 bytes.

uint32_t dCodedIR;
//
//  code exists here that we can ignore
//
dCodedIR = results.value

This decoded signal is then sent out the serial port to a second MCU which will be waiting for incoming data:
while (!Serial.available())  {
}

After this, there will ideally be a complete code of 4 bytes waiting in the FIFO. I will allow for times when < 4 bytes are ready (check for more, timed out? NO:loop   YES:reset), but this should rarely happen. So I want to optimize the sending code so that the receiver has the best chance of avoiding split groups. In theory, is it better to write as single bytes and repeat 4 times, or make a 4-byte array to send once?
Serial.write(dCodedIR & 255);
Serial.write((dCodedIR >> 8) & 255);
Serial.write((dCodedIR >> 16) & 255);
Serial.write((dCodedIR >> 24) & 255);

or
byte sendBuf[4];
//
//
sendBuf[3] = (byte) dCodedIR & 255;
sendBuf[2] = (byte) (dCodedIR >> 8) & 255;
sendBuf[1] = (byte) (dCodedIR >> 16) & 255;
sendBuf[0] = (byte) (dCodedIR >> 24) & 255;
Serial.write(sendBuf, 4);

(Since there will be plenty of storage space for the code, with performance being the priority, I decided against using for loops because updating an index, testing it, and looping would seem to add overhead.)

Unless you are using very high baud rates, (at least higher than
115.2 kb/s), it should make no difference.
The reason is that either version of your code should run faster than
the UART. Serial.write() doesn't wait for the bytes to be sent out the
wire. Instead, it just stores those bytes in a ring buffer that belongs
to the HardwareSerial library. When the UART is ready to accept an
outbound byte, it triggers an interrupt. The corresponding ISR takes one
byte from the ring buffer and handles it to the UART. Since the UART
itself is double-buffered, all this happens while the previous byte is
being sent.
The end result is that, with either version of your code, you end up
with a continuous byte stream. The start bit of the second byte comes
right after the stop bit of the first byte, and so on. The stream
doesn't pause until the full message is sent. That is, unless you have
somewhere in your program overly long critical sections that can impose
excessive latency to the whole process.
Side note: if your MCU is little endian (most Arduinos are), you
could also avoid one copy and just do
Serial.write((byte *) &dCodedIR, 4);

Addendum: The details may depend on the MCU you are using. On an
Uno, or similar AVR-based boards, the UART has no knowledge of the
software ring buffer. It rises the UDRE0 (data register empty) flag
whenever it is ready to accept an outbound byte in its sender data
register. When there is data in the buffer, the software enables the
data register empty interrupt, which is tied to the UDRE0 flag.

Re the interrupt handling: see expanded answer. Re Serial.available(): I don't know how the timing of your receiving code works.


text:
How to read voltage value from arduino to esp32
I am learning Arduino(uno)-ESP32 basics for a hobby project. In Arduino sketch, it's writing some random value(mimicking a sensor) to Arduino analog pin 9.
const int analogInPin = A0;  // NOT CONNECTED
const int outPin = 9;        // DIGITAL OUT. [ESP32 INPUT]

// SETUP()
randomSeed(analogRead(analogInPin));

// LOOP()
sensorValue = random(0, 1024);
// 0 - 5v WHEN MEASURED
// MAP VALUE OR JUST WRITE 'sensorValue'
outputValue = map(sensorValue, 0, 1023, 0, 255);
analogWrite(outPin, outputValue);

In ESP32 sketch, I'm trying to read this value
int adc_value = 0; // EXPECTS A VALUE B/W 0 - 4095

//SETUP()
pinMode(26,INPUT);

//LOOP()
adc_value = analogRead(26);
Serial.println(adc_value);// OUTPUT 2 VALUES; 0 AND 4095
// MAP_VALUE = (adc_value * 5 ) / (4095);

The output is only 2 values, 0 and 4095. Is it due to ESP 3.3V and Arduino 0-5v output range or some other mistakes?

it is because analogWrite is PWM. https://www.arduino.cc/en/Tutorial/PWM

esp32 analog pin's maximum is 1 V


text:
How to use while loop in arduino for infinte loop
I am doing code of esp while switching hotspot for connecting esp i am getting some problem .
I am using this line of code:
while ((!esp.find("WIFI ")) || (!esp.find("+CWJAP:3")));

but it is not working. Anybody please give me alternate how to use this type of looping.

What exactly is "not working".  Can you explain?  Otherwise it is hard, if not impossible, to help.

The find method reads the characters until the searched string is found or a timeout interval is passed.
In your case if the connection is not successful, the first find will not find "WIFI" and will read all the input including the "+CWJAP:3", then on timeout it returns false. The second find will wait until timeout and then return false.

so what i can do i have to wait until WIFI or +CWJAP=3 is come on serial monitor

read the lines returned by AT firmware into a buffer and compare the content of the buffer with expected strings. or use the WiFiEsp library, which handles the AT commands and responses for you


text:
Controller freezes
I am using atmega 2560 as main(master) controller and other 5 salve 2 atmega 8 and 3 atmega 328p, there is two device with analogue output connected to main controller atmega 2560 through ads1115 module ,ads1115 converts analogue signal into 16 bit digital data and give it to atmega 2560 via I2C,
also the main controller has serial communication with pc and I2C comm. with salves. and some motors are also connected with controllers.
Now, My issue is that there is one function which reads the data from ads1115 for fix instances and with fix time interval and prints it. for running code for some time lets say 4-5 hour , controller hangs in between that function. and after that no serial communication work. i have to switch of supply to restart the machine.

We cannot answer this without your code. Please provide a mininal working example,  that shows the observed behavior.

do you use String class?

It's hard to say anything for sure without seeing the code, but for a
program that freezes using I2C communication, I would seriously suspect
the Wire library. This library has a few loops here and there where it
waits for a specific condition on the bus, with no timeout. See
twi.c. If, for whatever reason, the condition never happens, then
the program is stuck in the infinite wait.
You could try finding al alternative I2C library or, if you can tolerate
the occasional crashes, enable the watchdog in order to get out of the
freezes.


text:
What is causing this warning in Arduino IDE?
I'm using DS3231 module with rinkydink library and it is working just fine, however every time i want to compile the code Arduino IDE shows this warning:
C:\Program Files (x86)\Arduino\libraries\DS3231\DS3231.cpp:291:106:
warning: ISO C++ forbids converting a string constant to 'char*'
[-Wwrite-strings]

What is this warning and how to solve it?

You're passing a string constant to a function that expects a variable.

But often it's library writer's mistake and that parameter could (and should) be const because there is no write access to it.

why do you use this old library?

On the face of it your argument sounds fine.  But looking at the nuts and bolts of why a const is used makes it a bit more obvious why this is a warning.  When a compiler encounters a const, it might try putting that value into (read only) program memory.  After all, you promised not to change it.  But passing it as a formal value may be interpreted as you wanting to create a variable in the called to function.  So there can be confusion or a disconnect in what the compiler does and what you expect to happen.

Before giving up, try passing a pointer to the const.  Let me know if that works and I'll post it as an answer.

@st2000, for Uno compiler doesn't put const into progmem. the problem is inside a library OP uses, so they don't do anything to cause this warning

@st2000 i don't know how to do it, sorry i'm very new to this... post an answer and if it can solve the warning i'll make it the correct answer.

I have started building up a list of common errors and their explanations: https://majenko.co.uk/blog/common-arduino-errors-and-warnings

The warning was caused by this line:
char *monthShort[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

In C++, the content of a character string such as "Jan" cannot be
modified. Thus, if you assign the string to a pointer, the pointer
should be declared as const char *:
const char *monthShort[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
                            "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

The same applies to the other arrays of strings: daysLong, daysShort
and monthLong. As a consequence, the prototypes of the methods
getDOWStr() and getMonthStr() should be changed in order to return a
const char *.
BTW, are you sure this library is still maintained? This should have
been fixed a long time ago, and it seems the source was last modified in
2015. You may be better off using a more modern alternative. For
instance, in the Arduino library manager, you can find DS3231 and
Adafruit's RTClib.

i use this library because i'm very new to arduino and everyone every where suggested this and it's easy to use, i'll try the new libraries. thanks.

The DS3231 library from Rinky Dink is the best RTC library there is...I know, I tried them ALL.  This library allows one to print date and time strings with only 3 Arduino print statements:  Serial.print(rtc.getDateStr());
      Serial.print(" -- ");
      Serial.println(rtc.getTimeStr());
Other RTC libraries force user to make the strings up themselves, at a cost of about 12 lines of useless Serial.print commands.


text:
HC-05 Bluetooth module on breakout board with straight header pins
Has anyone found the HC-05 bluetooth module (on the breakout board) with straight header pins?  I seem to only be able to find them with the 90 degree header pins.  Removing those and soldering on straight ones for my project is getting tiresome...  I would even be happy to find them without header pins (but still on the breakout board).

In short: no. How many do you need that it's becoming tiresome? If the quantity is that high it's worth designing a custom PCB to take the module directly.

That is what I thought :-\  Thanks Majenko.  I will move forward with redesign to integrate just the module.

please post a link to the module or a picture of the module


text:
RTClib library the second, second
I'm using RTClib for my DS3231 module, the problem is the library is displaying the second without zero behind it: 22:1:1 and when i print the time on my 16x2 LCD time is displaying like this:

22:22:59
22:23:19
22:23:29
...
22:23:59
22:23:10
22:23:11

the second number of seconds is not getting cleared.
i know one solution to this is to use lcd.clear() function to update the LCD in each loop but is there any other way to clear that second number or do something so library show zero behind second?

What do leap seconds have to do with anything?

@Majenko sorry there was a misunderstanding, updated the question.

Your problem is that you are printing 1. People don't do that for time. You use 01.

how to use "01"? is there a setting i have to change?

If the seconds are less than ten, then print a 0. Then print the seconds. It's that simple. The library has nothing to do with it. It's what you do with the number in your code that matters.

if you please post that as an aswer i'll pick it as correct answer. lcd.print(now.second());.

It's your responsibility to format the time properly, not the library. The library just gives you a number. If you want a leading zero then it's up to you to provide that leading zero.
For example:
if (now.seconds() < 10) {
    lcd.print("0");
}
lcd.print(now.seconds());

Or:
char timestr[9];
snprintf(timestr, 9, "%02d:%02d:%02d", now.hours(), now.seconds(), now.minutes());
lcd.print(timestr);

what's snprintf? it's giving me this error: expected constructor, destructor, or type conversion before '(' token

@newbie: It's a very standard libc function.

@EdgarBonet i'm sorry but what's the error is about?

Did you use the code inside a function or just dump it into global scope?

i'm guilty of dumping it inside the global scope... i know i'm being a headache right now but can you please explain a bit more? @Majenko

Put it in loop() where you want to display the time.

@Majenko  thank you.


text:
Can an Arduino Pro Mini interface with a full-sized WiFi shield?
We have an Arduino Pro Mini on a breadboard connected to a 9V battery and a sensor, reading data. We also have a full-sized Adafruit WINC1500 WiFi Shield with PCB Antenna. I would like to know if they can be connected and, if so, how.
I understand that a shield is usually stacked on a similarly sized board, but can we place the shield on the breadboard with the Mini and use jumper wire to connect the necessary pins so the Mini can use the WiFi (actually, we want to write to the SD card on the WiFi shield)? If so, how would we know which pins are used, and would we need to provide additional power? Or is connecting a Mini to a full-sized shield a ridiculous idea?

I would like to know if they can be connected and, if so, how.

Yes.

but can we place the shield on the breadboard

No, the pins are misaligned and won't plug in.

and use jumper wire to connect the necessary pins so the Mini can use the WiFi

Yes - connect the jumper wires directly to the WiFi shield pins.

If so, how would we know which pins are used,

Read the manual or schematic for your WiFi shield. It probably uses the SPI pins plus a few more.

and would we need to provide additional power?

It will need a power connection, yes - though "extra" power? Not sure what you mean.

Thanks. By extra power, I meant would I need an additional power source or if the shield could share the 9V battery with the mini.

@EllenSpertus Throw your 9V battery away. It's useless, so don't even start to use it. Use an AA or AAA battery pack.


text:
Person (phone) detector that trigger an event esp32 cam
So me and my dad are trying to catch would be thieves and also someone leaving behind alcohol bottles. At his storage business the cameras don't reach to these spots.
Without being too invasive I want to sense bluetooth and/or wifi signals of relatively close phones sort of like a pax counter. This is in lue of using a pir sensor which I have always found finicky and I want to make use of the esp32' cam's wifi/ble chip.
So to start I researched for the past few days or week. I found that most phones don't use ble so maybe that is out. I also found that the esp32 cam is a bit finicky and I'm not sure if it is compatible with other code I have found.
One time I was able to get the light to come on when my phone was near using code I found for the esp32.
Any help or direction would be nice
Edit: I understand this sounds weird but mostly I would just like to get proximity of bluetooth or wifi to trigger an event. The device is powered by battery and I understand not everyone carrys phones.

Sniffing for wifi request probes could be an option. Knowing the networks a person was connected to can even be sufficient to identify or at least recognise different persons. I have absolutely no idea if that's possible on an esp32. The most difficult thing when doing this on a raspberry pi is finding a network adapter that supports monitor mode and I don't actually know whether the esp's interface supports that or not.

"I was able to get the light to come on when my phone was near" - how did you do this? Was your phone somehoe connected before or was it incognito like a stranger's would be?

incognito. but looking back it is possible it was responding to other BLE devices near by. I would bring the phone close sometimes the light would change. sometimes it wouldnt. It was very strange. The esp32 supports monitor mode its just I havent found any code that would compare RSSI strength of nearby devices. Or if thats even possible?

Detecting a phone could be easily done by capturing WiFi probe requests which are sent by phones having at least one saved WiFi network. Note that such requests alone are often enough to identify the person, if their home WiFi SSID is set to something like "Davids_wifi".
Software-wise, this would be much easier to do on Linux (think Raspberry Pi or a similar device) which already have all the network sniffing software like tcpdump, which you would otherwise have to find or implement on ESP32.
I'm leaving out the legal implications of what you're trying to do as I don't know what country you are in, but bear in mind that hidden surveillance may be illegal in some cases.


text:
Is it possible to execute a code in runtime when gets updated over the air (OTA)?
I would like to build a lib like ArduinoOTA but with no downtime at runtime. To achieve that I am wondering if it is possible to create a simple setup and loop code to

Check for new releases
If we have a new one start download it
As download routine is not finished keep running the current release
When download has finished, swap current release to the new one.
Now the normal routine is running the new release.

I am pretty interested if it is possible to do by myself something like that.
I didn't find any paper or articles similar to this and I don't known if this is a challenge for Arduino scope or C/C++.
Maybe I am saying something bizarre but I have been thinking of save new release into flash memory, point to it and discard the old release from flash memory.

On an 8-bit Arduino? No. Or certainly not without a huge amount of work.

what are you trying to achieve? ... maybe it can be done without reflashing the program

@jsotola I am trying to deploy releases over the air without downtime in the middle of this process. That is, I want to download a new release from Internet and keep running the old one until the new has been downloaded.

that does not actually answer the question, it is a repeat of your question .... is it possible that an "update" could involve changing only some parameters that could be read from an online server

The "update" I am talking about is a new version of the current sketch previously uploaded to Arduino manually.

but the new sketch doesn't have everything on the same address. how will the instruction pointer be set to a good address. and what will initialize the new variables. reset is necessary

and about what MCU is it?

@Juraj Hmm make sense! Do you have any paper a could read for something like that? These questions is for my final paper and I am trying to do update OTA like we see in Web or Apps. It would be awesome if we have the same in IoT ecosystem.

The MCU will be an Arduino or ESP8266. I read both use Modified Harvard Architecture and can share instruction and data code. But you have a point when saying the MCU will don't know how to know the complete path for instruction pointer

Sorry. ESP8266 ESP-01

esp8266 has ArduinoOTA library supported by the  SDK. for SAMD Arduino has OTA anf I made this kind of OTA for ATmega  https://github.com/jandrassy/ArduinoOTA

On many Arduinos the processor is only a few dollar part.  You are asking for a feature that only starts appearing on platforms where the processor is over an order of magnitude higher in price.  Further, such inexpensive processors normally run a single program.  Running a sketch while managing a download & update would best be done by two programs existing in an operating system.  Again, likely requiring a processor an order of magnitude higher in price.
Instead, consider implementing your design using two different Arduinos.  Swapping one out for the other after updating.   Hot swapping may not be trivial.  This really depends on how your application interfaces with the world. But likely will be much easier than solving the problem of designing the supporting software to make sketch updates transparent to the Arduino user.

This is honestly the most simple and yet fun to implement. It is not be a perfect solution but definitely could attend me. Thank you so much for that!


text:
DS3231 and EEPROM
Currently to get time/date i'm using DS3231 module with the RTClib library, i want to use the Atmel 24C32 chip on the module to store some small values (temperature etc).
Can i use the current library AND an external EEPROM library (which one?) OR i need to change my RTC library in order to use EEPROM feature?

why not use the EEPROM of your MCU?

@Juraj because built in EEPROM have a limited number that can be write, i think it's 100,000 times.

every EEPROM has 'limited' count of writes. you have an Arduino Uno with removable ATmega328?

@Juraj yes but 24C32 have write cycle of 1 million times instead of 100,000 times of ATmega328.

Can i use the current library AND an external EEPROM library (which one?)

Yes. Devices on an I2C bus are separate devices and use their own separate libraries.

https://playground.arduino.cc/Main/LibraryForI2CEEPROM/

is this a proper library to use?

It's the first hit on Google so I guess so. I don't use Arduino and have my own chipKIT DTWI based library so I don't know.

just in case anyone stumble upon this question; i tested this library and it's working.


text:
Get 5V output from NodeMCU
I have a sensor that requires used of 5V as input to Vcc. But I dont see any 5V output pins on the NodeMCU 1.0(12E). Is there a way I could get 5V output pins?
Its not a duplicate question. I want a 5V output and not provide 5V input to NODEMCU.

Its not a duplicate question. I want a 5V output and not provide 5V input to NODEMCU.

I also did not know the Vin pin could be used for output; read the accepted answer from Majenko.

Got it. Thanks.

The VIN pin outputs 5V approximately (dependent on USB input voltage) from the NodeMCU board.

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

thank you @VE7JRO!

On my boards, the Vin pin outputs 4.76V because there's a Schottky diode between Vusb and the Vin pin which drops the voltage (see the circuit diagram). This Vin is also quite noisy and is a poor power source for analog circuitry.


text:
What is the use of reserved pins and SDD2, SDD3 pins of the NodeMCU?

How to use the reserved pins on the NODEMCU? What is their use? Also what is the use of SDD pins?
Thanks.

you can use GPIO10 as an input.

The ESP8266 uses an external flash memory chip to store your program. It communicates with this flash chip over a 4 bit SDIO interface, on GPIO6-11. These pins are labeled SDDn, SDCLK and SDCMD.
Usually, the interface uses all 4 data lines (QIO), but you can also configure it to use only 2 of the 4 lines (DIO), giving you access to two more GPIO pins (9 & 10).
The reserved pins are not mentioned in the schematic. They cannot be IO pins, because there simply are no other pins on the ESP8266/ESP-12. It could be pins connected to the USB chip, connected to power lines, or not connected at all. The designers probably wanted to allow for extra pins on next iterations of the board, without changing the form factor. A quick search online didn't yield any results, so your best bet is to trace the connection on the PCB, or measure it with a multimeter. You probably shouldn't be using them anyway, because they are "reserved".

it is SPI so in some special cases it can be used, but the SDK controls the CS pin of the flash. while it is HIGH, the bus is free


text:
ESP8266-01 is not working and it's hot
it has been so long since I tried to connect the esp8266 through Arduino Uno and get it to work my goal is to send data from the Arduino Uno to web site, I have tried everything and a lot of codes but none worked at first I could get a response  but sometimes it does and sometimes it does not I even bought an other one but the new one did not respond at all so I flashed the old one following the instructions in here and I got response the next day I tried to reuse it and it does not respond at all not even when I put the serial on 115200 and both NR&CR and tried AT but nothing showed in return .i found this tutorial
and I tried to get it to work using a mobile app but as usual, it does not work
AT
AT+RST
ATE0
AT+CWMODE=1
AT+CWQAP
AT+CWDHCP=1,1
AT+CWJAP="RemoteXY","12345678"

but i did not get hte name of it wifi in my wifi list
this is the code
// RemoteXY select connection mode and include library
#define REMOTEXY_MODE__ESP8266_HARDSERIAL

#include <RemoteXY.h>

// RemoteXY connection settings
#define REMOTEXY_SERIAL Serial
#define REMOTEXY_SERIAL_SPEED 115200
#define REMOTEXY_WIFI_SSID "RemoteXY"
#define REMOTEXY_WIFI_PASSWORD "12345678"
#define REMOTEXY_SERVER_PORT 6377

// RemoteXY configurate
#pragma pack(push, 1)
uint8_t RemoteXY_CONF[] =
  { 255,2,0,0,0,30,0,8,13,0,
  2,0,70,25,22,11,2,26,31,31,
  79,78,0,79,70,70,0,1,0,10,
  26,12,12,2,31,88,0 };

// this structure defines all the variables of your control interface
struct {

    // input variable
  uint8_t switch_1; // =1 if switch ON and =0 if OFF
  uint8_t button_1; // =1 if button pressed, else =0

    // other variable
  uint8_t connect_flag;  // =1 if wire connected, else =0

} RemoteXY;
#pragma pack(pop)

/////////////////////////////////////////////
//           END RemoteXY include          //
/////////////////////////////////////////////

#define PIN_SWITCH_1 2
#define PIN_BUTTON_1 12

void setup()
{
  RemoteXY_Init ();

  pinMode (PIN_SWITCH_1, OUTPUT);
  pinMode (PIN_BUTTON_1, OUTPUT);

  // TODO you setup code

}

void loop()
{
  RemoteXY_Handler ();

  digitalWrite(PIN_SWITCH_1, (RemoteXY.switch_1==0)?LOW:HIGH);
  digitalWrite(PIN_BUTTON_1, (RemoteXY.button_1==0)?LOW:HIGH);

  // TODO you loop code
  // use the RemoteXY structure for data transfer

}

i wired it like this

one last thing is it gets hot every time so what could be the problem what's wrong with is what should I do

Sounds like it's dead, Jim.

both, even the new one ?

Hit is not good. Maybe there is something fundamentally wrong that you are doing to them.

like what i connected the RX -> RX /TX-> TX/ CH_en and vcc to 3.3 v of the arduino / gnd ->gnd

Well yes, that's something fundamentally wrong. Connect RX to TX and TX to RX instead.

I tried that too I even tried to connect them to other arduino pins

It's probably already dead. It's too late to try changing things now.

Also you omitted the resistors for your LEDs. You're well on the way to killing the Arduino too.

but i tried to flash it and tried the at and responded yes then i tried at+rst and responded error but then i tried AT+UART_DEF=9600,8,1,0,0 i  then it does not respond at all again .i did not put the leds was trying it with without

when a chip gets hot as soon as the VCC/GND is connected, it means :

The VCC/GND are internally connected due to a previous failure (it
gets hot AFTER the accident).
An output pin, is connected to a supply rail through a very low resistance load (or short circuited). pins usually sink or
source as low as 20mA of current. so if you connect them to a load
less than (3.3/20)*1000 ~= 150 ohms (in your case with 3.3v supply),
you are going to fry the output driver. always be sure that a pin, even if it's defined as an input, has a little resistor (a 220 ohms res).
this accident happens between output/supply or output/output pins.

you may have misconnected TX pin to a wrong pin.

i have connected to tx the TX of the arduino in this example .how do i know if it is working

@ElaHidri you mean TX to RX right ? TX line connects to RX line of the other end

yes I even tried other Arduino pins .do I need to add level shifter?

no you don't need a level shifter for ESP8266 and Arduino as the esp pins are 5v tolerant. but it you connect TX to another "output" pin you may have damaged them. TX pin is an output, idle high pin. another output pin with idle low, short circuits the pins @ElaHidri

@ElaHidri even though people seem to successfully do so, by the official specs the esp8266 is not 5V tolerant. You supply the esp with 3.3V at vcc, so connecting any pin to a 5v logic level directly is incorrect.


text:
esp8266 esp01s EEPROM and flashing
which flash option do I need to take to use EEPROM?
Can I flash with 1MB and no SPIFFs and still write data to EEPROM?
thanks T

Can I flash with 1MB and no SPIFFS and still write data to EEPROM?

Yes. The EEPROM emulation is saved into different part of the flash, not to SPIFFS.
|--------------|-------|---------------|--|--|--|--|--|
^              ^       ^               ^     ^
Sketch    OTA update   File system   EEPROM  WiFi config (SDK)

the memory map is from esp8266 SPIFFS docs

which flash option do I need to take to use EEPROM?

There is no special option in Tools menu for EEPROM emulation. Only use the library.


text:
How to write a float value EEPROM
I'm using this library for my DS3231 which have a Atmel 24C32 on it.
i have a float value which increases by 0.5, like:
27.50
28
28.50
...
the code is like this:
float lowTemp= 10.5

float highTemp= 10.5

void setup(){
  lowTemp = i2c_eeprom.read(100);
  highTemp = i2c_eeprom.read(101);
}
void loop(){
  if ((menuswtichStatus == HIGH) && (lcdWelcome == HIGH)) {
    previousMillis = millis();
    lcd.clear();
    menuScroll++;
    lcdClear = 1;
    lcdClear2 = 1;
  }
  if (menuScroll == 1) {
    lcd.setCursor(0, 0);
    lcd.print("Temperature set:");
    lcd.setCursor(0, 1);
    lcd.print("Minimum  ");
    lcd.print(lowTemp);
    lcd.print((char)223);
    lcd.print("C ");
    if (plusSwitchstatus == HIGH) {
      lowTemp += 0.5;
    }
    if (minusSwitchstatus == HIGH) {
      lowTemp -= 0.5;
    }
  }
  if (menuScroll == 2) {
    lcd.setCursor(0, 0);
    lcd.print("Temperature set:");
    lcd.setCursor(0, 1);
    lcd.print("Maximum  ");
    lcd.print(highTemp);
    lcd.print((char)223);
    lcd.print("C ");
    if (plusSwitchstatus == HIGH) {
      highTemp += 0.5;
    }
    if (minusSwitchstatus == HIGH) {
      highTemp -= 0.5;
    }
  }
  if (menuScroll == 3) {
    lcd.setCursor(0, 0);
    lcd.print("   Saving the");
    lcd.setCursor(0, 1);
    lcd.print("   Settings...");
    delay(1000);
    i2c_eeprom.write(100, lowTemp);
    i2c_eeprom.write(101, highTemp);
    delay(1000);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("    SETTINGS");
    lcd.setCursor(0, 1);
    lcd.print("     SAVED!");
    delay(2000);
    menuScroll = 0;
    lcdClear = 0;
    lcdClear2 = 0;
  }
}

i have the library and stuff up there, it's just an example of my code...
The float value is not saving(written), what's the solution?

multiply by two before writing as an integer or a byte

@jsotola i don't know how...!

perhaps you need to be asking more basic questions about bytes, integers, floats, strings, etc.

You have multiple options:

According to jsotola's remark: the easiest is to multiply your value by 2, store it, and after reading, divide it by 2. In one byte you can store a value from 0 to 127.5 (255 / 2), or if you use signed from -64.0 to +63.5. Of course you also can use an offset in case you know the value cannot be less than e.g. -20.
If you need a higher range, you can still multiply it by 2, but store it in two bytes. Split the value in a 'high value' (value % 256) / 256, and a 'low value' (value % 256).
If you want to store the value completely, than use sizeof(float) to find the length, and a for loop to write each byte, starting from the first byte of the float until the last one.


text:
Arduino MKR 1010 WiFi as BLE central/client
I'm trying to use my new Arduino MKR 1010 WiFi as a Bluetooth Low Energy central/client, however I could only find information on how to use it as a peripheral/server (for example with the ArduinoBLE library, which only supports peripheral mode).
Is this possible? Maybe with a different library or firmware for the integrated NINA-W102 chip?

were you able to use it as central device?

@EinSoldiatGott Unfortunately not. I ended up using the ESP32 which worked perfectly.

In case this thread turns up in a search, the ArduinoBLE library now includes central and peripheral support.


text:
Firmware backup and restore
I need to have the firmware stored somewhere on the board in order to get back to it after flashing a new firmware.
Is there a way to store a backup of the firmware somewhere, and use a button to erase a newer firmware and get back to the old one, without re-flashing the old firmware again ?

you would need to use a device that could store multiple firmware files ... this device would reflash the firmware without the need of a computer .... possibly another arduino

possible theoretically - I noticed you tagged esp32 - they usually have 4MB flash, and the "standard" size for sketch binary is 1MB, so there's 3MB you could use. However, it's not going to be simple

Yes. You need to create a factory partition and upload your bin file to there.
You can read more about ESP32 partitions here
Note that none of the partition schemes in the ESP32 core have factory partitions, so you will need to create a custom one and link it to a menu entry (look at the boards.txt file to see how that is done).
The existing partition files are just .csv files within the ESP32 core. Copy one and modify it, then link that to a menu entry using the new file name.

Working on it. Thank you :)


text:
Optical mouse sensor M116504386 arduino libary
I am doing project and I used optical mouse IC sensor M116504386 with 16 pins and I don't know how to get this sensor libraries to interface it with arduino uno.

When I google "M116504386", I get 2 results in Chinese. Is this the sensor you are using? https://www.sparkfun.com/products/retired/12907 Can you tell us which library you're using?

do you still have the mouse? ... if you have it, try to determine the schematic diagram of the mouse


text:
Any possible way to stack Motor Driver shield L293D with Xbee Shield v03 on arduino?
So i am trying to stack these two shield on arduino, now the problem here is that i guess there is a conflict between the pins of arduino being used by both shields, so can anyone suggest a solution?

the XBee uses Serial on 0,1 (conflict with USB). the motor shield doesn't use the Serial pins. why do you think there is a conflict between shields?

Read the documentation for both boards. They should list the pins used. Their associated libraries will define variables to which you can assign non-conflicting pins. Review the sample code provided as well. Usually, the sample code included setting the pins to use, even if the code only sets them to their default.
There is another possibility. I don’t think this is the case, but I’ve run into this issue with different shields. If the shields use I2C, they may need to have jumpers shorted to set an address.


text:
Arduino OSX Mojave - Serial port only shows sometimes
I've found lots of issues about serial ports not showing up at all, but none about what I'm experiencing.
Sometimes I can see my Arduino Mega 2560 in the ports list, and sometimes I can't. I've tried unplugging, replugging, rebooting my PC, and installing various CH34X USB drivers
Is there some way I can troubleshoot this issue to work out where things are going wrong?
EDIT: I have a Macbook Pro 2017 with Thunderbolt 3.0 ports connected to an adapter that lets me plug in USB. The Mega is a CH340G -> Wemos® Mega +WiFi R3 Module ATmega2560+ESP8266 32Mb Memory USB-TTL CH340G Compatible For Arduino Mega NodeMCU ESP8266.
EDIT #2: It looks like it's working again, all I did was switch around some of the DIP switches and change it from RX/TX0 to RX/TX3, sometimes when that stops working ill change it back to RX/TX0 and itll start working again. I suspect it has something to do with the USB-C adapter but haven't nailed it down yet.

maybe you have a bad usb cable

@jsotola would a bad USB cable only work sometimes but not other times? surely the fact that it was working for a while means the USB cable is okay?

A cable could work "sometimes" if one or more of its connections were poorly soldered (for instance) and conducted or not, depending on how the cable was flexed. I'd certainly call that a bad cable. You could try flexing the cable near either cable-head, or (less likely, but who knows?) along its length, and watch your PC for detection or not. Or simpler: try another cable, especially a known good one if you can. If one works, and one works "sometimes", well ....

Thanks @JRobert I'll try with a couple different USB cables

A colleague at work was struggling with a similar problem just two days ago.
He said he resolved it by reinstalling the USB driver. I did not pay much attention to more details (because I did not have that problem). If you can not work how to reinstall and none can advise how, I can ask him on Monday.
In the meantime here are a couple of reinstall the USB driver links:
https://www.roland.com/global/support/support_news/18091014/
https://forum.arduino.cc/index.php?topic=570440.0
https://support.serato.com/hc/en-us/articles/115001883474-macOS-High-Sierra-10-13-macOS-Mojave-10-14-and-above-driver-install-process
Hopefully one of these will help you.
Here is the link that my colleague followed:
https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver
All I can add is that this one worked for him. He has I have High Sierra (version 10.13.3) and needed to reboot after the installation.

thanks @GMc I've tried reinstalling drivers a couple of times now to no avail

I will try to catch my colleague  tomorrow and ask him for more details about what he did.

@user2620825 I've finally caught up with my colleague and updated my answer with what he did. Hopefully this will help you with your problem,


text:
Getting "spikes" from an array of values - measure rpm using accelerometter
For a project where I intend to use an arduino and an accelerometer to get rpm of an diesel / gasoline engine i intend to use following solution.
I glued an mma8453 accelerometer to a neodium magnet which will be placed on a metallic part of the engine.
Using an arduino I am reading values from accelerometter and calculate one final value which is sqrt (acc.x^2 + acc.y^2 + acc.z^2), and also get millis for each value.
The values looks like this:
First column = millis, second acc value and third I identified maximums and millis since last maximum for them. Assuming that for an engine you have to max's per revolution I can calculate rpm of the engine.
My issue is that I have no idea how to write a function to do that.
Any help really appreciated
Thanks
269503  310
269504  303
269506  334
269507  326
269509  331
269510  330
269512  380
269513  377
269514  392
269516  400
269517  339
269519  393
269520  368
269521  353
269523  346
269524  316
269527  330
269528  281
269530  196
269531  195
269532  162
269534  119
269535  140
269537  132
269538  90
269539  99
269541  122
269542  168
269544  224
269545  219
269546  211
269548  268
269549  301
269551  334
269552  332
269554  316
269555  329
269556  379
269558  363
269559  381
269561  388
269562  403
269564  400
269565  420 49
269566  388
269569  360
269570  346
269572  259
269573  276
269574  284
269576  242
269577  207
269579  192
269580  145
269582  119
269583  113
269584  45
269586  125
269587  142
269589  123
269590  205
269591  243
269593  304
269594  308
269596  305
269597  298
269599  321
269600  340
269601  360
269603  380
269604  384
269606  370
269607  372
269608  413
269611  441 46
269612  395
269614  355
269615  332
269617  290
269618  317
269619  286
269621  227
269622  190
269624  172
269625  199
269627  146
269628  154
269629  177
269631  176
269632  156
269634  136
269635  174
269636  212
269638  260
269639  318
269641  291
269642  321
269644  304
269645  315
269646  343
269648  339
269649  360
269651  393
269652  390
269654  305
269656  405
269657  458 46
269659  358
269660  372
269662  339
269663  277
269664  298
269666  241
269667  203
269669  208
269670  185
269672  130
269673  165
269674  105
269676  87
269677  109
269679  128
269680  176
269681  229
269683  226
269684  271
269686  343
269687  307
269688  320
269690  318
269691  322
269693  322
269694  369
269697  363
269698  413
269699  399
269701  388
269702  426 45
269704  395
269705  380
269707  342
269708  311
269709  309
269711  315
269712  221
269714  227
269715  198
269716  113
269718  111
269719  88
269721  44
269722  69
269723  107
269725  158
269726  200
269728  232
269729  247
269731  313
269732  338
269733  348
269735  366
269736  339
269739  348
269740  377
269741  378
269743  385
269744  394
269746  403
269747  447
269749  454 47
269750  398
269751  380
269753  302
269754  245
269756  299
269757  310
269758  238
269760  206
269761  180
269763  108
269764  81
269766  83
269767  11
269768  119
269770  106
269771  169
269773  245
269774  270
269775  311
269777  338
269778  341
269780  332
269782  337
269783  337
269785  380
269786  387
269788  382
269789  373
269791  398
269792  414 43
269793  408
269795  387
269796  374
269798  285
269799  290
269801  326
269802  266
269803  211
269805  221
269806  191
269808  120
269809  175
269810  63
269812  147
269813  59
269815  120
269816  183
269817  196
269819  252
269820  301
269822  334
269824  325
269826  334
269827  310
269828  351
269830  354
269831  358
269833  373
269834  379
269835  332
269837  386
269838  404 46
269840  383
269841  385
269843  332
269844  266
269845  301
269847  282
269848  188
269850  199
269851  182
269852  128
269854  163
269855  119
269857  120
269858  140
269860  120
269861  129
269862  212
269864  230
269865  241
269868  290
269869  304
269871  340
269872  350
269873  327
269875  323
269876  351
269878  369
269879  387
269880  379
269882  380
269883  421 45
269885  373
269886  364
269888  360
269889  305
269890  302
269892  266
269893  249
269895  202
269896  229
269897  136
269899  122
269900  128
269902  49
269903  98
269904  107
269906  158
269907  211
269910  235
269911  225
269913  269
269914  314
269915  341
269917  335
269918  325
269920  348
269921  410
269923  375
269924  404
269925  419
269927  425
269928  442 45
269930  436
269931  400
269932  393
269934  326
269935  259
269937  307
269938  265
269940  220
269941  199
269942  183
269944  86
269945  83
269947  98
269948  23
269949  65
269952  124
269953  152
269955  221
269956  249
269957  287
269959  350
269960  331
269962  323
269963  341
269964  338
269966  389
269967  388
269969  380
269970  370
269972  358
269973  415 45
269974  403
269976  377
269977  381
269979  338
269980  328
269982  284
269983  246
269984  197
269986  178
269987  230
269989  162
269990  171
269991  141
269993  258
269995  138
269997  111
269998  163
270000  212
270001  192
270002  304
270004  287
270005  294
270007  349
270008  309
270009  334
270011  332
270012  364
270014  361
270015  408
270017  336
270018  421
270019  432 46
270021  361
270022  361
270024  342
270025  271
270027  288
270028  310
270029  235
270031  218
270032  166
270034  136
270035  146
270036  102
270039  78
270040  99
270042  122
270043  105
270044  181
270046  222
270047  293
270049  299
270050  299
270052  318
270053  349
270054  344
270056  349
270057  382
270059  381
270060  412
270062  380
270063  397
270064  425 45
270066  381
270067  367
270069  332
270070  272
270071  291
270073  296
270074  178
270076  177
270077  190
270080  123
270081  146
270082  107
270084  85
270085  108
270087  117
270088  148
270089  234
270091  223
270092  238
270094  283
270095  301
270097  332
270098  331

(Is this homework or are you really designing something?) You are leaving out stuff like why are you using a magnet?  Where are you placing the NXP part? That leaves us with having to guess at what is going on.  Calculating based on guessing, I'd say your engine is running at about 1304.3 rpms.

Is a mix actually between homework and design. The accelerometter is fixed on a magned and together attached to engine. Actually measure vibrations of the engine. When there is a detonation, then I have a high value. I don t know what you mean by NXP.

NXP (aka Motorola, Freescale & maybe Qualcomm) is the OEM for the chip you specified.

A simple approach would be to filter the signal using a low-pass filter, and then just calculate the time between two zero crossings.
Here's an example that works on your data. It's written in Python for easy testing and plotting, but trans-coding it to C++ should be trivial.

I used an Exponential Moving Average low-pass filter to get rid of the noise. Depending on the frequencies involved, you can change the shift factor. The higher this factor, the lower the cut-off frequency, and the greater the phase shift.
I chose a fixed DC offset, but if necessary, you could use another (very slow) filter to get rid of it before applying the zero-cross detection.
If you want to, you could use both zero crossings. Use the average of the two last RPM measurements in that case, to compensate for asymmetric waveforms.
You could add another EMA to smooth out the RPM measurements.
class ZeroCrossRPMCounter:
    def __init__(self,
                 max_rpm: float):
        self.min_distance = int(round(60_000 / max_rpm))

        self.first_crossing = True
        self.time_of_last_crossing = 0
        self.rpm = float('nan')
        self.previous_value = 0

    def __call__(self, time_ms: int, value: int):
        new_crossing = self.previous_value >= 0 and value < 0
        if new_crossing:
            if self.first_crossing:
                self.time_of_last_crossing = time_ms
                self.first_crossing = False
            elif (time_ms - self.time_of_last_crossing) >= self.min_distance:
                self.rpm = 60_000 / (time_ms - self.time_of_last_crossing)
                self.time_of_last_crossing = time_ms
            else:
                new_crossing = False
        self.previous_value = value
        return new_crossing

class EMA_shift_round:
    def __init__(self, shiftfac: int, initial: int = 0):
        self.shiftfac = shiftfac
        self.fixedPointOneHalf = 1 << (shiftfac - 1)
        self.z = initial << shiftfac

    def __call__(self, x: int):
        self.z += x
        shifted = (self.z + self.fixedPointOneHalf) >> self.shiftfac
        self.z -= shifted
        return shifted

if __name__ == '__main__':
    import numpy as np
    from matplotlib import pyplot as plt

    # Load the data
    data = np.genfromtxt('rpm-ctr-data.csv', delimiter='\t', dtype=np.int)
    time, signal = data[:, 0], data[:, 1]
    t_start, t_end = time[0] * 1e-3, time[-1] * 1e-3

    # Find the DC offset
    offset = int(round(np.mean(signal)))
    print(offset)

    # Initialize the filter and RPM counter
    lp_filter = EMA_shift_round(3)
    counter = ZeroCrossRPMCounter(2000)

    # Iterate over the data, filter it, and count the RPM
    peaks = []
    rpms = []
    filtered = np.zeros(len(time))
    for n in range(len(time)):
        filtered[n] = lp_filter(signal[n] - offset)
        new_crossing = counter(time[n], filtered[n])
        if new_crossing:
            peaks.append(time[n] * 1e-3)
            rpms.append(counter.rpm)

    # Plot the results
    plt.figure(figsize=(10, 6))
    plt.subplot(3, 1, 1)
    plt.title('Original signal')
    plt.plot(time * 1e-3, signal)
    for peak in peaks:
        plt.axvline(peak, color='red')
    plt.xlim((t_start, t_end))
    plt.subplot(3, 1, 2)
    plt.title('Filtered signal')
    plt.plot(time * 1e-3, filtered)
    for peak in peaks:
        plt.axvline(peak, color='red')
    plt.axhline(0, color='black', linestyle=':')
    plt.xlim((t_start, t_end))
    plt.subplot(3, 1, 3)
    plt.title('RPM measurements')
    plt.plot(peaks, rpms, '-o')
    plt.axhline(np.mean(rpms[1:]), color='red', linestyle=':')
    plt.xlim((t_start, t_end))
    plt.xlabel("Time [s]")
    plt.tight_layout()
    plt.show()

Those values are retrieved using i2c from accelerometer (mma8453). Not sure how can I add that filter. Also the rpm is around 670-680 rpm. I take actually time from each max and I have around 45-47 ms between each detonation. The issue is that the max is not always the same of course and somehow I try to get these points.

@lucian_v You just call counter(millis(), lp_filter(new_value)) every time you get a new measurement. It doesn't matter where the new value comes from. Finding the maximum is less accurate than using the zero crossings, because in the maximum, the slope is close to zero, resulting in a larger error on the time axis.

I think most cars use a magnetic pickup next to the fly wheel to derive engine timing.  The method picked here is likely to have several problems.  For example, how to avoid picking up the shock of more than one cylinder compressing and exploding.  Or, perhaps the motor developed on is out of balance.  And a more nominal motor vibrates less making the project difficult to apply universally.
That said, using FFTs (Fast Fourier Transforms) is an alternative but fundamentally similar approach to detecting zero crossings for finding fundamental frequencies, and hence the engine's RPM.
This "FFT on an Arduino" article describes how to implement Fast Fourier Transforms on an Arduino.  It uses the FFT libraries hosted here on github.

This being "partly" school, I think you will gain some points if you walk in knowing the basics of Fast Fourier Transforms.

The approach suggested by tttapa is an excellent suggestion. But just to
give you more options, you can consider using an hysteretic crossing
detector instead of a filter. The hysteresis in a comparator consists of
having one threshold value for detecting the high → low transition, and
another, higher value, for the low → high transition. This tends to
provide good immunity against noise, as noise spikes will not be able to
trigger false transitions as long as they are smaller than the
hysteresis (i.e. the difference between the thresholds).
Here is an example function that performs this detection. If you feed it
all your data samples, it will always return false, except exactly
once per signal period.
const int LOW_THRESHOLD = 220;
const int HIGH_THRESHOLD = 300;

/* Returns true when a high threshold crossing is detected. */
void crossing_detector(int x)
{
    static enum { BELOW, ABOVE } state;
    if (state == BELOW && x >= HIGH_THRESHOLD) {
        state = ABOVE;
        return true;
    }
    if (state == ABOVE && x < LOW_THRESHOLD) {
        state = BELOW;
    }
    return false;
}

Now, it is perfectly possible to combine tttapa's filter idea with this
hysteretic crossing detector. The issue with the low pass filter is that
it is tricky to find the right time constant. If you filter too
aggressively, you may kill the signal at high RPMs. If you don't filter
enough, you may end up keeping enough noise to trigger false zero
crossings. If you use an hysteretic detector instead of a plain
zero-crossing detector, then you will be able to use less aggressive
filtering, as you will not be sensitive to the small residual noise.

how did you choose 220 and 300 values?

@lucian_v: By looking at your data. Every oscillation goes well below 220 and above 300. No noise spikes cover that range.


text:
Is this the right way of using an RF communication?
I have a 433Mhz Superheterodyne receiver and a hand set remote of similar frequency, I'm using the RC-Switch library and I couldn't find a better way than using the "numbers" that I'm receiving like this:

#include <RCSwitch.h>

RCSwitch mySwitch = RCSwitch();

void setup() {
  Serial.begin(9600);
  mySwitch.enableReceive(0);  // Receiver on interrupt 0 => that is pin #2
  pinMode(13, OUTPUT);
}

void loop() {
  if (mySwitch.getReceivedValue() == 7264305) {
    digitalWrite(13, LOW);
  }
  if (mySwitch.getReceivedValue() == 7264308) {
    digitalWrite(13, HIGH);
  }
  if (mySwitch.getReceivedValue() == 7264306) {
    mySwitch.resetAvailable();
  }
}

Is there any other (better?) way than just using the "numbers" simply like that or everyone are using their remote commands like I'm using?

all data is just numbers ... your transmission data appear to be 24 bits long ... for example decimal 7264305 translates to 24 bit binary 011011101101100000110001, which can be described in hexadecimal as 6ED831 .... some of the bits are the switch states and the rest are probably a predetermined filler that could be used to check the validity of the transmission or they may be the address of the transmitter

for the received values of 7264305, 7264306 and 7264308, the last 4 bits of the received data are 0001, 0010 and 0100 respectively

Credits for this answer are mainly for jsotola (see his remarks above). But I want to show an alternative to the if statements, and a way to get the last 4 bits:

In case you want to check for the least significant bits, use ((mySwitch.getReceivedValue() & 0xFFFFF0)
TO check for the least significant four bits (the data you want to act upon), use ((mySwitch.getReceivedValue() & 0xF)
Use a switch statement instead of the if statement; also in theory (I don't know the code of mySwitch.getReceivedValue() does not need to be executed multiple times.

So you get something like this:
void loop()
{
  unsigned long receivedValue = mySwitch.getReceivedValue(); // Call function only once

  if ((receivedValue & 0xFFFF0) == 0x6ED830)
  {
    // Process action
    switch (receivedValue & 0xF)
    {
    case 0x5:
      digitalWrite(13, LOW);
      break;

    case 0x8:
      digitalWrite(13, HIGH);
      break;

    case 0x6:
      mySwitch.resetAvailable();
      break;

    default: // All other values
      break; // Ignore
  }
}