body:
What would be the best way to send the following information from one MCU to another?

Now I'm just sending the sentence over as is eg. Serial.print(sentence in here)

Example sentence: 1306,60.123456,50.123456,23.765382,40.897558,245,85,20.3,5,65,1500,0.9

Many thanks.

title: MCU to MCU communication over UART

Answers: 1

body:
It depends actually on your requirements what is 'best'.

If (transmission) speed is an issue, there are mainly some things you can do to improve this:

1. Increase the transmission speed (this depends on the distance of the wires and the noise).
2. Decrease the start/stop bits (this reduces the certainty the values will arrive ok)
3. Pack your data (takes more processing time possibly, and more programming work, but can be faster).

About the third option: since you are mostly sending values, you can make some improvements. So you can send them as float (by sending the float data, with the length of sizeof(float)). However, note there could be inaccuracies in the last digit.


body:
When using ESP8266 - getting seconds from epoch is done using

    NTP.begin(NTPserver, 2, true);
    delay(delay_tries);
    time_t t = now();

while `t` stores amount of seconds from 1-1-1970.

When trying to do the same, using ESP32 - I cant get that numeric representation.

code below is from ESP32 example- updating time using NTP server ( process is done correct ). BUT when using `now()` yields 1970, as if NTP update has never occured.

How can I get time from Epoch ?

    #include <WiFi.h>
    #include "time.h"
    #include <TimeLib.h>    <------- Added to original Code

    const char* ssid       = "YOUR_SSID";
    const char* password   = "YOUR_PASS";

    const char* ntpServer = "pool.ntp.org";
    const long  gmtOffset_sec = 3600;
    const int   daylightOffset_sec = 3600;

    void printLocalTime()
    {
      struct tm timeinfo;
      if(!getLocalTime(&timeinfo)){
        Serial.println("Failed to obtain time");
        return;
      }
      Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
    }

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

      //connect to WiFi
      Serial.printf("Connecting to %s ", ssid);
      WiFi.begin(ssid, password);
      while (WiFi.status() != WL_CONNECTED) {
          delay(500);
          Serial.print(".");
      }
      Serial.println(" CONNECTED");

      //init and get the time
      configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
      printLocalTime();

      //disconnect WiFi as it's no longer needed
      WiFi.disconnect(true);
      WiFi.mode(WIFI_OFF);
    }

    void loop()
    {
      delay(1000);
      printLocalTime();
      Serial.println(now());   <-------- Added to original code
    }

title: ESP32 seconds from epoch

Answers: 1

body:
to return 'epoch' seconds there is a function `time` in time.h

    time_t now;
    time(&now);

`time_t` is defined as `long`

this time is retrieved by the ESP32 SDK from NTP servers configured with  ESP32 Arduino function `configTime`

EDIT: it is the standard C `time()` [function][1]

  [1]: https://www.tutorialspoint.com/c_standard_library/c_function_time.htm


body: I use the watchdog timer to make Arduino sleep for 8 seconds and then wake it right after and make it sleep again if it didn't complete the loop for 450 times. I made it so that it will only do its job every 1 hour with a for loop. How much time does the Arduino keep awake until it sleeps again? I think it wouldn't be worth to put power consumption of this to calculation but still need to verify.

title: How much time passes between waking up and sleeping?

Answers: 0


body:
So I came across lots of Arduino program setting serial speed to 115200 instead of 9600, while many people just kept using 9600 for the same purpose.

Why did people choose to use 115200 or other available speed? Why not just use 9600?

title: Why do people use 115200 instead of 9600?

Answers: 1

body: https://www.arduino.cc/en/Reference/softwareSerial Because 115200 band was also the fastest communication enabled by the software serial.


body:
I created the below partition table for an esp32 and replaced the 'default_8MB.csv' with it.

    # Name,   Type, SubType, Offset,  Size, Flags
    nvs,      data, nvs,     0x9000,  0x5000,
    otadata,  data, ota,     0xe000,  0x2000,
    app0,     app,  ota_0,   0x10000, 0x330000,
    app1,     app,  ota_1,   0x340000,0x330000,
    eeprom,   data, 0x99,    0x670000,0x1000,
    spiffs,   data, spiffs,  0x671000,0x18f000,

After uploading a sketch, I confirmed that the partition table was correctly uploaded to the flash at address 0x8000, using `esptool.py --port /dev/ttyACM1 read_flash 0x8000 0x300 partition_table.bin && gen_esp32part.py partition_table.bin && cat partition_table.bin`.

Now my question is: what do I have to do so that the `EEPROM.h` library maps the eeprom emulation to the address that I have specified in the partition table? I naively assumed that `EEPROM.h` would automatically use the partition named "eeprom", which doesn't seem to be the case.

I uploaded the following test sketch to analyse the situation:

    #include <Arduino.h>
    #include <EEPROM.h>

    String s="this is a unique string";

    void setup(){
      EEPROM.begin(1024);

      for (uint32_t i=0;i<s.length();i++){
        EEPROM.write(i,s[i]);
      }
      EEPROM.commit();
      Serial.println("EEPROM stored");
    }

    void loop() {
      delay(10000);
    }

After the sketch has stored my unique string I read the flash memory using esptool and expected to find the string at an offset of 0x670000, but that wasn't the case. Instead it must be stored somewhere else because I can retrieve the string in a different sketch.

One thing that is confusing me: I'm pretty sure that I once ordered ESP-WROOM32s with 4MB flash, but the esptool's auto-flash-detection states that my board has 8MB. Can this flash-detection be trusted or does it simply fail because I try to flash 8MB to a 4MB ESP32? What is supposed to happen if I created a partition table that exceeds the flash memory size? When I put a partition table at an offset of 10M the build process still doesn't fail (is that what should happen?).

My main question: which additional steps do I have to take to get my ESP running with a custom_partion_table.csv (beside creating the table) and when using "EEPROM.h"?

title: make EEPROM.h use custom eeprom partition

Answers: 1

body:
EEPROM on the ESP32 doesn't work like you would expect.  It uses the SDK's "Non-Volatile Ram" storage system to store the data within the `nvs` partition.  This works through a system of "Key / Value" pairs, and the data is stored as a "BLOB" (Binary Large OBject) for the key `eeprom` in the namespace `eeprom`.

Quite what the internal layout of the data within the partition itself is I have no clue (the SDK is closed source), but it won't just have your string located at the start of the partition - it will be at the start of the BLOB, wherever that happens to be in the partition.

The `eeprom` partition is no longer used. It's just wasted space.

> Can this flash-detection be trusted or does it simply fail because I try to flash 8MB to a 4MB ESP32?

I can't comment on that I'm afraid. I would have thought it would look at the chip's JEDEC data, but it may just look at the partition table information instead.

> What is supposed to happen if I created a partition table that exceeds the flash memory size?

Probably not a lot, since much of the partition table refers to data storage, or a (presently) unused OTA partition.

When you compile your code you're only compiling it for the partition in which it will reside (app0 for example). When you upload the code you are only uploading to that partition.  Anything outside that range is irrelevant to the compilation / uploading.

> When I put a partition table at an offset of 10M the build process still doesn't fail (is that what should happen?).

As I mentioned, it won't care. The partition will not be accessible, since it doesn't actually exist, but it's just an entry in a table. The compiler doesn't know or care what it is.


body:
I am fairly new to processing and Arduino - I have a coursework deadline for both on Monday (6th January).

I am trying to write a script that uses the mouseX values to turn LEDs on and off. I haven't got any error messages on either of the scripts but currently, nothing happens to the LEDs (they remain off) when I move my mouse. I have tested the circuit with a simpler Arduino code and it is correct so there must be an error in my code!

I would be very grateful for some help. Thanks!

**Processing code:**

    import processing.serial.*;
    Serial port;
    byte lightsOn;

    void setup()
    {
      size(600,300);
      port=new Serial(this,"/dev/cu.usbmodem1411",9600);
    }

    void draw()
    {
      background(32,78,95);
      rect(300,0,300,300);
      noStroke();
      fill(185,215,216);

      lightsOn=byte(mouseX);
      port.write(lightsOn);

      println(lightsOn);
    }

**Arduino code:**

    #include <Servo.h>

    Servo myservo;
    int ledpinA=12;
    int ledpinB=13;

    void setup()
    {
      Serial.begin(9600);
      myservo.attach(ledpinA&&ledpinB);
      pinMode(ledpinA,OUTPUT);
      pinMode(ledpinB,OUTPUT);
    }

    void loop()
    {
      if(0<Serial.available())
      {
        int data = Serial.read();

      if (data>300)
      {
        digitalWrite(ledpinA, HIGH);
        digitalWrite(ledpinB, LOW);
      }
      else
      {
        digitalWrite(ledpinB, HIGH);
        digitalWrite(ledpinA, LOW);
      }
      }
    }

title: Using MouseX in processing to control LEDs. Error in code - LEDs remain off

Answers: 1

body:
    lightsOn=byte(mouseX);

A byte can be any number from -128 to 127 (Java has no concept of "unsigned" values). The Arduino will reinterpret that as a value from 0 to 255.

    if (data>300)

255, the maximum value, can never be more than 300 - so this will *always* fail.

You need to re-think what data you are sending and how you want to send it.


