body:
I am working on a smart IR receiver that reads an IR signal, decodes it and saves that decoded info in a json file stored on the NodeMCU's SPIFFS. This info is then displayed on the embedded web server in a table.

Now my problem is that even though I correctly save the signal's info in the json file (and when I try to print it in console it looks perfect), the son file is not correctly passed to my web server and the table remains empty. I am using jQuery to read the file and make the changes in the HTML. All the web server files (HTML, css & JavaScript) were tested first on my local machine with an example Json file of the same structure I am using on my SPIFFS so I know for sure the problem is not in there.

It is worth noting that I faced this problem when developing on my local machine, where the table would remain empty even though the json file is not, but it was fixed when I used the Live Server extension on VSCode. However, I don't understand if this is the problem how is it that there is no server to pass the json file on when all my web interface files are correctly passed and loaded from the SPIFFS.

I will include a portion of my code, and of course all help is appreciated.

```
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266mDNS.h>
#include <ESP8266WebServer.h>
#include <Arduino.h>
#include <IRremoteESP8266.h>
#include <IRrecv.h>
#include <IRutils.h>
#include<FS.h>   // Include the SPIFFS library
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <ArduinoJson.h>

ESP8266WiFiMulti wifiMulti;     // Create an instance of the ESP8266WiFiMulti class, called 'wifiMulti'

ESP8266WebServer server(80);    // Create a webserver object that listens for HTTP request on port 80

String getContentType(String filename); // convert the file extension to the MIME type
bool handleFileRead(String path);       // send the right file to the client (if it exists)

// Declaring a variable to hold JSON object size
//const size_t capacity = JSON_OBJECT_SIZE(10);

// Creating a JSON document to hold signal entry
//DynamicJsonDocument doc(capacity);

// Declaring array size
const size_t array_capacity = JSON_ARRAY_SIZE(16) + JSON_OBJECT_SIZE(1) + 16*JSON_OBJECT_SIZE(9);

// Creating a JSON document to hold all signal entries in a nested array
DynamicJsonDocument array_doc(array_capacity);

// Creating a nested JSON array to hold all signal entries
JsonArray signals = array_doc.createNestedArray("signals");

// Declaring a JSON object to hold single signal entry
JsonObject signal_entry;

// Declaring method that save JSON object to JSON file stored on SPIFFS
void saveJSON();

// Declaring method that prints JSON file stored on SPIFFS
void printJSON();

void setup(void){
  Serial.begin(115200);         // Start the Serial communication to send messages to the computer
  delay(10);
  Serial.println('\n');

  Serial.println("Connecting ...");
  int i = 0;
  while (wifiMulti.run() != WL_CONNECTED) { // Wait for the Wi-Fi to connect: scan for Wi-Fi networks, and connect to the strongest of the networks above
    delay(250);
    Serial.print('.');
  }

SPIFFS.begin();                           // Start the SPI Flash Files System

  server.begin();                           // Actually start the server
  Serial.println("HTTP server started");

  server.onNotFound([]() {                              // If the client requests any URI
    if (!handleFileRead(server.uri()))                  // send it if it exists
      server.send(404, "text/plain", "404: Not Found"); // otherwise, respond with a 404 (Not Found) error
  });

void loop(void){
  server.handleClient();                    // Listen for HTTP requests from clients

//Creating a JSON object from the JSON document
    signal_entry = signals.createNestedObject();

    //Assigning correct values to keys in JSON object
    signal_entry["date"] = currentDate;
    signal_entry["protocol_type"] = protocol_type;
    signal_entry["bitNr_device"] = bitNr_device;
    signal_entry["bitNr_op"] = bitNr_op;
    signal_entry["codeDec_device"] = codeDec_device;
    signal_entry["codeDec_op"] = codeDec_op;
    signal_entry["codeHex_device"] = codeHex_device;
    signal_entry["codeHex_op"] = codeHex_op;
    signal_entry["codeBin_device"] = codeBin_device;
    signal_entry["codeBin_op"] = codeBin_op;

    serializeJsonPretty(signal_entry, Serial);
    Serial.println("");

    saveJSON();
   }
}

String getContentType(String filename) { // convert the file extension to the MIME type
  if (filename.endsWith(".html")) return "text/html";
  else if (filename.endsWith(".css")) return "text/css";
  else if (filename.endsWith(".js")) return "application/javascript";
  else if (filename.endsWith(".ico")) return "image/x-icon";
  return "text/plain";
}

bool handleFileRead(String path) { // send the right file to the client (if it exists)
  Serial.println("handleFileRead: " + path);
  if (path.endsWith("/")) path += "index.html";         // If a folder is requested, send the index file
  String contentType = getContentType(path);            // Get the MIME type
  if (SPIFFS.exists(path)) {                            // If the file exists
    File file = SPIFFS.open(path, "r");                 // Open it
    size_t sent = server.streamFile(file, contentType); // And send it to the client
    file.close();                                       // Then close the file again
    return true;
  }
  Serial.println("\tFile Not Found");
  return false;                                         // If the file doesn't exist, return false
}

void saveJSON(){
  File jsonFile = SPIFFS.open("signals.json", "w");
  if (serializeJsonPretty(array_doc, jsonFile) == 0) {
    Serial.println("Failed to write to file");
  }
  jsonFile.close();
}

void printJSON(){
  uint8_t* pBuffer;
  File testFile = SPIFFS.open("signals.json", "r");
  if(testFile){
    unsigned int fileSize = testFile.size();
    pBuffer = (uint8_t*)malloc(fileSize + 1);
    testFile.read(pBuffer, fileSize);
    pBuffer[fileSize] = '\0';
    Serial.println((char*)pBuffer);                // Print the file to the serial monitor.
    testFile.close();
  }
  else{
    Serial.println("Failed to read to file");
  }
  free(pBuffer);
}

```

title: Reading a json file from SPIFFS and displaying the info it contains on an embedded web page

Answers: 1

body:
Besides the somewhat strange problem of loop() being nested inside setup() (which I will put down to a copy-and-paste error) I think your main problem is that of a lack of content-type.

The function `getContentType()` is supposed to guess the content type by the filename extension. However there is nothing there to handle a .json file. So it will just default to `text/plain` - which won't be interpreted as JSON data.

You need to add a bit in there to look for JSON files and set the content-type accordingly:

    ...
    } else if (filename.endsWith(".json")) {
        return "application/json";
    }


body:
I have a HC-05 Bluetooth module Version (+VERSION:2.0-20100601).
I am using Linux Mint Rosa on an Acer laptop

**Section 1 - How it's wired**
Wiring

    HC-05       Arduino
    VCC         5V
    GND         GND
    TX          pin 1
    RX          GND via voltage divider (GND to 2k resistor{2k to HC-05 RX and a 1k resistor} 1k to pin 0)

**Section 2 - Sequence to get into AT command state**
The sequence I use to get the BT module in AT command state

- Unplug the Arduino Uno
- Unplug both the RX and TX
- Press the button on the HC-05
- Plug in the Arduino
- HC-05 LED flashes 1 time every 2 seconds
- Initialize com ports via Linux terminal - sudo chmod 0777 /dev/ttyACM*
- Upload an empty sketch
- Plug in the HC-05 RX to Arduino pin 0, and TX to pin 1
- Open the Serial monitor
- Set Both NL & CR  and 38400 baud

**Section 3 - AT commands issued**
I use the following AT commands with the noted results.

    AT                                  > OK
    AT+ORGL                             > OK
    AT+RMAAD                            > OK
    AT+VERSION  +VERSION:2.0-20100601   > OK
    AT+ADDR     +ADDR:98d3:b1:fd85b0    > OK
    AT+NAME=Master1                     > OK
    AT+UART  +UART:38400,0,0            > OK
    AT+ROLE  +ROLE:0                    > OK

NOTE:HC-05 is set to slave and it will pair (see Section 4 below)

THE PROBLEM IS AFTER PAIRING, I RETURN TO AT COMMAND MODE (Section 2) and SET ROLE=1 (Section 5) BUT IT WILL NOT PAIR IN MASTER MODE.

**Section 4 - Pairing**
I do the following to pair the HC-05 to my phone

- Unplug the Arduino
- Plug the Arduino back in
- HC-05 LED flashes quickly blink/blink/blink
- Android phone>settings>connections>Bluetooth>Scan
- 1 device found > Master1 > pair 1234
- Android app > Serial BT terminal>device>Master1>connected
- Once Android app connects:
- HC-05 LED flashes blink/blink 2 seconds then blink/blink
- Remove the RX and TX cables from Arduino and put a jumper to connect HC-05 TX to RX (loopback)
- Serial BT terminal>hello>send
- Output both green and blue - which means the data was sent via RX and returned via TX.

**Section 5 - change ROLE=0 (slave) to ROLE=1 (Master)**
I then follow the same sequence that I used previously in Section 2 to return to AT command state.

Issue the following AT commands

    AT                      > OK
    AT+ROLE  +ROLE:0        > OK
    AT+ROLE=1               > OK

Since I changed the configuration I unpair the device on my phone.
I then follow the same sequence that I previously used in Section 4 to pair the HC-05 to my phone

- HC-05 LED flashes quickly blink/blink/blink
- Android phone>settings>connections>Bluetooth>Scan - CAN'T FIND THE DEVICE.

If I return to AT Command mode and change AT+ROLE=0 it will Pair.

In Master mode:

- I tried to swap the TX and RX pins - won't pair.
- I tried to pair with the TX and RX removed from the Arduino - won't pair.
- I tried NOT UNpairing the device on the phone but it won't communicate with it via the android app once I change it to Master (Section 5).
- As I mentioned above if I return to AT Command mode and change AT+ROLE=0 it will Pair.

Lastly I have 2 other HC-05 modules and they all fail to pair when set to Master mode, so I'm thinking I'm missing something but can't figure out what it is.

I would appreciate hearing from anyone with the same problem and anyone who can determine what I'm doing incorrectly.

title: HC-05 will NOT pair in Master mode (AT+ROLE=1). Same module will pair in slave mode (AT+ROLE=0)

Answers: 2

body: You might have already solved your problem, but I just wanted to say that a HC-05 Blueooth module will only connect to a phone when it is in slave mode. The phone acts like a master, and therefore, it can't connect to another master.

body:
I observed that these device do very well in slave more, however, in Master mode, they only connect to themselves ( I mean other HC-05).
I have sevceral slave devices ( gamepads, GPS modules, ...)  that never get connected, thoug the HC-05 sees them through the INQ  command, & accurately returns their address, class, signal force, and their name even.
Though, I never succeeded to pair them !!
As if they were designed to be used together and never tested with other slave devices !!?


body:
My professor wants me to implement a display to an old project prototype we had laying around on the lab.
But he wants me NOT to use LiquidCrystal.h library or any other to achieve that.

I read HD44780 datasheet and tried lots of tweaking and hacking stuff to finally write my name "AUGUSTO" on the screen. The problem is: "lots of tweaking and hacking stuff" which turns my code into trash and kind of impossible to implement it on other project. Eg: when I accidentally short circuit arduino, display "freezes" emtpty and does not work anymore so I have to upload a generic LiquidCrystal.h example code in order to "reset" the whole thing.

My code:

