body:
As I am learning the Arduino coding, I want to see if my program can turn on the LED light. I have tried all the things, but the code does not start the LED light I have installed on the board.

The code compiles successfully and upload on the board, but nothings happens after that. See the output logs as below:

**See all the configuration of board as below:**

**The board I have:**
UNO+WiFi R3 ATmega328P+ESP8266 CH340G Board compatible with Arduino

https://robocraze.com/uno-wifi-r3-atmega328p-esp8266-ch340g-board-compatible-with-arduino

**Board switch settings:**

5,6,7 => ON (to upload the code from Arduino IDE)

**Yellow LED installed:**

13 => Positive, GND => Negative

**Board setup:**

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

**Arduino IDE Setup:**

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

  [1]: https://i.stack.imgur.com/e6Oep.jpg
  [2]: https://i.stack.imgur.com/om58Q.png

**Program:**

    void setup()
    {
      pinMode(13, OUTPUT);
    }

    void loop()
    {
      digitalWrite(13, HIGH);
      delay(2000);
      digitalWrite(13, LOW);
      delay(2000);
    }

**Output logs after uploading the code:**

    esptool.py v2.8
    Serial port COM8
    Connecting....
    Chip is ESP8266EX
    Features: WiFi
    Crystal is 26MHz
    MAC: ec:fa:bc:3e:2e:6f
    Uploading stub...
    Running stub...
    Stub running...
    Configuring flash size...
    Auto-detected Flash size: 4MB
    Flash params set to 0x0340
    Compressed 261472 bytes to 193134...
    Wrote 261472 bytes (193134 compressed) at 0x00000000 in 17.1 seconds (effective 122.1 kbit/s)...
    Hash of data verified.

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

As you can see, the last message is **Hard resetting via RTS pin....**

Would anyone please tell me what is happening here? Why the program does not start the LED light even after everything looks fine?

Any help would be greatly appreciated.

Thanks.

title: LED does not blink - Arduino UNO+WiFi R3 ATmega328P+ESP8266 board

Answers: 1

body:
The [Uno+WiFi board][1] is an Uno. With DIP switches 3 and 4 in ON position it is a normal Arduino Uno clone with CH340 chip for USB. All the pin headers at board sides and the ICSP pins are as on an Arduino Uno. Every sketch for Uno will work.

The esp8266 is added for WiFi functionality. The DIP switches allow to program the esp8266 over the CH340 or to connect the esp8226 to Serial of the Uno part (ATmega328p).

To have Serial free for USB, it is usual to wire the esp8266 to a common Uno on some other pair of pins then RX/TX and use SoftwareSerial. There is no such connection on this Uno+WiFi, but the esp8266 header has the Rx/RX pins of the esp8266 so it is possible to wire SoftwareSerial pins with jumper wires (power and ground are connected on board of course).

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

Don't switch the DIP switches too frequently. They are not made for it and fall apart. Upload some permanent firmware to esp8266 or use OTA upload for esp8266.

  [1]: https://robotdyn.com/uno-wifi-r3-atmega328p-esp8266-32mb-flash-usb-ttl-ch340g-micro-usb.html
  [2]: https://i.stack.imgur.com/DpNEK.png


body:
The Arduino ATmega328 NANO uses COM3 on my WINDOWS 10 computer,
but COM3 is NOT available.

QUESTION:
Please explain in detail how I can change this Arduino NANO
to operate on COM4

title: How to change Windows 10 Device Manager so Arduino NANO COM3 can operate on COM4

Answers: 2

body: In device manager, right click on the device and select "Properties". Then go to the tab "Connection properties" and click on "Advanced". There you can change the COM port number assignment for a particular device.

body: In general, Windows assigns COM ports to USB devices when they are plugged in the first time.  If you have multiple USB sockets, the same physical device will be assigned a different COM port when plugged into different sockets.  Is it possible that you have changed your setup and are now using a different USB socket?  Try the others to see if that works.


body:
I'm trying to add a new item "index" to GUI-elements that are created by using ArduinoJSON and the Vue.js-framework inside the ESP-Dash-library.

The library creates GUI-elements like buttons, sliders etc. and provides easy to program call-back-procdures to make the microcontroller interact with the user-input from the website.

The code as it is iterates through all defined GUI-elements and creates the HTML-code. First all temperture-showing elements then all humidity elements, then all sliders etc...

This means the sequence and the position of the GUI-elements can't be defined by the programmer.

The new functionality I want to achieve is that the programmer can define the sequence and position of all GUI-elements on the website.

This means a new item like "index" must be added and the HTML-creation-code must be changed to another kind of iteration through the GUI-elements.

Now I'm very lost on where to look into all the Arduino- or the javascript-code  to find that place where the iteration must be changed.

Here is the link to the GiPo https://github.com/ayushsharma82/ESP-DASH

and especially to the app.vue javascript https://github.com/ayushsharma82/ESP-DASH/blob/master/vue-frontend/src/App.vue

If this kind of question is inapropriate please drop a few words what is wrong.
And then add a link to "how to post good questions"

best regards Stefan

title: Changing the order of GUI-elements inside Arduino ESP-Dash-library

Answers: 0


body:
I wanted the sensor to be high when I press the button, but when DigitalRead does low, the LED turns on, when it does high, the LED goes off.
Whereas when the digitalRead is high, isn't it supposed to turn on the led?

    int pirPin = 8;
    int ledPin = 13;
    int state;
    unsigned long previousMillis = 0;        // will store last time LED was updated
    const long interval = 1000;

    void setup() {
      pinMode(pirPin, INPUT);
      pinMode(ledPin, OUTPUT);

    }

    void loop() {

      unsigned long currentMillis = millis();
      state = digitalRead(pirPin);
      Serial.println(durum);

      if (state == HIGH) {
        previousMillis = currentMillis;
         }
        if (currentMillis - previousMillis >= interval) {
          digitalWrite(ledPin, LOW);
        }
        else
          digitalWrite(ledPin, HIGH);
      }

title: Why does the LED state behave differently?

Answers: 0


body:
I have a MariaDb database on a local server and I am using it to store data from various Arduino's around my shop. The database currently has 12 tables. I also have another Arduino Uno Wifi Rev2 that is able to connect to its two respective tables; it collects setpoint information from one table and inserts data perfectly into the other.

The Arduino I'm having a problem with can insert data perfectly fine into its data table (veg2_data) but fails when trying to select data from it's sp table (veg2_sp). It can also connect to any of the other tables in my database, including the one for the first arduino. Only veg2_sp is malfunctioning

Here is my code:
```
#include <SPI.h>
#include <WiFiNINA.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>
#include "config.h"
//Node Libraries
#include <DHT.h>

#define O_UPPER 9
#define O_LOWER 10

//Wifi
byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //Do I need this?
char ssid[] = CONFIG_SSID;
char pass[] = CONFIG_PASS;
int status = WL_IDLE_STATUS;
int keyIndex = 0;
WiFiClient client;

//MySQL
IPAddress server_addr(192, 168, 1, 133);
char user[] = CONFIG_MYSQL_USER;
char password[] = CONFIG_MYSQL_PASS;
char db[] = CONFIG_MYSQL_DB;
char query[128];
char DATA_QUERY[] = "INSERT INTO veg2_data VALUES (now(), %d, %d, %s, %s, %s, %s, %s, %s, %d);";
char SP_QUERY[] = "SELECT * FROM veg2_sp ORDER BY timestamp DESC LIMIT 1;";
char rawTime[30];
byte refreshRate = 1;
uint32_t dbContactTimer;
MySQL_Connection conn((Client *)&client);
MySQL_Cursor cur = MySQL_Cursor(&conn);

//Node Specific
bool o_UpperState, o_LowerState, daytime = 0;
byte dayTempSP = 25, dayHumiditySP = 30, nightTempSP = 10, nightHumiditySP = 20,
     o_UpperLock = 0, o_LowerLock = 0, sunrise = 7, sunset = 19;
int soilMoisture;
float intakeTemp, intakeHum, roomTemp, roomHum, exhaustTemp, exhaustHum ;
char intakeTempArray[7], intakeHumArray[7], roomTempArray[7], roomHumArray[7],
     exhaustTempArray[7], exhaustHumArray[7];

DHT exhaust(6, DHT11);
DHT intake(7, DHT11);
DHT room(8, DHT11);

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

  exhaust.begin();
  intake.begin();
  room.begin();

  pinMode(O_UPPER, OUTPUT);
  pinMode(O_LOWER, OUTPUT);
  digitalWrite(O_UPPER, LOW);
  digitalWrite(O_LOWER, LOW);

  //spCheck();
  dbContactTimer = millis();
}

void loop() {

  //Default refesh rate is 5 seconds. Some nodes need to increase refesh rate at specific times
  if (millis() - dbContactTimer >= (refreshRate * 1000)) {
    dbUpdate();
    spCheck();

    //If set to auto (2), my lights will turn on and off depending on day/night. Currently unfinished
    if (o_UpperLock == 2) {
      if (daytime) {
        digitalWrite(O_UPPER, HIGH);
        o_UpperState = 1;
      }
      else {
        digitalWrite(O_UPPER, LOW);
        o_UpperState = 0;
      }
    }
    dbContactTimer = millis();
  }

}

//------------------------------------MySql Functions-------------------------
void spCheck() { //Updates setpoints
  if (!conn.connected()) {
    conn.close();
    if (!conn.connect(server_addr, port, user, password, db)) {
      return 0;
    }
  }
  row_values *row = NULL;
  cur.execute(SP_QUERY);
  column_names *columns = cur.get_columns();
  do {
    row = cur.get_next_row();
    if (row != NULL) {
      //Serial.println(row->values[0]);
      o_UpperLock = atol(row->values[1]);
      //o_LowerLock = atol(row->values[2]);
      //dayTempSP = atol(row->values[3]);
      //dayHumiditySP = atol(row->values[4]);
      //nightTempSP = atol(row->values[5]);
      //nightHumiditySP = atol(row->values[6]);
      //sunrise = atol(row->values[7]);
      //sunset = atol(row->values[8]);
    }
  } while (row != NULL);

  if (o_UpperLock < 2) {
    if (o_UpperLock) {
      digitalWrite(O_UPPER, HIGH);
      o_UpperState = 1;
    }
    else {
      digitalWrite(O_UPPER, LOW);
      o_UpperState = 0;
    }
  }
  return 1;
}

void dbUpdate() { //Updates data
  if (!conn.connected()) {
    conn.close();
    if (!conn.connect(server_addr, port, user, password, db)) {
      return 0;
    }
  }

  intakeTemp = intake.readTemperature();
  dtostrf(intakeTemp, 4, 2, intakeTempArray);

  intakeHum  = intake.readHumidity();
  dtostrf(intakeHum, 4, 2, intakeHumArray);

  roomTemp = room.readTemperature();
  dtostrf(roomTemp, 4, 2, roomTempArray);

  roomHum = room.readHumidity();
  dtostrf(roomHum, 4, 2, roomHumArray);

  exhaustTemp = exhaust.readTemperature();
  dtostrf(exhaustTemp, 4, 2, exhaustTempArray);

  exhaustHum = exhaust.readHumidity();
  dtostrf(exhaustHum, 4, 2, exhaustHumArray);

  soilMoisture = analogRead(A0);

  sprintf(query, DATA_QUERY, o_UpperState, o_LowerState, intakeTempArray,
          intakeHumArray, roomTempArray, roomHumArray, exhaustTempArray, exhaustHumArray, soilMoisture);
  cur.execute(query);

  return 1;
}

void wifiInit() {

  String fv = WiFi.firmwareVersion();
  if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
    Serial.println("Please upgrade the firmware");
  }
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("No wifi Module - Abort");
    while (true);
  }
  while (status != WL_CONNECTED) {
    Serial.println("Connecting to wifi");
    for (byte i = 0; i < 2; i++) {
      digitalWrite(LED_BUILTIN, HIGH);
      delay(2000);
      digitalWrite(LED_BUILTIN, LOW);
      delay(1000);
    }
    status = WiFi.begin(ssid, pass);
  }

  IPAddress ip = WiFi.localIP();
  long rssi = WiFi.RSSI();
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());
  Serial.print("IP Address: ");
  Serial.println(ip);
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}
```