body:
I have this code running on ESP32 connected to SVM30-J

    #include <WiFi.h>
    #include <PubSubClient.h>
    #include <Arduino_JSON.h>
    #include <svm30.h>

    // Replace the next variables with your SSID/Password combination
    const char* ssid = "xxxx";
    const char* password = "xxxx";

    // Add your MQTT Broker IP address, example:
    const char* mqtt_server = "xxxx";
    const int mqtt_port = 18712;
    const char* mqtt_user = "xxxx";
    const char* mqtt_password = "xxxx";

    /* define driver debug
     * false : no messages
     * true : display driver debug messages
     */
    #define DEBUG true

    // define number of seconds between display results
    #define DELAY 10

    // function prototypes (sometimes the pre-processor does not create prototypes themself on ESPxx)
    void read_id();
    void read_featureSet();
    void Errorloop(char *mess);
    void read_values();
    void read_baseline();
    void KeepTrigger(uint8_t del);

    // create instance
    SVM30 svm;

    WiFiClient espClient;
    PubSubClient client(espClient);

    void setup() {

      Serial.begin(115200);

      setup_wifi();
      client.setServer(mqtt_server, mqtt_port);
      //client.setCallback(callback);

      Serial.println(F("Reading information from the SVM30"));

      // enable debug messages
      svm.EnableDebugging(DEBUG);

      svm.begin();

      Serial.print(F("Driver version : "));
      Serial.println(svm.GetDriverVersion());

      // try to detect SVM30 sensors
      if (svm.probe() == false) Errorloop("could not detect SVM30 sensors");
      else Serial.println(F("SVM30 detected"));

      // read and display the ID
      read_id();

      // read SGP30 feature set
      read_featureSet();
    }

    void loop() {
      char chipId[13]; // Don't forget one byte for the terminating NULL...
      uint64_t mac = ESP.getEfuseMac();
      sprintf(chipId, "2x", mac);
      Serial.println(chipId);

      JSONVar data;

      if (!client.connected()) {
        reconnect();
      }
      client.loop();

      // read measurement values
      read_values();

      // wait x seconds
      KeepTrigger(DELAY);
    }

    void setup_wifi() {
      delay(10);
      // We start by connecting to a WiFi network
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.begin(ssid, password);
      WiFi.setSleep(false);

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

      Serial.println("");
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
    }

    void callback(char* topic, byte* message, unsigned int length) {
      Serial.print("Message arrived on topic: ");
      Serial.print(topic);
      Serial.print(". Message: ");
      String messageTemp;

      for (int i = 0; i < length; i++) {
        Serial.print((char)message[i]);
        messageTemp += (char)message[i];
      }
      Serial.println();

      // If a message is received on the topic esp32/output, you check if the message is either "on" or "off".
      // Changes the output state according to the message
      if (String(topic) == "esp32/output") {
        Serial.print("Changing output to ");
        if(messageTemp == "on"){
          Serial.println("on");
          //digitalWrite(ledPin, HIGH);
        }
        else if(messageTemp == "off"){
          Serial.println("off");
          //digitalWrite(ledPin, LOW);
        }
      }
    }

    void reconnect() {
      // Loop until we're reconnected
      while (!client.connected()) {
        Serial.print("Attempting MQTT connection...");
        // Attempt to connect
        if (client.connect("ESP32Client", mqtt_user, mqtt_password)) {
          Serial.println("connected");
          // Subscribe
          //client.subscribe("esp32/output");
        } else {
          Serial.print("failed, rc=");
          Serial.print(client.state());
          Serial.println(" try again in 10 seconds");
          // Wait 10 seconds before retrying
          delay(10000);
        }
      }
    }

    /*
     * @brief : keep triggering SGP30 while waiting
     *
     * @param del : number of seconds to wait
     *
     * source datasheet SVM30:
     * The on-chip baseline compensation algorithm has been optimized
     * for 1HZ sampling rate. The sensor shows best performance when
     * used with this sampling rate.
     *
     */
    void KeepTrigger(uint8_t del)
    {
      uint8_t w_seconds = del;
      unsigned long startMillis;

      if (w_seconds == 0) w_seconds = 1;

      while (w_seconds--)
      {
        startMillis = millis();

        if (! svm.TriggerSGP30())
          Errorloop("Error during trigger waiting");

        // this gives 1Hz /1000ms (aboutisch)
        while(millis() - startMillis < 1000);
      }
    }

    /*
     * @brief : read and display the values from the SVM30
     *
     */
    void read_values() {
      struct svm_values v;
      uint16_t baseline;

      if (! svm.GetValues(&v))
          Errorloop("Error during reading values");

      JSONVar data;

      Serial.print(F("CO2 equivalent : "));
      Serial.print(v.CO2eq);
      data["co2_equivalent"] = v.CO2eq;

      Serial.print(F(", TVOC : "));
      Serial.print(v.TVOC);
      data["tvoc"] = v.TVOC;

      Serial.print(F(", H2_signal : "));
      Serial.print(v.H2_signal);
      data["h2_signal"] = v.H2_signal;

      Serial.print(F(", Ethanol_signal : "));
      Serial.print(v.Ethanol_signal);
      data["ethanol_signal"] = v.Ethanol_signal;

      Serial.print(F(", Humidity : "));
      Serial.print((float) v.humidity/1000);
      data["humidity"] = (float) v.humidity/1000;

      Serial.print(F(", temperature : "));
      Serial.print((float) v.temperature/1000);
      data["temperature"] = (float) v.temperature/1000;

      Serial.print(F(", absolute humidity : "));
      Serial.print(v.absolute_hum);
      data["absolute_hum"] = v.absolute_hum;

      if (! svm.GetBaseLine_CO2(&baseline))
          Errorloop("could not read SGP30 CO2 baseline");

      Serial.print(F(" CO2 equivalent baseline : 0x"));
      Serial.print(baseline, HEX);
      data["co2_equivalent_baseline"] = (baseline, HEX);

      if (! svm.GetBaseLine_TVOC(&baseline))
          Errorloop("could not read SGP30 TVOC baseline");

      Serial.print(F(", TVOC baseline : 0x"));
      Serial.println(baseline, HEX);
      data["tvoc_baseline"] = (baseline, HEX);

      char chipId[13]; // Don't forget one byte for the terminating NULL...
      uint64_t mac = ESP.getEfuseMac();
      sprintf(chipId, "2x", mac);
      data["chipid"] = chipId;

      Serial.print("Data = ");
      Serial.println(data);

      String data_json = JSON.stringify(data);
      char mqtt_publish_topic[] = "esp32/data";
      client.publish(mqtt_publish_topic, data_json.c_str());

    }

    /*
     * @brief: read and display the id of the SGP30 and SHTC1 sensors
     */
    void read_id() {

      uint16_t buf[3];    // SGP30 needs 3 words, SHTC1 is 1 word
      char  id[15];

      if ( ! svm.GetId(SGP30, buf))
          Errorloop("could not read SGP30 id");

      Serial.print(F("\nSGP30 id : "));
      sprintf(id, "x x x", buf[0], buf[1], buf[2]);
      Serial.println(id);

      if (svm.GetId(SHTC1, buf) == false)
          Errorloop("could not read SHTC1 id");

      Serial.print(F("SHTC1 id : "));
      // only bit 5:0 matter (source: datasheet)
      sprintf(id, "x", buf[0] & 0x3f);
      Serial.println(id);
    }

    /*
     * @brief: read and display the product feature set of the SGP30 sensor
     */
    void read_featureSet(){

      char buf[2];

      if ( ! svm.GetFeatureSet(buf))
          Errorloop("could not read SGP30 feature set");

      Serial.print(F("\nSGP30 product type : "));
      Serial.print((buf[0] & 0xf0), HEX);

      Serial.print(F(", Product version : "));
      Serial.println(buf[1], HEX);
      Serial.println();
    }

    /**
     *  @brief : continued loop after fatal error
     *  @param mess : message to display
     */
    void Errorloop(char *mess)
    {
      Serial.println(mess);
      Serial.println(F("Program on hold"));
      for(;;) delay(100000);
    }

This code run as expected, except get following in serial monitor

    000010a4ae30
    Attempting MQTT connection...connected
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x90 0x00 0x00 length: 4
    Sending to 0x58: 0x20 0x50 , Received: 0x31 0x8D 0x47 0x9D length: 4
    Sending to 0x70: 0x78 0x66 , Received: 0x61 0xBD 0x7B 0xBE length: 4
    CO2 equivalent : 400, TVOC : 0, H2_signal : 12685, Ethanol_signal : 18333, Humidity : 48.34, temperature : 21.81, absolute humidity : 9.28Sending to 0x58: 0x20 0x15 , Received: 0x00 0x00 0x00 0x00 length: 4
     CO2 equivalent baseline : 0x0Sending to 0x58: 0x20 0x15 , Received: 0x00 0x00 0x00 0x00 length: 4
    , TVOC baseline : 0x0
    Data = {"co2_equivalent":400,"tvoc":0,"h2_signal":12685,"ethanol_signal":18333,"humidity":48.33599853515625,"temperature":21.812999725341797,"absolute_hum":9.2800455093383789,"co2_equivalent_baseline":16,"tvoc_baseline":16,"chipid":"000010a4ae30"}
    [D][WiFiClient.cpp:509] connected(): Disconnected: RES: 0, ERR: 128
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x90 0x00 0x00 length: 4
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x90 0x00 0x00 length: 4
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x90 0x00 0x00 length: 4
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x90 0x00 0x00 length: 4
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x90 0x00 0x00 length: 4
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x90 0x00 0x00 length: 4
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x90 0x00 0x00 length: 4
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x90 0x00 0x00 length: 4
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x90 0x00 0x00 length: 4
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x90 0x00 0x00 length: 4
    000010a4ae30
    Attempting MQTT connection...connected
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x90 0x00 0x00 length: 4
    Sending to 0x58: 0x20 0x50 , Received: 0x31 0x94 0x47 0xAB length: 4
    Sending to 0x70: 0x78 0x66 , Received: 0x61 0xC4 0x7A 0xDC length: 4
    CO2 equivalent : 400, TVOC : 0, H2_signal : 12692, Ethanol_signal : 18347, Humidity : 47.99, temperature : 21.83, absolute humidity : 9.22Sending to 0x58: 0x20 0x15 , Received: 0x00 0x00 0x00 0x00 length: 4
     CO2 equivalent baseline : 0x0Sending to 0x58: 0x20 0x15 , Received: 0x00 0x00 0x00 0x00 length: 4
    , TVOC baseline : 0x0
    Data = {"co2_equivalent":400,"tvoc":0,"h2_signal":12692,"ethanol_signal":18347,"humidity":47.991001129150391,"temperature":21.830999374389648,"absolute_hum":9.223388671875,"co2_equivalent_baseline":16,"tvoc_baseline":16,"chipid":"000010a4ae30"}
    [D][WiFiClient.cpp:509] connected(): Disconnected: RES: 0, ERR: 128
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x90 0x00 0x00 length: 4
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x90 0x00 0x00 length: 4
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x90 0x00 0x00 length: 4
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x90 0x00 0x00 length: 4
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x90 0x00 0x00 length: 4
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x98 0x00 0x05 length: 4
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x90 0x00 0x03 length: 4
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x92 0x00 0x03 length: 4
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x96 0x00 0x01 length: 4
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x90 0x00 0x00 length: 4
    000010a4ae30
    Attempting MQTT connection...connected
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0xA1 0x00 0x0D length: 4
    Sending to 0x58: 0x20 0x50 , Received: 0x31 0x94 0x47 0xA8 length: 4
    Sending to 0x70: 0x78 0x66 , Received: 0x61 0xBD 0x7A 0xCC length: 4
    CO2 equivalent : 417, TVOC : 13, H2_signal : 12692, Ethanol_signal : 18344, Humidity : 47.97, temperature : 21.81, absolute humidity : 9.21Sending to 0x58: 0x20 0x15 , Received: 0x86 0x6C 0x8C 0x58 length: 4
     CO2 equivalent baseline : 0x8C58Sending to 0x58: 0x20 0x15 , Received: 0x86 0x6C 0x8C 0x58 length: 4
    , TVOC baseline : 0x866C
    Data = {"co2_equivalent":417,"tvoc":13,"h2_signal":12692,"ethanol_signal":18344,"humidity":47.966999053955078,"temperature":21.812999725341797,"absolute_hum":9.20920181274414,"co2_equivalent_baseline":16,"tvoc_baseline":16,"chipid":"000010a4ae30"}
    [D][WiFiClient.cpp:509] connected(): Disconnected: RES: 0, ERR: 128
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0xA6 0x00 0x0F length: 4
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x98 0x00 0x05 length: 4
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x9E 0x00 0x0F length: 4
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x98 0x00 0x0C length: 4
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x9C 0x00 0x0D length: 4
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x9A 0x00 0x11 length: 4
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x9A 0x00 0x0F length: 4
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x9D 0x00 0x09 length: 4
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x96 0x00 0x0A length: 4
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x90 0x00 0x06 length: 4