```c
/*
 * Driving LCD Display without library
 * Augusto
 */

//PINS(RS to D7): (2,3,4,6,7,8,9,10,11,12,13);

// WRITE HITACHI (datasheet)

/*
 *     RS RW D7 D6 D5 D4 D3 D2 D1 D0
 * 2.  0  0  0  0  1  1  0  0  *  * -> Function set
 * 3.  0  0  0  0  0  0  1  1  1  0 -> Display ON/OFF control
 * 4.  0  0  0  0  0  0  0  1  1  0 -> Entry Mode set (INCREMENT)
 * 5.  1  0  0  1  0  0  1  0  0  0 -> H
 * 6.  1  0  0  1  0  0  1  0  0  1 -> I
 * 7.  ...
 * 8.  1  0  0  1  0  0  1  0  0  1 -> I (HITACHI)
 * 9.  0  0  0  0  0  0  0  1  1  1 -> Entry Mode set (INCREMENT) - Display Shift
 * 10. 1  0  0  0  1  0  0  0  0  0 -> Escreve um espaco
 *
 */

/*  0000 0000 01 LIMPA
    0000 0000 1— RETORNA HOME
    0000 0 0 0 1 I/D S ENTRY MODE SET
    000 0 0 0 1 DCB SETS ENTIRE DISPLAY ON/OFF
*/

/*
 *  Instruction RS R/W DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0 Description fOSC is 270 kHz)
                1  0                                   Write data Writes data into DDRAM or

                1  1                                   Read data Reads data from DDRAM or

    I/D = 1: Increment
    I/D = 0: Decrement
    S = 1: Accompanies display shift
    S/C = 1: Display shift
    S/C = 0: Cursor move
    R/L = 1: Shift to the right
    R/L = 0: Shift to the left
    DL = 1: 8 bits, DL = 0: 4 bits
    N = 1: 2 lines, N = 0: 1 line
    F = 1: 5 × 10 dots, F = 0: 5 × 8 dots
    BF = 1: Internally operating
    BF = 0: Instructions acceptable

*/

#define RS 2
#define RW 3
#define E 4
#define DB0 6
#define DB1 7
#define DB2 8
#define DB3 9
#define DB4 10
#define DB5 11
#define DB6 12
#define DB7 13

void setup() {

    for (int i = 2; i <= 4; i++) {
        pinMode(i, OUTPUT);
    }

    for (int i = 6; i <= 13; i++) {
        pinMode(i, OUTPUT);
    }

    digitalWrite(E, 0);
    returnHome();
    delay(100);
    limpa();
    delay(100);
}

void loop() {

    functionSet();
    displayOnOff();
    entryModeSet(HIGH, LOW);
    //A
    escreve(1, 0, 0, 1, 0, 0, 0, 0, 0, 1); //Writes A
    //piscaE();
    //U
    escreve(1, 0, 0, 1, 0, 1, 0, 1, 0, 1); //Writes U and so on...
    //G
    escreve(1, 0, 0, 1, 0, 0, 0, 1, 1, 1);
    //U
    escreve(1, 0, 0, 1, 0, 1, 0, 1, 0, 1);
    //S
    escreve(1, 0, 0, 1, 0, 1, 0, 0, 1, 1);
    //T
    escreve(1, 0, 0, 1, 0, 1, 0, 1, 0, 0);
    //O
    escreve(1, 0, 0, 1, 0, 0, 1, 1, 1, 1);
    piscaE();

    entryModeSet(HIGH, HIGH);

    //escreveEspaco();

    while(1) {} //infinite loop to "stop" void loop()

}

void escreve(int rs, int rw, int db7, int db6, int db5, int db4, int db3, int db2, int db1, int db0) { // Function to WRITE something on the display

    piscaE();
    digitalWrite(RS, rs);
    digitalWrite(RW, rw);
    digitalWrite(DB7, db7);
    digitalWrite(DB6, db6);
    digitalWrite(DB5, db5);
    digitalWrite(DB4, db4);
    digitalWrite(DB3, db3);
    digitalWrite(DB2, db2);
    digitalWrite(DB1, db1);
    digitalWrite(DB0, db0);
    //piscaE();
    delay(10);

}

void escreve(int db7, int db6, int db5, int db4, int db3, int db2, int db1, int db0) {
    digitalWrite(RS, HIGH);
    digitalWrite(RW, LOW);
    digitalWrite(DB7, db7);
    digitalWrite(DB6, db6);
    digitalWrite(DB5, db5);
    digitalWrite(DB4, db4);
    digitalWrite(DB3, db3);
    digitalWrite(DB2, db2);
    digitalWrite(DB1, db1);
    digitalWrite(DB0, db0);
}

void piscaE() { //Function to blink ENABLE pin

    // NOT shure how enable pin works
    digitalWrite(E, 1);
    delay(11);
    digitalWrite(E, 0);
}

void limpa() { //Function to clear display
    piscaE();
    digitalWrite(RS, LOW);
    digitalWrite(RW, LOW);
    digitalWrite(DB7, LOW);
    digitalWrite(DB6, LOW);
    digitalWrite(DB5, LOW);
    digitalWrite(DB4, LOW);
    digitalWrite(DB3, LOW);
    digitalWrite(DB2, LOW);
    digitalWrite(DB1, LOW);
    digitalWrite(DB0, HIGH);
    returnHome();
}

void entryModeSet(int id, int s) {

    //0 0 0 0 0 0 0 1 I/D S   -   ENTRY MODE SET

    digitalWrite(RS, LOW);
    digitalWrite(RW, LOW);
    digitalWrite(DB7, LOW);
    digitalWrite(DB6, LOW);
    digitalWrite(DB5, LOW);
    digitalWrite(DB4, LOW);
    digitalWrite(DB3, LOW);
    digitalWrite(DB2, HIGH);
    digitalWrite(DB1, id);
    digitalWrite(DB0, s);
}

void functionSet() {
    // 0  0  0  0  1  1  0  0  *  * -> Function set

    digitalWrite(RS, LOW);
    digitalWrite(RW, LOW);
    digitalWrite(DB7, LOW);
    digitalWrite(DB6, LOW);
    digitalWrite(DB5, HIGH);
    digitalWrite(DB4, HIGH);
    digitalWrite(DB3, LOW);
    digitalWrite(DB2, LOW);

}

void displayOnOff() {
    //0  0  0  0  0  0  1  1  1  0 -> Display ON/OFF control

    digitalWrite(RS, LOW);
    digitalWrite(RW, LOW);
    digitalWrite(DB7, LOW);
    digitalWrite(DB6, LOW);
    digitalWrite(DB5, LOW);
    digitalWrite(DB4, LOW);
    digitalWrite(DB3, HIGH);
    digitalWrite(DB2, HIGH);
    digitalWrite(DB1, HIGH);
    digitalWrite(DB0, LOW);
}

void escreveEspaco() { //Function to write a space
    //1  0  0  0  1  0  0  0  0  0 -> Writes a space
    piscaE();
    digitalWrite(RS, HIGH);
    digitalWrite(RW, LOW);
    digitalWrite(DB7, LOW);
    digitalWrite(DB6, LOW);
    digitalWrite(DB5, HIGH);
    digitalWrite(DB4, LOW);
    digitalWrite(DB3, LOW);
    digitalWrite(DB2, LOW);
    digitalWrite(DB1, LOW);
    digitalWrite(DB0, LOW);
    piscaE();
}

void escreveEspaco(int quant) { //Function to write a specific number of spaces
    //1  0  0  0  1  0  0  0  0  0 -> Writes a space

    for (int i = 1; i <= quant; i++) {
        piscaE();
        digitalWrite(RS, HIGH);
        digitalWrite(RW, LOW);
        digitalWrite(DB7, LOW);
        digitalWrite(DB6, LOW);
        digitalWrite(DB5, HIGH);
        digitalWrite(DB4, LOW);
        digitalWrite(DB3, LOW);
        digitalWrite(DB2, LOW);
        digitalWrite(DB1, LOW);
        digitalWrite(DB0, LOW);
        //piscaE();
    }
    piscaE();
}

void returnHome() { //Function to return cursor to adress 0 according to datasheet
    piscaE();
    digitalWrite(RS, LOW);
    digitalWrite(RW, LOW);
    digitalWrite(DB7, LOW);
    digitalWrite(DB6, LOW);
    digitalWrite(DB5, LOW);
    digitalWrite(DB4, LOW);
    digitalWrite(DB3, LOW);
    digitalWrite(DB2, LOW);
    digitalWrite(DB1, HIGH);
    digitalWrite(DB0, LOW);
    piscaE();
}

```

title: How to use LCD display HD44780 with arduino without using any library

Answers: 0


body:
so i replaced the mainboard in (what was) an anet a8 3d printer with a proper RAMPS setup. there was nothing wrong with it, (or at least it wasnt damaged, there are a number of severe design flaws) so i thought it might be a good start point for a remote controlled crawler/bot thing. it already has four a4988 drivers on board, plus a few mosfets and other bits which will be great for accessories (planning headlights, horn, maybe light sensor). its built around the atmega1284p, which is something of an oddball inbetween the 328 on the uno and the 2560 on the mega, but is the same product line. ive already worked out the libraries/drivers for the ch340 or whatever it is that is needed to flash code to the board,**it already has already been added to the arduino ide**, i have successfully flashed sketches to it before, but not my own. what im wondering is how to declare pins when im writing my own code. the bottom right of [this][1] schematic lists connections to the main chip, is it reasonably safe to assume that the digital pin numbers listed there can be used like the normally labeled headers on a standard board? how exactly are those numbers determined?

  [1]: https://ibb.co/5LG643b

title: pin numbering for non-standard chips

Answers: 1

body: ok so what ive found is that pins are declared in a file, `pins_arduino.h`. for each board/chip/variant another file is added(or created, if writing your own) to the arduino hardware files. in my specific case the numbers in the graphic are consistent with those listed in the hardware file, so im good


body: Can anyone send me a link tutorial about Arduino Object Oriented Programming? I want to learn Arduino, I am just a beginner.

title: Arduino Object Oriented Programming

Answers: 4

body:
Have you programmed OOP before? For alot of projects you can get away with not knowing it.

I'll also point out that if you are just a beginner, I don't recommend starting off with OOP. Stick to simpler scripts (Trust me, OOP is a pain sometimes).

If you still INSIST on starting your arduino knowledge with OOP, look up "C++ classes" or "C++ OOP" as the default language that the arduino IDE uses is just a modified version of "C++"

body:
"Arduino" is just plain old C++ with (in some cases) bits removed and some helper functions and classes.

For the smaller (lower powered AVR for example) there is no full STL in the C++ library, and some functions are of a reduced complexity (such as no floating point support in the `printf` family of functions by default).

For OOP you don't need to know anything "Arduino" - it's just C++. Any C++ OOP tutorial will teach you what you need to know for Arduino OOP.

body:
I used OOP with C++ on an Arduino Due in an open source project.

Since I did not find any tutorila for the same the example might be helpful for You.