The problem is with the SP_QUERY. I can change the table to any other in my database, and the code functions fine. If I read from veg2_sp, I get the error.

Tables: The first one is the one im having problems with, the second is the one that is currently functioning.
[![Tables:][1]][1]

I'm utterly baffled.

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

title: Receiving "ERROR: Timeout waiting for client." when connecting to a single table in database - mysql connector on Arduino Uno Wifi Rev2

Answers: 0


body:
I recently found this model with the ID 'HW-0519' on it. It can be found online ([HW-0519 in Aliexpress][1]) and is sold for the purpose of converting UART to RS485 communication using Arduino devices. The MAX485 module ([MAX485 in Banggood][2]) is the more commonly used module for this purpose and has been used in many projects. The MAX485 has the following pins DI (data in), RO (receiver out), DE (Data Enable), RE (Receiver Enable), VCC, GND and the 'A' and 'B' pins for the RS485 device (Shown below).

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

The HW-0519 module, has a slightly different pin configuration, and I can't seem to wrap my head around it. It has Tx and Rx pins, which I am guessing match up with RO and DI respectively, but don't have enable pins. They have the VCC and GND pins along with the 'A' and 'B' pins, but also come with this pin marked in Chinese. I translated it using Google translate and it translates to something similar to 'Ground'. Which is not connected to the GND pin though (Shown below).

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

Does anyone know whether I can use the HW-0519 module in the same manner as the MAX485? If so, are there any libraries written for this module? I want to use the module for communication with a pH sensor like the one in [this link][5].

  [1]: https://www.aliexpress.com/item/32817749136.html
  [2]: https://sea.banggood.com/2Pcs-5V-MAX485-TTL-To-RS485-Converter-Module-Board-p-948302.html
  [3]: https://i.stack.imgur.com/MprWM.jpg
  [4]: https://i.stack.imgur.com/wUGOT.jpg
  [5]: https://www.seeedstudio.com/RS485-Soil-Moisture-Temperature-EC-Sensor-S-Soil-MTEC-02-p-4633.html

title: When it comes to UART to RS485 communication, what is the difference between the 'MAX485' and the 'HW-0519' module?

Answers: 2

body:
I did a bit of research and found others who use this particular component for their RS485 communication purposes. It is difficult to get clear info because the device goes by different names and the most commonly used name is MAX485 (name of the IC), which is used interchangeably for both the components shown in the question.

It seems the more I search for the 'HW-0519', the more names I find for it. So far, it goes by the name 'MAX485', 'XY-017', and 'XY-K485'. A clear advantage for this 'HW-0519' is that it does not require D or R enabling, just straightforward Tx and Rx. It also has LEDs to show the data transfers. I found a project that used this module [here][1]. I am unsure about their pin connections from the ESP-32 though. It looks like they've connected the ESP-32's TX2 to the HW-0519's Tx, and the RX2 to the Rx. I thought it should be the other way around.

  [1]: http://pdacontrolen.com/basic-modbus-rtu-master-rs485-test-with-esp32-xy-k485-pzem-016-without-libraries/