Here ESP try to connect to MQTT because it looses wifi connection

    Attempting MQTT connection...connected
    Sending to 0x58: 0x20 0x08 , Received: 0x01 0x90 0x00 0x00 length: 4
    Sending to 0x58: 0x20 0x50 , Received: 0x31 0x8D 0x47 0x9D length: 4
    Sending to 0x70: 0x78 0x66 , Received: 0x61 0xBD 0x7B 0xBE length: 4
    CO2 equivalent : 400, TVOC : 0, H2_signal : 12685, Ethanol_signal : 18333, Humidity : 48.34, temperature : 21.81, absolute humidity : 9.28Sending to 0x58: 0x20 0x15 , Received: 0x00 0x00 0x00 0x00 length: 4
     CO2 equivalent baseline : 0x0Sending to 0x58: 0x20 0x15 , Received: 0x00 0x00 0x00 0x00 length: 4
    , TVOC baseline : 0x0
    Data = {"co2_equivalent":400,"tvoc":0,"h2_signal":12685,"ethanol_signal":18333,"humidity":48.33599853515625,"temperature":21.812999725341797,"absolute_hum":9.2800455093383789,"co2_equivalent_baseline":16,"tvoc_baseline":16,"chipid":"000010a4ae30"}
    [D][WiFiClient.cpp:509] connected(): Disconnected: RES: 0, ERR: 128

I am not using deep sleep yet, which would have disconnected from wifi.

**Update** :
I had ESP32-CAM connected to same AP, when I turn off ESP32-CAM then this code works without any error (`ERR: 128`)

Dont know how ESP32-CAM WiFi connection affects ESP32 WiFi connectivity ?

title: esp32 arduino wifi disconnect

Answers: 0


body:
I'm very new to the Arduino game I wanted to make a small auto watering system for my plants. I bought these items

 - 5V 1 CHANNEL RELAY MODULE FOR ARDUINO PIC AVR DSP ARMB
 - 9 VOLT BATTERY SNAP CONNECTOR B
 - ARDUINO UNO R3
 - CAMELION 9V BATTERY SUPER HEAVY DUTY
 - PIN TO HOLE DUPONT 40 PIN 30CM ARDUINO JUMPER WIRE 12 INCH
 - SOIL MOISTURE METER FOR ARDUINO.

I followed a video on youtube I attached the guys circuit diagram as well. After following instructions my pump wont turn on I also programmed it as well. Please help if anyone can show me how to rewire the device and codes or if I'm doing something wrong. Please help.

    int Relay = 13;
    int sensor = 8;
    int val;
    void setup() {
      pinMode(13,OUTPUT); //Set pin 13 as OUTPUT pin, to send signal to relay
      pinMode(8,INPUT); //Set pin 8 as input pin, to receive data from Soil moisture sensor.
    }

    void loop() {
      val = digitalRead(8);
      if(val == LOW)
      {
        digitalWrite(13,LOW); //if soil moisture sensor provides LOW value send LOW value to relay
      }
      else
      {
        digitalWrite(13,HIGH); //if soil moisture sensor provides HIGH value send HIGH value to relay
      }
      delay(400);
    }

![enter image description here](https://i.stack.imgur.com/bIMhV.jpg)

title: Plant irrigation system

Answers: 1

body:
I've seen so much fake projects from "Viral science". I'm not sure whether he/she simply don't know what he/she does or if he/she simply tries to trap people. This project is a race condition itself ;-).

Besides your battery is empty. I don't think it is a big problem to use a 9V block battery, but Gerben is right, it won't do its job for very long. Have you thought about using a LiPo or LiOn Accu and a Solar loader?

There are worse things I see:

The sensor is powered by 3.3V but you read the ON/OFF signal with a 5-Volt Pin. That could be a problem, if there are other voltage drops that lead to a signal the PIN can not recognize as HIGH. Check the documentation of the moisture sensor and if it allows 5V use 5V to power it. All sensors I have found on Google have at least a range from 3.3 Volt to 5 Volt.

Check the current consumption of the relay. It must not draw more current than the Arduino PIN can provide (40mA for the UNO). And, don't use PIN13 to switch the relay. There are so many others and PIN 13 is connected to the onboard LED, which draws 10 - 20 mA on its own.


body:
I used the BLE example from [here](https://raw.githubusercontent.com/nkolban/ESP32_BLE_Arduino/master/examples/BLE_server/BLE_server.ino).

But any device can read and write to the advertised characteristic. Is there a way to make the data inaccessible to other devices except for my app somehow. What I would really like to do is something like SDP and then connect and exchange data over RFCOMM but it seems impossible to do so in esp32. I have done it using bluez library on Linux but in case of esp32 I found only one library btstack that is impossible to use with esp-idf because of lack of CMakeLists.txt. Is there some way I can achieve what I want?

title: How to make BLE data accessible to a particular app?

Answers: 1

body:
In general terms, you could simply require a client to authenticate first. This would require a bit of a deviation from the example you linked to (which actually only handles reading of the characteristic) to handle multiple connections and their state, but it should be pretty straightforward.

The Arduino BLE library seems to lack sending quite a bit of information via the callbacks, so you just know there's a connect or disconnect or a write to a characteristic, and not which devices did. This means you won't be able to handle multiple connections at the same time, but making sure you reset your authentication state whenever you receive a connect or disconnect should be enough to prevent anyone but your own client from "talking" to your device.


body:
I am receiving data from an LDR which I am inputting into processing. The data seems to be received to Arduino correctly and I have looked at the data being sent via the serial monitor and it all seems correct. However, the data that is being received in processing doesn't reflect the data received by the LDR so I think I have done something wrong here but not sure what as I am fairly new to this all. (Please see image for what is printing in the processing serial monitor).

Any help identifying where I have gone wrong would be so so helpful!

**ARDUINO CODE**

```c++
int rval=0;
int lightval;

//Recorded minimum and maximum values
int minval=0;
int maxval=950;

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

void loop()
{
  rval = analogRead(1);
  //Serial.println(rval);
  rval=constrain(rval,minval,maxval);
  lightval=map(rval,minval,maxval,0,255);
  //Serial.println(lightval);
  Serial.write(lightval);
}
```
  **PROCESSING CODE**
```c++
import processing.serial.*;

Splash paintsplash;
Serial port;

float value=0;

void setup()
{
  size(600,600);
  smooth();
  background(255);
  paintsplash= new Splash();
  port=new Serial(this, Serial.list()[6],9600);
  //printArray(Serial.list());
}

void draw()
{
  paintsplash.display();
  paintsplash.splash();
  delay(200);

  if(0<port.available())
  {
    value=port.read();
  }

  println(value);

  if(value<=75)
  {
    fill(255,137,132);
  }

  else if(value>75 && value<=125)
  {
    fill(32,78,95);
  }

  else
  {
    fill(183,215,216);
  }
}
```
  **PROCESSING CLASS - PAINT_SPLASH**
```
class Splash
{
  float x;
  float y;
  float size;

  Splash()
  {
    x=0;
    y=0;
    size=int(random(35));
  }

  void display()
  {
    //fill(255,137,132);
    noStroke();
    ellipse(x,y,size,size);
  }

  void splash()
  {
  float xcord=int(random(600));
  float ycord=int(random(600));
  pushMatrix();
  translate(xcord,ycord);

     for ( float i =3; i < 29; i ++)
     {
       float splashX = x + random(100);
       float splashY = y + random(100);

       ellipse(splashX,splashY,size-i,(size-i+random(3)));
     }

   popMatrix();
  }
}
```

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

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

title: UPDATE: Fault in processing code - doesn't receive correct data from Arduino

Answers: 1

body:
You're sending your `lightval` twice - once as a textual representation of the number, and once as a character representing the lower 8 bits:

    Serial.println(lightval);
    Serial.write(lightval);

For example:

    Q308
    R304
    Q306

If you take the 308 and AND it with 255 you get 52.  52 as an ASCII character is `R`.

So you print 308, including a newline, then you print "R".  Then you print 304, which would be 48 after ANDing with 255 - which of course is a Q.


body:
I am planning to build a network with five Arduino Mega devices, each of which will collect data using multiple sensors. Each Arduino will periodically transmit the sensor data to a gateway Raspberry Pi using XBees. As it is the first time I am working with Arduino and Raspberry Pi, I need help with the following:

1. Which protocol to use to transmit data from Arduinos to the Raspberry Pi? Do I have to write code for both Arduino and Raspberry Pi or are there existing solutions that I can use for this purpose?

2. Does MQTT, Node-RED or Node.js have any role in the above?

Thank you for your advice!

A.

title: How to transmit data from Arduino to Raspberry Pi?

Answers: 1

body:
> 1. Which protocol to use to transmit data from Arduinos to the Raspberry Pi? Do I have to write code for both Arduino and Raspberry Pi or are there existing solutions which I can use for this purpose?
>
> 2. Does MQTT, Node-RED or Node.js have any role in the above?

I have searched, explored, read and found that MQTT can be used to send and receive data from Arduinos to RaspberryPi as in [1] and [2]. So, no need to design and develop a new protocol.

MQTT libraries, such as PubSubClient [3] are available for Arduino. So Arduino code can use these libraries and no need to write much code either.

Simple and straight!

A.

[1] https://funprojects.blog/2018/03/04/arduino-talking-mqtt-to-node-red/

[2] https://iotdesignpro.com/projects/interface-arduino-with-node-red-to-send-sensor-data-on-webpage

[3] https://www.arduinolibraries.info/libraries/pub-sub-client


body:
I've been trying to work with Waveshare SIM 808 shield on arduino, quite similar to this one:
https://www.waveshare.com/wiki/GSM/GPRS/GPS_Shield_(B)#How_to_use_with_Arduino_UNO_R3

I tried using multiple examples, such as this:

    #include <DFRobot_sim808.h>

    #include <SoftwareSerial.h>

    DFRobot_SIM808 sim808(&Serial);

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

      //******** Initialize sim808 module *************
      while(!sim808.init()) {
          delay(1000);
          Serial.print("Sim808 init error\r\n");
      }

      //************* Turn on the GPS power************
      if( sim808.attachGPS())
          Serial.println("Open the GPS power success");
      else
      Serial.println("Open the GPS power failure");

    }

    void loop() {
        //************** Get GPS data *******************
        if (sim808.getGPS()) {
        Serial.print(sim808.GPSdata.year);
    Serial.print("/");
    Serial.print(sim808.GPSdata.month);
    Serial.print("/");
    Serial.print(sim808.GPSdata.day);
    Serial.print(" ");
    Serial.print(sim808.GPSdata.hour);
    Serial.print(":");
    Serial.print(sim808.GPSdata.minute);
    Serial.print(":");
    Serial.print(sim808.GPSdata.second);
    Serial.print(":");
    Serial.println(sim808.GPSdata.centisecond);

    Serial.print("latitude :");
    Serial.println(sim808.GPSdata.lat,6);

    sim808.latitudeConverToDMS();
    Serial.print("latitude :");
    Serial.print(sim808.latDMS.degrees);
    Serial.print("\^");
    Serial.print(sim808.latDMS.minutes);
    Serial.print("\'");
    Serial.print(sim808.latDMS.seconeds,6);
    Serial.println("\"");
    Serial.print("longitude :");
    Serial.println(sim808.GPSdata.lon,6);
    sim808.LongitudeConverToDMS();
    Serial.print("longitude :");
    Serial.print(sim808.longDMS.degrees);
    Serial.print("\^");
    Serial.print(sim808.longDMS.minutes);
    Serial.print("\'");
    Serial.print(sim808.longDMS.seconeds,6);
    Serial.println("\"");

    Serial.print("speed_kph :");
    Serial.println(sim808.GPSdata.speed_kph);
    Serial.print("heading :");
    Serial.println(sim808.GPSdata.heading);

    //************* Turn off the GPS power ************
    sim808.detachGPS();
      }

    }

or this

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(2, 3); // RX, TX
    String comdata = "";
    void setup()
    {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);

     while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      // set the data rate for the SoftwareSerial port
      mySerial.begin(9600);
      delay(200);
    }

    void loop() // run over and over
    {
      delay(2000);
       mySerial.println("AT");
       delay(200);
       //Send message
       mySerial.println("AT+CGNSPWR=1");
       delay(200);
       //reset GPS in autonomy mode
       mySerial.println("AT+CGNSTST=1");
       delay(200);
       mySerial.listen();
       while(1)
      {
        while(mySerial.available()>0)
            Serial.write(mySerial.read());
        while(Serial.available())
        mySerial.write(Serial.read());
      }
    }