[https://github.com/eschlot/Box-Joint-Jig-Control][1]

  [1]: https://github.com/eschlot/Box-Joint-Jig-Control

W.r.t. the usability of OOP in embedded systems for scenarios like the above one there are plenty of good reasons to use OOP. A good example is the menu structure and the display control in the project.
Nevertheless from my experience it is important to understand the effects of automatic object creation and tentative memory reorganization to the behavior of real time systems. This is much less predictable with C++ then with plain C and can be a reason to not use OOP in any real time system.

body: http://paulmurraycbr.github.io/ArduinoTheOOWay.html really helped me understand what was happening. i had some previous oop expierence with java, but i still have a hard time using multiple files vs writing more methods in one file


body:
I'm trying to make a sensor to detect that a person is within 50cm to trigger a function. But when I use the HR-SR04 sensor, it works accurately on flat surfaces (e.g. walls, books) with a margin of error around 5cm, but not on uneven surfaces (e.g. humans) where the value randomly jumps between 0cm to 1000cm.

I was thinking whether using an IR distance sensor would be better.

title: Is an Ultrasonic Sensor or Infrared Sensor better for measuring distance (to/from a human body)?

Answers: 2

body:
That depends on your requirements. An IR distance sensor will work better with different materials, since IR light is mostly reflected in very broad angles (expect for very reflective materials, like mirrors), so that uneven surfaces are also detected. But you will get a significantly worse error margin in your 50cm range. Normal IR distance sensors are just an LED and an IR photo transistor, sometime with some extra components. So the LED is lighting up and the photo transistor is measuring, how much of the IR light is coming back. The IR sensor depends also on the reflectiveness of the materials and the level of surounding IR light.

But as you don't really need to measure the distance, but just want to know, if there is an object in the range, an IR sensor might be enough. You would need to change the threshold of your IR sensor according to your needs (by experimenting with it).

All in all I think, yes, an IR sensor can give you better results for your application, though not for really measuring the distance, but only for the presence in a range with rather big error margin.

body:
I have found IR accuracy to be poor resolution (+/- a few centimeters), as it's highly dependent on the refectivity of the surface. It also frequently has very poor range (a few cm to tens of cm), depending on the emitting power of the illumination source.

I have found ultrasonics, however, even the cheap $0.99 ones you mention, to have much better resolution (+/- mm), and much better range (about 2m), depending on the code driving them. I have yet to see good non-blocking code in any library for one of these, but when I write my own non-blocking code with interrupts and basic digital signal processing, such as a median filter, I get excellent results.

So, I recommend you use ultrasonics, but it requires advanced knowledge to do it well and do it right, such as using interrupts and taking the median of every 3 to 5 samples to remove spurious results.

On very flat surfaces, such as walls, at angles 45 deg or larger, ultrasonics also do poorly, since they end up measuring the distance *including* the extra reflections off the walls, but contrary to what you experienced, on odd shaped or softer objects, such as humans, I find them to do much better. I have used ultrasonics as the means of detecting humans several times before with good results. The real secret/challenge is your code. And again, I have yet to find a library worth using, and good code on these cheap things makes a HUGE difference in results and reliability and accuracy!


body:
I have a project which needs to sleep most of the time, and when a button gets pressed, it does its thing which is producing a fading sound wave (using interrupts) until it's time to sleep again.

The goal is to reduce work load on the battery so the item can last as long as possible.

    #include <avr/sleep.h>
    void setup(){
      /*givePin! This is the pin that will spark the waking up!*/
      pinMode(givePin,INPUT);
      noInterrupts();
      set_sleep_mode(SLEEP_MODE_IDLE);
      /*changes to timers registers*/
      interrupts();
    }
    void loop(){
      ampCurrentlyOn = digitalRead(givePin);
      ampPulse =  (ampCurrentlyOn && !ampPreviouslyOn) * 255     //Reset
               + !(ampCurrentlyOn && !ampPreviouslyOn) * ampPulse//Same
               -   bool(ampPulse);  //Decay
      ampPreviouslyOn = ampCurrentlyOn;

      if(!ampPulse){//Once that value reaches 0 time to GOTO bed;
        /*This! Is this what I need to do?*/
        cli();
        sleep_mode();
        sei();
      }
    }

Am I doing in the right direction? Could any pin work? How do I get the chip to understand a pin set to digital HIGH to wake up from nap time?

Thank you!

title: Wake up from a pin, Sleep when work is done

Answers: 0


body:
I have wrote a code that communicate with my website to retrieve data to power on or off a 5V relay. I'm running the code every second to make sure it is real time. Is there more efficient way to tell Arduino to get the data whenever it is changed rather than continuous GET request.

    // Send HTTP GET request
      int httpResponseCode = http.GET();

      if (httpResponseCode>0) {
        Serial.print("HTTP Response code: ");        Serial.println(httpResponseCode);        String payload = http.getString();
            StaticJsonDocument<2000> doc;             DeserializationError error = deserializeJson(doc, payload);
            if (error) {              Serial.print(F("deserializeJson() failed: "));              Serial.println(error.c_str());              return;            }

            String status = doc["status"];
            Serial.println(status);
             if ( status == "ON" ) {
               digitalWrite(ledPin, LOW);
             } else {
               digitalWrite(ledPin, HIGH);
             }
      }

title: Frequency of Retrieving Data from Website

Answers: 1

body:
Your two best options would be [MQTT][1] and [WebSockets][2].

Both would open a long lived TCP connection that the ESP8266 and browser could use to transmit and receive data. Both would avoid constant polling to see if there's a new command.

MQTT requires an external broker. There are MQTT services with free tiers you could use for this or you could run one locally - [Eclipse Mosquitto][3] is a popular MQTT broker that runs nicely on a Raspberry Pi. MQTT is particularly useful for networks with multiple publishers and subscribers (it's a "pubsub" protocol) and is probably overkill if you just have a single device and endpoint.

It's easy to use MQTT from a browser using Javascript. The [Paho Javascript MQTT][4] client works well. The ESP8266 would establish a connection to the MQTT broker, subscribe to a topic name and set a callback function that would be called when data was published to that topic. The browser would also establish a connection to the MQTT broker and would publish a message to the topic when responding to events from the user.

WebSockets would allow the ESP8266 and browser to establish a full duplex connection between them. The ESP8266 would create a websocket server which the browser would connect to. The ESP8266 would check for data on the websocket during while running code in `loop()` and would assemble messages from the browser.

Either works easily if both your devices are on the same network (for instance, at home). If your browser is outside the network, it won't be able to communicate directly with the ESP8266.

MQTT has the advantage that an MQTT server located outside of the network (not one running locally on a Raspberry Pi) would allow the browser and ESP8266 to communicate with one another through it. WebSockets would require the use of a proxy server (there are modules for popular web servers like NGINX and Apache, but this requires control of the web server to configure). If you only ever want to use the browser to control the ESP8266 while they're both on the same network you don't need to worry about this.

  [1]: https://en.wikipedia.org/wiki/MQTT
  [2]: https://en.wikipedia.org/wiki/WebSocket
  [3]: https://mosquitto.org/
  [4]: https://www.eclipse.org/paho/clients/js/


body:
[![This is the image][1]][1]

  [1]: https://i.stack.imgur.com/e6NSE.png
I can't figure out how to do this the only wires I have are Jumper Wire and M-F 20 Pin DuPont Wire.

title: I am very new to Arduino and the kit tutorial just told me to wire this, I do not know how to wire it. Can Someone plz help!

Answers: 1

body:
If you don't have a breadboard, get one. It's a board with lots of holes in it that you can use for experimenting.

Something like this:

[![enter image description here][1]][1]
https://www.adafruit.com/product/64?gclid=EAIaIQobChMIz9XDj9bF6wIVcuW1Ch2_kgD3EAQYAiABEgL4DvD_BwE

As Delta_G said in their comment, you could wire a circuit as simple as yours by just putting the wires from the components directly into the terminals on the Arduino, but that quickly becomes impractical. Get a breadboard and learn how to use it.

  [1]: https://i.stack.imgur.com/tq9Hz.jpg


body:
I started one project where i need 4 servos to control 4 grabbers jaws. i use STM32F103C8T6 with arduino IDE for programming it. The motor TZT Micro Servo 9g SG 90. First, I was playing with stepper motors to make them rotate how I want, then I added one servo on the same protoboard where are steppers and drivers for each. I used servo sweep example, and it randomly started twitching and sometimes to spin until power is off. the STM is powered with usb cable from PC. Then i tried other 3 motors and got same result.

Then i put STM on separate protoboard and there connected servo and it was not perfect but it was much stable than on onther protoboard. Then i used old PC power supply which i modified long time ago to have jacks for 12V, 5V and 3,3V, and connected servo to it and it worked normally.

So I started connecting motors 1 by one back to protoboard with other elements and tested them while adding them, first the first one , then added second and tested both, then added 3rd and tested all 3...

First two worked fine, but when i added third, all of them started twitching again, but then it stopped. So i added fourth and now all of them are twitching even if I write in code to rotate only one or two of them, which I don't understand how they can move if I do not give them signal from code.

Here is code for controlling both servo and stepper motors:

    #include<Servo.h>

    const int stepPin1 = PA4;
    const int dirPin1 = PA0;
    const int stepPin2 = PA5;
    const int dirPin2 = PA1;

    const int stepPin3 = PA6;
    const int dirPin3 = PA2;

    const int stepPin4 = PA7;
    const int dirPin4 = PA3;

    Servo servo1;
    Servo servo2;
    Servo servo3;
    Servo servo4;

    void setup() {
      pinMode(stepPin1,OUTPUT);
      pinMode(stepPin2,OUTPUT);
      pinMode(stepPin3,OUTPUT);
      pinMode(stepPin4,OUTPUT);

      pinMode(dirPin1,OUTPUT);
      pinMode(dirPin2,OUTPUT);
      pinMode(dirPin3,OUTPUT);
      pinMode(dirPin4,OUTPUT);

      servo1.attach(PB12);
      servo2.attach(PB14);
      servo3.attach(PA8);
      servo4.attach(PA10);

      //servo1.write(0);
      //servo2.write(0);
      //servo3.write(0);
      //servo4.write(0);
    }

    void loop() {
      digitalWrite(dirPin1,HIGH);
      digitalWrite(dirPin2,HIGH);
      digitalWrite(dirPin3,HIGH);
      digitalWrite(dirPin4,HIGH);

       //servo1.write(100);
       servo2.write(100);
       //servo3.write(100);
       //servo4.write(100);

      for(int x = 0; x < 200; x++) {
        digitalWrite(stepPin1,HIGH);
        digitalWrite(stepPin2,HIGH);
        digitalWrite(stepPin3,HIGH);
        digitalWrite(stepPin4,HIGH);

        delayMicroseconds(750);

        digitalWrite(stepPin1,LOW);
        digitalWrite(stepPin2,LOW);
        digitalWrite(stepPin3,LOW);
        digitalWrite(stepPin4,LOW);

        delayMicroseconds(750);
      }

      delay(1000); // One second delay

      digitalWrite(dirPin1,LOW);
      digitalWrite(dirPin2,LOW);
      digitalWrite(dirPin3,LOW);
      digitalWrite(dirPin4,LOW);

      //servo1.write(-100);
      servo2.write(-100);
      //servo3.write(-100);
      //servo4.write(100);

      for(int x = 0; x < 200; x++) {
        digitalWrite(stepPin1,HIGH);
        digitalWrite(stepPin2,HIGH);
        digitalWrite(stepPin3,HIGH);
        digitalWrite(stepPin4,HIGH);

        delayMicroseconds(750);

        digitalWrite(stepPin1,LOW);
        digitalWrite(stepPin2,LOW);
        digitalWrite(stepPin3,LOW);
        digitalWrite(stepPin4,LOW);

        delayMicroseconds(750);
      }

      delay(1000);

    }

[Here is also link to a short video of how the servos are behaving:][1]

  [1]: https://drive.google.com/file/d/1FaKXvKQmiXgVDbzvWSbjzkILVPN4dsSE/view?usp=sharing

title: SG 90 servos randomly spinning

Answers: 0


body:
I saw the following code from <https://circuits4you.com/2018/03/10/esp8266-jquery-and-ajax-web-server/> but I could not understand it thoroughly...

I looked at the documentation of PROGMEM from this <https://www.arduino.cc/reference/en/language/variables/utilities/progmem/> but could not understand the importance in the code on why you should put your variables in flash memory instead of SRAM (the usual memory?)?

    const char MAIN_page[] PROGMEM = R"=====(
      <!DOCTYPE html>

If you click on me, I will disappear.

Click me away!

Click me too!

      circuits4you.com

    )=====";

Also, I could not understand the definition of R"====()====", what is meant by this in arduino?

title: Confuse about PROGMEM and R"====()===="

Answers: 1

body:
> why you should put your variables in flash memory instead of SRAM

Because the Arduino has only a very small amount of memory. If you have data that will never change it's better to store it in flash (of which there is much more) so as to leave the SRAM free for data that *does* change.

> Also, I could not understand the definition of R"====()====", what is meant by this in arduino?

The `R` means "Treat everything between these delimiters as a raw string".  That is, everything between `"=====(` and `)====="`. It's not an Arduino thing, but a general C++ thing ([see here](https://en.cppreference.com/w/cpp/language/string_literal)). The `=====` can be anything you like (within certain bounds) as long as it's the same at both the start and end of the string.  So you could use `R"-=(This is "text")=-"` which would assign the string `This is "text"`. It's a great way of working with long strings that may want to contain `"` as otherwise you would have to escape each and every `"` as `\"`. So the string I showed just now would otherwise have to be written as: `"This is \"text\""`, which can get very messy if there are lots of `"` in there.  The important thing to remember is that `)=====` mustn't appear in your text anywhere, so make sure it's something really obscure.


body:
I just bought an APDS-9960 sensor yesterday and tried it out today using Sparkfun's example from its APDS-9960 lib, and the only thing it printed out was:
"SparkFun APDS-9960 - ProximitySensor" twice then it didn't show any output
Using an Arduino Uno, and wires are connected correctly:

APDS :  Arduino Uno

VCC  :  3.3V

GND  :  GND

SDA  :  A4

SCL  :  SCL

INT  :  D2

I've also tried I2C scanning, and the device address was shown, but SparkFun's example code just didn't work at all.

[![IRL Wiring Pic][1]][1]

Using PCB terminals because another sensor will also be integrated into the Arduino Uno.

[![I2C Scanner Output][2]][2]

[![SparkFun Program Output][3]][3]

  [1]: https://i.stack.imgur.com/0CnoC.png
  [2]: https://i.stack.imgur.com/lM5PZ.png
  [3]: https://i.stack.imgur.com/utaT4.png

Code:

```
/****************************************************************
...
****************************************************************/

#include <Wire.h>
#include <SparkFun_APDS9960.h>

// Global Variables
SparkFun_APDS9960 apds = SparkFun_APDS9960();
uint8_t proximity_data = 0;

void setup() {

  // Initialize Serial port
  Serial.begin(9600);
  Serial.println();
  Serial.println(F("------------------------------------"));
  Serial.println(F("SparkFun APDS-9960 - ProximitySensor"));
  Serial.println(F("------------------------------------"));

  // Initialize APDS-9960 (configure I2C and initial values)
  if ( apds.init() ) {
    Serial.println(F("APDS-9960 initialization complete"));
  } else {
    Serial.println(F("Something went wrong during APDS-9960 init!"));
  }

  // Adjust the Proximity sensor gain
  if ( !apds.setProximityGain(PGAIN_2X) ) {
    Serial.println(F("Something went wrong trying to set PGAIN"));
  }

  // Start running the APDS-9960 proximity sensor (no interrupts)
  if ( apds.enableProximitySensor(false) ) {
    Serial.println(F("Proximity sensor is now running"));
  } else {
    Serial.println(F("Something went wrong during sensor init!"));
  }
}

void loop() {

  // Read the proximity value
  if ( !apds.readProximity(proximity_data) ) {
    Serial.println("Error reading proximity value");
  } else {
    Serial.print("Proximity: ");
    Serial.println(proximity_data);
  }

  // Wait 250 ms before next reading
  delay(250);
}
```

I've tried putting ```delay(100);``` below ```Serial.begin(9600);``` as suggested here: https://learn.sparkfun.com/tutorials/apds-9960-rgb-and-gesture-sensor-hookup-guide/discuss and it did not help.

Any help is appreciated!

title: APDS-9960 detected but not showing output on serial monitor

Answers: 0


body:
I managed to build a system using Wemos D1 R1 connected to my website to retrieve data to power on or off a 5V relay. Now I would like to expand the project to control all my house outlet. Assuming I have, 5 rooms each of which has 5 electricity wires to control. My question is what is the best setup to achieve my goal in terms of efficiency and cost optimization. If I clone my current setup, I would be needing Wemos Module for every room that connecting separately to my Wifi and then to my server which seems too much for me. So what would you recommend?

Thoughts:
 - Can I use one single central Wemos and then communicate to each room through ESP2866 or 433MHZ RF modules.
- I would be using at least 4 channel 5V relay Module. Could it be powered using 5V in Wemos or Arduino or should be powered with adapter
- If I want to control a fridge or AC or water heater, should I need SS Relay or any relay would suffice
- if SS Relay to be used, I have read that heat sink or fan should be included, is that a must?

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/dAtkz.png

title: Most Efficient & Cost Effective Home Automation Setup

Answers: 1

body:
I advice you to buy some Sonoff devices, either the basic or S20. (they are pretty cheap on AliExpress/ebay etc.) They are perfect for the job. Flash them with Tasmota, which you find on github [Tasmota][1]. Then use a RaspberryPi (or similar) as a server. Run Node-RED on this server to communicate via MQTT to all your (Sonoff) devices. Use Mosquitto as the MQTT broker.
I know this sounds like a lot, but thank me later when your done.

  [1]: https://github.com/arendst/Tasmota


body:
I was trying to run a code from this <https://circuits4you.com/2018/03/10/esp8266-jquery-and-ajax-web-server/>

I am pasting it here.

    /*
     * ESP8266 NodeMCU jQuery CDN Demo
     *
     * https://circuits4you.com
     */
    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>

    //ESP Web Server Library to host a web page
    #include <ESP8266WebServer.h>

    //---------------------------------------------------------------
    //Our HTML webpage contents in program memory
    const char MAIN_page[] PROGMEM = R"=====(
      <!DOCTYPE html>

If you click on me, I will disappear.

Click me away!

Click me too!

      circuits4you.com

    )=====";
    //---------------------------------------------------------------

    //On board LED Connected to GPIO2
    #define LED 2

    //SSID and Password of your WiFi router
    const char* ssid = "circuits4you.com";
    const char* password = "yourWiFipassword";

    //Declare a global object variable from the ESP8266WebServer class.
    ESP8266WebServer server(80); //Server on port 80

    //===============================================================
    // This routine is executed when you open its IP in browser
    //===============================================================
    void handleRoot() {
     Serial.println("You called root page");
     String s = MAIN_page; //Read HTML contents
     server.send(200, "text/html", s); //Send web page
    }
    //==============================================================
    //                  SETUP
    //==============================================================
    void setup(void){
      Serial.begin(115200);

      WiFi.begin(ssid, password);     //Connect to your WiFi router
      Serial.println("");

      //Onboard LED port Direction output
      pinMode(LED,OUTPUT);

      //Power on LED state off
      digitalWrite(LED,HIGH);

      WiFi.mode(WIFI_STA); //WiFi mode station (connect to wifi router only

      WiFi.begin(ssid, password);

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

      //If connection successful show IP address in serial monitor
      Serial.println("");
      Serial.print("Connected to ");
      Serial.println(ssid);
      Serial.print("IP address: ");
      Serial.println(WiFi.localIP());  //IP address assigned to your ESP

      server.on("/", handleRoot);      //Which routine to handle at root location. This is display page

      server.begin();                  //Start server
      Serial.println("HTTP server started");
    }
    //==============================================================
    //                     LOOP
    //==============================================================
    void loop(void){
      server.handleClient();          //Handle client requests
    }