body:
I have the HW-0519 (bought as https://www.amazon.co.uk/gp/product/B0BCFLTLGJ/ at £9.98 for 8x in 2023-09) and it matches the picture above quite closely enough. It is a variant, and the first difference I see is the (?) polyfuses JK075 above are T010 on mine.

I picked this because it has protection components on the board which others don't have - including the MAX485 board from Banggood linked above.

Both boards lack mounting holes but the MAX485 board has pins which (if they align?) might assist breadboard usage. For me, the prototyping phase will start with epoxying HW-0519 to a Lego brick.

I found a circuit diagram at https://easyeda.com/modules/HW-0519-TTL-to-RS485-converter_c4836920e8ec45b3924add8ac2acbe57 for something similar which helped me work out what's what. I'm not going to steal a copy and upload here but it looks like https://web.archive.org/web/*/https://image.easyeda.com/components/c4836920e8ec45b3924add8ac2acbe57.png .
* Starting at the A+ / B- lines,
* fuses F1 and F2 of type "108L" (presumably polyfuse type),
* 120Ω bus termination R14 across,
* then an SM712 asymmetric TVS protection chip https://www.semtech.com/products/circuit-protection/rs485/sm712 ,
* finally the pull-up resistors 4k6 and MAX348 chip named U6.

My board is a cousin of the circuit diagram I found.
* chips are named U2 (unmarked SOIC14, maybe 74HC04) and anon unmarked SOIC8,
* its TVS protection is done as three chunky 2-pin diodes marked WK as in the HW-0519 above,
* bus termination resistor is R9 and **you have to short R0 to terminate the bus**, so one at each end but not in the middle, in the usual way.
* TVS protection comes to that third bus pin 球大(??) which I think is "earth big (something)"

Note that the bus ground is *not* connected to the logic ground GND on the 4-pin connector. You need to **provide bus ground separately** and maybe from a different source after considering fault currents.


body:
this is my first post, im not an expert but I managed to build an Arduino Mega with an ESP8266 to water my plants inside a tent, unfortunately its freezes/crashes randomly and I have to go and reset it manually all the time. I read that this is because im using string and I should use C string type.

Could you please help me out to find a way to stop reseting manually all the time?
Thanks!

Here is the code:

```cpp
#include <DHT.h>
#include <DS3231.h>
#define DHTPIN 51 // before it was 53
#define DHTTYPE DHT11
#include <ESP8266_Lib.h>
#define EspSerial Serial1

#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);

const int AirValue = 820;   // 778
const int WaterValue = 437;  //
int soilmoisturepercentA0=0;
int soilmoisturepercentA1=0;
int soilmoisturepercentA2=0;
int soilmoisturepercentA3=0;

String agAdi = "XXXXXX";
String agSifresi = "XXXXX";
String ip = "184.106.153.149";
float sicaklik, nem;

int led = 38;
int UV_Light = 27;
int Tent_Humid = 29;
int Heater = 26;
//int Free_IN3 = 28;
const int button1 = 53;
int buttonState1 = 0;

DHT dht = DHT(DHTPIN, DHTTYPE);
DS3231  rtc(SDA, SCL);
Time t; // Main time to display

//Schedule R2 UV_Light
const int OnHour_R2 = 6;
const int OnMin_R2 = 00;
const int OffHour_R2 = 1;
const int OffMin_R2 = 00;

int IN1 = 22;
int IN2 = 23;
int IN3 = 24;
int IN4 = 25;

int Pin1 = A0;
int Pin2 = A1;
int Pin3 = A2;
int Pin4 = A3;

float value1 = 0;
float value2 = 0;
float value3 = 0;
float value4 = 0;

void setup() {
  Serial.begin(9600);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);

  pinMode(Pin1, INPUT);
  pinMode(Pin2, INPUT);
  pinMode(Pin3, INPUT);
  pinMode(Pin4, INPUT);

  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, HIGH);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, HIGH);

  pinMode(led, OUTPUT);
  pinMode(UV_Light, OUTPUT);
  pinMode(Tent_Humid, OUTPUT);
  pinMode(Heater, OUTPUT);
  pinMode(button1, INPUT_PULLUP);

  digitalWrite(UV_Light, HIGH);
  digitalWrite(Tent_Humid, HIGH);
  digitalWrite(Heater, HIGH);

  dht.begin();
  rtc.begin();

  delay(500);

  Serial.println("Started");
  EspSerial.begin(9600);                                          // We are starting serial communication with ESP8266.
  EspSerial.println("AT");                                         // We do the module control with the AT command.
  Serial.println("AT  sent ");
  while(!EspSerial.find("OK")){                                     // We wait until the module is ready.
    EspSerial.println("AT");
    Serial.println("ESP8266 Not Found.");
  }
  Serial.println("OK Command Received");
  EspSerial.println("AT+CWMODE=1");                                 // We set the ESP8266 module as a client.
  while(!EspSerial.find("OK")){                                     // We wait until the setting is done.
    EspSerial.println("AT+CWMODE=1");
    Serial.println("Setting is ....");
  }
  Serial.println("Set as client");
  Serial.println("Connecting to the Network ...");
  EspSerial.println("AT+CWJAP=\""+agAdi+"\",\""+agSifresi+"\"");    // We are connecting to our network.
  while(!EspSerial.find("OK"));                                     // We wait until it is connected to the network.
  Serial.println("CONNECTED to the Network ");
  delay(500);
//OLED
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);  // initialize with the I2C addr 0x3D (for the 128x64)
  display.display(); // show splashscreen
  delay(500);
  display.clearDisplay();   // clears the screen and buffer

}
void loop() {

//  DHT11.read(dht11Pin);
  dht.read(DHTPIN);
  sicaklik = (float)dht.readTemperature();
  nem = (float)dht.readHumidity();
//  value1 = analogRead(Pin1);
  soilmoisturepercentA0 = map(value1, AirValue, WaterValue, 0, 100);
  soilmoisturepercentA1 = map(value2, AirValue, WaterValue, 0, 100);
  soilmoisturepercentA2 = map(value3, AirValue, WaterValue, 0, 100);
  soilmoisturepercentA3 = map(value4, AirValue, WaterValue, 0, 100);
  String veri = "GET https://api.thingspeak.com/update?api_key=123456";   // Thingspeak command. We write our own api key in the key part.
  veri += "&field1=";
  veri += String(sicaklik);// The temperature variable we will send
  veri += "&field2=";
  veri += String(nem);// The moisture variable we will send
  veri += "&field3=";
  veri += String(soilmoisturepercentA0);// Soil A0
  veri += "&field4=";
  veri += String(soilmoisturepercentA1);// Soil A1
  veri += "&field5=";
  veri += String(soilmoisturepercentA2);// Soil A2
  veri += "&field6=";
  veri += String(soilmoisturepercentA3);// Soil A3
  veri += "\r\n\r\n";
  EspSerial.print("AT+CIPSEND=");                                   // We give the length of data that we will send to ESP.
  EspSerial.println(veri.length()+3);
//  delay(500);

  if(EspSerial.find(">")){                                          // The commands in it are running when ESP8266 is ready..
    EspSerial.print(veri);                                          // We send the data.
    Serial.println(veri);
    Serial.println("Data sent.");
    delay(500);
  }
  Serial.println("Connection Closed.");
  EspSerial.println("AT+CIPCLOSE");                                // we close the link
  delay(500);

  Serial. print('\n');
  Serial.print("MOISTURE LEVEL A0:");
  value1 = analogRead(Pin1);
  Serial.println(value1);
  Serial.println(soilmoisturepercentA0);
    if(value1>750)
  //if(soilmoisturepercentA0>35)

  {
      digitalWrite(IN1, LOW);
  }
  else
  {
    digitalWrite(IN1, HIGH);
    }

  Serial.print("MOISTURE LEVEL A1:");
  value2 = analogRead(Pin2);
  Serial.println(value2);
  Serial.println(soilmoisturepercentA1);
  if(value2>750)
 //  if(soilmoisturepercentA1>35)
  {
      digitalWrite(IN2, LOW);
  }
  else
  {
    digitalWrite(IN2, HIGH);
    }

  Serial.print("MOISTURE LEVEL A2:");
  value3 = analogRead(Pin3);
  Serial.println(value3);
  Serial.println(soilmoisturepercentA2);
  if(value3>750)
  //  if(soilmoisturepercentA2>35)
  {
      digitalWrite(IN3, LOW);
  }
  else
  {
    digitalWrite(IN3, HIGH);
    }

  Serial.print("MOISTURE LEVEL A3:");
  value4 = analogRead(Pin4);
  Serial.println(value4);
  Serial.println(soilmoisturepercentA3);
  if(value4>750)
   // if(soilmoisturepercentA3>35)
  {
      digitalWrite(IN4, LOW);
  }
  else
  {
    digitalWrite(IN4, HIGH);
    }
    Serial.println();
  delay(500);

{
    t = rtc.getTime();
  Serial.print(t.hour);
  Serial.print(" hour(s), ");
  Serial.print(t.min);
  Serial.print(" minute(s)");
  Serial.println(" ");
  delay (500);

  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(500);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(500);
  }
    // Relay UV_Light
  if (t.hour == OnHour_R2 && t.min == OnMin_R2) {
    digitalWrite(UV_Light, LOW);
  }
  else if (t.hour == OffHour_R2 && t.min == OffMin_R2) {
    digitalWrite(UV_Light, HIGH);
  }
   buttonState1 = digitalRead(button1);
   if (buttonState1 == LOW) {
    digitalWrite(UV_Light, LOW);
    delay (100);
  }
  // Read the Humidity in %:
  float h = dht.readHumidity();
  // Read the Temperature as Celsius:
  float t = dht.readTemperature();
  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
   // Display Humidizador
if (h <40)
  {
  digitalWrite(Tent_Humid, LOW);
  Serial.print("Humid ON");
  Serial. print('\n');
  } else{
    digitalWrite(Tent_Humid, HIGH);

    Serial.print("Humid OFF");
    Serial. print('\n');
}

// Display Heater
if (t <18)
  {
  digitalWrite(Heater, LOW);
  Serial.print("Heater ON");
  Serial. print('\n');
  } else{
    digitalWrite(Heater, HIGH);

    Serial.print("Heater OFF");
    Serial. print('\n');
}
    delay (100);
    float hic = dht.computeHeatIndex(t, h, false);
  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" % ");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" \xC2\xB0");
  Serial.print("C ");
//  Serial.print("Heat index: ");

   EspSerial.println("AT+CIPSTART=\"TCP\",\""+ip+"\",80");           // We connect to Thingspeak.
  if(EspSerial.find("Error")){                                      // We check the connection error.
    Serial.println("AT+CIPSTART Error");
  }

// OLED
{
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

  // Check if any reads failed.
  if (isnan(h) || isnan(t) || isnan(f)) {
    delay(500);
  } else{
    // routine for converting temp/hum floats to char arrays
    char temp_buff[5]; char hum_buff[5];
    char temp_disp_buff[11] = "Tmp:";
    char hum_disp_buff[11] = "Hum:";

    // appending temp/hum to buffers
    dtostrf(t,2,1,temp_buff);
    strcat(temp_disp_buff,temp_buff);
    dtostrf(h,2,1,hum_buff);
    strcat(hum_disp_buff,hum_buff);

    // routine for displaying text for temp/hum readout
    display.clearDisplay();
    display.setTextSize(2);
    display.setTextColor(WHITE);
    display.setCursor(0,0);
    display.println(temp_disp_buff);
    display.println(hum_disp_buff);
    display.display();
    delay(500);
{
   digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(500);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(500);

  }
  }
}
}
```

title: Arduino freezes , how can I convert Arduino String to C string type?

Answers: 0


body:
I have two files

blink1.cpp
```
typedef unsigned char int8_t;
typedef volatile int8_t * volatile port_type;

port_type portB = (port_type) 0x25;
port_type ddrB = (port_type) 0x24;

void delay_500ms()
{
    asm (
    // 8000000 cycles
    "ldi  r19, 150 \n\t"
    "ldi  r20, 128 \n\t"
    "ldi  r23, 41 \n\t"
    "L1: \n\t"
    "dec  r20 \n\t"
    "brne L1 \n\t"
    "dec  r19 \n\t"
    "brne L1 \n\t"
    "dec  r23 \n\t"
    "brne L1 \n\t"
    );
}

int main()
{
    ddrB = (port_type) 0x20;

    while(true)
    {
        *portB = (int8_t) 0x20;
        delay_500ms();
        *portB = (int8_t) 0x00;
        delay_500ms();
    }
}

```

[![Blink1][1]][1]

blink2.cpp
```
typedef unsigned char int8_t;
typedef volatile int8_t * volatile port_type;

port_type portB = (port_type) 0x25;
port_type ddrB = (port_type) 0x24;
port_type portC = (port_type) 0x28;
port_type ddrC = (port_type) 0x27;
port_type portD = (port_type) 0x2B;
port_type ddrD = (port_type) 0x2A;

void delay_500ms()
{
    asm (
    // 8000000 cycles
    "ldi  r19, 150 \n\t"
    "ldi  r20, 128 \n\t"
    "ldi  r23, 41 \n\t"
    "L1: \n\t"
    "dec  r20 \n\t"
    "brne L1 \n\t"
    "dec  r19 \n\t"
    "brne L1 \n\t"
    "dec  r23 \n\t"
    "brne L1 \n\t"
    );
}

int main()
{
    ddrB = (port_type) 0x20;

    while(true)
    {
        *portB = (int8_t) 0x20;
        delay_500ms();
        *portB = (int8_t) 0x00;
        delay_500ms();
    }
}

```

[![Blink2][2]][2]

------

The difference between these two files are the definition of only a few unused ports in blink2.

I compile and upload them to the board by

```
avr-g++ blink1.cpp -o blink1
avr-objcopy -O ihex -R .eeprom blink1 blink1.hex
avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyUSB0 -b 115200 -U flash:w:blink1.hex

avr-g++ blink2.cpp -o blink2
avr-objcopy -O ihex -R .eeprom blink2 blink2.hex
avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyUSB0 -b 115200 -U flash:w:blink2.hex
```

The first one does not blink properly but the second one does. What is the problem of the first code?

  [1]: https://i.stack.imgur.com/3zQOj.gif
  [2]: https://i.stack.imgur.com/Jkb5t.gif

title: Why my arduino board does not blink properly?

Answers: 1

body:
There are a couple of issues here.

One of them has already been raised in a comment:

```diff

 int main()
 {
-    ddrB = (port_type) 0x20;
+    *ddrB = (int8_t) 0x20;

     while(true)
     {
```

The more serious issue is in the command line you used to compile the
program. When compiling for an Uno, you should add the option
`-mmcu=atmega328p`. This way the compiler knows which version of the C
runtime it should add to your program. Otherwise the compiler will
include no runtime at all.

The C runtime does some important initializations. For example, it
clears the register `r1`, which is _required_ by the ABI, and _assumed_
to be the case by the compiler. For example, when you write `*portB =
(int8_t) 0x00;`, the compiler copies `r1` to the port, without first
clearing it. Another important role of the C runtime is to call
`main()`. Without it, the program will start by executing whichever
function happens to be at the start of the flash. Unless you program in
assembly, you have no control over that. If the first function happens
to be `main()`, the program may work as expected. If it is another
function, that function may then return to the bootloader. Any seemingly
innocuous change in the program can then change the behavior.

Then a few minor issues, that should not prevent the program from
working:

* `int8_t` is meant to be a signed type. If you want the unsigned
  version, use `uint8_t` instead. Sure, these are your own type
  definitions, but creating a type that conflicts with a standard type
  can only create confusion. Best option is to drop the definition and
  include `<stdint.h>` instead.

* Whereas `port_type` should certainly be a “pointer to volatile” data,
  there is no point in making the pointer itself volatile. That can only
  hinder valid optimizations.

* `portB` and `ddrB` should be `const`, and that may allow the compiler
  to better optimize them. But why not use `PORTB` and `DDRB` from
  `<avr/io.h>`?


body:
ESP32 with RTOS, test app with 2 independent tasks. Each prints a message to OLED display.
Why text gets frequently scrambled? Mutex have been used to share display resource.

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

    #define DEBUG_ESP              //comment out to deactivate debug console verbose
    #ifdef DEBUG_ESP
      #define pDBGln(x) Serial.println(x)
      #define pDBG(x)   Serial.print(x)
    #else
      #define pDBG(...)
      #define pDBGln(...)
    #endif

    //create handle for the mutex. It will be used to reference mutex
    SemaphoreHandle_t  xMutex;

    //*********************************SSD1306 OLED Display
    #define I2C_SDA              14
    #define I2C_SCL              15
    #include <Wire.h>
    #include <Adafruit_SSD1306.h>
    #define SCREEN_WIDTH 128 // OLED display width, in pixels
    #define SCREEN_HEIGHT 64 // OLED display height, in pixels
    #define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
    Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
    //*****************************************************

    void setup() {

      // create mutex and assign it a already create handler
      xMutex = xSemaphoreCreateMutex();

      Wire.begin(I2C_SDA,I2C_SCL);
      Serial.begin(115200);

       // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
      if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
        pDBGln("SSD1306 allocation failed - Halt");
        for(;;); // Don't proceed, loop forever
      }else{
        // Show initial display buffer contents on the screen --
        // the library initializes this with an Adafruit splash screen.
        display.setTextSize(1);
        display.setTextColor(SSD1306_WHITE);
        display.setCursor(0, 0);
        display.clearDisplay();
      }

        xTaskCreatePinnedToCore(
            task01,             /* Function to implement the task */
            "task01",           /* Name of the task */
            10000,              /* Stack size in words */
            NULL,               /* Task input parameter */
            1,                  /* Priority of the task */
            NULL,               /* Task handle. */
            0);                 /* Core where the task should run */

        xTaskCreatePinnedToCore(
            task02,             /* Function to implement the task */
            "task02",           /* Name of the task */
            10000,              /* Stack size in words */
            NULL,               /* Task input parameter */
            1,                  /* Priority of the task */
            NULL,               /* Task handle. */
            1);                 /* Core where the task should run */
    }

    void loop() {}

    void task01( void * parameter ){
      while(1){
        printToDisplay("Task01..............");
        vTaskDelay(1500);
      }
    }

    void task02( void * parameter ){
      while(1){
        printToDisplay("Task02..............");
        vTaskDelay(2500);
      }
    }

    void printToDisplay(String text){
      bool myMutex;
      while(1){
        // take mutex
        myMutex = xSemaphoreTake(xMutex, portMAX_DELAY);
        if(myMutex){
          static byte   lineCounter = 0;
          static String displayText[8];
          if(lineCounter>7){
            for(int i=0;i<7;i++){
              displayText[i] = displayText[i+1];
            }
            displayText[7] = text;
            display.clearDisplay();
            display.setCursor(0, 0);
            for(int i=0;i<8;i++){
              display.println(displayText[i]);
            }
          }else{
            displayText[lineCounter] = text;
            display.println(displayText[lineCounter]);
            if(lineCounter<8){lineCounter++;}
          }
          display.display();

          // release mutex
          xSemaphoreGive(xMutex);
          break;
        }
      }
    }