In first case, I obviously don't declare RX, TX pins and use the Arduino's general purpose RX, TX pins (0, 1).
------------------------------------------------------------------------

In second case I used wires to connect Arduino pins 2 and 3, to shield's D0 and D1 pins.

In both cases, neither RX or TX leds on shield's module light up, which means that it doesn't receive the sent data.

I made sure to set UART/ARDUINO switch on ARDUINO position and I did reset the module several times.

I am using Arduino Uno. What goes wrong here?

title: Trouble with SIM808 shield

Answers: 0


body:
I am using UIPEthernet to get an Arduino Nano to drive an ENC28J60 Ethernet Shield for a UDP-based application. I'm customizing a number of its `#define` parameters to change default settings to save space, but I'm not sure I'm doing it correctly.  It's clearly designed to facilitate per-sketch customization, but things aren't quite working for me, and I can't tell if it's me doing it wrong, or if the customization doesn't quite do what I'm expecting.

Specifically, the comments at the top of `utilities/uip-conf.h` say:

>uIP has a number of configuration options that can be overridden  for each project. These are kept in a project-specific uip-conf.h file and all configuration names have the prefix UIP_CONF.

So that sounds great - I've copied `uip-conf.h` into my sketch (into the top directory next to my other sources), adjusted it appropriately, and ... nothing changes.

Now, I'm #including `<UIPEthernet.h>` into my source files, and everything compiles using the Arduino IDE (v1.8.10). Looking in the library, I can see `<UIPEthernet.h>` includes `<utilities/uipopt.h>`, which in turn includes `"uip-conf.h"` (note the quotes). So I think it's intended to be picking up my local one. But it doesn't - it uses the original one from the library.

My understanding of `#include "example.h"` is that it looks for `example.h` relative to the *current file location*, (ie `<utilities/uipopt.h>`, so *utilities/*), so I'm actually seeing correct inclusion behaviour and now I don't see how this customization approach could ever work!

I tried adding the `#include "uip-conf.h"` to my own sources, and that sort of works for my sources, but of course doesn't affect the library `.cpp` files themselves which still see the original version.

I could probably drag the entire lib into my sketch and fix up the includes, but that seems like the wrong answer. It's extensively designed to be customizable. Do you know what steps need to be taken to do it please? (Or a pointer to some docs would be fine!) Thanks!

title: How should I customize UIPEthernet constants?

Answers: 1

body:
Creating a copy of the include file in sketch folder will not work. At library compilation the source files of sketch are not included. The "" for include is "search first in the same folder as the including file".

The *project* in the description of use of uip-conf.h is UIPEthernet. It includes the UIP library by Adam Dunkels and configures it with this file.

----------

A project with UIPEthernet library can configure the library with options in uipopt.h. Most of the options in uipopt.h are defined as

    #ifdef UIP_CONF_UDP_CONNS
    #define UIP_UDP_CONNS UIP_CONF_UDP_CONNS
    #else /* UIP_CONF_UDP_CONNS */
    #define UIP_UDP_CONNS    10
    #endif /* UIP_CONF_UDP_CONNS */

this allows to define the value on compiler command line as -D. Most IDEs enable to set project defines in project settings. Arduino IDE does not enable this yet, because it doesn't have a project configuration file.

With Arduino IDE you can add defines for platform or for board definitions with build.extra_flags in platform.local.txt or in boards.local.txt. Example for boards.local.txt for Arduino Mega:

  mega.build.extra_flags=-DUIP_CONF_UDP_CONNS=20 -DUIP_CONF_MAX_LISTENPORTS=30

platform.local.txt and boards.local.txt must be in boards package folder nect to platform.txt and boards.txt.


body:
I would like to read multiple pins at once in Arduino Due via registers just like PINB, PINC, PIND of the arduino uno. I know that the pins will be scattered to multiple registers, but i deduce it would still be faster this way since there for sure there will be multiple pins on a single register rather than call digitalRead 40 times.

Arduino shared the documentation for what digital/analog pins corressponds to the what ports to the actual sam chip, i just need that snippet of code that reads via registers.

So if any can give me the equivalents to these, It would be greatly appreciated:

- DDRx - The Port C Data Direction Register - read/write
- PORTx - The Port C Data Register - read/write
- PINx - The Port C Input Pins Register - read only

title: Reading multiple pins via registers on the Arduino Due

Answers: 1

body:
You will find a good introduction on using port registers [here][1]. It also mentions some cons and pros of using port manipulation.

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


body:
I am implementing an FIR filter using Arduino. I am using an input signal as an audio signal. The audio signal has a duration of 3 seconds with total samples, 66150. What I am doing is reading this file in python and storing the data in an array. Using Serial, I want to send this sampled data to Arduino serial and process it, then send it back to serial and receive in  Python.

**Python Code**

    import matplotlib.pyplot as plt
    from scipy.fftpack import fft
    from scipy.io import wavfile # get the api
    import serial, time

    samplerate, data = wavfile.read("sample.wav")
    samples = len(data)
    plt.plot(data[:20000])
    arduino = serial.Serial('COM4', 9600, timeout=.1)
    time.sleep(1) #give the connection a second to settle

    for i in range(0,samples):

        arduino.write(data[i])
        time.sleep(1)
        print(arduino.readline())

**Arduino Code**

      void setup() {

      Serial.begin(9600);
      }
      int i = 0;
      int newdata[10];
      void loop() {
         if(Serial.available() > 0) {
              int data = Serial.read();
              newdata[i] = data;
              Serial.print(newdata[i]);
              i = i+1;
            }
       }
The problem I am facing is that I am stuck at very first step. As a check, I sent 10 samples values at start from Python to arduino using a loop and tried to recover them back to read on Python console. These values were not correct. When I entered a string inside the arduino.write(), it was receiving but when I input a variable inside the arduino.write(), it doesn't print that value after transferring back to python.
I just tried many things like changing to string but I didn't get the desired result. The output for this code is attached. Tomorrow is my submission and I am stuck in this thing. Help will be highly appreciated.[![Python cmd window output][1]][1]

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

title: Interfacing Arduino with Python Serial

Answers: 2

body:
```
    arduino.write(data[i].tobytes())
    time.sleep(.1)
    print(int.from_bytes(arduino.readline(),byteorder='little') )
```
Is this what you whant?

body:
I have found a way to tackle this.
Here is my arduino code:

    char buf[100];
    const double coefficients[28] = {
    -0.006416610121367, -0.01179616274682, -0.01212859343535,-0.001491136183145,
     0.0175211951058,  0.03193599126761,   0.0259553014052,-0.004580133449276,
    -0.04206485416456, -0.05260424218688,-0.007566809377484,  0.09242896920118,
     0.2100842841173,   0.2894365184419,   0.2894365184419,   0.2100842841173,
     0.09242896920118,-0.007566809377484, -0.05260424218688, -0.04206485416456,
    -0.004580133449276,   0.0259553014052,  0.03193599126761,   0.0175211951058,
    -0.001491136183145, -0.01212859343535, -0.01179616274682,-0.006416610121367
    };

    int order_of_filter = 27;
    int sample_array[28] = {};
    double output_sample = 0;
    void setup()
    {
      Serial.begin(9600);
      Serial.setTimeout(50000);
    }
    void loop()
    {
      int  sample_in;
      int num_read = Serial.readBytesUntil('\n', buf, 100);
      buf[num_read] = '\0';
      sscanf(buf, "%d", &sample_in);
      for (int i = order_of_filter; i > 0; i--)
      {
        sample_array[i] = sample_array[i-1];
      }

      sample_array[0] = sample_in;

      for(int i = 0; i<=order_of_filter; i++)
      {
        output_sample = output_sample + sample_array[i]*coefficients[i];
      }
      Serial.println(output_sample);
      output_sample = 0;
    }
And here is my Python Code:

   import matplotlib.pyplot as plt
   from scipy.fftpack import fft
   from scipy.io import wavfile # get the api
    import serial, time
    import numpy as np
   import sounddevice as sd

   arduino = serial.Serial('COM4', 9600, timeout=1) #COM port depends on the USB port
  time.sleep(3) #time to get connection ready
  # %%

  fs, data = wavfile.read('hfsound.wav')
  samples = len(data)
  #Plot the signal
  plt.plot(data[:samples])
  plt.ylabel("Amplitude")
  plt.xlabel("Time")
  plt.title("Time Domain Response of the Input Signal")
  plt.grid()
  plt.show()
  #Plotting fft
  fft_input = fft(data)
  half_length = int(len(fft_input)/2)
  omega_axis = np.linspace(0, fs/2, half_length)
  fft_n = fft_input[:half_length]
  plt.plot(omega_axis,abs(fft_n))
  plt.xlabel('frequency')
  plt.ylabel('Amplitude')
  plt.title("Frequency Domain Response of the Input Signal")
  plt.grid()
  plt.show()
  # %%

  #Declare an Array of zeros
  outputArray = np.zeros(64000)
  #Sending data to aurdino
  for i in range(samples):
       number = data[i]
       string = str(number).encode(encoding='utf-8') + b'\n'
       arduino.write(string)
       byt = arduino.read_until();
       print(byt.strip())
       outputArray[i] = byt.strip()

  arduino.close()
  # %%

  #Plotting Output waveform
  #Plot the time-domain output signal
  plt.plot(outputArray[:len(outputArray)])
  plt.ylabel("Amplitude")
  plt.xlabel("Time")
  plt.title("Time Domain Response of the Output Signal")
  plt.grid()
  plt.show()

  #Plotting fft of output
  fft_out = fft(outputArray)
  half_length = int(len(fft_out)/2)
  omega_axis = np.linspace(0, fs/2, half_length)
  fft_n = fft_out[:half_length]
  plt.plot(omega_axis,abs(fft_n))
  plt.xlabel('frequency')
  plt.ylabel('Amplitude')
  plt.title("Frequency Domain Response of the Output Signal")
  plt.grid()
  plt.show()
  # %%

  #Playback code
  sd.play(outputArray, fs)
  # %%


body:
I've been working on trying to get [this][1] arduino project I found to work but I've been encountering some problems.

The project was designed for an Arduino mega 2560 but I've been using my UNO and breadboard for it along with the Software Serial library. I'm very, very new to working with Arduinos so if there are any basic things I might be missing please do mention them.

Components:

 - Arduino UNO
 - Bluetooth HC-05 module
 - E18-D80NK Proximity Sensor
 - Saeed Grove 420 Proximity Sensor
 - 10k Ohm resistor
 - Breadboard
 - The included app in the above link

The issues I'm facing are

a)Initially, the proximity sensor would detect if I e.g. moved my hand infront of it and send the data to the app and it would increment the score and play the sound.