When I deploy this to my nodemcu esp-12e, I a m getting below error

I used the exception decoder

    Exception 3: LoadStoreError: Processor internal physical address or data error during load or store
    PC: 0x4000bf64
    EXCVADDR: 0x4023d581

From the decoder it says the offending line is this one

    void handleRoot() {
     Serial.println("You called root page");
     String s = MAIN_page; //<<<<<<<<<<<<<<<<<<<<<< Error on this line
     server.send(200, "text/html", s);
    }

It looks like it cannot read from the variable in PROGMEM..

I replaced that line with this code and converting it into a string and the error was gone.

    String MAIN_page = R"=====(
      <!DOCTYPE html>

If you click on me, I will disappear.

Click me away!

Click me too!

      circuits4you.com

    )=====";

Is there something wrong in the code that I am following on how it reads the variable from the PROGMEM flash memory?

title: Error reading from PROGMEM

Answers: 2

body:
You cannot assign a PROGMEM string directly to a String object. Besides, the whole concept makes no sense, since String objects store their data in RAM regardless.

If you want to use PROGMEM you need to use `const char *` not `String`.

body: The whole point of using PROGMEM is to save the RAM for other uses.  If you have a huge string that would overflow your RAM then PROGMEM is essential.  However, if the string isn't too large and the program works fine, then just use String instead of PROGMEM.


body:
I am using an Arduino Leonardo to have hotkeys for OBS but they don't work when the OBS Studio window is not focused.

I have the Leonardo press Ctrl + Alt + Shift + F7 when I press a button connected to the Leonardo. On OBS I have Ctrl + Alt + Shift + F7 switch to a slide. When I have the OBS window focused and I press the button it works fine. But when I have another application focused it does not work. The strange thing is, is that when I press (on my keyboard) Ctrl + Alt + Shift + F7, it will switch to the slide, but when I press the button it does not work.

I am running OBS as an Administrator btw.

My code for the Leonardo is below
```
int pinA = 8;

void setup() {
    pinMode(pinA, INPUT);
}

void loop(){
digitalWrite(pinA, HIGH);
readPinA = digitalRead(pinA);
if (readPinA == 0){
    Serial.print("A\n");
    Keyboard.press(KEY_RIGHT_CTRL);
    Keyboard.press(KEY_RIGHT_ALT);
    Keyboard.press(KEY_RIGHT_SHIFT);
    Keyboard.press(KEY_F7);
    Keyboard.releaseAll();
    delay(250);
    }
}
```

title: Leonardo keypresses not working with OBS

Answers: 1

body:
*Warning: the below is all supposition.*

When the OBS window is focused the OS can send keyboard events to the window. That means that it gets "The button has been pressed" messages. These are generated when the "press" events are sent from the Leonardo.

When the OBS window *isn't* focused it can't be sent those messages - so it has to manually poll the state of the keyboard to see what buttons are pressed at any one time. It can't be doing this *all* the time, so it does it periodically (but still pretty fast).

The knock-on effect is, though, that when not focused it can only see buttons that have been pressed for at least enough time for it to poll the state.