The code below uses no RTOS and works perfectly: (my project requires RTOS)

    #define DEBUG_ESP              //comment out to deactivate debug console verbose
    #ifdef DEBUG_ESP
      #define pDBGln(x) Serial.println(x)
      #define pDBG(x)   Serial.print(x)
    #else
      #define pDBG(...)
      #define pDBGln(...)
    #endif

    byte lineCounter = 0;

    //*********************************SSD1306 OLED Display
    #define I2C_SDA              14
    #define I2C_SCL              15
    #include <Wire.h>
    #include <Adafruit_SSD1306.h>
    #define SCREEN_WIDTH 128 // OLED display width, in pixels
    #define SCREEN_HEIGHT 64 // OLED display height, in pixels
    #define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
    Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
    //*****************************************************

    void setup() {

      Wire.begin(I2C_SDA,I2C_SCL);
      Serial.begin(115200);

       // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
      if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
        pDBGln("SSD1306 allocation failed - Halt");
        for(;;); // Don't proceed, loop forever
      }else{
        // Show initial display buffer contents on the screen --
        // the library initializes this with an Adafruit splash screen.
        display.setTextSize(1);
        display.setTextColor(SSD1306_WHITE);
        display.setCursor(0, 0);
        display.clearDisplay();
      }
    }

    void loop() {
      pDBGln("Start Display Test...");
      task01();
      task02();
    }

    void task01(){
      printToDisplay("Task01..............");
      delay(500);
    }

    void task02(){
      printToDisplay("Task02..............");
      delay(500);
    }

    void printToDisplay(String text){
      static byte   lineCounter = 0;
      static String displayText[8];
      if(lineCounter>7){
        for(int i=0;i<7;i++){
          displayText[i] = displayText[i+1];
        }
        displayText[7] = text;
        display.clearDisplay();
        display.setCursor(0, 0);
        for(int i=0;i<8;i++){
          display.println(displayText[i]);
        }
      }else{
        displayText[lineCounter] = text;
        display.println(displayText[lineCounter]);
        if(lineCounter<8){lineCounter++;}
      }
      display.display();
    }

  [1]: https://i.stack.imgur.com/JD6cJ.jpg
  [2]: https://i.stack.imgur.com/Ab7tB.jpg

title: Why SSD1306 OLED display get scrambled text when printing messages from separate tasks in RTOS? (revised)

Answers: 1

body:
This is a formal answer to the question based on the comments between Paulo Borges and Majenko.

----

The ESP32 is dual core, meaning that it comes with 2 Xtensa LX6 32-bit microprocessors: core 0 and core 1.

The issue is not a bug in your code but rather that you are running your threads on Core 0 instead of Core 1.

In the ESP, the Core 0 is used for the RF communications. Even with the mutex protection, it is highly likely that your tasks are having timing issues.

Move Task01 and Task02 into Core 1 and your program will run without any display issues.


body:
I want the number from an RFID tag read by a reader connected to an Arduino Mega to end up as a string on a NodeMCU connected to the Mega. I am trying to confirm that the string is on the NodeMCU using the serial monitor. With the code below, the serial monitor for the NodeMCU prints "receivedChars:" only and not the number from the tag. What am I missing?

Code for Arduino Mega

```

#include <SPI.h>
#include <MFRC522.h>

#define SS_PIN 53
#define RST_PIN 5
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.

String sent = "n";
String UID_string = "";

void setup() {

    SPI.begin();            // Init SPI bus
    mfrc522.PCD_Init(); // Init MFRC522 card
    Serial.begin(115200); // Initialize serial communications with the PC
    Serial.println("Running Version Jan5a");
    Serial.println("Mega:Serial Monitor initialized at 115200 baud...");
    Serial3.begin(9600); // Initialize serial communication with ESP
    Serial.println("Mega:Serial Port 3 for NodeMCU initialized at 9600 baud...");
    Serial.println("Mega: Scan PICC to see UID and type...");
}

////////

void SendUIDtoESP() {

if (sent == "n") {
  Serial.print("sent= ");
  Serial.print(sent);
  //if (UID_string.length() > 0)  {
  UID_string = "Hello World"; //test line
  Serial3.print("<");
  Serial3.print(String(UID_string));
  Serial3.print(">");
  Serial.println("Mega:Sending UID string to ESP");
  sent = "y";
  Serial.print("after sending, sent= ");
  Serial.print(sent);
//  } else {
 //   Serial.println("Mega: Error: UID-string not set yet!");
  //}

}
} // end Send UID to ESP

void loop {
SendUIDtoESP() ;
}

```

**Code for NodeMCU**

```

int numChars = 0;
String receivedChars = "";
boolean newData = false;
String tag = "";
unsigned long lastTime = 0;
unsigned long timerDelay = 5000;

SoftwareSerial s(D1,D2);// assign pins to send data to and receive data from NodeMCU to Arduino Mega rx, tx

void setup() {
Serial.begin(9600);
    s.begin(9600);
    Serial.println("NodeMCU: Waiting for serial connection with Mega to be available over s");
  while (! s.available() >0){
    Serial.print("."); // waiting
    return;
  }
  Serial.println("NodeMCU: Looks like Mega is available.");
} // end void setup

 void recvWithStartEndMarkers() { //listen to Mega
    static boolean recvInProgress = false;
    static byte ndx = 0;
    char startMarker = '<';
    char endMarker = '>';
    char rc;

    while (s.available() > 0 && newData == false) {
        rc = s.read();

        if (recvInProgress == true) {
            if (rc != endMarker) {
                Serial.println(rc);
                receivedChars[ndx] = rc;
                ndx++;
                if (ndx >= numChars) {
                    ndx = numChars - 1;
                }
            }
            else {
                receivedChars[ndx] = '\0'; // terminate the string
                recvInProgress = false;
                ndx = 0;
                newData = true;
            }
        }
        else if (rc == startMarker) {
          Serial.println("startMarker received");
            recvInProgress = true;
        }
    }
} // end recvWithStartEndMarkers()

void loop() {
recvWithStartEndMarkers();
}
```

title: How can I get an integer from an RFID tag from Arduino Mega to NodeMCU 1.0 over serial communication?

Answers: 0


body:
**For debugging purposes I want my serial connection to resume after sleep.**  After running LowPower.sleep() from the <ArduinoLowPower.h> library, I don't get any new serial messages in the serial monitor.