However, if I tried flicking the vibration sensor and not moving my hand infront of the proximity sensor, a miss wouldn't be recorded. Initially, even just flicking the proximity sensor would record a score as well, but later it would just do nothing.

b)I'm not sure what is the problem, but now nothing happens at all. The wiring and everything is all connected in the same way as before, but now even though the proximity sensor lights up if I move my hand infront of it, no scores are transmitted by the HC-05 module or anything. I have tried keeping the Serial Monitor open but nothing is printed on it.

Also, the code I've pasted below is after including the SerialSoftware library header and after deleting all the code for setting the LED lights which is still available in the link above. Problem B started occurring before I did this, so I don't think that has anything to do with it. Just didn't want to include the LEDs in my project.

Any help would be really appreciated, thank you!! If there's any information I've missed out on, please let me know.

Edit: Okay, so I had the RX and TX wires of the module in the incorrect sockets. The RXD of the hc-05 module is now in pin 11 and the TXD in pin 10. Data is being transmitted, but it just endlessly keeps incrementing the shots even if the proximity sensor isn't detecting anything. :/ Any suggestions?

Edit2: Alright, issue resolved. I hadn't set the correct baud rate in the Bluetooth setup portion. Should've been 9600.

```
#include <SoftwareSerial.h>
SoftwareSerial Serial1(10, 11); // RX, TX

//----------------------------------------------------------------------------//
// Filename    : Scoreboard.ino                                               //
// Description : Smart Basketball Scoreboard                                  //
// Version     : 1.1.0                                                        //
// Author      : Marcelo Avila de Oliveira <marceloavilaoliveira@gmail.com>   //
//----------------------------------------------------------------------------//

//----------------------------------------------------------------------------//
// DEFINITIONS                                                                //
//----------------------------------------------------------------------------//

// TURN ON DEBUG MODE
// #define DEBUG
// #define DEBUG_PROX
// #define DEBUG_VIBR

//----------------------------------------------------------------------------//
// CONSTANTS                                                                  //
//----------------------------------------------------------------------------//

// PINS
const int prox_pin = 2;
const int vibr_pin = 3;

// TIME
const unsigned long wait_interval = 3000;

//----------------------------------------------------------------------------//
// VARIABLES                                                                  //
//----------------------------------------------------------------------------//

// TIME
unsigned long wait_time;

// STATUS
boolean prox = false;
boolean vibr = false;
boolean wait = false;

//----------------------------------------------------------------------------//
// FUNCTIONS (SETTINGS)                                                       //
//----------------------------------------------------------------------------//

void setup() {
    // INITIATE PINS
    pinMode(prox_pin, INPUT);
    pinMode(vibr_pin, INPUT);

    // INITIATE SERIAL COMMUNICATION
    Serial.begin(9600);

    // INITIATE BLUETOOTH COMMUNICATION
    setup_bluetooth();

    #ifdef DEBUG
        Serial.println("Board is alive");
        Serial.println();
    #endif
}

void setup_bluetooth() {
    #ifdef DEBUG
        Serial.println("Setting Bluetooth");
        Serial.println();
    #endif

    Serial1.begin(38400);                   // Set baud rate
    Serial1.print("\r\n+STWMOD=0\r\n");     // Set to work in slave mode
    Serial1.print("\r\n+STNA=Arduino\r\n"); // Set name
    Serial1.print("\r\n+STOAUT=1\r\n");     // Permit Paired device to connect me
    Serial1.print("\r\n+STAUTO=0\r\n");     // Auto-connection should be forbidden here
    delay(2000);                            // This delay is required.
    Serial1.print("\r\n+INQ=1\r\n");        // Make the slave inquirable
    delay(2000);                            // This delay is required.
    while (Serial1.available()) {           // Clear data
        delay(50);
        Serial1.read();
    }
}

//----------------------------------------------------------------------------//
// FUNCTIONS (CHECK)                                                          //
//----------------------------------------------------------------------------//

void check_prox() {
    if (!prox) {
        if(digitalRead(prox_pin) == LOW) {
            #ifdef DEBUG_PROX
                Serial.println("Proximity detected");
                Serial.println();
            #endif

            prox = true;
            if (!vibr) {
                wait = true;
                wait_time = millis() + wait_interval;
            }
            set_shot(1);
        }
    }
}

void check_vibr() {
    if (!prox && !vibr) {
        if(digitalRead(vibr_pin) == HIGH) {
            #ifdef DEBUG_PROX
                Serial.println("Vibration detected");
                Serial.println();
            #endif

            vibr = true;
            wait = true;
            wait_time = millis() + wait_interval;
        }
    }
}

void check_wait() {
    if (wait && millis() > wait_time) {
        if (!prox) {
            set_shot(0);
        }
        reset();
    }
}

//----------------------------------------------------------------------------//
// FUNCTIONS (MIS)                                                            //
//----------------------------------------------------------------------------//

void set_shot(int mode) {
    // MODE:
    // 0 = WRONG SHOT (MISS)
    // 1 = RIGHT SHOT (SCORE)

    Serial1.print(mode);
    delay(1000);
}

void reset() {
    vibr = false;
    prox = false;
    wait = false;
}

//----------------------------------------------------------------------------//
// MAIN                                                                       //
//----------------------------------------------------------------------------//

void loop() {
    check_prox();
    check_vibr();
    check_wait();
}

```

  [1]: https://create.arduino.cc/projecthub/marceloavilaoliveira/smart-basketball-scoreboard-f922cb#schematics

title: Basketball board arduino endlessly transmitting shot scored

Answers: 1

body: Alright, issue resolved. I hadn't set the correct baud rate in the Bluetooth setup portion. Should've been 9600.


body:
I discovered a curios behavior of my Nano v3. The analog Pin A0 seems to measure data in a non-linear way while the other pins seem to work normal.

Please have a look at the screenshot. This is the normal ReadAnalogVoltage example with a 50K potentiometer. A1 (red line) raise and falls linear when turning the knob. But the A0 line (blue) does not.

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

Is there a way to change it back to the normal behavior? Some weeks ago it worked fine on A0 as well. So these results are quite surprising for me. In general it would have been easy using another pin, but I already created a pcb which utilize A0.

Thanks

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

title: Non-Linear readings on Analog Pin A0 vs. other Pins A1

Answers: 0


body:
I’ve been trying to make this project: https://create.arduino.cc/projecthub/chummer1010/electronic-safe-with-arduino-25d039

I’m confident that I’ve assembled everything correctly, but my LCD doesn’t display characters. Other projects seem to have fixed it by changing the potentiometer but I’m not using one.