If you add a delay into your routine between the last "press" and the "release all" commands that is longer than the period between polling (no idea what that is - you'll have to experiment, but starting at around 50ms to 100ms should be adequate) you should give OBS enough time to see that the buttons are pressed before you then release them.


body:
My problem is actually in two stages.
I am very new to arduino uno and 8266-01. I have read many documents and watched videos for nearly 2 weeks, but I cannot even run the simplest "blink" example.

First of all, I installed the compatible software with an esp download tool as follows according to 6014h. And it seems okay.
[![enter image description here][1]][1]

After triple check, my wires and connections where they have to .
Rx->Rx  Tx->Tx  CH-3.3v GPI0 grounded Ground->Ground  and also 8266-01 VCC connected to Arduino 5v with 3.3v regulator and connected with capacitor, to debug voltage i check with voltmeter.

Problem is:
When I try to upload simple Blink example below imag.  My IDE gives a very different output from the videos I watched. I could not understand the reason for this.

the IDE outputs on the all of videos that i watched, are while uploading

[![enter image description here][2]][2]

This kind of upload starts when it says upload and when it's finished, the program runs.

BUT!In my case my  IDE is acts like that and nothing happens end of the upload.

[![enter image description here][3]][3]

My 8266 generic settings are as follows.

[![enter image description here][4]][4]

Led out pin in the blink example is 2 and GPI1 is connected to led to blink after all this explanation, where i missed up ?

Why i am taking different uploading process and code is not working?

  [1]: https://i.stack.imgur.com/MxcFy.png
  [2]: https://i.stack.imgur.com/eSnmN.png
  [3]: https://i.stack.imgur.com/smQU1.png
  [4]: https://i.stack.imgur.com/htFM1.png

title: ESP8266-01 Upload Sketch Problem Arduino UNO

Answers: 0


body:
I'm working on a hobby project with Sparkfun OBDII UART + Arduino Uno + 16x2 LCD Screen, i'm trying to read my car's RPM-Speed-Coolant Temprature-Oxy Sensor on runtime.

[Product Page][1]

Wired OBDII to Arduino as:
OBD TX -> ARDUINO RX
OBD RX-> ARDUINO TX
OBD GND -> ARDUINO GND

As far as i understand OBDII board does all the job and it's just communicating with arduino through serial, they provided an example here : [Hookup Guide][2]

I don't have sparkfun serial lcd, so i've changed codes according to my lcd as follow;

    #include <SoftwareSerial.h>
    #include "DFRobot_RGBLCD.h"
    const int colorR = 255;
    const int colorG = 0;
    const int colorB = 0;
    DFRobot_RGBLCD lcd(16,2);  //16 characters and 2 lines of show
    char rxData[20];
    char rxIndex=0;
    int vehicleSpeed=0;
    int vehicleRPM=0;
    void setup()
    {
    lcd.init();
    lcd.setRGB(colorR, colorG, colorB);
    Serial.begin(9600);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Hiz: ");
    lcd.setCursor(0,1);
    lcd.print("Devir: ");
    delay(1500);
    Serial.println("ATZ");
    delay(2000);
    Serial.flush();
    }

    void loop()
    {
    Serial.println("010D");
    getResponse();
    getResponse();
    vehicleSpeed = strtol(&rxData[6],0,16);
    lcd.setCursor(4,0);
    lcd.print(vehicleSpeed);
    lcd.print(" km/h");
    delay(100);
    Serial.flush();
    Serial.println("010C");
    getResponse();
    getResponse();
    vehicleRPM = ((strtol(&rxData[6],0,16)*256)+strtol(&rxData[9],0,16))/4;
    lcd.setCursor(6,1);
    lcd.print(vehicleRPM);
    delay(100);
    }
    void getResponse(void){
      char inChar=0;
      while(inChar != '\r'){
        if(Serial.available() > 0){
          if(Serial.peek() == '\r'){
            inChar=Serial.read();
            rxData[rxIndex]='\0';
            rxIndex=0;
          }
          else{
            inChar = Serial.read();
            rxData[rxIndex++]=inChar;
          }
        }
      }
    }

with above code i believe arduino receives last rpm and speed record before i shut down the engine which is 832RPM - 13 Kmh (at this point i'm not sure if arduino receive speed value correctly because when i shut down the engine i was parked the car and speed was 0kmh), in normal case when i start the car rpm and speed value should have changed but even after started the car the value stands still,it's not changing.

I bought waveshare's USB FTDI(TTL) adapter to figure it out is this board communicate with car or pc properly, connected usb ttl as;
OBD TX -> TTL RX
OBD RX-> TTL TX
OBD GND -> TTL GND

connected to OBDII port of my car, opened tera term, connected to COM20 (ttl defined as com20 on the pc) and run below commands as suggested in their manual;

    ATZ -- resetted card successfully
    ATRV -- returned 12.4 V as it should be, which is my battery voltage
    ATSP0 -- auto find and select car's protocol it returned OK
    010C -- RPM of the car it returned 41 0C 00 00 (engine wasn't started)
    010C -- RPM of the car it returned 41 0C 10 F4 (engine started--idle RPM arround 1.000 rpm)
    010D -- speed of the car it returned 41 00 00
    010D -- speed of the car it returned 41 00 00 both value is the same because the car is not moving :)

According to above outcome the board is fine and communicating with car or pc or arduino without any problem.

But when i try with arduino when i connect the board to my car and turn my ignition to battery mode it reads rpm as 832 and speed as 13 and don't update those values even i start the engine.

What am i doing wrong?

[![enter image description here][2]][2]
[![enter image description here][3]][3]
[![enter image description here][4]][4]
[![enter image description here][5]][5]

  [1]: https://i.stack.imgur.com/JJyY9.jpg
  [2]: https://i.stack.imgur.com/Uuamb.jpg
  [3]: https://i.stack.imgur.com/SsyIA.jpg
  [4]: https://i.stack.imgur.com/ImPzf.jpg
  [5]: https://i.stack.imgur.com/n2eeV.jpg

title: Sparkfun OBDII - Arduino Uno Stuck at 832RPM-13Kmh

Answers: 1

body:
after 1 week of try i finally solved it :)

As you guys know UNO has 1 i/o serial port, and Sparkfun's OBDII board doesn't work on same i/o serial port (at least i couldn't be able to), with uno when you send a command through serial to obd board you need to wait minimum 3 seconds to send another command or car's can-bus thinks that you canceled the first command returns STOPPED error, but with MEGA it works perfectly because mega has 3 i/o serial ports. You simply define Serial(TX)-Serial1(RX) and it works perfectly with 75ms delay.

Here is the working code.

    //Set up ring buffer
    char rxData[20];
    char rxIndex = 0;
    int rpmstored = 0;

        void setup()
        {
          Serial.begin(9600); // prints to serial monitor
          Serial1.begin(9600); //Hardware serial connection to the obdii uart
          OBD_init(); //initiates obd link
          delay(3000);
        }

        void loop()
    {
    rpmstored = getRPM();
    //int mph = (int)((getSPEED() * 10000L + 5) / 16090); //convert to mph
    //  Serial.print (mph);
    Serial.print("S:");
    Serial.print (getSPEED());
    Serial.print (",");
    Serial.print("R:");
    Serial.println (getRPM());
    //Serial.print (",");
    //Serial.print("W:");
    //Serial.print (getWATERTEMP());
    //Serial.print (",");
    //Serial.print("O:");
    //Serial.print (getOILTEMP());
    //Serial.print (",");
    //Serial.print("F:");
    //Serial.print (getFUEL());
    //Serial.print (",");
    //Serial.print("V:");
    //Serial.println (getVOLT());
    delay(100);
    Serial.flush();
        }

        void OBD_init(void)
        {
          //Wait for a little while before sending the reset command to the OBD-II-UART
          delay(2000);
          //Reset the OBD-II-UART
          Serial1.print("ATZ\r");
          //Wait for a bit before starting to send commands after the reset.
          delay(2);
          OBD_read();
          Serial1.print("ATE0\r");
          OBD_read();
          //Serial1.flush();
        }

        int getRPM(void)
        {
          //Query the OBD-II-UART for the Vehicle rpm
          Serial1.flush();
          Serial1.print("010C\r");
          OBD_read();

          return ((strtol(&rxData[6], 0, 16) * 256) + strtol(&rxData[9], 0, 16)) / 4;
        }

        int getSPEED(void)
        {
          //Query the OBD-II-UART for the vehicle speed
          Serial1.flush();
          Serial1.print("010D\r");
          OBD_read();

          return strtol(&rxData[6], 0, 16);
        }

        int getOILTEMP(void)
        {
          //Query the OBD-II-UART for the vehicle speed
          Serial1.flush();
          Serial1.print("015C\r");
          OBD_read();

          return strtol(&rxData[6], 0, 16);
        }

        int getFUEL(void)
        {
          //Query the OBD-II-UART for the vehicle speed
          Serial1.flush();
          Serial1.print("012F\r");
          OBD_read();

          return strtol(&rxData[6], 0, 16);
        }

        int getVOLT(void)
        {
          //Query the OBD-II-UART for the vehicle speed
          Serial1.flush();
          Serial1.print("0142\r");
          OBD_read();

          return strtol(&rxData[6], 0, 16);
        }

        int getWATERTEMP(void)
        {
          //Query the OBD-II-UART for the Engine Coolant Temp
          Serial1.flush();
          Serial1.print("0105\r");
          OBD_read();

          return strtol(&rxData[6], 0, 16) - 40;
        }

        void OBD_read(void)
        {
          char c;
          do {
            if (Serial1.available() > 0)
            {
              c = Serial1.read();
              if ((c != '>') && (c != '\r') && (c != '\n')) //Keep these out of our buffer
              {
                rxData[rxIndex++] = c; //Add whatever we receive to the buffer
              }
            }
          } while (c != '>'); //The ELM327 ends its response with this char so when we get it we exit out.
          rxData[rxIndex++] = '\0';//Converts the array into a string
          rxIndex = 0; //Set this to 0 so next time we call the read we get a "clean buffer"

        }

I only need RPM & Speed that's why i comnented out other parameters but tested all and works perfectly.


body: How can I set the number of bits that need to be transferred in SPI communication from a Slave chip to Master MCU using Arduino SPI Library in a SPI transaction? Let us say I want to read 14-bits data from Slave into my Master Arduino MCU then how would set this 14-bits in the SPI Library?

title: How to set the data length for SPI communication in Arduino library?

Answers: 0


body:
Have a problem: new house but it gets super-windy and the doggy doors' magnets are too weak and blow open. Can't use bigger magnets because the doggies are too small.

So I thought I'd reinforce the pet-doors with a latch.

Next problem: the dogs are too dumb to learn wait for the doors to open. So the release mechanism must be rapid.

My plan was:
Arduino - uno or beetle/leonardo
motion sensor or ultrasonic sensors x2 (one inside and one outside) -> arduino -> relay ->wall power supply -> electromagnet release (normally on)

- only the electromagnet gets super hot, so may not be best. Do servos or solenoids open fast? as in < 1s

Anyone have any suggestions on a  better way?? THanks so much!

title: Arduino-controlled Pet Door Lock

Answers: 0


body:
I’ve bought [this shield ][1].
I’m looking for a way to display decimal point, without using any a designated library.
Most examples as [this one][2] shows only 0-9.

**EDIT1** update link
[Link][3]

  [1]: https://www.google.com/search?q=multi function shield&rlz=1CDGOYI_enIL782IL782&hl=he&prmd=isnv&source=lnms&tbm=isch&sa=X&ved=2ahUKEwj74tiqk8jrAhXc6OAKHeSUBbQQ_AUoAXoECAwQAQ&biw=375&bih=640&dpr=3#imgrc=lRdKBzXtX0i0tM
  [2]: https://www.google.com/amp/arduinolearning.com/code/multi-function-shield-examples.php
  [3]: http://arduinolearning.com/code/multi-function-shield-examples.php

title: 7segment display on Multi Function shield - Arduino Uno

Answers: 1

body:
So if you click your 2nd link, it includes sample code for various sections of the multi-function shield.

One of them is titled "segment display".

If you look at that code, line 7 defines the bit patterns for each of the digits from 0 to 9:

    const byte SEGMENT_MAP[] = {0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0X80,0X90};

 If you map them out in binary, you get:

```
0xC0, 1100 0000 0
0xF9, 1111 1001 1
0xA4, 1010 0100 2
0xB0, 1011 0000 3
0x99, 1001 1001 4
0x92, 1001 0010 5
0x82, 1000 0010 6
0xF8, 1111 1000 7
0X80, 1000 0000 8
0X90 1001 0000 9
```

A 0 character has all the segments lit except the middle "cross-bar". An 8 character has ALL of the segments lit. But the bit pattern for 8 is `1000 0000`. That suggests that a 0 bit means a segment is lit, and 1 means it is off. Since the highest order bit of all of those characters is 1 (off) it suggests that the high-order bit is the decimal place bit. (It's the only bit that never changes.)

So if you replace

    const byte SEGMENT_MAP[] = {0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0X80,0X90};

with

    const byte SEGMENT_MAP[] = {0x40,0x79,0x24,0x30,0x19,0x12,0x02,0x78,0X00,0X10};

You should get all the digits drawn with their corresponding decimal place lit.

I'd try that first to verify that I'm correct.

I'd then suggest writing code that reads the segments value for each digit, decides if you want a decimal place at that position, and if so, doing a bitwise AND (`&` in C/C++) on the value with 0X7F to clear the decimal bit for that character. (Remember it looks like a 0 means a given LED segment should be lit.

You could modify the function WriteNumberToSegment() to take a "lightDot" parameter, and have it change the bit if you pass TRUE (1):

```
void WriteNumberToSegment(byte Segment, byte Value, bool lightDot)
{
    digitalWrite(LATCH_DIO,LOW);
    bool bits = SEGMENT_MAP[Value]);
    if (lightDot) {
       bits &= 0x7F; //To light the decimal for this digit, clear the 0x80 bit
    }
    shiftOut(DATA_DIO, CLK_DIO, MSBFIRST, bits);
    shiftOut(DATA_DIO, CLK_DIO, MSBFIRST, SEGMENT_SELECT[Segment] );
    digitalWrite(LATCH_DIO,HIGH);
}
```

(I don't remember for sure if `bool` is a valid type in Arduino C/C++. If not, just replace `bool` with `uint8` in the above.)


body: I have done communication between ESP01 and Arduino NANO (ATMEGA328 based). ESP pins used are GPIO-0 and GPIO2. In NANO, used D2 and D3. This program working Ok. Now I want to add external interrupt in my Arduino NANO program while continuing communication with ESP01. But I cannot use D2 and D3 because it was used by communication program. Now Arduino NANO's limit is it has only two interrupt pins which are D2 and D3. So if I use this for external interrupt program, I lose communication with ESP01. Can anybody help me to use my both task at the same time: Task1- External interrupt in Arduino Nano, Task2- Communication with ESP01. Your reply will help me to solve this issue. Thanks in advance.

title: Communication between ESP01 Arduino NANO and using External Interrupt in Arduino NANO for other than communication program same time

Answers: 1

body:
D2 and D3 Pins on Arduino nano support external Interrupt. Hence, you have to use one of those for the interrupt.

Since you are using `softwareSerial()` you can easily remap it to other digital pins of the Nano.

Pins from `D4-D12`can be used for communication.
You just have to change the parameters in the `softwareserial()` as below:

    SoftwareSerial mySerial(4, 5); // RX, TX;;for example

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/c3pHR.png


body:
I have a network consisting 10 slaves and one master. I am using ESP-NOW to send the messages between the nodes. All of the nodes are within close proximity. I do NOT need a mesh network to reach all the nodes.

ESP-NOW works amazing. It is simple to use and the library is easy to understand. **But in this project esp-now is not working for me and here is why:**

1. If the 10 slaves want to send data at the same time it does not work. With 10 nodes they can send data every 200ms. If I lower the time some nodes even crash and restart.

2. Because all nodes cannot send data at the same time I am having the master ping each node to synchronize who can send a message. The moment a slave receives a message it can reply back.

3. If one slave node sends data to the wrong peer for some reason the web server of the master node stops working. It freezes until that node is done sending data.

4. If I send a broadcast message all the nodes reply. **How can I configure esp-now so that no acknowledgment is sent back?**

5. With esp-now when you send a packet the destination node always replies with a confirmation. I want to send that confirmation once the job that the slave had to perform worked. Because I am planing to work with a lot of nodes with close proximity I want to reduce network traffic. Moreover, on esp-now if a packet is not delivered it attempts again increasing the network traffic. I only want to resend packets that are important in order to reduce network traffic.

6. esp-now limits the number of nodes you can have specially if you encrypt the messages.

**So my question is:** is there a way to instruct esp-now to NOT send an acknowledgment? Can I instruct esp-now to only send one packet regardless if it failed or not? On the NRF24L01 you can set this value with the method `setRetries`. I just want something like UDP where it is a fire and forget. I cannot use UDP because I do not want to be connected to a WiFi network.

It will be great if I could have 2 methods. One for sending a simple raw packet and another for reading those packets on another esp32. I know I will be having to do a lot of filtering on the receiving side.

------------

Edit
---

-----------

Here is a solution that works but needs improvement
-----

It is possible to send raw packets with the function `esp_wifi_80211_tx`. But still esp32 sends 5 packets when using that function! Moreover, in order to use that function you must send a wifi beacon with whatever data you want. The minimum size of a beacon packet I believe is 128 bytes. So this is a solution but not a good one.

Anyways I bellow is the code for the transmitter esp32 and the receiver esp32. The transmitter code has to be compiled with the ESP-IDF framework and NOT arduino. If I use arduino framework it compiles fine (replace main function with setup) but it does not work once I upload it to the esp32. The receiver code I compiled it using the arduino IDE.

**transmitter code (tx)**

    #include <stdio.h>

    #include "driver/gpio.h"
    #include "freertos/FreeRTOS.h"
    #include "freertos/task.h"

    #include "esp_event_loop.h"
    #include "esp_system.h"
    #include "esp_event.h"
    #include "esp_wifi.h"

    #include "nvs_flash.h"
    #include "string.h"

    // pin used to flash led
    #define PIN GPIO_NUM_2

    /*
     * This is the (currently unofficial) 802.11 raw frame TX API,
     * defined in esp32-wifi-lib's libnet80211.a/ieee80211_output.o
     *
     * This declaration is all you need for using esp_wifi_80211_tx in your own application.
     */
    esp_err_t esp_wifi_80211_tx(wifi_interface_t ifx, const void *buffer, int len, bool en_sys_seq);

    esp_err_t event_handler(void *ctx, system_event_t *event)
    {
     return ESP_OK;
    }

    void send_raw_packet_task(void *pvParameter)
    {

     for (;;)
     {
      uint8_t dataToSend[] = { 0 } ;

      esp_wifi_80211_tx(WIFI_IF_AP, dataToSend, sizeof(dataToSend) , false);

      // turn on and off led AND wait 10 seconds
      gpio_pad_select_gpio(PIN);
      gpio_set_direction(PIN, GPIO_MODE_OUTPUT);
      gpio_set_level(PIN, 1);
      vTaskDelay(9500 / portTICK_PERIOD_MS);
      gpio_set_level(PIN, 0);
      vTaskDelay(500 / portTICK_PERIOD_MS);
     }
    }

    extern "C" void app_main(void)
    {
     nvs_flash_init();
     tcpip_adapter_init();

     wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();

     ESP_ERROR_CHECK(esp_event_loop_init(event_handler, NULL));
     ESP_ERROR_CHECK(esp_wifi_init(&cfg));
     ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));

     // Init dummy AP to specify a channel and get WiFi hardware into
     // a mode where we can send the actual fake beacon frames.
     ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_AP));
     wifi_config_t ap_config;

     // SSID = TTTT (4 times the letter t in uppercase)
     wifi_ap_config_t x;
     x.ssid[0] = 84; x.ssid[1] = 84; x.ssid[2] = 84; x.ssid[3] = 84;
     x.ssid[4] = 0;
     x.ssid_len = 4;

     //x.password = "dummypassword"; // for some reason this does not compile
     x.password[0] = 84; x.password[1] = 84; x.password[2] = 84; x.password[3] = 84; x.password[4] = 84; x.password[5] = 84; x.password[6] = 84; x.password[7] = 84;
     x.password[8] = 0;

     x.channel = 1;
     x.authmode = WIFI_AUTH_OPEN;
     x.ssid_hidden = 0;
     x.max_connection = 4;
     x.beacon_interval = 60000;
     ap_config.ap = x;

     //ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &ap_config));
     auto res = esp_wifi_set_config(WIFI_IF_AP, &ap_config);
     if (res == ESP_OK)
     {
      printf("set esp_wifi_set_config. It worked!\n");
     }
     else
     {
      printf("It did NOT worked :/\n");
      return;
     }

     // ESP_ERROR_CHECK(esp_wifi_start());
     res = esp_wifi_start();
     if (res == ESP_OK)
     {
      printf("wifi started! It worked!\n");
     }
     else
     {
      printf("It did NOT worked :/\n");
      return;
     }

     // ESP_ERROR_CHECK(esp_wifi_set_ps(WIFI_PS_NONE));
     wifi_ps_type_t t = WIFI_PS_NONE;
     res = esp_wifi_set_ps(t);
     if (res == ESP_OK)
     {
      printf("wifi set to WIFI_PS_NONE! It worked!\n");
     }
     else
     {
      printf("It did NOT worked :/\n");
      return;
     }

     res = esp_wifi_set_channel(1, WIFI_SECOND_CHAN_NONE);
     if (res == ESP_OK)
     {
      printf("wifi set channel to 1! It worked!\n");
     }
     else
     {
      printf("It did NOT worked :/\n");
      return;
     }

     // output size of bytes that we will be sending
     printf("*** Size of configuration is %i bytes. Starting task send_raw_packet_task...", (int)sizeof(ap_config));
     xTaskCreate(&send_raw_packet_task, "send_raw_packet_task", 2048, NULL, 5, NULL);
    }