Several factors seem to be at play (which I've listed at the bottom) and I've developed a partial solution but it's not great because it requires some long artificial delays of about 1 second after each sleep to resume the serial.  **So to recap, my question is how I can get serial to work after sleeping the microcontroller without having to insert long delays.**

For background, I am using an Adafruit Feather M0, which I think actually uses SerialUSB and automatically converts serial commands to that according to the [guide][1], but I am not sure what any of that means.

Here's some stuff I looked into:

 1. COM Port: One factor is that the Arduino disconnects from the my Windows 10 computer at sleep and reconnects when it wakes up sometimes on a different COM port.  Using the program Tera Term instead of the Arduino IDE Serial Monitor seems to keep it on the same COM port.

 2. Serial Flush and End: As notes in my code example, both of these commands seem necessary before sleeping or else I won't receive new messages after sleep.

 3. Delay: Seems that the arduino can send messages right after waking up that Tera Term wont see.  I have to put a delay of 1 full second after waking up or else I won't see the messages.

Here's some code I have tried.

    #include <ArduinoLowPower.h>

    void setup() {
      Serial.begin(115200);
      while(!Serial){delay(10);}
      Serial.println("start");
    }

    void loop() {

      Serial.println("");
      Serial.println("sleep");
      Serial.flush();  //if this line is commented out, only one cycle of "sleep" will show
      Serial.end();   //if this line is commented out, only one cycle of "sleep" will show
      //delay(2000);  //doesn't seem to fix anything so commented out
      LowPower.sleep(2000);
      delay(1000);  //at 750 misses some "awake" messages
      //Serial.begin(115200);  //this line doesn't appear to fix anything so commented out
      Serial.println("awake");

Output:

    start

    sleep
    awake

    sleep
    awake

    sleep
    awake

  [1]: https://learn.adafruit.com/adafruit-feather-m0-basic-proto/adapting-sketches-to-m0

title: Resuming Serial Connection after sleep on Arduino M0

Answers: 0


body:
I am trying to make a auto feeder for birds!,
I can't setup my code, the aim is to move servo when the certain time comes,
My commend if doesnt work, what else commend can I use?

```c++
#include <Wire.h>
#include "RTClib.h"
#include <Servo.h>

RTC_DS1307 RTC;
Servo myservo;

void setup () {
    Serial.begin(9600);
    Wire.begin();
    RTC.begin();
    myservo.attach(9);
    myservo.write(45);

  if (! RTC.isrunning()) {
   Serial.println("RTC is NOT running!");

  RTC.adjust(DateTime(2017,05,18,11,10,0));
  }
}

void loop () {
    DateTime now = RTC.now();
Serial.print(now.year(), DEC);
 Serial.print('/');
 Serial.print(now.month(), DEC);
 Serial.print('/');
 Serial.print(now.day(), DEC);
 Serial.print(" (");
 Serial.print(") ");
 Serial.print(now.hour(), DEC);
 Serial.print(':');
 Serial.print(now.minute(), DEC);
 Serial.print(':');
 Serial.print(now.second(), DEC);
 Serial.println();
 Serial.print(" since midnight 1/1/1970 = ");
 Serial.print(now.unixtime());
 Serial.print("s = ");
 Serial.print(now.unixtime() / 86400L);
 Serial.println("d");

    if ( now.hour()== 10 && now.minute() == 18){
      Serial.print('a');

    }

}
```

title: Hello, help with CODE servo mechanism and DS1307

Answers: 0


body:
I am trying to make a production counter for a machine. I want to display production count of the last minute for each seconds. So, display should update every second and should display real value of last 60 seconds.  I have a system for detect real-time product output and get it to the Arduino using digital input pin.

I wrote below codes and for that.
what I have done is count output and get output per second. Then store it on an array as separated value for each seconds. Every second the array updated and added new value for current second. At last add all count value of last 60 seconds and output as production rate of current minute.

**My question is, Is there any easy and efficient way for do this without using few variables ?**

        #define countSensor 8  //count sensor input

        uint8_t records[60];
        uint8_t countSensorState = 0;
        uint8_t totalCount = 0;
        uint8_t countOfLastSec = 0;
        uint8_t lastCount = 0;
        uint8_t lastMinCount;
        uint32_t preMills = 0;

        void setup() {
          Serial.begin(9600);
          //init sensor input pin
          pinMode(countSensor, INPUT_PULLUP); //change according to sensor type

          //clear random value of memory locations
          for (int i = 0; i < 60; i++) {
            records[i] = 0;
          }

        }

        void loop() {
          //get count at falling edge
          if (digitalRead(countSensor)^ countSensorState) {
            if (!digitalRead(countSensor)) {
              totalCount++;

            }
            countSensorState = digitalRead(countSensor);
          }
          //get count of last second
          if (millis() - preMills > 1000) {
            preMills = millis();
            countOfLastSec = totalCount - lastCount;
            lastCount = totalCount;
            //record last 60s counts
            //--shift back a second in the array
            for (int i = 0; i < 59; i++) {
              records[i] = records[i + 1];
            }
            //--record current second in array at 59th index
            records[59] = countOfLastSec;
            //get last 60s count
            for (int i = 0; i < 60; i++) {
              lastMinCount += records[i];
            }
            Serial.println(lastMinCount);
          }

        }

title: Get production count for current minute

Answers: 1

body:
As I said in a comment, if you really need to compute that moving sum,
you absolutely need to store the last 60 one-second counts in memory.
That being said, there are a few small issues with this code for which I
would have some suggestions:

* There is no point in storing `totalCount`. You do not really use it,
  and it will eventually overflow.

* You do not need to explicitly initialize all globals to zero, as that
  is implicitly done by the runtime: it is a requirement of the
  language.

* Your are calling `digitalRead(countSensor)` three times in a row. The
  logic for counting edges is sound as long as the three calls yield the
  same result, but that is not guaranteed. It is safer to only read the
  pin once per loop iteration.

* Similarly, the two calls to `millis()` can yield different results,
  and that will make your timings slightly off.

* The condition `millis() - preMills > 1000` will only fire when
  1001 milliseconds have elapsed. Because of the way `millis()` works,
  sometimes you will miss the 1001th millisecond, and process on the
  1002nd millisecond. In order to avoid accumulating these small timing
  errors, it is best to update `preMills` by always adding exactly 1000.

* As pointed out by jsotola, you do not need to shift the array: you can
  instead reuse the array cell that holds the data you do not need
  anymore.

* You do not need to perform the whole sum every time. You can instead
  update the previously computed sum by removing the count of the second
  that falls off the current one-minute window, and adding the count of
  the current second.

Here is my attempt at applying all the above suggestions. Warning: it
has not been tested.

```c++
const uint8_t countSensor = 8;

uint8_t record[60];       // last 60 one-second counts
uint8_t currentIndex;     // current index in record[]
uint8_t oldSensorState;   // previous state of countSensor input
uint32_t previousSecond;  // last time we printed minuteCount
uint8_t thisSecondCount;  // count of items in the current second
uint16_t minuteCount;     // count of items in the last minute

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

void loop() {
    // Count falling edges.
    uint8_t sensorState = digitalRead(countSensor);
    if (oldSensorState == HIGH && sensorState == LOW) {
        thisSecondCount++;
    }
    oldSensorState = sensorState;

    // Update stats every full second.
    if (millis() - previousSecond >= 1000) {
        previousSecond += 1000;

        // Update minuteCount by removing the second that falls off
        // the window and adding the one that enters the window.
        minuteCount += thisSecondCount - record[currentIndex];

        // Replace the count that is not needed anymore by
        // the current one.
        record[currentIndex] = thisSecondCount;

        // Start counting a new second.
        thisSecondCount = 0;

        // Update current index, wrapping at 60.
        if (++currentIndex >= 60) {
            currentIndex = 0;
        }

        Serial.println(minuteCount);
    }
}
```


body:
I am trying to detect whether a signal is high or low from an ESU LokSound 5 decoder for HO locomotives. My idea was to use one of the auxiliary pins used to drive an LED (AUX 3 in my case).

[![Bottom view of the motherboard that the decoder connects to][1]][1]

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

The problem is that these decoders are common positive rather than common negative, which means I can't directly connect AUX 3 to a digital pin on the Arduino and expect it to work flawlessly since it outputs a negative voltage rather than positive.

I'm trying my best to not use an op amp, as the locomotive I'm making this accessory for is already cramped. It sort of works if I directly connect it, but it is not smooth at all. I've tried using the built-in pull-up resistor, I've tried using an external pull-down resistor, I've tried using a resistor in line and I can't seem to figure out how to solve this without resorting to using an op-amp.

title: Reading ground signal from circuit

Answers: 0


body:
I'm trying to make a compact prototype with Attiny2313A, and want to connect VCC to pin 18 with a push button as in the picture. Is it safe? Or do I need a resistor there?

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

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

title: Is it safe to connect VCC to a data pin on Attiny chips?

Answers: 1

body:
As mentioned by @chrisl, here you would need a pull-down resistor to make sure that pin was not high when the button was not pushed.

It is more typical to connect the button between the IO pin and ground since then you can use the built-in pull-up resistors to make sure the pin is high when the button is not pushed. (This chip only has built-in pull-ups, although some chips have pull-downs).


body: I want to capture photographs from the ESP32 camera, but not doing it manually. Specifically, when a signal is sent from a sensor, I want ESP32 to understand that, and start taking photographs **automatically** for some seconds. The main problem, is the automation. I have searched on the web a lot, but can't find any answers. I am not expecting answers with code -since this is difficult- rather than some sites that provide solution to my problem. Thank you.

title: Automate capturing photograph on ESP32-CAM

Answers: 1

body:
Please have a look https://github.com/Yurik72/ESPHap/tree/master/examples/ESPHAPCamera
The project has different things, but definetelly doing what you asked, captures photo by external event, command...


body:
I do not know much electronics.

I have Nano v3 as I2C master, it reads 5-byte packets (of delimtted data) from PC's USB port, processes it and forwards it.

I now need to implement a way to signal PC if something went wrong down the line. I don't want to clutter I2C channel and its just a flag so I think interrupt is best for my purpose.

While writing the ISR function I am not sure if its advisable to write data using Serial, because loop might have read 2-3 bytes of the 5-byte message packet. And I don't know if it will overwrite data coming from PC or what...

**What will happen if I Serial.write(0x1) (suddenly, in an ISR function) while loop() was reading data from same Serial**?

I don't know how to test this myself.

title: Is it advisable to use Serial.write in an ISR when loop() routinely uses Serial.read?

Answers: 1

body:
Reading and writing of serial data are separate functions. When you `.write()` you just append the data to the TX buffer. When you `.read()` you just take the next character from the RX buffer.

All actual sending and receiving, and filling/emptying of the buffers is done inside the ISRs for the UART module.

That said, you *really* shouldn't use `Serial` inside an ISR. This is because the sending and receiving is done by an ISR, and if you are in *your* ISR then the sending can never happen until you leave your ISR.  For the odd occasional byte it's not really a problem, but if the TX buffer fills up `Serial.write()` will block until the TX ISR has sent some data - which won't happen since your ISR is blocking the TX ISR.

So it's best to avoid any `Serial` operations inside an ISR. Instead you would normally set flags and values in an ISR then check for those flags in `loop()` to report anything.


body:
I've been doing a personal project.
The idea of the bigger project is to feed my fish using a robot.
My specific problem is that I would like to see some data from the various sensors that I will be adding. But at the moment I am wanting to be able to use serial communication between my 2 boards to transfer an integer from  my Mega board to my MKR1000 board, and then for my MKR1000 to connect to the WIFI where I can see the information on my phone from the IP address.

Below is the 2 pieces of code, first being for the Mega board, where intergers are turned into strings and then sent the Mrk1000.
The sencond piece of code is for the MKR1000. Main goal is to recieve the data from the Mega board and then diaplayed on the client (over WIFI).

FOR MEGA BAORD ------------------------------------------------------------------------------------------

                char str[4];
                char str1[4];
                char str2[4];
                char str3[4];
                char str4[4];

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

                void loop() {
                  int value= 500; //this would be much more exciting if it was a sensor value
                  int value1= 400;
                  int value2= 300;
                  int value3= 200;
                  int value4= 100;

                  itoa(value, str, 10); //Turn value into a character array
                  itoa(value1, str1, 10);
                  itoa(value2, str2, 10);
                  itoa(value3, str3, 10);
                  itoa(value4, str4, 10);
                  Serial.write(str, 4);
                  delay(10);
                    Serial.write(str1, 4);
                    delay(10);
                      Serial.write(str2, 4);
                      delay(10);
                        Serial.write(str3, 4);
                        delay(10);
                          Serial.write(str4, 4);
                          delay(10);

                }

FOR MRK1000 -----------------------------------------------------------------------------------------

                #include <SPI.h>
                #include <WiFi101.h>
                #include <stdio.h>
                #include <math.h>

                //#include "arduino_secrets.h"
                ///////please enter your sensitive data in the Secret tab/arduino_secrets.h
                char ssid[] = "";//SECRET_SSID;        // your network SSID (name)
                char pass[] ="";// SECRET_PASS;    // your network password (use for WPA,
                or use as key for WEP)
                int keyIndex = 0;                 // your network key Index number (needed only for WEP)

                char str[4];
                char str1[4];

                int status = WL_IDLE_STATUS;
                WiFiServer server(80);

                void setup() {
                  Serial.begin(9600);      // initialize serial communication
                  pinMode(6, OUTPUT);      // set the LED pin mode
                  Serial1.begin(9600);

                  // check for the presence of the shield:
                  if (WiFi.status() == WL_NO_SHIELD) {
                    Serial.println("WiFi shield not present");
                    while (true);       // don't continue
                  }

                  // attempt to connect to WiFi network:
                  while ( status != WL_CONNECTED) {
                    Serial.print("Attempting to connect to Network named: ");
                    Serial.println(ssid);                   // print the network name (SSID);

                    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
                    status = WiFi.begin(ssid, pass);
                    // wait 10 seconds for connection:
                    delay(10000);
                  }
                  server.begin();                           // start the web server on port 80
                printWiFiStatus();                        // you're connected now, so print out the status
                }

                int x = 0;       int i = 0;
                void loop() {
                  WiFiClient client = server.available();   // listen for incoming clients

                  if (client) {                             // if you get a client,
                    Serial.println("new client");           // print a message out the serial port
                    String currentLine = "";                // make a String to hold incoming data from the client
                    while (client.connected()) {            // loop while the client's connected
                      if (client.available()) {             // if there's bytes to read from the client,
                        char c = client.read();             // read a byte, then
                        Serial.write(c);                    // print it out the serial monitor
                        if (c == '\n') {                    // if the byte is a newline character

                            if (Serial1.available()) {
                                delay(100); //allows all serial sent to be received together
                                while(Serial1.available() && i<4) {
                                  str[i++] = Serial1.read();
                                }
                              str[i++]='\0';
                            }

                          // if the current line is blank, you got two newline characters in a row.
                          // that's the end of the client HTTP request, so send a response:
                          if (currentLine.length() == 0) {
                            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
                            // and a content-type so the client knows what's coming, then a blank line:
                            client.println("HTTP/1.1 200 OK");
                            client.println("Content-type:text/html");

                                  //strcpy(str, "98993489");
                              int val = atoi(str);
                                //Serial.println(str,4);
                                client.print("str = ");
                                client.print(x);

                            client.println();
                            client.print(x);
                             client.println("
");

                            // the content of the HTTP response follows the header:
                            client.print("Click here turn the LED on pin 9 on
");
                            client.print("Click here turn the LED on pin 9 off
");

                            // The HTTP response ends with another blank line:
                            client.println();
                            // break out of the while loop:
                            break;
                          }
                          else {      // if you got a newline, then clear currentLine:
                            currentLine = "";
                          }
                        }
                        else if (c != '\r') {    // if you got anything else but a carriage return character,
                          currentLine += c;      // add it to the end of the currentLine
                        }

                        // Check to see if the client request was "GET /H" or "GET /L":
                        if (currentLine.endsWith("GET /H")) {
                          Serial.println("high");
                          digitalWrite(9, HIGH);               // GET /H turns the LED on

                          }
                        if (currentLine.endsWith("GET /L")) {
                          Serial.println("low");
                          digitalWrite(9, LOW);                // GET /L turns the LED off

                        }
                      }
                    }
                    // close the connection:
                    client.stop();
                    Serial.println("client disonnected");
                    x++;
                  }
                }

                void printWiFiStatus() {
                  // print the SSID of the network you're attached to:
                  Serial.print("SSID: ");
                  Serial.println(WiFi.SSID());

                  // print your WiFi shield's IP address:
                  IPAddress ip = WiFi.localIP();
                  Serial.print("IP Address: ");
                  Serial.println(ip);

                  // print the received signal strength:
                  long rssi = WiFi.RSSI();
                  Serial.print("signal strength (RSSI):");
                  Serial.print(rssi);
                  Serial.println(" dBm");
                  // print where to go in a browser:
                  Serial.print("To see this page in action, open a browser to http://");
                  Serial.println(ip);
                }

title: Problem displaying data sent from Arduino Mega to Arduino Mrk1000 using serial communications

Answers: 0


body:
I am making an application that is used to measure the velocity, it has an accelerometer that measures the component acceleration in the XYZ-axis. When the car is moving just straight the measurement is ok, as only linear components are involved.

My doubt came when the car is on a curve, I am not sure if the accelerometer can measure correctly in such situation or if it is necessary to apply a gyroscope to measure any missing component.

The code snippet for measure the total acceleration is shown below, I measure the acceleration in each axis and I remove the gravitational to finally calculate the velocity and the speed

        float AccTotal_X = ((AcX - grav_X)*9.81);
        float AccTotal_Y = ((AcY - grav_Y)*9.81);
        float AccTotal_Z = ((AcZ - grav_Z)*9.81);

        float Vx = vx_0 + AccTotal_X*dt;
        vx_0 = Vx;
        float Vy = vy_0 + AccTotal_Y*dt;
        vy_0 = Vy;
        float Vz = vz_0 + AccTotal_Z*dt;
        vz_0 = Vz;

        speed_dt = sqrt(pow(Vx,2)+pow(Vy,2)+pow(Vz,2))*3.6;

title: Can I use an accelerometer to measure the velocity of a car in a curve?

Answers: 1

body:
I found out the answer to the question in the following article [**SenSpeed: Sensing Driving Conditions to Estimate Vehicle Speed in Urban Environments**][1]

  [1]: https://ieeexplore.ieee.org/document/6847999

According to the article

> When a vehicle makes a turn, it experiences a centripetal force, which
> is related to its speed, angular speed and turning radius. Thus, by
> utilizing the accelerometer and the gyroscope, we can derive the
> tangential speed of a vehicle.

Therefore, just with the accelerometer is not possible to measure the velocity when an object is making a turn, it is necessary a gyroscope also.

The equation to measure the tangential velocity is:

**v = Rω** (1),

Where **v** is the tangential speed, **R** the radius of the curve and **ω** the angular speed.

As the centripetal acceleration is given by **a = ω²R** (2), reformulating (2) and substituting in (1), it is obtained:

**v = a/ω** (3).

Both **a** and **ω** are given by the accelerometer and the gyroscope respectively.


body:
Edit:
What I'm looking for is some kind of library which could be used with an arduino to read the HID protocol output from the Data+ and Data- cables of the USB.

==========
If I cut the cable of a usb keyboard, plug in power and ground can I use the clk and data wires to read keystrokes into the Arduino? If so any pointers to libraries and schematics?

Simple I instructions? The "for dummies" version?

***EDIT***

Following some of the suggestions below I found this:

https://github.com/julianschuler/USBKeyboard

Which looks like what I want to do, basically hook up the lines into the arduinio and read from the keyboard using the HID protocol in this library.

***EDIT 2***

That doesn't do what I want. Does anyone know how this could be accomplished?

title: connect USB keyboard to Arduino using clk and data wires

Answers: 1

body:
USB doesn't have data and clock lines. It has a pair of data lines with inverted polarity (D+ and D-). The USB protocol is considerably more complex than you seem to imagine.

**However** there is a caveat: some keyboards have the ability to work in *IBM PS/2* mode. For this you will need a USB to PS/2 adaptor (pictured below) and then use the [PS2Keyboard.h](https://github.com/PaulStoffregen/PS2Keyboard) library. Your mileage may vary, though, as not all keyboards will work.

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

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


body:
In `.ino` file I have a class defined (called `IPmonitoring`).Also, inside the same `.ino` file, I call a `.h` file ( which is located "above" class `IPmonotoring`).

When I try to call members of `IPmonitoring` inside .h file - I get an error, which usually I solve using `extern`, but seemingly it is not the same for classes.

What should be done ?

Guy

title: Calling class member from .h file

Answers: 1

body:
You need to re-think your layout, and your usage of the .h file.

* You should never have code in a .h file unless it is either `inline` or part of a `template` class.

A .h file should only contain hints about where other things are. Those things should then be in .cpp or .ino files.

For example your IPmonitoring class would be *declared* in a .h file, and *defined* (or *implemented*) in a .cpp file (or .ino file if you prefer). Any place you want to use that class you `#include` the .h file. In one place you may choose to create an instance of that class. It is that instance that you then reference with `extern`.

In the Arduino world it is common to create a single instance of the class in the class's .cpp file and `extern` it in the .h file so everywhere that you include the .h file instantly has access to that single instance of the object.

This is how most libraries are written.

For example:

```c++
// IPMonitoring.h

class IPMonitoring {
    public:
        void doStuff();
};

extern IPMonitoring ipMon;

```

And:

```c++
// IPMonitoring.cpp

#include <IPMonitoring.h>

IPMonitoring ipMon;

void IPMonitoring::doStuff() {
    // Do something
}
```

And finally:

```c++
// mySketch.ino

#include <IPMonitoring.h>

void setup() {
    ipMon.doSomething();
}

void loop() {
}
```


body: I am reading sd card .txt file, I want to read the first line then how to save the position of the pointer for the next line read?

title: read first line from sd card and save the position for again reading from sd card

Answers: 2

body:
You should not need to save the position, the file knows where you last read from. You'd only need to manually save such information if you close the file and re-open it again, which unless you have a good reason is actually a very wasteful operation.

If you really *do* need to you can use the `.position()` and `.seek()` functions:

Save the location:
```c++
uint32_t pos = myFile.position();
```

Recall the location:
```c++
myFile.seek(pos);
```

Documentation:

* https://www.arduino.cc/en/Reference/FilePosition
* https://www.arduino.cc/en/Reference/FileSeek

body:
File myFile = SD.open("test.txt", O_RDWR);

    if (myFile) {

      while (myFile.available()) {
        int i = 0;
        while (i < myFile.size()) {
          inputString =  myFile.readStringUntil('\n');
          //Serial.print(inputString);
          if (myFile.readStringUntil('\n')) {

I have set a size for the loop, every time it returns "I want it to read a new line" but it skips, what could be the reason?

To help with this question, I wanted to show the process I did on the same question. Thank you, I will ask the question elsewhere.
I am sending from the serial port when the end of the line is not read twice, during each reading. I'm sending line by line


body:
Referring to this thread
https://arduino.stackexchange.com/questions/43173/how-to-declare-and-use-variabled-arrays-inside-arrays

Example

```
byte array[2][4] = { {1,2,3,4}, {5,6,7,8} };
Serial.println(array[0][2]); is equal to '3'.
```

Instead of using {1, 2, 3, 4} and {5, 6, 7, 8} I want to be able to declare separate arrays for each of them and just put the name.

Another big issue is putting arrays of different sizes for each entry and it would be wrong to do so. Is this really not possible? Do I have to use some other concept instead if I want to have an array that contains entries of arrays that have different sizes? I heard about pointers but not familiar with that.

Example,

```
byte arrayX[3] = {1, 2, 3}
byte arrayY[4] = {5, 6, 7, 8}

byte array[2][4] = { arrayX , arrayY };
```

Take note that the code was not taken from the link I mentioned, I just used the same array names. Also I changed arrayX from the link to 3 entries because I want to emphasize the part of my question if it is possible if arrays have different sizes and you would just use the biggest size?

Now I think this is wrong and I haven't tested it currently but I want to ask if there is a solution that makes use of what I have mentioned? The site I linked to gave a solution which feels very redundant in terms of declaration and I would not want that. This is the solution mentioned there.

```
byte arrayZ[2][4] = {
  {arrayX[0],arrayX[1],arrayX[2],arrayX[3]},
  {arrayY[0],arrayY[1],arrayY[2],arrayY[3]}
};
```

The issue I had when searching the internet is the same as the link. "Surfed on the internet to find a bunch of examples but the only difference is that they don't use arrays that have been declared to have a name inside array."

title: In multidimensional arrays, can you use variable arrays or their names instead of the actual data?

Answers: 1

body:
Two-dimensional arrays come in two "flavours". Actually, multi-dimensional arrays are possible in any combination of these.

- All elements in a rectangular grid, at least from the abstract view of the programming language;
- A one-dimensional array of one-dimensional arrays.

If you declare:

    byte array[n][m];

then you have reserved space for "n times m" bytes. From the programmer's view it is a rectangular grid, actually all bytes are in sequence in a one-dimensional array. This is because the memory of our computers are commonly organized as a big one-dimensional array of bytes. The compiler generates the correct calculation for the offset into this array, multiplying one index with the size of the width (or length, depending on your mental model) and adding the other index.

You can initialize such an array with the nested set of curly braces like this:

    byte array[n][m] = {
        { /* ... */ },
        /* ... */
    };

But you cannot initialize it as you show.

Otherwise, if you declare

    byte* array[n];

then you have reseved space for "n" pointers to bytes, that is a one-dimensional array of pointers. Each of these pointers can point to a different or the same one-dimensional array of bytes, or to no array at all if it's `nullptr`.

Now you can set up the array as you like:

    byte arrayX[m1] = { /* ... */ };
    byte arrayY[m2] = { /* ... */ };

    byte* array[n] = { arrayX, arrayY, /* ... */ };

The arrays `arrayX` and `arrayY` (and any further) don't need to have the same length. Each can have its own length. But beware, you need to trace the length somehow to avoid out-of-bounds accesses. And of course, you need to check or be sure that a pointer is not null before dereferencing it.

In both cases you can access a single element with:

    byte element = array[i][j];
    array[k][l] = 23;

This is because the syntax with the brackets is equivalent to the dereferencing operator:

    x[y] == *(x + y)

_Note 1: Since Arduinos are programmed in C++, there is another option. You can use references instead of pointers. Because it is really hard to create a null reference, some see it as a safety measure against null pointers._

_Note 2: Again, since Arduinos are programmed in C++, you can implement an own class that provides the `operator[]`. With this option you can do any magical stuff, but it might break the user's expectation. Be careful if you go that route._


body:
When I open my serial plotter to get the graph for my HC-SR04 sensor it doesn't show anything. My plotter looks different too. I have attached images below as well.

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

[![This is what it shows][2]][2]

  [1]: https://i.stack.imgur.com/xdbuk.png
  [2]: https://i.stack.imgur.com/TUIj1.png

Only those numbers on the **top-most** move with time.(100,200,300)
Here's my code:

```c++
int trigPin = 12;
int echoPin = 11;

int pingTravelTime;
float pingTravelDistance;
float distToTarget;

int baudRate = 9600;

int dT = 10;
int dT2 = 500 ;

String msg1 = "The distance is equal to ";
String msg2 = "cm";

void setup() {
  // put your setup code here, to run once:
  Serial.begin(baudRate);

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(trigPin, LOW);
  delayMicroseconds(dT);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(dT);
  digitalWrite(trigPin, LOW);

  pingTravelTime = pulseIn(echoPin, HIGH);

  pingTravelDistance = pingTravelTime * ((765. * 5280. * 12.) / (3600. * 1000000));
  pingTravelDistance = 2.54 * pingTravelDistance;
  distToTarget = (pingTravelDistance / 2);

  Serial.println(msg1 + distToTarget + msg2);

  delay(dT2);
}
```

What do I do??

title: Serial plotter looks different and doesnt print graph

Answers: 1

body:
The serial plotter expects you to send numbers, and only numbers. If it
reads any other text, like for example

“The distance is equal to 9.88cm”

It assumes these are the names of the columns of data that are to
follow. So it chooses one color for each column and prints the color key
on top of the graph.

> What do I do??

Just remove the prose and print only the numbers. You may print
something like “distance(cm)” in `setup()` if you want to have the key
displayed, but that is not required.


body:
I have a simple method that simply waits for an input, computes a response, and sends it:

    void loop() {
      if (Serial.available() > 0){
        input = Serial.read();

        if (input == 10){
          digitalWrite(trigPin, LOW);
          delayMicroseconds(2);

          digitalWrite(trigPin, HIGH);
          delayMicroseconds(10);
          digitalWrite(trigPin, LOW);

          duration = PulseDuration(echoPin, HIGH, 6000);
          distance = duration * 0.00034/2;  // 0.00034 m/us is speed of sound

          Serial.println(distance, 4);
          }
      }
    }

My question: What happens to the arduino if I close the serial connection from the receiving end while it's printing out data (in the last line of the loop)?

Context and motivation:

The program works well most times. I can open a python program that sends the requests and prints out the reply using pyserial. After I close the python side and reopen it, connection is set and I can start listening on the side nicely just like the first time. Sometimes, however, when I try to restart the python program, I get a connection error saying that the port is already opened (I'm running in Windows.. there are tons of posts about this problem, but none of them have been helpful). Some other times, when connecting with the python program (which connects with `connection = serial.Serial(self.arduino_port, 9600, timeout=0)` it just blocks and doesn't connect, it doesn't give the "port already opened" error, and it doesn't advance to the next statement.
I am confident I did close the previous python run before attempting a new one (process explorer shows no active python programs running, it also shows no open processes using a serial handler). I'm not here to solve that problem directly, though, just to ask a related question.

I'm also confident running `connection.close()` does not terminate the arduino program, as I have been able to restart my python program without having to reset the arduino or anything, suggesting the arduino kept running its loop after I closed the connection on the python side.

All that to say that my latest hypothesis is that these issues arise when I close the serial connection `connection.close()` while the arduino is printing, but because the port is closed, that Arduino is stuck and cannot do the Serial.println(), as the USB never asks to flush the data in its buffer.
Is this possible/does it make sense? What happens to the arduino if I close the serial connection while it's printing out data?

I'm not posting my python program here as it's not directly relevant to the question and I can't seem to make a minimum reproducible program that doesn't expose confidential code.

title: What does an Arduino do if the serial connection is closed on the other end?

Answers: 1

body:
That's some strange Intel monstrosity. It's impossible to know what it does or how. Intel's foray into the Arduinosphere was brief and somewhat abortive.

In general though (for most cores) the DTR signal (and sometimes the RTS signal too) of the CDC/ACM protocol is used to "gate" the serial data - if it's asserted then serial data gets sent through to the host PC. If it's not asserted then it just gets thrown away.

I have seen cores where if DTR is not asserted the data gets buffered until the TX buffer is full and then blocks, but that is rare.

You might find your answer if you delve into the core's source code, but you may find that big chunks of it are hidden away in closed source pre-compiled libraries, and the fact it seems to run some custom RTOS means it'll be even more obfuscated. YMMV...


body:
- I need a 2KHz **complimentary** PWM waves with **adjustable duty and phase** that is triggered by an **external** 4KHz source.
- After reading the datasheet I think there might be 2 way to do this:

1. Use a TC unit in capture mode, and somehow generate an interrupt when the count reaches 2. Use another TC unit in waveform mode to output phase-correct PWM. Use yet another TC unit to implement dead-time and generate the complimentary PWM.

2. Use the PWM controller, which already have complimentary PWM with dead-time build-in, but I'm not sure if it accepts external trigger.

If either of them is possible, could you please provide and example code ?

Thanks in advance !

title: Generating Externally Triggered Complimentary PWM with Arduino Due

Answers: 0


body:
I'm using `ESP8266Ping` lib inside my `iot` lib which hanldes Wifi connectivity and MQTT messages. Since it create its own instance called `Ping` when calling `#include <ESP8266Ping.h>`- it had to be place in `iot.cpp`.

I writing another library, `IPmonitor` which checks clients on the network (using pings), I wanted to use `ESP8266Ping` again.

My sketch file, create an instance of `iot` and `IPmonitor` for check/ log errors on monitored clients.

But I get error of using the same library twice.

I guess that since `ESP8366Ping.h` library is defined it creates an instance of the class ( see mark below ):

    class PingClass {
      public:
        PingClass();

        bool ping(IPAddress dest,   byte count = 5);
        bool ping(const char* host, byte count = 5);

        int averageTime();

      protected:
        static void _ping_sent_cb(void *opt, void *pdata);
        static void _ping_recv_cb(void *opt, void *pdata);

        IPAddress _dest;
        ping_option _options;

        static byte _expected_count, _errors, _success;
        static int _avg_time;
    };

    #include "ESP8266Ping.impl.h"
    PingClass Ping;                     // <----- This

    #endif

How can it be solved ?

title: 2 instanced of ESP8266Ping

Answers: 1

body:
With that library... you can't. All the code is in one big monolithic .h file. As you well know by now that is a big no-no. The author should be given a big slap on the wrists.

The closest you could do without re-writing the whole library is to just copy the class definition from the outer .h file and create an `extern` to the existing object - maybe make your own copy of the `ESP8266Ping.h` file without the `#include "ESP8266Ping.impl.h"` and `PingClass Ping;` (the latter of which you change to an `extern`).


body:
I'm able to get quaternion data from the BNO055 sensor, and would like to convert these to angular velocity for my project. I know you can pull the gyroscope directly for the data, but from what I understand using quaternions and converting those is more robust?

I found a function that does this in a Adafruit repository for the sensor. However, I'm not sure what the Delta time variable should be equal to, in relation to the sample frequency. Could anyone advise?

Here is the function code:

      Vector<3> toAngularVelocity(double dt) const {
        Vector<3> ret;
        Quaternion one(1.0, 0.0, 0.0, 0.0);
        Quaternion delta = one - *this;
        Quaternion r = (delta / dt);
        r = r * 2;
        r = r * one;

        ret.x() = r.x();
        ret.y() = r.y();
        ret.z() = r.z();
        return ret;
      }

And the [link][1]

  [1]: https://github.com/adafruit/Adafruit_BNO055/blob/master/utility/quaternion.h

title: Obtaining angular velocity from quaternion data (BNO055)

Answers: 1

body:
I do not know how to interpret the data given by that sensor, but from
reading the code, the meaning of `dt` is pretty clear.

The function you show assumes that the sensor started in the reference
orientation (quaternion `one`), then rotated at a constant angular
velocity until it reached the current orientation (quaternion `*this`),
and this rotation happened over a time `dt`.

Then `dt` is the time required for moving from the reference orientation
to the orientation described by the quaternion `*this`. You should
probably check out the sensor's datasheet for more details on how the
orientations are provided.


body:
Class `myIOT2` contains a function that need to be called from class `IPmonitoring`:

    bool myIOT2::checkInternet(char *externalSite, byte pings)
    {
     return Ping.ping(externalSite, pings);
    }

This function is needed as a pinger in `IPmonitor`:

    void IPmonitoring::start(cb_func ping)
    {

            _ping_cb = ping;
    }

and this `cb_func` is defined by (inside `IPmonitor.h`):

    typedef bool (*cb_func)(char *externalSite, byte pings);
    cb_func _ping_cb;

inside my sketch (relevant parts only) I fail when `iot.checkInternet` is passed, while using a function `test` that calls `iot.checkInternet` succeeds:

    myIOT2 iot;
    IPmonitoring WiFi_service(ROUTER_IP, "Router");

    bool test(char *a, byte b)
    {
            bool x = iot.checkInternet(ROUTER_IP);
            return x;
    }

    void setup()
    {
    WiFi_service.start(iot.checkInternet); // <---- Trial a)fails
    WiFi_service.start(test);              // <-----Trail b)succeeds
    }

error is :

    home/guy/Documents/git/Arduino/IPmonitor/IPmonitor.ino: In function 'void setup()':
    IPmonitor:436:45: error: no matching function for call to 'IPmonitoring::start(<unresolved overloaded function type>)'
             WiFi_service.start(iot.checkInternet);//
                                                 ^
    /home/guy/Documents/git/Arduino/IPmonitor/IPmonitor.ino:436:45: note: candidate is:
    In file included from /home/guy/Documents/git/Arduino/IPmonitor/IPmonitor.ino:2:0:
    /home/guy/Documents/git/Arduino/libraries/myIPmonitor/myIPmonitor.h:42:10: note: void IPmonitoring::start(IPmonitoring::cb_func)
         void start(cb_func ping);
              ^
    /home/guy/Documents/git/Arduino/libraries/myIPmonitor/myIPmonitor.h:42:10: note:   no known conversion for argument 1 from '<unresolved overloaded function type>' to 'IPmonitoring::cb_func {aka bool (*)(char*, unsigned char)}'
    Multiple libraries were found

What is done wrong ? and why `test` succeeds ?

title: Calling functions between 2 classes

Answers: 1

body:
There is a fundamental difference between a simple function and a function that is a member of a class.  You can't use a function pointer to point to a member function of a class: simply because that member function also includes information about the class instance that it belongs to.

The *proper* C++ way to handle it is to use [`std::function`](https://en.cppreference.com/w/cpp/utility/functional/function), but the Arduino AVR compiler lacks the full STL (Standard Template Library), so that can't be used on normal Arduinos. Other cores do have it, so you may well be able to use it on the ESP8266.

If you want to make your code portable between systems that may not have the full STL then there's other tricks you have to do:

* Use a wrapper function (which as you have found works), or
* Make a polymorphic class and store a pointer to the instance cast to the parent class - the parent class defines the functions that are allowed to be called from the pointer.


body:
I am writing a program in Python (using PySerial) that needs to read data from the Arduino quickly. For this reason I have set the serial timeout to 0.01 seconds. (Baud rate is 115k) If I don't set the timeout this low I run into issues with there being a noticeable delay between sending a command and receiving a reply. As long as I have the timeout set low enough then its all fine, but the downside is that I have a message print out when I first connect to the Arduino to confirm that it has indeed connected. (Message reads "Connected" once the serial connection has been established in void setup)

Okay, the problem: If I don't have the timeout set to 0.9 seconds or higher, the initial 'connected' message gets cut off. Of course if I have it set that high I get the issues I first described.

I'm looking for a way to keep the timeout very low but also get this first connected message when the void setup runs. Is there a way to have my cake and eat it too?

I did try starting with the timeout set to 1 second and once the connected message prints out change it to 0.01 seconds, but it just kept giving me an error.

Any help would be appreciated.

title: Initial setup print getting cut off from printing

Answers: 0


body:
I have a project split into several files:

```
//Loop.cpp
#include "LiquidCrystal.h"

void setup(){
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    lcd.begin(16, 2);
}

void loop() {
//Code
}
```

```
//Display.cpp
#include "LiquidCrystal.h"

namespace display {
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void displayData(const InputPacket &inputPacket, const DataPacket &dataPacket) {
    lcd.setCursor(0,1);
    lcd.print("Foo");    //This creates display error, unless i call lcd.begin(16, 2) in this function
}

} //namespace display
```

My initial problem is that - without calling lcd.begin() from within displayData() - the characters aren't displayed correctly. In other words, calling lcd.begin() in setup() doesn't help. (It appears to me that setup() has implicit static property, no?)

As an attempted solution, i could create an lcd object in Display.cpp, and call lcd.begin() from within displayData(). Even though characters are displayed properly, this gives me display flickering. (Presumably as a result of calling these functions repeatedly in the loop during runtime).

So, the only solution to this dilemma that i can come up with is to call lcd.begin() from a function written to run only once inside of displayData(). Or is it?

My question is, are there other more elegant solutions/alternatives?

title: How can i call lcd.begin() from several different code files in a proper way?

Answers: 1

body:
The object called `lcd` that you create inside the `setup` function is a local variable. It only lives as long as that function is executing - so not very long. It doesn't exist outside that function.

The `lcd` object you have in `namespace display` on the other hand is a global variable. That one lives as long as your program, which means until you reset your Arduino here. (It is completely unrelated to the object inside `setup`.)

If you want all your LCD code to be grouped inside the `display` namespace, you could do this in `Display.cpp`:

    namespace display {
      // This is a global variable, full name `display::lcd`
      LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

      void setup() {
        // this `lcd` refers to the global `display::lcd` defined above
        lcd.begin(16, 2);
      }

      // rest of the display functions
    }

Create a `Display.h` file to provide prototypes for the display module:

    #ifndef DISPLAY_H
    #define DISPLAY_H

    // Include the header that defines InputPacket and DataPacket here

    namespace display
    {
    void setup();
    void displayData(const InputPacket &inputPacket, const DataPacket &dataPacket);
    }

    #endif

Then your main file can call the display function. The main file doesn't even have to know that you're using an LCD if you do package all LCD code in the display file.

    #include "Display.h" // no need to include LiquidCrystal.h if all
                         // LCD handling is done in Display.cpp

    void setup(){
      // Initialize display
      display::setup();
    }


body:
I want to make a Wi-Fi Direct connection with an android device using my ESP8266. According to [ESP8266WiFi Documentation][1] and [ESP8266 datasheet][2], the board has a SoftAP mode which is I think what is needed in a P2P connection (Being an AP and a client at the same time).

There is also ESP-NOW in the Espressif website but I think it's made only for esp-to-esp p2p connection and I can't modify it. (Correct me if I'm wrong)

I couldn't find any pre-made libraries for this job, so I decided to make my own, but I can't seem to find anything related to making a new type of protocol or connection. Is it even possible to develop a new type of protocol? If yes, I'd really appreciate a guide on how to get started.

  [1]: https://arduino-esp8266.readthedocs.io/en/2.7.4_a/
  [2]: https://www.espressif.com/sites/default/files/documentation/0a-esp8266ex_datasheet_en.pdf

title: Using or creating Wi-Fi Direct (P2P) connection on ESP8266

Answers: 0


body:
Here's a schematic of my project:

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

The purpose is to make laptop work as keyboard for desktop PC. Nano uses Serial.read() to get keystrokes from laptop and forwards key press and release data to Leonardo (using I2C) acting as USB-HID keyboard.

Nano's setup looks like:
```
void setup() {
  Wire.begin();
  Serial.begin(14400);
  Serial.write("Hello");  // https://serialport.io/docs/api-stream#serialpor|
  pinMode(LED_BUILTIN, OUTPUT);
}
```

Leonardo's setup looks like:
```
void setup() {
  Keyboard.begin();
  Wire.begin(4);
  Wire.onReceive(cbfunc);
}
```
I have tested both boards individually, but not the whole setup. Whenever either board connects to USB port it powers up due to +5 volt from USB. Now that I have i2c wires in place, I am confused -

if I connect leonardo & desktop first [and i2c-master (Nano) isn't powered on yet], what will happen at `Wire.begin(4)`? Will it wait (1s, 5s, forever) until i2c-master comes online?

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

title: What's the time out of Wire.begin()?

Answers: 1

body:
Generally you should not provide power to any pin of a device, which is powered off. That can cause current flowing through clamping diodes to ground and might destroy the pins hardware or the device (also it can lead to weird situations, where the device is somewhat powered through the IO pin, which might lead to instability).

You can either cut the connection between the devices, if only one of them is powered (this should be possible with some extra components), or you can power both devices from one USB port. For the other port you would cut the V+ (positive supply voltage) line of the USB port/cable (this makes sure, that you don't get a bad current between both computers on the USB power line, if they provide a bit different voltage). Since the ground wire still connects both computers and the Arduinos, the communication will still work correctly.

> if I connect leonardo & desktop first [and i2c-master (Nano) isn't powered on yet], what will happen at Wire.begin(4)?

The `Wire.begin()` line won't get stuck, since it doesn't do much on the lines and it doesn't know, if something is connected on the other end, until some transaction happens on the bus. But it might be, that any transaction from the powered Arduino (the master) might cause a blocked I2C bus (since at some places the library waits for the lines to get high. The connection through the clamping diodes might hold the line at low. I'm not sure about that). Then you would need to reset both Arduinos, to make sure, that the bus is in a healthy state.

The solution from above (powering both Arduinos from one USB port) will also make sure, that both Arduinos start at the same time and thus won't block the bus through the clamping diodes.


body:
**I Took a output from ESP8266 and Connected it with Arduino Nano Analog input A0**

i use BLYNK app to on/off D0 pin in ESP8266 , and i connected ESP8266 D0 pin with Arduino Nano A0 analogPin.

when esp8266 D0 in high state , the analogRead value in arduino nano serial monitor it show the value 395.

why not 1023 on high state .[![enter image description here][1]][1]

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

title: Why AnalogRead shows value (395) when its on HIGH State ? why not shows 1023 when its high State

Answers: 1

body:
There are two problems here - one immediate and one which will be come apparent.

First off, you appear not to have connected the ground pins of the two boards together. This is important. Voltage is not an absolute value, it's a value *relative to some other point in the circuit*. This is why "voltage" is sometimes called "potential *difference*". Normally the point in the circuit that voltages are referenced to is termed "ground". Note: there is nothing special about ground, it's just an arbitrary point in the circuit - usually, but not always, the point where the voltage is lowest.  If the ground of the Arduino that it's using to compare incoming voltages against is not the same as the ground that the ESP8266 is using to create its output voltage in relation to, then the Arduino really can't know what the voltage is.

You can think of it as a person standing on the ground. Now I am about 6 feet tall. When I am stood up the top of my head is about 6 feet above the ground. But to someone who is stood on a nearby rise in the ground my head is only maybe 3 feet above the ground. Their ground is not the same as my ground.

The second problem, which will become apparent once you have connected the grounds, is that the Arduino measures voltages between 0 and 5V as values between 0 and 1023. However the ESP8266 doesn't operate at 5V, it operates at 3.3V. The highest voltage it can ever put out is 3.3V. The Arduino can never read that as 1023 because it's not 5V.  Instead it will read somewhere around 675. That is, 3.3V is two thirds of 5V, and 675 is two thirds of 1023.


body:
    void Sensor_value()
    {   server.handleClient();
        humidity = dht.readHumidity();
        temperature = dht.readTemperature();
     }

I want to make condition if temperature = null and Humidity= null that means the sensor fails to take reading so I want to return and take value again

title: Dht 11 sensors give null value

Answers: 1

body:
The way to do this is:

    float h = dht.readHumidity();
    float t = dht.readTemperature();
    float f = dht.readTemperature(true);

    if (isnan(h) || isnan(t) || isnan(f)) {
      Serial.println("Failed to read from DHT sensor!");
      return;
    }

See https://www.hackster.io/MisterBotBreak/how-to-use-temperature-and-humidity-dht-sensors-9e5975 and https://stackoverflow.com/questions/40874880/getting-nan-readings-from-dht-11-sensor.

`NULL` should only be used with pointers.