Arduino code:

    /*
    Made by Marco Fusco
    May 20, 2016
    Contact me at: marcofusco111@gmail.com
    */

    #include <LiquidCrystal.h>
    #include <EEPROM.h>
    #include <Servo.h>

    int address = 0;
    static unsigned long SaveTimer;
    static unsigned long SaveDelay = (30 * 1000);

    char CODE[10] = "1234E";
    char Str[10];
    char CodeLength = 4;
    int Pos = 0;
    bool Unlocked;
    static unsigned long DisplayTimer;
    static unsigned long DisplayDelay = 200;

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

    int buttonPin1 = 2;
    int buttonPin2 = 3;
    int buttonPin3 = 4;
    int buttonPin4 = 5;

    int enterbutton = 10;
    int clearlockbutton = 13;

    Servo myServo;

    void setup() {

      myServo.attach(A1);

      int EEPROMCodeOK = true;
      for (Pos = 0; Pos <= (CodeLength); Pos++) {
        Str[Pos] =  EEPROM.read(Pos);
        if (!(strrchr("1123456789", Str[Pos]))) {
          // not a valid code
          EEPROMCodeOK = false;
        }
      }
      Pos++;
      Str[Pos] =  EEPROM.read(Pos);
      if (Str[CodeLength + 1] != 'E') EEPROMCodeOK = false;
      if (EEPROMCodeOK) {
        Str[CodeLength + 2] = '\0';
        strncpy(CODE, Str, CodeLength + 1);
      }
      ClearCode();

      pinMode(buttonPin1, INPUT_PULLUP);
      pinMode(buttonPin2, INPUT_PULLUP);
      pinMode(buttonPin3, INPUT_PULLUP);
      pinMode(buttonPin4, INPUT_PULLUP);

      pinMode(enterbutton, INPUT_PULLUP);
      pinMode(clearlockbutton, INPUT_PULLUP);

      lcd.begin(16, 2);
      lcd.setCursor(0, 0);
      lcd.print("Hello.");
      delay(2000);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("Password:");

      DisplayTimer = millis() + 200;
    }

    void loop() {

      Lock();

      Pos = constrain(Pos, 0, CodeLength);

      int buttonState1 = digitalRead(buttonPin1);
      int buttonState2 = digitalRead(buttonPin2);
      int buttonState3 = digitalRead(buttonPin3);
      int buttonState4 = digitalRead(buttonPin4);

      int clButtonState = digitalRead(clearlockbutton);
      int enterButtonState = digitalRead(enterbutton);

      lcd.setCursor(9, 0);

      if (buttonState1 == LOW) {
        Str[Pos] = '1';
        Pos++;
        Str[Pos] = '\0';
        delay(250);
        while (digitalRead(buttonPin1) == LOW);

      }

      else if (buttonState2 == LOW) {
        Str[Pos] = '2';
        Pos++;
        Str[Pos] = '\0';
        delay(250);
        while (digitalRead(buttonPin2) == LOW);

      }

      else if (buttonState3 == LOW) {
        Str[Pos] = '3';
        Pos++;
        Str[Pos] = '\0';
        delay(250);
        while (digitalRead(buttonPin3) == LOW);
      }

      else if (buttonState4 == LOW) {
        Str[Pos] = '4';
        Pos++;
        Str[Pos] = '\0';
        delay(250);
        while (digitalRead(buttonPin4) == LOW);

      }
      else if (enterButtonState == LOW) {
        Str[Pos] = 'E';
        Pos++;
        Str[Pos] = '\0';
        delay(250);
        while (digitalRead(buttonPin1) == LOW);
         if (strcmp (Str,CODE) == 0) {
          Unlocked = true;
          lcd.setCursor(0, 0);
          lcd.print(" Access Granted");
          delay(2000);
          lcd.clear();
          lcd.print("    Unlocked");
        }
        else if (SaveTimer > millis() && (Pos + 1) == CodeLength) {

          strcpy(CODE, Str);
          for (Pos = 0; Pos <= (CodeLength + 1); Pos++) {
            EEPROM.write(Pos, Str[Pos]);
          }
          lcd.setCursor(0, 0);
          lcd.print("Saving Code:");
          lcd.setCursor(0, 1);
          lcd.print(Str);

          Unlocked = true;
        }

        else {

          lcd.clear();
          lcd.print(" Access Denied.");
          delay(2000);
          lcd.clear();
          lcd.print("Password:");

        }

        while (Unlocked) {
          Unlock();
          if (digitalRead(clearlockbutton) == LOW) {
            delay(200);
            lcd.clear();
            lcd.print("     Locked");
            delay(2000);
            lcd.clear();
            Unlocked = false;
            SaveTimer = millis() + 30000;
          }
        }

        ClearCode();

      }

      else if (clButtonState == LOW) {
        delay(500);

        while (clearlockbutton == LOW);
        if ((millis() - SaveTimer) > 4500) {

        }

        ClearCode();

      }

      if ( (long)( millis() - DisplayTimer ) >= 0) {
        DisplayTimer += DisplayDelay;
        lcd.setCursor(9, 0);
        lcd.print(Str);
        lcd.print("     ");

      }
    }

    void ClearCode() {

      Pos = 0;
      Str[Pos] = '\0';
      lcd.setCursor(0, 0);
      lcd.print("Password:");
      lcd.setCursor(0, 1);
      lcd.print("          ");

    }

    void Unlock() {

      myServo.write(150);

    }

    void Lock() {

      myServo.write(50);

    }

title: LCD Backlight doesn’t work even at 5V. Using 330 Ohm resistor

Answers: 2

body: Please add a foto of the display. Most likely you have problem with a contrast. Schematic at the link you've provided is very strange: pin 3, which is responsible for the contrast, is tied directly to GND, which sets the display to the minimum contrast. You should use either a potentiometer, or a voltage divider for this pin.

body:
Start with the Liquid Crystal, HelloWorld, Example.   Find out if it's your pin configuration or pot/no pot issue, or if you have a doofed LCD.

Some LCD 1602 have an on board pot, so make sure that's not there too.

Process of elimination.


body:
my code:

```c++
// Get Yaw, Pitch and Roll values
#ifdef OUTPUT_READABLE_YAWPITCHROLL
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
    // Yaw, Pitch, Roll values - Radians to degrees
    ypr[0] = ypr[0] * 180 / M_PI;
    ypr[1] = ypr[1] * 180 / M_PI;
    ypr[2] = ypr[2] * 180 / M_PI;

    // Skip 300 readings (self-calibration process)
    if (j <= 300) {
      correct = ypr[0]; // Yaw starts at random value, so we capture last value after 300 readings
      j++;
    }
    // After 300 readings
    else {
      ypr[0] = ypr[0] - correct; // Set the Yaw to 0 deg - subtract  the last random Yaw value from the currrent value to make the Yaw 0 degrees
      // Map the values of the MPU6050 sensor from -90 to 90 to values suatable for the servo control from 0 to 180
      int servo0Value = map(ypr[0], -90, 90, 0, 180);
      int servo1Value = map(ypr[1], -90, 90, 0, 180);
      int servo2Value = map(ypr[2], -90, 90, 180, 0);

      // Control the servos according to the MPU6050 orientation
      servo0.write(servo0Value);
      servo1.write(servo1Value);
      servo2.write(servo2Value);
    }
#endif

// Yaw, Pitch, Roll values - Radians to degrees
    ypr[0] = ypr[0] * 180 / M_PI;
    ypr[1] = ypr[1] * 180 / M_PI;
    ypr[2] = ypr[2] * 180 / M_PI;

// Skip 300 readings (self-calibration process)
    if (j <= 300) {
      correct = ypr[0]; // Yaw starts at random value, so we capture last value after 300 readings
      j++;
    }

// After 300 readings
    else {
      ypr[0] = ypr[0] - correct; // Set the Yaw to 0 deg - subtract  the last random Yaw value from the currrent value to make the Yaw 0 degrees
      // Map the values of the MPU6050 sensor from -90 to 90 to values suatable for the servo control from 0 to 180
      int servo0Value = map(ypr[0], -90, 90, 0, 180);
      int servo1Value = map(ypr[1], -90, 90, 0, 180);
      int servo2Value = map(ypr[2], -90, 90, 180, 0);

      // Control the servos according to the MPU6050 orientation
      servo0.write(servo0Value);
      servo1.write(servo1Value);
      servo2.write(servo2Value);
    }
```

it says ypr does not name a type