**receiver code (rx)**

    #include "freertos/FreeRTOS.h"
    #include "esp_wifi.h"
    #include "esp_wifi_types.h"
    #include "esp_system.h"
    #include "esp_event.h"
    #include "esp_event_loop.h"
    #include "nvs_flash.h"

    uint8_t channel = 1;

    static void wifi_sniffer_packet_handler(void* buff, wifi_promiscuous_pkt_type_t type);
    void wifi_sniffer_packet_handler(void* buff, wifi_promiscuous_pkt_type_t type) {

        // in here esp32 will capture all wifi traffic

        auto t = (unsigned char*)buff;

        // create flag to see if packet contains "TTT"
        bool containsX = false;

        // index where the first T is located on the buffer in case it is found
        int indexWhereNameOfSsidWasFound = 0;

        // look to see if its a packet of interest
        for (int i = 45; i < 100; i++)
        {
            if (t[i] == 84 && t[i + 1] == 84 && t[i + 2] == 84)
            {
                containsX = true;

                indexWhereNameOfSsidWasFound = i;
                Serial.println(i);

                break;
            }
        }

        if (containsX == false)
            return;

        // print SSID if found
        for (int i = indexWhereNameOfSsidWasFound; i < indexWhereNameOfSsidWasFound + 20; i++)
        {
            Serial.print((int)t[i]);
            Serial.print(" ");
        }
        Serial.println();

    }

    esp_err_t event_handler(void* ctx, system_event_t* event)
    {
        return ESP_OK;
    }

    // the setup function runs once when you press reset or power the board
    void setup() {

        Serial.begin(115200);

        // delay 2 seconds so that esp32 initializes
        Serial.println("Starting...");
        vTaskDelay(2000 / portTICK_PERIOD_MS);

        // init wifi sniffer
        {
            // order of initializations matter!

            wifi_country_t wifi_country = { .cc = "IT", .schan = 1, .nchan = 13 }; // Most recent esp32 library struct

            nvs_flash_init();
            tcpip_adapter_init();

            ESP_ERROR_CHECK(esp_event_loop_init(event_handler, NULL));

            wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
            ESP_ERROR_CHECK(esp_wifi_init(&cfg));
            ESP_ERROR_CHECK(esp_wifi_set_country(&wifi_country)); /* set country for channel range [1, 13] */
            ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
            ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_NULL));
            ESP_ERROR_CHECK(esp_wifi_start());

            // turn on promiscuous to capture everything
            esp_wifi_set_promiscuous(true);
            esp_wifi_set_promiscuous_rx_cb(&wifi_sniffer_packet_handler);

            // listen on channel 1
            esp_wifi_set_channel(channel, WIFI_SECOND_CHAN_NONE);
        }
    }

    void loop() {
        // empty
    }

So basically the receiver code is listening for all network trafic in promiscuous mode. Kind of like wireshark. If it sees a packet that contains the string "TTTT" it will output it.

Because there is so much wifi traffic this is way slower than esp-now. I could not figure out how to send smaller packets. Lastly when sending a packet it takes about 2 second to capture the packet. I belive esp32 stores all those packets on a queue and then latter calls the call back function.

I guess I will go back on using esp-now. **Can I modify the source code of esp-now?** I just want want to remove the part where it send the packet multiple times and also the part where it replies with an acknowledgment.

title: Send only one packet from one ESP32 to another ESP32 without acknowledgment

Answers: 1

body:
I surmise that the esp32 'raw' tx isn't really that, based on the restrictions on what can be sent (data, but not QoS data, for example.)

I think that among the 5 packets you report seeing are 1.RTS, 2. CTS, 3. DATA, 4. ACK. These (at least 1,2) are necessary to avoid collision.

ESPNow sends a vendor-specific packet which doesn't (I surmise) require or follow the CTS/RTS or ACK 802.11 conventions.

Point to Point ESPNow, however, is written to expect a packet acknowledgement from the receiver, and will resend for a certain number of times until it receives one.

Broadcast ESPNow does not expect, and in fact cannot automatically receive, one of these ESPNow-specific acknowledgements.

If you need the fastest, least reliable 802.11 packet transmission, I would advise to use Broadcast ESPNow.

Having said that, you must be aware that you will not get the full collision-avoidance protections of more usual 802.11 protocol usage. You may need to provide your own ... such as listen-before-send, random exponential backoff, and who knows what else.

Seems to me that you are embarking on a wilderness adventure :)


body:
I want to control an AC load such that it powered on for 1 minute, then off for 1 hour, then on again for 1 min, and so on, in a loop.

I just modified the blink sketch to do:
1. Turn `A1` on
1. Then delay for 60,000 ms
1. Then turn `A1` off
1. Then delay for 3,600,000 ms (3,600 sec, or 1 hr)

...but it doesn't seem to work.

It looks like the LED connected to `A0` turns on but instead of turning off after 1 min, it turns off after 8 min 30 s.

Any suggestions?

---

I rectified the sketch. Now its takes 1 sec as actual 1 sec 1 choose 1 MHz clock in IDE.