```c++
/*
   Arduino and MPU6050 Accelerometer and Gyroscope Sensor Tutorial
   by Dejan, https://howtomechatronics.com
*/
#include <Wire.h>
const int MPU = 0x68; // MPU6050 I2C address
float AccX, AccY, AccZ;
float GyroX, GyroY, GyroZ;
float accAngleX, accAngleY, gyroAngleX, gyroAngleY, gyroAngleZ;
float roll, pitch, yaw;
float AccErrorX, AccErrorY, GyroErrorX, GyroErrorY, GyroErrorZ;
float elapsedTime, currentTime, previousTime;
int c = 0;
void setup() {
  Serial.begin(19200);
  Wire.begin();                      // Initialize comunication
  Wire.beginTransmission(MPU);       // Start communication with MPU6050 // MPU=0x68
  Wire.write(0x6B);                  // Talk to the register 6B
  Wire.write(0x00);                  // Make reset - place a 0 into the 6B register
  Wire.endTransmission(true);        //end the transmission
  /*
  // Configure Accelerometer Sensitivity - Full Scale Range (default +/- 2g)
  Wire.beginTransmission(MPU);
  Wire.write(0x1C);                  //Talk to the ACCEL_CONFIG register (1C hex)
  Wire.write(0x10);                  //Set the register bits as 00010000 (+/- 8g full scale range)
  Wire.endTransmission(true);
  // Configure Gyro Sensitivity - Full Scale Range (default +/- 250deg/s)
  Wire.beginTransmission(MPU);
  Wire.write(0x1B);                   // Talk to the GYRO_CONFIG register (1B hex)
  Wire.write(0x10);                   // Set the register bits as 00010000 (1000deg/s full scale)
  Wire.endTransmission(true);
  delay(20);
  */
  // Call this function if you need to get the IMU error values for your module
  calculate_IMU_error();
  delay(20);
}

void loop() {
  // === Read acceleromter data === //
  Wire.beginTransmission(MPU);
  Wire.write(0x3B); // Start with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU, 6, true); // Read 6 registers total, each axis value is stored in 2 registers
  //For a range of +-2g, we need to divide the raw values by 16384, according to the datasheet
  AccX = (Wire.read() << 8 | Wire.read()) / 16384.0; // X-axis value
  AccY = (Wire.read() << 8 | Wire.read()) / 16384.0; // Y-axis value
  AccZ = (Wire.read() << 8 | Wire.read()) / 16384.0; // Z-axis value
  // Calculating Roll and Pitch from the accelerometer data
  accAngleX = (atan(AccY / sqrt(pow(AccX, 2) + pow(AccZ, 2))) * 180 / PI) - 0.58; // AccErrorX ~(0.58) See the calculate_IMU_error()custom function for more details
  accAngleY = (atan(-1 * AccX / sqrt(pow(AccY, 2) + pow(AccZ, 2))) * 180 / PI) + 1.58; // AccErrorY ~(-1.58)
  // === Read gyroscope data === //
  previousTime = currentTime;        // Previous time is stored before the actual time read
  currentTime = millis();            // Current time actual time read
  elapsedTime = (currentTime - previousTime) / 1000; // Divide by 1000 to get seconds
  Wire.beginTransmission(MPU);
  Wire.write(0x43); // Gyro data first register address 0x43
  Wire.endTransmission(false);
  Wire.requestFrom(MPU, 6, true); // Read 4 registers total, each axis value is stored in 2 registers
  GyroX = (Wire.read() << 8 | Wire.read()) / 131.0; // For a 250deg/s range we have to divide first the raw value by 131.0, according to the datasheet
  GyroY = (Wire.read() << 8 | Wire.read()) / 131.0;
  GyroZ = (Wire.read() << 8 | Wire.read()) / 131.0;
  // Correct the outputs with the calculated error values
  GyroX = GyroX + 0.56; // GyroErrorX ~(-0.56)
  GyroY = GyroY - 2; // GyroErrorY ~(2)
  GyroZ = GyroZ + 0.79; // GyroErrorZ ~ (-0.8)
  // Currently the raw values are in degrees per seconds, deg/s, so we need to multiply by sendonds (s) to get the angle in degrees
  gyroAngleX = gyroAngleX + GyroX * elapsedTime; // deg/s * s = deg
  gyroAngleY = gyroAngleY + GyroY * elapsedTime;
  yaw =  yaw + GyroZ * elapsedTime;
  // Complementary filter - combine acceleromter and gyro angle values
  roll = 0.96 * gyroAngleX + 0.04 * accAngleX;
  pitch = 0.96 * gyroAngleY + 0.04 * accAngleY;

  // Print the values on the serial monitor
  Serial.print(roll);
  Serial.print("/");
  Serial.print(pitch);
  Serial.print("/");
  Serial.println(yaw);
}

void calculate_IMU_error() {
  // We can call this funtion in the setup section to calculate the accelerometer and gyro data error. From here we will get the error values used in the above equations printed on the Serial Monitor.
  // Note that we should place the IMU flat in order to get the proper values, so that we then can the correct values
  // Read accelerometer values 200 times
  while (c < 200) {
    Wire.beginTransmission(MPU);
    Wire.write(0x3B);
    Wire.endTransmission(false);
    Wire.requestFrom(MPU, 6, true);
    AccX = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    AccY = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    AccZ = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    // Sum all readings
    AccErrorX = AccErrorX + ((atan((AccY) / sqrt(pow((AccX), 2) + pow((AccZ), 2))) * 180 / PI));
    AccErrorY = AccErrorY + ((atan(-1 * (AccX) / sqrt(pow((AccY), 2) + pow((AccZ), 2))) * 180 / PI));
    c++;
  }
  //Divide the sum by 200 to get the error value
  AccErrorX = AccErrorX / 200;
  AccErrorY = AccErrorY / 200;
  c = 0;
  // Read gyro values 200 times
  while (c < 200) {
    Wire.beginTransmission(MPU);
    Wire.write(0x43);
    Wire.endTransmission(false);
    Wire.requestFrom(MPU, 6, true);
    GyroX = Wire.read() << 8 | Wire.read();
    GyroY = Wire.read() << 8 | Wire.read();
    GyroZ = Wire.read() << 8 | Wire.read();
    // Sum all readings
    GyroErrorX = GyroErrorX + (GyroX / 131.0);
    GyroErrorY = GyroErrorY + (GyroY / 131.0);
    GyroErrorZ = GyroErrorZ + (GyroZ / 131.0);
    c++;
  }
  //Divide the sum by 200 to get the error value
  GyroErrorX = GyroErrorX / 200;
  GyroErrorY = GyroErrorY / 200;
  GyroErrorZ = GyroErrorZ / 200;
  // Print the error values on the Serial Monitor
  Serial.print("AccErrorX: ");
  Serial.println(AccErrorX);
  Serial.print("AccErrorY: ");
  Serial.println(AccErrorY);
  Serial.print("GyroErrorX: ");
  Serial.println(GyroErrorX);
  Serial.print("GyroErrorY: ");
  Serial.println(GyroErrorY);
  Serial.print("GyroErrorZ: ");
  Serial.println(GyroErrorZ);
}

  Wire.beginTransmission(MPU);
  Wire.write(0x1C);                  //Talk to the ACCEL_CONFIG register (1C hex)
  Wire.write(0x10);                  //Set the register bits as 00010000 (+/- 8g full scale range)
  Wire.endTransmission(true);
  // Configure Gyro Sensitivity - Full Scale Range (default +/- 250deg/s)
  Wire.beginTransmission(MPU);
  Wire.write(0x1B);                   // Talk to the GYRO_CONFIG register (1B hex)
  Wire.write(0x10);                   // Set the register bits as 00010000 (1000deg/s full scale)
  Wire.endTransmission(true);
  */

  Wire.beginTransmission(MPU);
  Wire.write(0x3B); // Start with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU, 6, true); // Read 6 registers total, each axis value is stored in 2 registers
  //For a range of +-2g, we need to divide the raw values by 16384, according to the datasheet
  AccX = (Wire.read() << 8 | Wire.read()) / 16384.0; // X-axis value
  AccY = (Wire.read() << 8 | Wire.read()) / 16384.0; // Y-axis value
  AccZ = (Wire.read() << 8 | Wire.read()) / 16384.0; // Z-axis value

  accAngleX = (atan(AccY / sqrt(pow(AccX, 2) + pow(AccZ, 2))) * 180 / PI) - 0.58; // AccErrorX ~(0.58) See the calculate_IMU_error()custom function for more details
  accAngleY = (atan(-1 * AccX / sqrt(pow(AccY, 2) + pow(AccZ, 2))) * 180 / PI) + 1.58; // AccErrorY ~(-1.58)

  previousTime = currentTime;        // Previous time is stored before the actual time read
  currentTime = millis();            // Current time actual time read
  elapsedTime = (currentTime - previousTime) / 1000; // Divide by 1000 to get seconds
  Wire.beginTransmission(MPU);
  Wire.write(0x43); // Gyro data first register address 0x43
  Wire.endTransmission(false);
  Wire.requestFrom(MPU, 6, true); // Read 4 registers total, each axis value is stored in 2 registers
  GyroX = (Wire.read() << 8 | Wire.read()) / 131.0; // For a 250deg/s range we have to divide first the raw value by 131.0, according to the datasheet
  GyroY = (Wire.read() << 8 | Wire.read()) / 131.0;
  GyroZ = (Wire.read() << 8 | Wire.read()) / 131.0;
  GyroX = GyroX + 0.56; // GyroErrorX ~(-0.56)
  GyroY = GyroY - 2; // GyroErrorY ~(2)
  GyroZ = GyroZ + 0.79; // GyroErrorZ ~ (-0.8)
  // Currently the raw values are in degrees per seconds, deg/s, so we need to multiply by sendonds (s) to get the angle in degrees
  gyroAngleX = gyroAngleX + GyroX * elapsedTime; // deg/s * s = deg
  gyroAngleY = gyroAngleY + GyroY * elapsedTime;
  yaw =  yaw + GyroZ * elapsedTime;

  roll = 0.96 * gyroAngleX + 0.04 * accAngleX;
  pitch = 0.96 * gyroAngleY + 0.04 * accAngleY;

void calculate_IMU_error() {
  // We can call this funtion in the setup section to calculate the accelerometer and gyro data error. From here we will get the error values used in the above equations printed on the Serial Monitor.
  // Note that we should place the IMU flat in order to get the proper values, so that we then can the correct values
  // Read accelerometer values 200 times
  while (c < 200) {
    Wire.beginTransmission(MPU);
    Wire.write(0x3B);
    Wire.endTransmission(false);
    Wire.requestFrom(MPU, 6, true);
    AccX = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    AccY = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    AccZ = (Wire.read() << 8 | Wire.read()) / 16384.0 ;
    // Sum all readings
    AccErrorX = AccErrorX + ((atan((AccY) / sqrt(pow((AccX), 2) + pow((AccZ), 2))) * 180 / PI));
    AccErrorY = AccErrorY + ((atan(-1 * (AccX) / sqrt(pow((AccY), 2) + pow((AccZ), 2))) * 180 / PI));
    c++;
  }
  //Divide the sum by 200 to get the error value
  AccErrorX = AccErrorX / 200;
  AccErrorY = AccErrorY / 200;
  c = 0;
  // Read gyro values 200 times
  while (c < 200) {
    Wire.beginTransmission(MPU);
    Wire.write(0x43);
    Wire.endTransmission(false);
    Wire.requestFrom(MPU, 6, true);
    GyroX = Wire.read() << 8 | Wire.read();
    GyroY = Wire.read() << 8 | Wire.read();
    GyroZ = Wire.read() << 8 | Wire.read();
    // Sum all readings
    GyroErrorX = GyroErrorX + (GyroX / 131.0);
    GyroErrorY = GyroErrorY + (GyroY / 131.0);
    GyroErrorZ = GyroErrorZ + (GyroZ / 131.0);
    c++;
  }
  //Divide the sum by 200 to get the error value
  GyroErrorX = GyroErrorX / 200;
  GyroErrorY = GyroErrorY / 200;
  GyroErrorZ = GyroErrorZ / 200;
  // Print the error values on the Serial Monitor
  Serial.print("AccErrorX: ");
  Serial.println(AccErrorX);
  Serial.print("AccErrorY: ");
  Serial.println(AccErrorY);
  Serial.print("GyroErrorX: ");
  Serial.println(GyroErrorX);
  Serial.print("GyroErrorY: ");
  Serial.println(GyroErrorY);
  Serial.print("GyroErrorZ: ");
  Serial.println(GyroErrorZ);
}
```

We simply print the values on the serial monitor and once we know them, we can implement them in the code as shown earlier, for both the roll and pitch calculation, as well as for the 3 gyroscope outputs.

MPU6050 Pitch Roll and Yaw outputs

Finally, using the Serial.print function we can print the Roll, Pitch and Yaw values on the serial monitor and see whether the sensor works properly.