```cpp
int ledPin =  A3;      // the number of the LED pin
int ledState = HIGH;             // ledState used to set the LED
unsigned long previousMillis = 0;        // will store last time LED was updated
unsigned long OnTime = 60000;           // milliseconds of on-time
unsigned long OffTime = 10000;          // milliseconds of off-time

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

void loop()
{
  // check to see if it's time to change the state of the LED
  unsigned long currentMillis = millis();

  if((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
  {
    ledState = LOW;  // Turn it off
    previousMillis = currentMillis;  // Remember the time
    digitalWrite(ledPin, ledState);  // Update the actual LED
  }
  else if ((ledState == LOW) && (currentMillis - previousMillis >= OffTime))
  {
    ledState = HIGH;  // turn it on
    previousMillis = currentMillis;   // Remember the time
    digitalWrite(ledPin, ledState);    // Update the actual LED
  }
}
```

then it turns on for 1 sec and then turn off for 1 sec,
then randomly turning on at 30 sec or 1 min 30 sec.
I want to make it on for 1 min every hour.

**I tried blink sketch modified as follows:**

```cpp
void setup() {
  pinMode(A3, OUTPUT);
}

void loop() {
  digitalWrite(A3, HIGH);
  delay(60000);
  digitalWrite(A3, LOW);
  delay(900000);
}
```

but it still turns on for 1 min and turns off for 1 min.

I also tried this:

```cpp
void setup() {
  pinMode(A3, OUTPUT);
}

void loop() {
  digitalWrite(A3, HIGH);
  delay(60000);
  digitalWrite(A3, LOW);
  delay(3.6e+6);
}
```

No matter what I do on time and off time always remain same.

I just wanted to know one thing: can I set 1 hour off and 1 min on timer using ATtiny13A or not?

Tried 1.2 MHz, 1 MHz, all clocks in the IDE, nothing seems to work.

title: How to create a 1 hour timer with ATtiny13A microcontroller?

Answers: 2

body:
As the unchanged blink sketch blinks with 8.4 seconds, I think my assumption is right. The clock of the Attiny is running 8 times slower, than the code thinks.

When you have installed the Attiny core, there should be a menu entry for the clock frequency. Most likely the standard is 8MHz. But having 8MHz set does not mean, that the Attiny is using 8MHz. To choose between different clock sources and frequencies, you must change the fuses of the microcontroller (which are just some bits of special non-volatile memory in the chip, that set special hardware configuration; more information in [this question][1]). This is done, when you burn the bootloader to the chip. That's the easy version. Alternatively you can use the `avrdude` command directly to set the fuses. That's the advanced way.

Currently the fuses of your Attiny seem to be set to the 1MHz internal clock. But the compiler uses the frequency, that you have chosen in the menu, hence 8MHz internal clock. So the compiler thinks, that the chip runs at 8MHz and thus generates the timing code for this execution speed. But your chip is currently 8 times slower, than the compiler thinks.

**TL;DR:** Burn the bootloader onto the chip to let the Arduino IDE set the right fuses for your clock frequency.

  [1]: https://electronics.stackexchange.com/questions/1262/what-are-atmel-fuses

body:
The code you wrote should work as expected. If it doesn't, I suspect
there is something broken in the Arduino core you are using. However,
such a trivial task can very easily be programmed in plain C, at the
avr-libc level:

```cpp
#define F_CPU 1000000  // 1 MHz
#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
    DDRB |= _BV(PB3);  // PB3 as output
    for (;;) {
        PORTB |= _BV(PB3);   // PB3 high
        _delay_ms(60e3);     // 1 min
        PORTB &= ~_BV(PB3);  // PB3 low
        _delay_ms(3.6e6);    // 1 h
    }
}
```

I would compile it with:

```shell
avr-gcc -mmcu=attiny13a -Os -Wall -Wextra 1h-timer.c -o 1h-timer.elf
```

See the [Port Registers][] Arduino tutorial for the meaning of the
macros used here. You can tweak `F_CPU` to fine-tune the delays, in case
your ATtiny clock is not quite 1 MHz.

[Port Registers]: https://www.arduino.cc/en/Reference/PortManipulation


body:
I am working on an anemometer project using Arduino. I don't know barely anything from Arduino and I am following [this tutorial][1].

I have some doubts on the making part. This is what I have to make: [![2]][2]

and this is the code:

````
//anemómetro con LCD
#include <LiquidCrystal.h>

LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

float veloc1 = 0; // entrada A0
int tiempo = 0;
int cnt = 0;
float v1 = 0;
float v2 = 0;

void setup() {
  lcd.begin(16, 2); // Fijamos el numero de caracteres y filas
  lcd.begin(16, 2); // Fijamos el numero de caracteres y filas
  lcd.print("Anemometro EC"); // Aqui va el mensaje
  analogReference(INTERNAL);// pone como referencia interna 1.1V
}

void loop() {
  v1 = (analogRead(0)); // lectura de sensor a0
  veloc1 = (v1 * 0.190); // 0,190 corresponde a la pendiente de la curva aca deben poner el numero que calcularon
  lcd.setCursor(0, 1); // Ponte en la line 1, posicion 0
  lcd.print(veloc1); //muestra la velocidad del viento en el LCD
  lcd.setCursor(4, 1); // ponte en linea 1, posicion 5
  lcd.print("Km / h");
  lcd.setCursor(9, 1);
  lcd.print("Max");
  if (veloc1 > v2)v2 = veloc1, lcd.print (v2, 1); // muestra la velocidad maxima que alcanzo
  delay(1000);
}
````

 1. What is the potentiometer doing here? Why is it necessary?
 2. My lcd screen doesn't show anything. Does anyone knows why??

Thanks in advance.

  [1]: https://espaciodecesar.com/2017/03/25/como-medir-el-viento-muy-facil-anemometro-simple-y-con-arduino/?unapproved=5086&moderation-hash=5df410840f50fe7de9b9a5d4ab73b37e#comment-5086
  [2]: https://i.stack.imgur.com/VRyGq.png

title: What is this potentiometer for?

Answers: 1

body:
> What is the potentiometer doing here? Why is it necessary?

It's there to control the "offset voltage" of the LCD, which is what controls the contrast of the display.

> My lcd screen doesn't show anything. Does anyone knows why??

Maybe you wired it wrong. Maybe you didn't put the potentiometer in the circuit because you didn't understand what it is for. Maybe you just need to adjust the contrast by turning said potentiometer. It's hard for us to tell. By showing us what you *intended* to build and then telling us that what you *actually* built doesn't work, there is nothing we can tell you. There must be some difference between what you intended to build and what you did build, but we can't see what you built, so we can't have any clue.


body:
So I'm working with an arduino uno and I want to read the UID from one card and write it to another with the code of Miguel Balboa but the RC522 doesn't appear to read anything on the serial monitor. However, if I the one below, it actually reads everything. I've also used the hardware checker and it says that everything is working fine. What am I doing wrong or what do I have to do to clone the UID with this code? Thank you very much in advance.
```#include <MFRC522.h>
#include <SPI.h>

#define SAD 10
#define RST 5

MFRC522 nfc(SAD, RST);

void setup() {
  SPI.begin();
  // Read a fast as possible. There is a limit for how long we are
  // allowed to read from the tags.
  Serial.begin(115200);

  Serial.println("Looking for MFRC522.");
  nfc.begin();

  // Get the firmware version of the RFID chip
  byte version = nfc.getFirmwareVersion();
  if (! version) {
    Serial.print("Didn't find MFRC522 board.");
    while(1); //halt
  }

  Serial.print("Found chip MFRC522 ");
  Serial.print("Firmware ver. 0x");
  Serial.print(version, HEX);
  Serial.println(".");
}

byte keyA[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, };
byte keyB[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, };

void loop() {
  byte status;
  byte data[MAX_LEN];
  byte serial[5];
  int i, j, pos;

  // Send a general request out into the aether. If there is a tag in
  // the area it will respond and the status will be MI_OK.
  status = nfc.requestTag(MF1_REQIDL, data);

  if (status == MI_OK) {
    Serial.println("Tag detected.");
    Serial.print("Type: ");
    Serial.print(data[0], HEX);
    Serial.print(", ");
    Serial.println(data[1], HEX);

    // calculate the anti-collision value for the currently detected
    // tag and write the serial into the data array.
    status = nfc.antiCollision(data);
    memcpy(serial, data, 5);

    Serial.println("The serial nb of the tag is:");
    for (i = 0; i < 3; i++) {
      Serial.print(serial[i], HEX);
      Serial.print(", ");
    }
    Serial.println(serial[3], HEX);

    // Select the tag that we want to talk to. If we don't do this the
    // chip does not know which tag it should talk if there should be
    // any other tags in the area..
    nfc.selectTag(serial);

    // Assuming that there are only 64 blocks of memory in this chip.
    for (i = 0; i < 64; i++) {
      // Try to authenticate each block first with the A key.
      status = nfc.authenticate(MF1_AUTHENT1A, i, keyA, serial);
      if (status == MI_OK) {
        Serial.print("Authenticated block nb. 0x");
        Serial.print(i, HEX);
        Serial.println(" with key A.");
        // Reading block i from the tag into data.
        status = nfc.readFromTag(i, data);
        if (status == MI_OK) {
          // If there was no error when reading; print all the hex
          // values in the data.
          for (j = 0; j < 15; j++) {
            Serial.print(data[j], HEX);
            Serial.print(", ");
          }
          Serial.println(data[15], HEX);
        } else {
          Serial.println("Read failed.");
        }
      } else {
        // If we could not authenticate with the A key, we will try
        // the B key.
        status = nfc.authenticate(MF1_AUTHENT1B, i, keyB, serial);
        if (status == MI_OK) {
          Serial.print("Authenticated block nb. 0x");
          Serial.print(i, HEX);
          Serial.println(" with key B.");
          status = nfc.readFromTag(i, data);
          if (status == MI_OK) {
            for (j = 0; j < 15; j++) {
              Serial.print(data[j], HEX);
              Serial.print(", ");
            }
            Serial.println(data[15], HEX);
          } else {
            Serial.println("Read failed.");
          }
        } else {
          Serial.print("Access denied at block nb. 0x");
          Serial.println(i, HEX);
        }
      }
    }

    // Stop the tag and get ready for reading a new tag.
    nfc.haltTag();
  }
  delay(2000);
}```

title: RFID-RC522 not working properly?

Answers: 0


body:
I'm new to Arduino programming. I want to make my ESP8266 get a static IP address based on the gateway's IP address.

I mean if the gateway is at 192.168.0.1 then the ESP8266 should get 192.168.0.15 as a static IP address. And if the gateway is at 192.168.1.1 then it should get 192.168.1.15 as an IP address.

title: Static IP for ESP8266 based on gateway

Answers: 2

body:
You can either set the router to allocate a static IP address based on your ESP8266's MAC address, or go the DHCP-way first, read the gateway IP address you got, and then do a `WiFi.config()`, something roughly like this (untested):

```c++
WiFi.begin(ssid, password);
IPAddress ip = WiFi.gatewayIP();
IP[3] = 15;
IPAddress dns(8, 8, 8, 8);
WiFi.config(ip, WiFi.gatewayIP(), dns, WiFi.subnetMask());
```

It is a bit of a trick, and not pretty, and you don't get to set the DNS as provided by the DHCP, because there is no `getDNS()`, for some silly reason, hence the use of Google's DNS server.

Note that when doing this, you run the risk of setting the ESP8266's IP address to an address already taken by another device on the same router.

body:
Here is the idea that I have not implemented yet.

 1. Connect to the wifi and let the router assign the IP to it.
 2. After getting the IP from the router save that IP to eeprom
 3. Now next time you want to connect to the wifi use this code.

```
// Set your Static IP address
IPAddress local_IP(192, 168, 1, 184);
// Set your Gateway IP address
IPAddress gateway(192, 168, 1, 1);

IPAddress subnet(255, 255, 0, 0);
IPAddress primaryDNS(8, 8, 8, 8);   //optional
IPAddress secondaryDNS(8, 8, 4, 4); //optional

if (!WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS)) {
    Serial.println("STA Failed to configure");
  }

  // Connect to Wi-Fi network with SSID and password
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);

```
load the saved ip, gateWay and other information saved in the eeprom before passing to wifi.config function.