```c++
#ifdef OUTPUT_READABLE_YAWPITCHROLL
    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

    ypr[0] = ypr[0] * 180 / M_PI;
    ypr[1] = ypr[1] * 180 / M_PI;
    ypr[2] = ypr[2] * 180 / M_PI;

    if (j <= 300) {
      correct = ypr[0];
      j++;
    }
    else {
      ypr[0] = ypr[0] - correct;
      int servo0Value = map(ypr[0], -90, 90, 0, 180);
      int servo1Value = map(ypr[1], -90, 90, 0, 180);
      int servo2Value = map(ypr[2], -90, 90, 180, 0);

      servo0.write(servo0Value);
      servo1.write(servo1Value);
      servo2.write(servo2Value);
    }
#endif

    ypr[0] = ypr[0] * 180 / M_PI;
    ypr[1] = ypr[1] * 180 / M_PI;
    ypr[2] = ypr[2] * 180 / M_PI;

    if (j <= 300) {
      correct = ypr[0];
      j++;
    }
    else {
      ypr[0] = ypr[0] - correct;
      int servo0Value = map(ypr[0], -90, 90, 0, 180);
      int servo1Value = map(ypr[1], -90, 90, 0, 180);
      int servo2Value = map(ypr[2], -90, 90, 180, 0);

      servo0.write(servo0Value);
      servo1.write(servo1Value);
      servo2.write(servo2Value);
    }
```

title: My gimbal program does not compile

Answers: 1

body:
I know this is more of a comment but I can't do that yet.

This is for the code with wire.h at the top of the code.

I loaded your code into my arduino IDE and my line numbers reference those

1. You have lines 22-32 commented out.

2. The // at the end of line 40 may cause you problems.

3. If lines 41-43 the same that you have in
void setup ()
the same then you have the program doing something over and over again, that has already been set up.

4. line 145 you have a lone */ that the compiler should have found.

5. Lines 136 to 178 are not inside {} are not being run.  They also look very similar to what is inside your void loop()

6. Line 180 has the same ````void calculate_IMU_error() { ```` as on line 80, which one is being ran?


body:
I'm having an irritating situation with my Arduino Uno wifi rev2 board.
I made an installation with an LCD, keypad and little servo motor. I first wrote the code for my regular Arduino Uno and everything worked fine. Now I migrated my installation to my new Arduino Uno wifi rev2 because I needed it to make a request. But the problem is when I try to upload my code to the wifi rev2 it gives me a compilation error. I tried to upload a blink test sketch to see if it would work and it did but somehow it doesn't want to compile this code:
```
#include <Wire.h>

#include <LiquidCrystal_I2C.h>
#include <Servo.h>
#include <Keypad.h>

LiquidCrystal_I2C lcd(0x27,16, 2);
Servo myservo;
const byte ROWS = 4;
const byte COLS = 3;

char hexaKeys[ROWS][COLS] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

byte rowPins[ROWS] = {3, 4, 5, 6};
byte colPins[COLS] = {9, 8, 7};

Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
String value = "";

void setup(){
  lcd.begin();
  Serial.begin(9600);
  myservo.attach(A0);
 lcd.backlight();
 //myservo.write(0);

}

void loop(){
    lcd.clear();
    char customKey = customKeypad.getKey();   // get the key pressed
    value = value + String(customKey);
    lcd.print("Geef bestelcode");
     lcd.setCursor(0,1);
    lcd.print("in: " + value);
 // char customKey = customKeypad.getKey();   // get the key pressed
 if(customKey=='#'){
        if(value == "1234#"){
          myservo.write(0);
          }
     // int pos = value.toInt();             // convert value to int
     // myservo.write(pos);                 // rotate the servo
         else{exit;}                   // clear the string
    }

     if(customKey=='*'){                       // 'D' works as "enter"
      myservo.write(90);                   // rotate the servo
      value = "";                           // clear the string
    }

 /*
  if(customKey && customKey!= '#'){         // if the key pressed is not 'D'
      value = value + String(customKey);    // concatenate the number to value
      //Serial.println(value);
  }*/
   delay(175);
}

```

The output of my error console :
```
In file included from C:\Users\TONES-PC\Documents\Arduino\sketch_dec15a_parcelbox_tester\sketch_dec15a_parcelbox_tester.ino:5:0:

C:\Users\TONES-PC\Documents\Arduino\libraries\Keypad/Keypad.h: In member function 'virtual void Keypad::pin_write(byte, boolean)':

C:\Users\TONES-PC\Documents\Arduino\libraries\Keypad/Keypad.h:88:81: error: cannot convert 'boolean {aka bool}' to 'PinStatus' for argument '2' to 'void digitalWrite(pin_size_t, PinStatus)'

  virtual void pin_write(byte pinNum, boolean level) { digitalWrite(pinNum, level); }

                                                                                ^

Several libraries found for "Wire.h"
used: C:\Users\TONES-PC\AppData\Local\Arduino15\packages\arduino\hardware\megaavr\1.8.5\libraries\Wire
Several libraries found for "LiquidCrystal_I2C.h"
used: C:\Users\TONES-PC\Documents\Arduino\libraries\Arduino-LiquidCrystal-I2C-library-master
Several libraries found for "Servo.h"
used: C:\Program
Several libraries found for "Keypad.h"
used: C:\Users\TONES-PC\Documents\Arduino\libraries\Keypad
exit status 1
Error with compiling for board Arduino Uno WiFi Rev2
```

Any thoughts on how to solve this?

title: Arduino uno wifi rev2 error compiling sketch to board

Answers: 0


body:
I am using :
-arduino uno r3
-SIM800L

connection:

Arduino   SIM800L
5v     -->  vcc
gnd    -->  gnd
pin10  --> TX
pin11  --> RX

the led on the module blinks once each 3~5 seconds
but when i use the function sim.available() i got 0;
thus as i guess there is a problem .

the code :

    #include <SoftwareSerial.h>
    SoftwareSerial sim(10, 11);
    int _timeout;
    String _buffer;
    String number = "000000000000"; //-> change with your number
    void setup() {
      delay(7000); //delay for 7 seconds to make sure the modules get the signal
      Serial.begin(9600);
      _buffer.reserve(50);
      Serial.println("Sistem Started...");
      sim.begin(9600);
      delay(1000);
      Serial.println("Type s to send an SMS, r to receive an SMS, and c to make a call");
    }
    void loop() {
      Serial.print(Serial.available());
      if (Serial.available() > 0)
        switch (Serial.read())
        {
          case 's':
            SendMessage();
            break;
          case 'r':
            RecieveMessage();
            break;
          case 'c':
            callNumber();
            break;
        }
      if (sim.available() > 0)
        Serial.write(sim.read());
    }

i looked the internet they say the voltage should be 3.7~4.2 itriedgivving 3.55 and it didn't work

title: SIM800l is not Avalible

Answers: 1

body:
Try to connect your module with the power supply useing wires as short as are is possible. I was fight with this module for few months and now I know that almost all of issue with it are regarding power supply.

For short test you can connect module directly to LiPo 3,7V.

You have to be sure that your power supplay can handle 2A current. The voltage never can drop below 3,4V.

> The power IC and the bypass capacitor should be placed to the module
> as close as possible.

[*SimCom, SIM800_Hardware Design_V1.09, available 27.11.2020*][1]

  [1]: https://simcom.ee/documents/SIM800/SIM800_Hardware Design_V1.09.pdf


body:
In examples of FastLED library, there's the animation of a dot sweeping back and forth, with fading trails (file "DemoReel100", animation "sinelon"). How can I alter the code so instead of moving back, the dot begins at LED #1 again; so when using a LED ring, then the movement is continuous and circular.
Since the code will be part of a more complex project with reading of button states etc, the animation code has to be non-blocking, i.e. `delay()` is not an option.

    void sinelon()
    {
    fadeToBlackBy( leds, NUM_LEDS, 20);
    int pos = beatsin16( 13, 0, NUM_LEDS-1 );
    leds[pos] += CHSV( gHue, 255, 192);
    }

title: Continous running light with fading trail

Answers: 1

body:
If you look at the surrounding methods, you'll see that 'fadeToBlackBy' will give a fading effect on anything you feed in. You'll want to locate method 'beatsin16' and then edit it yourself so that it doesn't bounce back but restarts the counter at the first LED. (hint: phase_offset)

You'll find the code snippet you want to copy in lib8tion.h

    /// beatsin16 generates a 16-bit sine wave at a given BPM,
    ///           that oscillates within a given range.
    LIB8STATIC uint16_t beatsin16( accum88 beats_per_minute, uint16_t lowest = 0, uint16_t highest = 65535,
                                   uint32_t timebase = 0, uint16_t phase_offset = 0)
    {
        uint16_t beat = beat16( beats_per_minute, timebase);
        uint16_t beatsin = (sin16( beat + phase_offset) + 32768);
        uint16_t rangewidth = highest - lowest;
        uint16_t scaledbeat = scale16( beatsin, rangewidth);
        uint16_t result = lowest + scaledbeat;
        return result;
    }


body:
I'm using a [120 W DC power supply][1] connected in parallel with ESC and Arduino nano through Vin. However, somehow the Arduino get fried near the CH340 chip[![enter image description here][2]][2], i.e. around the big black square chip near the micro usb port on the back of the board, kept getting fried. It's working for a while, until it melted.

This didn't quite make sense, since Arduino Vin can take voltage from 6V to 12V. The ESC also had a maximum current consumption of over 30A, equivalent to 360W. Thus there wasn't an obvious reason for which Arduino ought to get fried at all.

Why CH340 chip getting fried after connecting Arduino to a powerful 12V source?

  [1]: https://www.amazon.com/dp/B00Z9X4GLW/
  [2]: https://i.stack.imgur.com/84SYD.jpg

title: CH340 chip getting fried after connecting Arduino to a powerful 12V souce

Answers: 1

body:
It's impossible to say for sure what is going on without proper equipment (mostly you need oscilloscope), but I'm pretty sure that due to very high current consumption of the motors, there are voltage spikes at the input of the voltage regulator. If voltage exceeds safe value (15V for most of them), then regulator fails and all the input voltage is now on the output (that's how they fail 99% if the time, not as an open unfortunately, but as a short). Then for some reasons the weakest IC is CH340G which is fried. Try to use destroyed Arduino without ESC, and see what's on the 5V pin.
You say that you have currents up to 30A, but PSU is rated for 120W which means it can deliver only 10A at 12V. So at some point PSU falls into protection mode, switches off the output, and after some time tries to switch it on again. Situation with voltage spikes can be very nasty during this period.
Also please post your schematic and photo of the actual wiring, this can also give us some clues.