body:
The code to set up the nrf24 is from Electronoobs. The further if-clauses are suposed the drive a motor. The problem I am facing is, that if ther is no data transmission (emitter turend off; or receiver antenna unplugged) the Arduino-Nano-Chip is receiving random values, but there should not be anything at all. I need something which sets the variables left/right to 512 as long as there is no data transmission, when the remote/controller is turned off for example.

    //Emitter-Code
    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>

    //const uint64_t my_radio_pipe = 0xE8E8F0F0E1LL; //Remember that this code should be the same for the receiver
    const uint64_t my_radio_pipe = 0xE8E80000E1LL; //Remember that this code should be the same for the receiver

    RF24 radio(9, 10); //CSN and CE pins

    // The sizeof this struct should not exceed 32 bytes
    struct Data_to_be_sent {
      byte ch1;
      byte ch2;
    };

    Data_to_be_sent sent_data;

    void setup()
    {
      radio.begin();
      radio.setAutoAck(false);
      radio.setDataRate(RF24_250KBPS);
      radio.openWritingPipe(my_radio_pipe);
      sent_data.ch1 = 119;
      sent_data.ch2 = 58;
    }

    /**************************************************/

    void loop()
    {
      /*If your channel is reversed, just swap 0 to 255 by 255 to 0 below
      EXAMPLE:
      Normal:    data.ch1 = map( analogRead(A0), 0, 1024, 0, 255);
      Reversed:  data.ch1 = map( analogRead(A0), 0, 1024, 255, 0);  */

      sent_data.ch1 = map(analogRead(A1), 0, 1023, 0, 255);
      radio.write(&sent_data, sizeof(Data_to_be_sent));
      sent_data.ch2 = map(analogRead(A3), 0, 1023, 0, 255);
      radio.write(&sent_data, sizeof(Data_to_be_sent));
    }

    //Receiver-Code
    #include <SPI.h>
    #include <nRF24L01.h>
    #include <RF24.h>

    const uint64_t pipeIn = 0xE8E8F0F0E7LL;     //veränderter
    //const uint64_t pipeIn = 0xE8E80000E1LL; //echter
    RF24 radio(9, 10);  //CSN and CE pins

    // The sizeof this struct should not exceed 32 bytes
    struct Received_data {
      byte ch1;
      byte ch2;
    };

    int ch1_value = 0;
    int ch2_value = 0;
    Received_data received_data;

    /**************************************************/
    //PIN-Deklaration
    short enB = 5;
    short enA = 6;
    short in1 = 1;
    short in2 = 2;
    short in3 = 3;
    short in4 = 4;

    //Variablendeklaration
    short linker;
    short rechter;
    short vLinker;
    short vRechter;
    short ivLinker;
    short ivRechter;
    short gem;
    short gemRest;
    short rest;
    short mitte = 512;
    short ober = 561;
    short unter = 462;
    short orest;
    short urest;

    void lV(){
      digitalWrite(enA,LOW);
      digitalWrite(in1,HIGH);
      digitalWrite(in2,LOW);
      digitalWrite(enA,HIGH);
    }

    void lR(){
      digitalWrite(enA,LOW);
      digitalWrite(in1,LOW);
      digitalWrite(in2,HIGH);
      digitalWrite(enA,HIGH);
    }

    void lF(){ //links aus / Leergang
      digitalWrite(enA,LOW);
    }

    void rV(){ //rechter Motor vorwärts
      digitalWrite(enB,LOW);
      digitalWrite(in3,HIGH);
      digitalWrite(in4,LOW);
      digitalWrite(enB,HIGH);
    }

    void rR(){ //rechter Motor rückwärts
      digitalWrite(enB,LOW);
      digitalWrite(in3,LOW);
      digitalWrite(in4,HIGH);
      digitalWrite(enB,HIGH);
    }

    void rF(){ //rechts aus / Leergang
      digitalWrite(enB,LOW);
    }

    void lrF(){ //beide aus / Leergang
      digitalWrite(enA,LOW);
      digitalWrite(enB,LOW);
    }

    void setup(){

      Serial.begin(9600);

      //Pinfestlegung
      pinMode(enA,OUTPUT);
      pinMode(enB,OUTPUT);
      pinMode(in1,OUTPUT);
      pinMode(in2,OUTPUT);
      pinMode(in3,OUTPUT);
      pinMode(in4,OUTPUT);

      //We reset the received values
      received_data.ch1 = 119;
      received_data.ch2 = 58;

      //Once again, begin and radio configuration
      radio.begin();
      radio.setAutoAck(false);
      radio.setDataRate(RF24_250KBPS);
      radio.openReadingPipe(1,pipeIn);

      //We start the radio comunication
      radio.startListening();

    }

    /**************************************************/

    unsigned long last_Time = 0;

    //We create the function that will read the data each certain time
    void receive_the_data()
    {
      while ( radio.available() ) {
      radio.read(&received_data, sizeof(Received_data));
      last_Time = millis(); //Here we receive the data
    }
    }

    /**************************************************/

    void loop(){

      while(true){ //!!!receiving two analog values, and storing them in left and right
         lrF();
         ch1_value = map(received_data.ch1,0,255,0,1023);
         ch2_value = map(received_data.ch2,0,255,0,1023);
         linker = ch1_value;
         rechter = ch2_value;
         Serial.print("left: ");
         Serial.println(left);
         Serial.print("right: ");
         Serial.println(right);
      } //why is the Serial print showing ramdom values, even if there should not be a transmission

      //beide vorerst aus
      lrF();
      linker = 512;
      rechter = 512;

      //Receive the radio data
      receive_the_data();

      //Übernahme der Analogreferenzwerte für beide Knüppel
      //ch1_value = received_data.ch1;
      ch1_value = map(received_data.ch1,0,255,0,1023);
      ch2_value = map(received_data.ch2,0,255,0,1023);
      //Überschreibung der Werte in Variablen links/rechts
      linker = ch1_value;
      rechter = ch2_value;

      for(int i = 200; i > 0; i--){ //PWM-Signalanlegung

      if((linker <= ober && linker >= unter) && (rechter <= ober && rechter >= unter)){ //Leergang
        lrF();
        delayMicroseconds(463);
      }

      if((rechter == linker) && (linker > ober)){ //geradeaus
        vLinker = linker - ober;
        gem = vLinker;
        rest = 463 - gem;
        lV();
        rV();
        delayMicroseconds(gem);
        lrF();
        delayMicroseconds(rest);

      }

      if((linker > ober) && (rechter > ober) && (linker > rechter)){ //linksvorwärts
        vLinker = linker - ober;
        vRechter = rechter - ober;
        gem = vRechter;
        gemRest = vLinker - vRechter;
        rest = 463 - gem - gemRest;
        rV();
        lV();
        delayMicroseconds(gem);
        lV();
        rF();
        delayMicroseconds(gemRest);
        lrF();
        delayMicroseconds(rest);
      }

      if((rechter > ober) && (linker > ober) && (rechter > linker)){ //rechtsvorwärts
        vLinker = linker - ober;
        vRechter = rechter - ober;
        gem = vLinker;
        gemRest = vRechter - vLinker;
        rest = 463 - gem - gemRest;
        rV();
        lV();
        delayMicroseconds(gem);
        rV();
        lF();
        delayMicroseconds(gemRest);
        lrF();
        delayMicroseconds(rest);
      }

      if((rechter == linker) && (linker < unter)){ //rückwärts
        vLinker = linker;
        ivLinker = 463 - linker;
        gem = ivLinker;
        rest = 463 - gem;
        lR();
        rR();
        delayMicroseconds(gem);
        lrF();
        delayMicroseconds(rest);
      }

      if((linker < unter) && (rechter < unter) && (rechter > linker)){ //linksrückwärts
        vLinker = linker;
        vRechter = rechter;
        ivRechter = 463 - rechter;
        ivLinker = 463 - linker;
        gem = ivRechter;
        gemRest = ivLinker - ivRechter;
        rest = 463 - gem - gemRest;
        lR();
        rR();
        delayMicroseconds(gem);
        lR();
        rF();
        delayMicroseconds(gemRest);
        lrF();
        delayMicroseconds(rest);
      }

      if((linker < unter) && (rechter < unter) && (rechter < linker)){ //rechtsrückwärts
        vLinker = linker;
        vRechter = rechter;
        ivRechter = 463 - rechter;
        ivLinker = 463 - linker;
        gem = ivLinker;
        gemRest = ivRechter - ivLinker;
        rest = 463 - gem - gemRest;
        lR();
        rR();
        delayMicroseconds(gem);
        rR();
        lF();
        delayMicroseconds(gemRest);
        lrF();
        delayMicroseconds(rest);
      }

      if((linker < unter) && (rechter > ober) && (463 - linker >= rechter - ober)){ //linker rück rück, rechter vor
        ivLinker = 463 - linker;
        vRechter = rechter - ober;
        gem = vRechter;
        gemRest = ivLinker - vRechter;
        rest = 463 - gem - gemRest;
        lR();
        rV();
        delayMicroseconds(gem);
        lR();
        rF();
        delayMicroseconds(gemRest);
        lrF();
        delayMicroseconds(rest);
      }

      if((linker < unter) && (rechter > ober) && (463 - linker < rechter - ober)){ //linker rück, rechter vor vor
        ivLinker = 463 - linker;
        vRechter = rechter - ober;
        gem = ivLinker;
        gemRest = vRechter - ivLinker;
        rest = 463 - gem - gemRest;
        rV();
        lR();
        delayMicroseconds(gem);
        rV();
        lF();
        delayMicroseconds(gemRest);
        lrF();
        delayMicroseconds(rest);
      }

      if((linker > ober) && (rechter < unter) && (463 - rechter <= linker - ober)){ //linker vor vor, rechter rück
        ivRechter = 463 - rechter;
        vLinker = linker - ober;
        gem = ivRechter;
        gemRest = vLinker - ivRechter;
        rest = 463 - gem - gemRest;
        lV();
        rR();
        delayMicroseconds(gem);
        lV();
        rF();
        delayMicroseconds(gemRest);
        lrF();
        delayMicroseconds(rest);
      }

      if((linker > ober) && (rechter < unter) && (463 - rechter > linker - ober)){ //linker vor, rechter rück rück
        ivRechter = 463 - rechter;
        vLinker = linker - ober;
        gem = vLinker;
        gemRest = ivRechter - vLinker;
        rest = 463 - gem - gemRest;
        rR();
        lV();
        delayMicroseconds(gem);
        rR();
        lF();
        delayMicroseconds(gemRest);
        lrF();
        delayMicroseconds(rest);
      }

      if((linker > ober) && (rechter > unter) && (rechter < ober)){ //linker allein vor
        vLinker = linker - ober;
        gem = vLinker;
        rest = 463 - vLinker;
        lV();
        rF();
        delayMicroseconds(gem);
        lrF();
        delayMicroseconds(rest);
      }

      if((rechter > ober) && (linker > unter) && (linker < ober)){ //rechter alleine vor
        vRechter = rechter - ober;
        gem = vRechter;
        rest = 463 - vRechter;
        rV();
        lF();
        delayMicroseconds(gem);
        lrF();
        delayMicroseconds(rest);
      }

      if((linker < unter) && (rechter > unter) && (rechter < ober)){ //linker alleine rück
        ivLinker = 463 - linker;
        gem = ivLinker;
        rest = 463 - ivLinker;
        lR();
        rF();
        delayMicroseconds(gem);
        lrF();
        delayMicroseconds(rest);
      }

      if((rechter < unter) && (linker > unter) && (linker < ober)){ //rechter alleine rück
        ivRechter = 463 - rechter;
        gem = ivRechter;
        rest = 463 - ivRechter;
        rR();
        lF();
        delayMicroseconds(gem);
        lrF();
        delayMicroseconds(rest);
      }
      }

    }

title: NRF24 receiving data while turned off

Answers: 0