body:
Hello all I am back again with another issue concerning a code for my job. The code I have been working on is meant to connect to a IP server where some options are listed and I can control the servo motor through there. The options listed are FORWARD, BACKWARD, STEP, and STOP. Each command makes the servo motor move a certain way but the problem I need help with is I need the edited the code to work with three input switches which when pressed in real time they allow the motor to make turns without the need of pressing any button on the server and so far the code is not working. They work with some LED lights which when the input switches are pressed also light up each input is paired with an output (LED) respectively and I tried to create a marker that when the input is pressed also says on the server that "LED1 is on" for example. Each input corresponds to an INPUT switch and each output corresponds to an LED light. The Pin variable corresponds to the motor. Here is the code in question:

```
#include <ESP8266WiFi.h>
#include <Servo.h>

const char* ssid = "RETProject";
const char* password = "mporfiri";

WiFiServer server(80);

int Pin = 16; // GPIO13
int var = 0;
int D1 = 5;
int D2 = 4;
int D4 = 2;
int D5 = 14;
int D6 = 12;
int D7 = 13;
int temp1 = 0;
int temp2 = 0;
int temp3 = 0;

Servo servoMotor;

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

  pinMode(D1, INPUT);
  pinMode(D2, OUTPUT);
  pinMode(D4, INPUT);
  pinMode(D5, OUTPUT);
  pinMode(D6, INPUT);
  pinMode(D7, OUTPUT);
  pinMode(Pin,INPUT);
  //pinMode(LED_BUILTIN, OUTPUT);
  //digitalWrite(LED_BUILTIN, LOW);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

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

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");

  //servoMotor.attach(Pin);

}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  temp1 = digitalRead(D1);
  temp2 = digitalRead(D4);
  temp3 = digitalRead(D6);
  if (!client) {
    return;
  }

  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }

  // Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();

  // Match the request
  if(temp1 == HIGH) {
    digitalWrite(D2,HIGH);
    servoMotor.attach(Pin);
    servoMotor.write(90);
  }
  else{
    digitalWrite(D2,LOW);
  }

  if(temp2 == HIGH) {
    digitalWrite(D5,HIGH);
    servoMotor.attach(Pin);
    servoMotor.write(-90);
}
  else {
    digitalWrite(D5,LOW);
}

  if(temp3 == HIGH) {
    digitalWrite(D7,HIGH);
}
  else{
    digitalWrite(D7,LOW);
}

  int value = LOW;
  while (value = LOW); {
  if (request.indexOf("/LED=ON") != -1)  {
    //digitalWrite(LED_BUILTIN, HIGH);
    value = HIGH;
    servoMotor.attach(Pin);
    servoMotor.write(0);
    delay(1000);

  }
  if (request.indexOf("/LED=OFF") != -1)  {
    //digitalWrite(LED_BUILTIN, LOW);
    value = LOW;
    servoMotor.attach(Pin);
    servoMotor.write(180);
    delay(1000);

  }
  if (request.indexOf("/LED=STP") != -1){
      var = 1;
      while(var < 10){
    //digitalWrite(LED_BUILTIN, LOW);
    value = LOW;
    servoMotor.attach(Pin);
    servoMotor.write(90);
    delay(200);
    servoMotor.write(-90);
    delay(200);
    var=var+1;
    }
  }
  if (request.indexOf("/LED=STOP") != -1)  {
    //digitalWrite(LED_BUILTIN, LOW);
    value = LOW;
    servoMotor.detach();
    delay(1000);
  }

// Set ledPin according to the request
//digitalWrite(ledPin, value);

  // Return the response
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("<html>");

  client.print("Robot is now: ");

  if(value == HIGH) {
    client.print("Moving Forward");
  } else if(value == LOW) {
    client.print("Moving Backward");
  } else if(request.indexOf("/LED=STP") != -1) {
    client.print("Moving in Step");
  }else {
    client.print("Stopped");
  }

  if(temp1 == HIGH) {
    client.print("Led_1 is on");
  }else if (temp1 == LOW);{
    client.print("Led_1 is off");
  }

  if(temp2 == HIGH) {
    client.print("Led_2 is on");
  }else if (temp2 == LOW);{
    client.print("Led_2 is off");
  }

  if(temp3 == HIGH) {
    client.print("Led_3 is on");
  }else if (temp3 == LOW);{
    client.print("Led_3 is off");
  }

  client.println("<br><br>");
  client.println("<a href=\"/LED=ON\"\"><button>Move Forward </button></a>");
  client.println("<a href=\"/LED=STP\"\"><button>Step </button></a>");
  client.println("<a href=\"/LED=OFF\"\"><button>Move Backward </button></a><br />");
  client.println("<a href=\"/LED=STOP\"\"><button>STOP </button></a><br />");
  client.println("<a href=\"/Temp1=HIGH\"\"><Input>LED_1 ON </Input></a><br />");
  client.println("<a href=\"/Temp2=HIGH\"\"><Input>LED_2 ON </Input></a><br />");
  client.println("<a href=\"/Temp3=HIGH\"\"><Input>LED_3 ON </Input></a><br />");
  client.println("</html>");

  delay(1);
  Serial.println("Client disonnected");
  Serial.println("");
  }
}
```

P.S. I just edited the code to do the turns when the input is pressed for the third input it is supposed to make a random turn (either left or right the machine needs to decide on its own) and I am not sure how to write that in the code.

title: Need my code to do multiple commands when inputs are pressed

Answers: 1

body:
Your code will only do anything if a client has connected to it because of this line
```
if (!client) {
    return;
  }
```

Your physical button will never do anything on their own unless a client has connected and has sent some data.

For the random direction you use a line like the following to randomly pick a direction
```
int direction = random(0,2) ? 1 : 0 ;
```
your direction variable will be with either 1 or 0 randomly


body:
Some sensors give as output a voltage between 0 and 5V. The analog inputs of the NodeMCU require voltages between 0 and 3.3V. I plan to make a voltage divider with two resistors like in this [link][1] for compatibility.

To provide the desired voltage the quotient of the values of the resistances is fixed (approx. 1/2 for this case). However, the absolute values of the resistances are not.

**Q:** How to choose those absolute values? Which are the criteria and why?

I have a good background in electromagnetism but I know very few about electronic Engineering.

I think that low values must work, e.g. 1Ω and 2Ω (and surely greater values). But I am unsure of VERY high resistance values because I suspect that there should be some current intensity requirements.

Thank you.

  [1]: https://learn.sparkfun.com/tutorials/voltage-dividers/all

title: Voltage divider and NodeMCU inputs

Answers: 3

body:
The low end of the values is limited by how much current your sensor can provide. If you use 1Ω and 2Ω resistors in series then your sensor will need to provide 1.67A to create 5V across the divider. I doubt that your sensor can do that. For most sensors, you would want to use resistors in the kilohm or tens of kilohm range.

The high end is limited by the input impedance of the analog input pin. If your resistor values are large compared to this input impedance then the input impedance of the analog pin will affect how the voltage divider works. If the analog input is multiplexed and the ADC has a sample-and-hold at the input, then very large resistances in the divider will not allow the sampling capacitor to charge fast enough. For most ADC inputs, you would want to use resistors in the tens or hundreds of kilohms.

body:
As @Majenko commented, the A0 input has a fixed voltage divider (see [NodeMCU Schematics)][1] that connects the A0 input to a 220kOhm resistor, then to the ADC pin of the ESP8266, then to ground via a 100kOhm resistor.

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

This effectively fixes the resistor values that can be used to scale the input of the NodeMCU. For a 0-5.0V input range (with sufficiently low impedance) you need to scale the ADC pin from 0-1.0V by adding a ~180kOhm resistor between the 5V output and the A0 input of the NodeMCU, creating a 400kOhm-> ADC -> 100kOhm divider like this:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/3rS2N.png)

<!-- End schematic -->

  [1]: https://github.com/nodemcu/nodemcu-devkit-v1.0/blob/master/NODEMCU_DEVKIT_V1.0.PDF
  [2]: https://i.stack.imgur.com/QGkPV.jpg

body:
To better understand voltage divider, one can look at this online calculator https://ohmslawcalculator.com/voltage-divider-calculator to see the actual formula and try the calculator to compute the unknown wanted.

It is not well publish the existing voltage divider on the NodeMCU, of course you need to browse the schematic to figure it out.

It goes the same with existing pullup resistor for some GPIO.

@Majenko your explanation is excellent!


body:
I have a temperature/humidity project using an ESP-01 and DHT11.  I want to be able to put t into deep sleep to preserve battery life.  I have soldered a wire from GPIO16 to RST.

    #include <SimpleTimer.h>  //https://github.com/jfturcot/SimpleTimer
    #include <ESP8266WiFi.h>
    #include <PubSubClient.h>  //https://github.com/knolleary/pubsubclient
    #include <ESP8266mDNS.h>
    #include <WiFiUdp.h>
    #include <ArduinoOTA.h>  //https://github.com/esp8266/Arduino/tree/master/libraries/ArduinoOTA
    #include "DHT.h"

    //USER CONFIGURED SECTION START//
    #define DHTPIN 2     // what digital pin we're connected to

    const char* ssid = "mySSID";
    const char* password = "password";
    const char* mqtt_server = "mqttserverip";
    const int mqtt_port = 1883;
    const char *mqtt_user = "usser";
    const char *mqtt_pass = "pass";
    const char *mqtt_client_name = "DryerMCU"; // Client connections can't have the same connection name
    //USER CONFIGURED SECTION END//

    // Uncomment whatever type you're using!
    #define DHTTYPE DHT11   // DHT 11
    //#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
    //#define DHTTYPE DHT21   // DHT 21 (AM2301)

    // Initialize DHT sensor.
    // Note that older versions of this library took an optional third parameter to
    // tweak the timings for faster processors.  This parameter is no longer needed
    // as the current DHT reading algorithm adjusts itself to work on faster procs.
    DHT dht(DHTPIN, DHTTYPE);

    WiFiClient espClient;
    PubSubClient client(espClient);
    SimpleTimer timer;

    bool boot = true;
    int status = WL_IDLE_STATUS;

    //Functions
    void setup_wifi()
    {
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);
      WiFi.begin(ssid, password);
      while (WiFi.status() != WL_CONNECTED)
      {
        delay(500);
        Serial.print(".");
      }
      Serial.println("");
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
    }

    void getTemperature()
    {
      // Reading temperature or humidity takes about 250 milliseconds!
      // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
      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 and exit early (to try again).
      if (isnan(h) || isnan(t) || isnan(f)) {
        Serial.println("Failed to read from DHT sensor!");
        return;
      }

      // Compute heat index in Fahrenheit (the default)
      float hif = dht.computeHeatIndex(f, h);
      // Compute heat index in Celsius (isFahreheit = false)
      float hic = dht.computeHeatIndex(t, h, false);

      Serial.print("Humidity: ");
      Serial.print(h);
      Serial.print(" %\t");
      Serial.print("Temperature: ");
      Serial.print(t);
      Serial.print(" *C ");
      Serial.print(f);
      Serial.print(" *F\t");
      Serial.print("Heat index: ");
      Serial.print(hic);
      Serial.print(" *C ");
      Serial.print(hif);
      Serial.println(" *F");

      char temperature[50];
      char humidity[50];

       // Update temperature and humidity
      String temp_str = String(f);
      temp_str.toCharArray(temperature, temp_str.length() + 1);
      client.publish("dryer/temperature", temperature);

      String hum_str = String(h);
      hum_str.toCharArray(humidity, hum_str.length() + 1);
      client.publish("dryer/humidity", humidity);

    }

    void setup() {
      Serial.begin(38400);
      delay(2000);
      Serial.println("Booting");

      dht.begin();
      setup_wifi();
      client.setServer(mqtt_server, mqtt_port);
      getTemperature();

      Serial.println("Going to sleep");
      ESP.deepSleep(10000000,RF_DEFAULT);
    }

    void loop() {

    }

When I start it up it takes one measurement, goes to sleep and then wakes up, but nothing happens once it wakes up.  Serial output:

    Booting

    Connecting to SSID
      ......
    WiFi connected
    IP address:
    mqttip
    Humidity: 51.00 % Temperature: 20.00 *C 68.00 *F Heat index: 19.39 *C 66.90 *F
    Going to sleep

    ets Jan  8 2013,rst cause:5, boot mode:(3,7)

    ets_main.c

title: ESP-01 Deep Sleep not waking up properly

Answers: 2

body:
I guess you have a race condition between automatic connection to WiFi by the Espressif SDK and your WiFi.begin(). You have two options how to solve it.

**1. option:** Don't use WiFi.begin in this sketch. Use an utility sketch to set the SSID and password and the SDK remembers it persistent on flash. Then it is able to connect fast to WiFi specially on reset, because it has the WiFi channel number in RTC memory which is not cleared at reset (only on power down).

**2. option:** turn of remembering of the SSID and password and the automatic connection at start. Then the esp8266 will connect to the WiFi only with your `WiFi.begin` call. The commands are [`WiFi.persistent(false)`][1] and [`WiFi.setAutoConnect(false)`][2].

You can turn of the SoftAP too. At default it starts automatically. The command is [`WiFi.softAPdisconnect()`][3]

  [1]: https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/generic-class.html#persistent
  [2]: https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/station-class.html#setautoconnect
  [3]: https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/soft-access-point-class.html#softapdisconnect

body:
*In the question the OP said:*

>  I have soldered a wire from GPIO16 to RST.

*But, I'm going to post an answer for the people who find this question and need the ESP-01 modification instructions in order to wake an ESP-01 module up from deep-sleep:*

The ESP8266 mounted on an ESP-01 board will not wake up from deep-sleep because the ESP8266 wake up signal is not connected to the reset pin of the ESP8266 on an ESP-01 board.  You need to add this connection which can be difficult for most people.  You can see the modification in this picture:
[![enter image description here][1]][1]
...which comes from [this instructables posting][2].

If this is too difficult, consider using a different ESP8266 board which brings these ESP8266 pins to board edge connectors.

  [1]: https://i.stack.imgur.com/bdHi8.jpg
  [2]: https://www.instructables.com/id/Enable-DeepSleep-on-an-ESP8266-01/


body:
I am interfacing a CR95HF with an Arduino to detect NFC tags. I have taken the code from [this link][1] as reference. I am able to get the response to the IDN command, and also set the protocol (ISO/IEC 14443-A). But the tag is not detected. What should I do to detect the tag?

  [1]: https://arduino.stackexchange.com/questions/64903/nodemcu-cant-communicate-with-bm019-nfc-via-spi/71935?noredirect=1#comment156745_71935

title: Problem interfacing CR95HF with Arduino Uno

Answers: 0


body:
I'm trying to find a solution for a given task in a problem I want to solve.
Assume I have 6 individual Points in a 3D environment of about 1m³. Each point will be able to change position (almost) freely.
Is there a way I can get the information of which distance each point is to any of the remaining 5 points?
Background Idea for understanding: Say its 2 wooden triangles (one of those points on each angle) and I need to calculate how far and in which direction one is moving from or towards the other.
By comparing all those distances, direction and step-width may be easily calculated.
Are there like "coded" distance-sensors so they don't mix their signals?
Any thoughts highly appreciated.

title: Distance Measurement - between 6 points, individually moving in (almost) any direction within 1m

Answers: 2

body:
The vertices of two (wooden) triangles already constrains the problem - in a positive way - since the inter-point distances of each triangle's vertices is constant. If they were 6 individual, free-floating points, the job would be that much more complex -- 30 unknown distances (each point to each other point), instead of only 18 (each vertex to each of 3 vertices on the other triangle). That's the math part.

The technology part - what kind of sensors - will need more specifics to answer. For instance, ultrasonic sensors may have an interference problem with wooden triangles drifting about. Light and radar may have visibility issues - i.e., can't see certain of the points, depending on the physical shape and implementation of the drifting objects.

body:
You may try to implement some kind of ultrasonic [transponders][]. The
emitter sends a code addressing a specific receiver. Upon recognizing
its address, the receiver replies after a short, fixed delay. The
emitter measures the time it took the response to reach it, and from
there computes the distance.

You may need some kind of omnidirectional transducers (e.g. [this
models][sensortech]) if you want the measurement to work in any
direction. And also a protocol to avoid several emitters talking at the
same time.

This seems to me like a very complex project though.

[transponders]: https://en.wikipedia.org/wiki/Transponder
[sensortech]: https://sensortechcanada.com/products/custom-acoustic-transducers/omnidirectional/


body:
I downloaded the SimpleTimer library from the Arduino's library manager and navigated to Arduino Playground website for some sample code for testing - [SimpleTimer - Arduino Playground][1]. After copying the following code into the Arduino IDE:

    #include <SimpleTimer.h>

    // the timer object
    SimpleTimer timer;

    // a function to be executed periodically
    void repeatMe() {
        Serial.print("Uptime (s): ");
        Serial.println(millis() / 1000);
    }

    void setup() {
        Serial.begin(9600);
        timer.setInterval(1000, repeatMe);
    }

    void loop() {
        timer.run();
    }

I receive the following error:

    exit status 1
    no matching function for call to 'SimpleTimer::setInterval(int, void (&)())'

Please help me out here as I am doing everything according to the instructions given in the arduino playground page of SimpleTimer.

  [1]: https://playground.arduino.cc/Code/SimpleTimer/

title: Unable to compile SimpleTimer code - Exit status 1

Answers: 1

body:
There are quite a few Arduino libraries called “SimpleTimer”. [According
to arduinolibraries.info][arduinolibraries], the one you get through the
library manager is [Alexander Kiryanenko's SimpleTimer][kiryanenko]. The
one described in Arduino Playground is [Marcello Romani's
version][marcelloromani]. You should try the examples that come with the
specific library you install.

[arduinolibraries]: https://www.arduinolibraries.info/libraries/simple-timer
[kiryanenko]: https://github.com/kiryanenko/SimpleTimer
[marcelloromani]: https://github.com/marcelloromani/Arduino-SimpleTimer


body:
I am using NeoPixel strips, and I want to be able to declare a pointer to them, but not initialize them until the `setup` function (because they will initialize with certain variables only made available in `setup`).

For simpler data types, I am just doing:

    int totalNumColors = 4; //number of colors user can cycle through`
    uint32_t* colorArray = new uint32_t[totalNumColors];
    void setup() {
      for (int i=0;i<totalNumColors;i++){
        colorArray[i] = totalColorArray[i];
      }
    }

How do I do this for NeoPixel strip intializers? I tried:

    Adafruit_NeoPixel* pixels = new Adafruit_Neopixel;`

but I get the error:

    expected type-specifier before 'adafruit neopixel'

title: How to declare a pointer for arduino neopixels library so I can set it up in the setup function with dynamic variables?

Answers: 1

body:
You can assign the pointer to NULL, and in the `setup` function give it a value. Note you have to add () for the arguments, even if there are none like in this case. Also you have to include the library (but probably you did but not added in your question).

    #include "Adafruit_NeoPixel.h"

    Adafruit_NeoPixel* pixels = NULL;

    void setup()
    {
      pixels = new Adafruit_NeoPixel();
    }


body:
I have written a code but I am facing a problem in pseudo-code that I am not able to change this code, so can anyone help me in translating the Arduino IDE program code to pseudo-code?

```c++
#define BLYNK_PRINT Serial
#include <SPI.h>
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <SimpleTimer.h>
#include<DHT.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
char auth[] = "py0oKurvtk_Rv2GGkKtghpKqlxLQug8F";
char ssid[] = "Hostal1";
char pass[] = "shakajutt7867";
DHT dht(D4, DHT11);
SimpleTimer timer;
int Relay = D5;
int PIR = D3;
void sendSensor()
{
  float humi = dht.readHumidity();
  float temp = dht.readTemperature();
  int value = digitalRead(PIR);
  if (value == 1)
  {
  digitalWrite(Relay, HIGH);
  Serial.print("Detected");
  Serial.print('\n');
  lcd.setCursor(0,0);
  lcd.print("PIR = Detected");
  lcd.setCursor(0,1);
  lcd.print("T: ");
  lcd.print(temp);
  lcd.setCursor(7,1);
  lcd.print(" H:");
  lcd.print(humi);

  }
  else if (value== 0)
  {
    digitalWrite(Relay, LOW);
    Serial.print("Not Detected");
    Serial.print('\n');
  lcd.setCursor(0,0);
  lcd.print("PIR = Not Det");
  lcd.setCursor(0,1);
  lcd.print("T:");
  lcd.print(temp);
  lcd.setCursor(7,1);
  lcd.print(" H:");
  lcd.print(humi);

  }
  Blynk.virtualWrite(V7, value);
  Blynk.virtualWrite(V5, humi);
  Blynk.virtualWrite(V6, temp);
  delay(1500);
}
void setup()
{
  pinMode(Relay, OUTPUT);
  pinMode(PIR, INPUT);
  digitalWrite(Relay,LOW);
  Serial.begin(115200);
  Blynk.begin(auth, ssid, pass);
  dht.begin();
  lcd.begin(16,2);
  lcd.init();
  lcd.clear();
  lcd.backlight();
  lcd.setCursor(0,0);
  timer.setInterval(1000L, sendSensor);
}
void loop()
{

  Blynk.run();
  timer.run();
}
```

title: Pseudo-code of a program

Answers: 1

body: "Pseudo-code" isn't a programming language. It is just a term that we use when we write code that looks like code but can't be compiled, because it's half-English, half-code. You write pseudo code when you want to communicate to another human how code is supposed to work without getting bogged down in the details.


body:
I have been working on a small switch panel for flight sims, but I wanted to use  the CYT1100 Digital Rotary encoders to move instruments in-game. I have the code  set up to press a certain joystick button for each pulse. The code seems to work fine, but I might have some issues with hardware.

Components:

- Arduino Micro
- CYT1100 Digital Rotary Encoders
- Acer Aspire E5 (Windows 10)

I get serial monitor outputs when I move the board, but the rotary encoders aren't plugged in. The values are around 2 to -2 but don't change depending on the encoders. The joystick buttons are getting almost randomly pressed with no certain pattern. I was wondering if anyone has had issues like this in the past or if I'm missing something.

Here's my code:
```
#include <Joystick.h>

#define outputA 2
#define outputB 3

int counter = 0;
int aState;
int aLastState;

void setup() {
  Joystick.begin();
  pinMode(2, INPUT);
  pinMode(3, INPUT);
}

void loop() {
  aState = digitalRead(outputA);
  if (aState != aLastState) {
    if (digitalRead(outputB) != aState) {      // Clockwise
      Joystick.pressButton(1);
      delay(10);
      Joystick.releaseButton(1);
      counter ++;
    } else {                   // Counterclockwise
      Joystick.pressButton(2);
      delay(10);
      Joystick.releaseButton(2);
      counter --;
    }
    Serial.print("Counter:  ");
    Serial.println(counter);
  }
  aLastState = aState;
}
```

title: Using digital rotary encoders for HID input using the Joystick library

Answers: 0


body:
I don't understand Arudino IDE. Ever.
This is a part of the compilation output:

    Alternatives for ArduinoJson.h: [ArduinoJson@6.14.0]
    ResolveLibrary(ArduinoJson.h)
      -> candidates: [ArduinoJson@6.14.0]
    /home/mark/.arduino15/packages/STM32/tools/xpack-arm-none-eabi-gcc/9.2.1-1.1/bin/arm-none-eabi-g++ -mcpu=cortex-m4 -mfpu=fpv4-sp-d16 -mfloat-abi=hard -mthumb @/tmp/arduino_build_952252/sketch/build_opt.h -c -Os -w -std=gnu++14 -ffunction-sections -fdata-sections -nostdlib -fno-threadsafe-statics --param max-inline-insns-single=500 -fno-rtti -fno-exceptions -fno-use-cxa-atexit -I/home/mark/OSC -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/avr -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/stm32 -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/stm32/LL -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/stm32/usb -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/stm32/usb/hid -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/stm32/usb/cdc -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Drivers/STM32F4xx_HAL_Driver/Inc -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Drivers/STM32F4xx_HAL_Driver/Src -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/STM32F4xx -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Middlewares/ST/STM32_USB_Device_Library/Core/Inc -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Middlewares/ST/STM32_USB_Device_Library/Core/Src -w -x c++ -E -CC -DSTM32F4xx -DARDUINO=10810 -DARDUINO_NUCLEO_F429ZI -DARDUINO_ARCH_STM32 "-DBOARD_NAME=\"NUCLEO_F429ZI\"" -DSTM32F429xx -DHAL_UART_MODULE_ENABLED -I/home/mark/.arduino15/packages/STM32/tools/CMSIS/5.5.1/CMSIS/Core/Include/ -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Drivers/CMSIS/Device/ST/STM32F4xx/Include/ -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Drivers/CMSIS/Device/ST/STM32F4xx/Source/Templates/gcc/ -I/home/mark/.arduino15/packages/STM32/tools/CMSIS/5.5.1/CMSIS/DSP/Include -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/variants/NUCLEO_F429ZI -I/home/mark/Arduino/libraries/STM32duino_LwIP/src -I/home/mark/Arduino/libraries/STM32duino_STM32Ethernet/src -I/home/mark/Arduino/libraries/ArduinoJson/src /tmp/arduino_build_952252/sketch/OSC.ino.cpp -o /dev/null
    Alternatives for FlexyStepper.h: [FlexyStepper@1.0.0]
    ResolveLibrary(FlexyStepper.h)
      -> candidates: [FlexyStepper@1.0.0]
    /home/mark/.arduino15/packages/STM32/tools/xpack-arm-none-eabi-gcc/9.2.1-1.1/bin/arm-none-eabi-g++ -mcpu=cortex-m4 -mfpu=fpv4-sp-d16 -mfloat-abi=hard -mthumb @/tmp/arduino_build_952252/sketch/build_opt.h -c -Os -w -std=gnu++14 -ffunction-sections -fdata-sections -nostdlib -fno-threadsafe-statics --param max-inline-insns-single=500 -fno-rtti -fno-exceptions -fno-use-cxa-atexit -I/home/mark/OSC -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/avr -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/stm32 -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/stm32/LL -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/stm32/usb -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/stm32/usb/hid -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino/stm32/usb/cdc -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Drivers/STM32F4xx_HAL_Driver/Inc -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Drivers/STM32F4xx_HAL_Driver/Src -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/STM32F4xx -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Middlewares/ST/STM32_USB_Device_Library/Core/Inc -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Middlewares/ST/STM32_USB_Device_Library/Core/Src -w -x c++ -E -CC -DSTM32F4xx -DARDUINO=10810 -DARDUINO_NUCLEO_F429ZI -DARDUINO_ARCH_STM32 "-DBOARD_NAME=\"NUCLEO_F429ZI\"" -DSTM32F429xx -DHAL_UART_MODULE_ENABLED -I/home/mark/.arduino15/packages/STM32/tools/CMSIS/5.5.1/CMSIS/Core/Include/ -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Drivers/CMSIS/Device/ST/STM32F4xx/Include/ -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/system/Drivers/CMSIS/Device/ST/STM32F4xx/Source/Templates/gcc/ -I/home/mark/.arduino15/packages/STM32/tools/CMSIS/5.5.1/CMSIS/DSP/Include -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/cores/arduino -I/home/mark/.arduino15/packages/STM32/hardware/stm32/1.8.0/variants/NUCLEO_F429ZI -I/home/mark/Arduino/libraries/STM32duino_LwIP/src -I/home/mark/Arduino/libraries/STM32duino_STM32Ethernet/src -I/home/mark/Arduino/libraries/ArduinoJson/src -I/home/mark/Arduino/libraries/FlexyStepper/src /tmp/arduino_build_952252/sketch/OSC.ino.cpp -o /dev/null
    Alternatives for Tasker.h: [Tasker@2.0]
    ResolveLibrary(Tasker.h)
      -> candidates: [Tasker@2.0]

    Più di una libreria trovata per "ArduinoJson.h"
    Usata: /home/mark/Arduino/libraries/ArduinoJson
    Più di una libreria trovata per "FlexyStepper.h"
    Usata: /home/mark/Arduino/libraries/FlexyStepper
    Più di una libreria trovata per "Tasker.h"
    Usata: /home/mark/Arduino/libraries/Tasker

*Più di una libreria trovata* in English means *more than one library found*.
And *Usata* means *Used*.

It's telling me it finds multiple libraries and selects one among them. Cool. But why it doesn't tell me *where* are the others?

Ok, I do:

    $ sudo find / -name Tasker.h
    /home/mark/Arduino/libraries/Tasker/Tasker.h

the same happens with the others.
So, **where are the multiples libraries it finds**?

title: IDE finds multiple libraries

Answers: 1

body:
When you install your Arduino, 3 locations are used for your libraries:

- Installation folder
- Personal folder
- Boards folder

### Installation folder
This is the location where you installed Arduino. Normally they are:
On Windows: `%ProgramFilesDir%\Arduino\libraries`
On Linux: `/home/{USERNAME}/arduino-{VER}/libraries`
There, you can find 5-10 base libraries.

### Personal folder
Since, on each update, the installation folder is deleted, the sketches and custom libraries are stored in your personal data folder:
On Windows: `%userprofile%\documents\Arduino\libraries`
On Linux: `/home/{USERNAME}/Arduino/libraries/`
There, you can find all libraries that you downloaded from the IDE.

### Boards folder
Some libraries comes with your board and are board optimized. Arduino IDE will always check this folder, before it search for other libraries.
On Windows: `%LOCALAPPDATA%\Arduino15\packages\{BOARD}\hardware\{MODEL}\{VERSION}\libraries`
On Linux: `/home/{USERNAME}/.arduino15/packages/{BOARD}/hardware/{MODEL}/{VERSION}/libraries`

---

As I can see, you have a custom board selected. So the Arduino IDE search on the boards folder. If it can find a library it will take this one. If not, it will search on your personal folder and finally in the installation folder. I am not sure, but it could also get the newer one, if there is a version on it. Can't say how the right library is selected by the IDE.

If more than 1 are found, a warning message will appear. But it is just a message, you can just check if the right library was taken.


body:
    /*
    Please note as I have used the android app you told , the string inputs are taken as
    A,B,C,D,E,F,G and a,b,c,d,e,f,g.
    I have also written code for voice on and off which has all on and all off function
    but since the android app we are using dosent have such key so i didnt took them
    */

    String inputs;
    #define relay1 2 //Connect relay1 to pin 9
    #define relay2 3 //Connect relay2 to pin 8
    #define relay3 4 //Connect relay3 to pin 7
    #define relay4 5 //Connect relay4 to pin 6
    #define relay5 6 //Connect relay5 to pin 5
    #define relay6 7 //Connect relay6 to pin 4
    #define relay7 8 //Connect relay7 to pin 3
    #define relay8 9 //Connect relay8 to pin 2

    void setup()
    {
     Serial.begin(9600); //Set rate for communicating with phone
     pinMode(relay1, OUTPUT); //Set relay1 as an output
     pinMode(relay2, OUTPUT); //Set relay2 as an output
     pinMode(relay3, OUTPUT); //Set relay1 as an output
     pinMode(relay4, OUTPUT); //Set relay2 as an output
     pinMode(relay5, OUTPUT); //Set relay1 as an output
     pinMode(relay6, OUTPUT); //Set relay2 as an output
     pinMode(relay7, OUTPUT); //Set relay1 as an output
     pinMode(relay8, OUTPUT); //Set relay2 as an output
     digitalWrite(relay1, LOW); //Switch relay1 off
     digitalWrite(relay2, LOW); //Swtich relay2 off
     digitalWrite(relay3, LOW); //Switch relay1 off
     digitalWrite(relay4, LOW); //Swtich relay2 off
     digitalWrite(relay5, LOW); //Switch relay1 off
     digitalWrite(relay6, LOW); //Swtich relay2 off
     digitalWrite(relay7, LOW); //Switch relay1 off
     digitalWrite(relay8, LOW); //Swtich relay2 off
    }
    void loop()
    {
     while(Serial.available()) //Check if there are available bytes to read
     {
      delay(10); //Delay to make it stable
      char c = Serial.read(); //Conduct a serial read
      if (c == '#'){
       break; //Stop the loop once # is detected after a word
      }
      inputs += c; //Means inputs = inputs + c
     }
     if (inputs.length() >0)
     {
      Serial.println(inputs);

      if(inputs == "A")
      {
       digitalWrite(relay1, LOW);
      }
      else if(inputs == "a")
      {
       digitalWrite(relay1, HIGH);
      }
      else if(inputs == "B")
      {
       digitalWrite(relay2, LOW);
      }
      else if(inputs == "b")
      {
       digitalWrite(relay2, HIGH);
      }
      else if(inputs == "C")
      {
       digitalWrite(relay3, LOW);
      }
      else if(inputs == "c")
      {
       digitalWrite(relay3, HIGH);
      }
      else if(inputs == "D")
      {
       digitalWrite(relay4, LOW);
      }
      else if(inputs == "d")
      {
       digitalWrite(relay4, HIGH);
      }
      else if(inputs == "E")
      {
       digitalWrite(relay5, LOW);
      }
      else if(inputs == "e")
      {
       digitalWrite(relay5, HIGH);
      }
      else if(inputs == "F")
      {
       digitalWrite(relay6, LOW);
      }
      else if(inputs == "f")
      {
       digitalWrite(relay6, HIGH);
      }
      else if(inputs == "G")
      {
       digitalWrite(relay7, LOW);
      }
      else if(inputs == "g")
      {
       digitalWrite(relay7, HIGH);
      }
      else if(inputs == "H")
      {
       digitalWrite(relay8, LOW);
      }
      else if(inputs == "h")
      {
       digitalWrite(relay8, HIGH);
      }
      inputs="";
     }
    }

title: How to initialize digital output pin as low on arduino board??? I am getting lights on initially and i want lights off

Answers: 0


body:
Here is the shiftOut function code from wiring_shift.c
```
void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
{
     uint8_t i;

     for (i = 0; i < 8; i++)  {
           if (bitOrder == LSBFIRST)
                 digitalWrite(dataPin, !!(val & (1 << i)));
           else
                 digitalWrite(dataPin, !!(val & (1 << (7 - i))));

           digitalWrite(clockPin, HIGH);
           digitalWrite(clockPin, LOW);
     }
}
```
Does this mean that least significant bit is on the left and most significant bit is on the right? Or LSBFIRST means that will be the last outputted bit so it will be "first" in outputted sequence?

One more thing

here is a sample code:
```
shiftOut(dataPin, clockPin, LSBFIRST, B00101001);
shiftOut(dataPin, clockPin, LSBFIRST, B11010011);
```

Why does this
```
union
{
     word uniform;
     byte separate[2];
} state;

state.uniform = 54057; // aka 11010011 00101001
shiftOut(dataPin, clockPin, LSBFIRST, state.separate[1]);
shiftOut(dataPin, clockPin, LSBFIRST, state.separate[0]);
```
have different output but if i swap last two lines it works correctly?

title: LSB/MSB and shiftOut

Answers: 2

body: Integer values of the Arduino have the MSB left and the LSB right. The `shiftOut()` function let's you choose, how the order should be timewise. If you provide `LSBFIRST`, the function will start the transmit with the LSB (on the right) and then go left to the MSB. Otherwise it will start with the MSB and then go right to the LSB. So this effects only the time order of the bits, in that they get transmitted.

body:
There is no "left" or "right" in a binary number, only in the human representation of that number.

It is traditional for us to place the most significant bit on the left, purely because that his how we represent other numbers - like 1234 (1 is the most significant digit, the thousands).

Given the pseudo-number `12345678` if you shift out LSBFIRST the 8 gets output first, then the 7, then the 6, etc. In MSBFIRST the 1 gets output first, then the 2, then the 3, etc.


body:
I am trying to implement a mDNS for esp8266 in Arduino IDE following this guide.

https://tttapa.github.io/ESP8266/Chap08 - mDNS.html

I cannot get the esp8266.local name to work - when i ping it it returns an error unresolved host and putting it in a browser also does not resolve...

The IP address does resolve though. Any advice would be greatly appreciated. I am using Mac OS High Sierra and have seen that many people have experienced this problem on both windows and mac but there does not seem to be a solution yet.

Any ideas?

Thanks x

title: ESP8266 unresolved mDNS host in .local domain

Answers: 1

body:
There is a known bug in the example code you are using.  The author has been notified on github but has apparently chosen to not update their published code.

You need to add the following line to the loop() { } ; section of the code :    **MDNS.update();**

```
 void loop() {
    MDNS.update();
 }
```
Once you do that. it should start working. And without that there is not way to get it working.

Adding this comment for anyone following and searching for a solution to this same problem.


body:
    int mamank=13;
    void setup() {
      pinMode (mamank,OUTPUT);
      Serial.begin(9600);
    }

    void loop() {
      int sensorValue = analogRead(A0);
      Serial.println(sensorValue);
      if(sensorValue>550)digitalWrite(mamank,HIGH);
      else if(sensorValue<500)digitalWrite(mamank,LOW);
      delay(100);
    }

-----------------------------------------------AND this code----------------------

    int red=2;
    int green=3;
    int blue=4;

    void setup () {
      pinMode (red,OUTPUT);
      pinMode (green,OUTPUT);
      pinMode (blue,OUTPUT);
      Serial.begin (9600);}

    void loop() {
      // read the input on analog pin 0:
      int value = analogRead(A1);

      if (value > 500) {
        Serial.println("Very heavy Rain");
        digitalWrite (red,HIGH);
        digitalWrite(green,LOW);
        digitalWrite(blue,LOW);}
      else if ((value > 300) && (value <= 500)) {
        Serial.println("AVERAGE Rain");
        digitalWrite (green,HIGH);
        digitalWrite (red,LOW);
        }
      else{
        Serial.println("Dry Weather");
        digitalWrite (blue,HIGH);
        digitalWrite (red,LOW);
        digitalWrite (green,LOW);
      delay(100);
      }
      }

title: how to combine two code of arduino uno

Answers: 1

body:
Put the stuff before setup() together, fix any duplicates:

    int mamank=13; <<< pin assignment? If yes, this can be byte
    int red=2; <<< pin assignment? If yes, this can be byte
    int green=3; <<< pin assignment? If yes, this can be byte
    int blue=4; <<< pin assignment? If yes, this can be byte

Put the stuff in setup() together, fix any duplicates

    void setup() {
    pinMode (mamank,OUTPUT);
    Serial.begin(9600);
    pinMode (red,OUTPUT);
    pinMode (green,OUTPUT);
    pinMode (blue,OUTPUT);
    Serial.begin(9600);  <<< duplicate, so delete this line
    }

Put the stuff in loop() together, then check the desired functionality:

    void loop() {
    int sensorValue = analogRead(A0);
    Serial.println(sensorValue);
    if (sensorValue>550) {
    digitalWrite(mamank,HIGH);
    }
    else if (sensorValue<500) {
    digitalWrite(mamank,LOW);
    }
    delay(100);
    // read the input on analog pin 0:
    int value = analogRead(A1);
    if (value > 500) {
    Serial.println("Very heavy Rain");
    digitalWrite (red,HIGH);
    digitalWrite(green,LOW);
    digitalWrite(blue,LOW);
    }
    else if ((value > 300) && (value <= 500)) {
    digitalWrite (green,HIGH);
    digitalWrite (red,LOW);
    }
    else {
    Serial.println("Dry Weather");
    digitalWrite (blue,HIGH);
    digitalWrite (red,LOW);
    digitalWrite (green,LOW);
    delay(100);
    }

    }


body:
I'm programming a ESP32 modue and I have a code that generates an Access Point and displays an html with two buttons that changes the state of 3 leDs. I want to insert a button that calls a second html code that is within (void engine() ) and on this page has the following text ( This page turns on the engine ). Detail: The page that is already displaying in the browser has to be updated by the new html code of the second html page. How can I change my Code to get this third button ?

    #include <WiFi.h>
    #include <WebServer.h>

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

    WiFiServer server(80);

    String header;

    String output26State = "off";
    String output27State = "off";

    const int output26 = 26;
    const int output27 = 27;

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

     pinMode(output26, OUTPUT);
     pinMode(output27, OUTPUT);

     digitalWrite(output26, LOW);
     digitalWrite(output27, LOW);

     WiFi.softAP(ssid, password);
     delay(10);

     IPAddress IP = WiFi.softAPIP();
     Serial.print("IP Address: ");
     Serial.println(IP);

     server.begin();

    }

    void one()
    {
      WiFiClient client = server.available();
      client.println("
Page One
");
      client.println("
<button class=\"button\">Pag Two 2</button>
");
      client.println();
    }

    void two()
    {
      WiFiClient client = server.available();   // Listen for incoming clients
      client.println("
Page Two
");
      client.println("
<button class=\"button\">Page One 1</button>
");
      client.println();
    }

    void loop()
    {
     WiFiClient client = server.available();   // Listen for incoming clients

     if (client)
     {                             // If a new client connects,
      Serial.println("New Client.");          // print a message out in 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
        header += c;
        if (c == '\n')                      // if the byte is a newline character
        {
          if (currentLine.length() == 0)
          {

           client.println("HTTP/1.1 200 OK");
           client.println("Content-type:text/html");
           client.println("Connection: close");
           client.println("<!DOCTYPE html>");
           client.println("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
           client.println("<link rel=\"icon\" href=\"data:,\">");
           client.println("");
           client.println("");
           client.println();

           if (header.indexOf("GET /one") >= 0)
           {
            Serial.println("Page One");
            output26State = "on";
            digitalWrite(output26, HIGH);
            one();
           }
           else if (header.indexOf("GET /two") >= 0)
           {
            Serial.println("Page Two");
            output26State = "off";
            digitalWrite(output26, LOW);
            two();
           }
           client.println("
<button class=\"button\">Page Two</button>
");
           client.println("");
           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
        }
      }
    }

     header = "";
     client.stop();
     Serial.println("Client OFF.");
     }

    }

Thank You

title: ESP32 - Html link

Answers: 0


body:
HC-05 Bluetooth module does not send or receive data when its on-board light blinks(light blinking after its connected to a device)
as soon as the on-board led starts glowing it does not send or receive data but when the light turns off it works perfectly.

Answers: 0


body:
```
#include <ESP8266WiFi.h>

#include <ESP8266HTTPClient.h>
#include <WiFiClientSecureBearSSL.h>

#define WIFI_SSID "ssid"
#define WIFI_PASSWORD "password"

void setup() {
  Serial.begin(9600);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();
  ////////////////////////////////////////////

  std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
  client->setInsecure();
  HTTPClient http;

  http.begin(*client, "https://jsonplaceholder.typicode.com/photos");
  http.addHeader("Accept", "*/*");

  int httpCode = http.GET();
  Serial.print("HTTP CODE: "); Serial.println(httpCode);

  //reading response with buffer
  static char buff[128] = { 0 };
  while (http.connected() ) {
    size_t size = client->available();
    if (size) {
      int c = client->readBytes(buff, ((size > sizeof(buff) ) ? sizeof(buff) : size));
      //if i uncomment this next line, everything is fine.
      //Serial.write(buff, c); Serial.println();

      //but if i dont use serial.write program never gets here
      if (char * pch = strstr (buff, "quis fuga")) {
        char str[20] = { 0 }; int g =   0 ;
        while (pch[g] != '\"') {
          str[g] = pch[ g];
          g++;
        }
        Serial.print("FOUND IT: "); Serial.println(str);
      }

    }
    else if (!size) {
      Serial.println( "reading done");
      break;
    }
    delay(1);
  }

}

void loop() {

  delay(222222);

}

```
**EDIT**
here i created a compilable runnable code. basically i am trying to find a word in a http response. my real example`s response isnt json and it is as long as this example`s response. one other problem is i cant read all of the repsponse. it unexpectedly finishes reading sometimes after a few lines sometimes after a few hundred. in this particular request my nodemcu cant read after id 258. or id 8. object in the json response: <https://jsonplaceholder.typicode.com/photos>

if i dont use serial.write print buffer content, it finishes reading immideatly and thats exactly where i have the problem.

title: I can't use buffer without printing in my Nodemcu esp8266

Answers: 1

body:
The Serial printing creates a delay. That delay enables to collect more characters in the buffer. If you read the input in small pieces (3 to 10 bytes) then the buffer doesn't contain the searched substring because it splits into two subsequent buffers. Even if you could read full buffers, it still can happen that the search string will be split.

To search for a string in a stream of data you can use function `find(string)`. The networking Client class inherits this function from Arduino Stream class. `find` will read the stream until it finds the searched string. Then the next read from the stream will read the data right after the searched string.


body:
This is NOT my code; was [posted on Project Hub](https://projects.digilentinc.com/Shaeroden/humidity-controller-c13dad).   I tried to use the code (humidity controller) but it returns an error on line 270:

    else if (DHT.humidity >= setpoint + 3 and syson == true) { //if humidity is 3% above setpoint
Error: expected primary-expression before '.' token

The OP is not responding to comments and I'm no expert.   Would appreciate if someone could help debug the code;
Thanks!

           //HUMIDITY CONTROLLER 1.1
    //written for NANO

    //controls and displays relative humidity
    //sesnor used is DHT11
    //uses active-low relay module to control live lines for 2 standard electrical outlets
    //uses i2c lcd to display humidity and humidity setting
    //turns display off during inactivity
    //setting is adjustable from 10%-90% using 2 buttons
    //backlight of LCD is controlled by pin 4, connected to top LED jumper pin on i2c backpack
    //serial communications to monitor to ensure all code is working.

    //added: "system off" function - allows both outlets to be turned off

    // █ G █ L █ O █ B █ A █ L █ S █
    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    #include <dht.h>

    // set the LCD address to 0x27 for a 16 chars and 2 line display
    LiquidCrystal_I2C lcd(0x27, 16, 2);

    dht DHT;

    #define DHT11_PIN A2

    //buttons and variables to adjust calibration
    int calupbtn = A0;
    int calup;
    int caldownbtn = A1;
    int caldown;

    //i2c PINS A4, A5

    //pin for turning on humidifier relay
    int humidifier = 3;
    //pin for turning on the fan relay
    int fan = 2;
    //pin for turning on LCD backlights
    int lcdlight = 4;

    //calibration variable
    int setpoint = 50;  //feedback setpoint.
    bool calstate = false;  //enables calibration adjustments only when LCD is ON.

    //backlight timing variables
    int displtime = 12000;  //amount of time the display is to be on before turning off
    unsigned long displtimeon;  //last recorded time display timer was reset
    int calunlock = 0;   //loop counter for unlocking calibration

    //sensor timing variables
    unsigned long lastcheck;  //last time DHT was read
    long interval = 30000;      //time between DHT readings

    //system variables
    bool syson = true;    //reference for system on/off.
    byte systog = 2;       //even number toggles on, odds toggle off
    int syslock = 0;     //loop counter for unlocking system toggle

    // █ S █ E █ T █ U █ P █ + █ + █ + █ + █ + █ + █ + █ + █ + █ + █ + █ + █ + █ + █
    void setup(){

      Serial.begin(9600);  //serial communication used to ensure code is working correctly.

      lcd.init();  //initialize LCD
      lcd.backlight(); //enable LCD backlight, but doesn't turn it on

      lastcheck = 0;
      digitalWrite(lcdlight, HIGH);
      Serial.println("STARTING");
      lcd.print("   STARTING");

      //pin assignments
      pinMode(calupbtn, INPUT);
      pinMode(caldownbtn, INPUT);
      pinMode(humidifier, OUTPUT);
      pinMode(fan, OUTPUT);
      pinMode(lcdlight, OUTPUT);
      delay(1000);

      //test fan
      lcd.setCursor(0,1);
      lcd.print("<FAN>     HMDFR  ");
      digitalWrite(fan, LOW);
      digitalWrite(humidifier, HIGH);
      delay(6000);
      //test humidifier
      lcd.setCursor(0,1);
      lcd.print(" FAN     <HMDFR> ");
      digitalWrite(fan, HIGH);
      digitalWrite(humidifier, LOW);
      delay(6000);
      //stop startup test
      digitalWrite(humidifier, HIGH);
      digitalWrite(fan, HIGH);
      lcd.clear();

      displtimeon = millis();

      int chk = DHT.read11(DHT11_PIN);
      lastcheck = millis();

      lcd.setCursor(0,0);
      lcd.print("Humidity: ");
      lcd.setCursor(13,0);
      lcd.print(DHT.humidity);
      lcd.setCursor(15,0);
      lcd.print("%  ");
      lcd.setCursor(0,1);
      lcd.print("setting: ");
      lcd.setCursor(13,1);
      lcd.print(setpoint);
      lcd.setCursor(15,1);
      lcd.print("%  ");
      delay(100);
    }

    // █ L █ O █ O █ P █ = █ = █ = █ = █ = █ = █ = █ = █ = █ = █ = █ = █ = █ = █ = █
    void loop(){

      //check calibration buttons
      calup = digitalRead(calupbtn);
      caldown = digitalRead(caldownbtn);

      if(calup == HIGH and caldown == HIGH){  //--------SYSTEM TOGGLE
        syslock ++;
        Serial.println(syslock);
        if(syslock == 20){  //if both buttons held down for this many loops
          systog++;
          if(systog % 2 == 1){  //--------SYSTEM OFF
            syson = false;
            digitalWrite(fan, HIGH);
            digitalWrite(humidifier, HIGH);
            digitalWrite(lcdlight, HIGH);
            Serial.println("SYSTEM TURNED OFF");
            lcd.clear();
            lcd.print("   SYSTEM OFF");
            lcd.setCursor(0,1);
            lcd.print("  hold both btns");
            delay(2000);
            lcd.setCursor(0,1);
            lcd.print("  to turn on    ");
            displtimeon = millis();
          }
          if(systog % 2 == 0){  //--------SYSTEM ON
            syson = true;
            Serial.println("SYSTEM TURNED ON");
            digitalWrite(lcdlight, HIGH);
            lcd.clear();
            lcd.print("   SYSTEM ON");
            delay(2000);
            lcd.clear();
            displtimeon = millis();
          }
          syslock = 0;
        }
      }
      else(syslock = 0);

      //read humidity at appropriate intervals
      if(millis() > lastcheck + interval and syson == true){  //read the DHT humidity
        int chk = DHT.read11(DHT11_PIN);
        lastcheck = millis();
        Serial.print("DHT read = ");
        Serial.print(DHT.humidity);
        Serial.print("%");
        Serial.println(" ");
        }

      //turn on the led lights when calibration buttons are pressed
      if(calup == HIGH xor caldown == HIGH){
        digitalWrite(lcdlight, HIGH);
        calstate = true;
        displtimeon = millis();  //set display timer
        Serial.println("cal btn ACTIVE");
        if(syson == false){
          digitalWrite(lcdlight, HIGH);
          lcd.clear();
          lcd.print("   SYSTEM OFF");
          lcd.setCursor(0,1);
          lcd.print("  hold both btns");
          delay(3000);
          lcd.setCursor(0,1);
          lcd.print("  to turn on    ");
          displtimeon = millis();
        }
      }

      if(calstate == true and syson == true){  //--------DISPLAY ROUTINE
        Serial.println("printing display");
        //display variables on LCD
        lcd.setCursor(0,0);
        lcd.print("Humidity: ");
        lcd.setCursor(13,0);
        lcd.print(DHT.humidity);
        lcd.setCursor(15,0);
        lcd.print("%  ");
        lcd.setCursor(0,1);
        lcd.print("setting: ");
        lcd.setCursor(13,1);
        lcd.print(setpoint);
        lcd.setCursor(15,1);
        lcd.print("%  ");
        delay(100);

        calunlock ++;
        //keeps calibration locked until display cycles 5 times after initially turned on
        //prevents adjustments on initial button press.
      }

    //--------CALIBRATION ADJUSTMENTS
      if(calup == HIGH and caldown == LOW and calstate == true and syson == true){
        if(setpoint < 90 and calunlock > 5){
          setpoint = setpoint + 5;  //increase setpoint
          Serial.println("adj setpoint up");
        }
        Serial.println(setpoint);
        delay(100);
        displtimeon = millis();     //reset backlight timeout
      }

      if(caldown == HIGH and calup == LOW and calstate == true and syson == true){
        if(setpoint > 10 and calunlock > 5){
          setpoint = setpoint - 5;  //decrease setpoint
          Serial.println("adj setpoint dn");
          }
        Serial.println(setpoint);
        delay(100);
        displtimeon = millis();     //reset backlight timeout
      }

      if(millis() > displtimeon + displtime){  //-----------------BACKLIGHT TIMEOUT
        digitalWrite(lcdlight, LOW); //turn off the screen
        calstate = false;
        Serial.println("displ + backlights off");
        lcd.clear();
        calunlock = 0;  //lock calibration
      }

      if(millis() < lastcheck){
        lastcheck = millis();  //reset timers in a millisecond rollover
      }

                                          //--------SETPOINT ERROR PROCEDURE
      if(setpoint > 91 or setpoint < 9){  //in case setpoint is ever out of bounds
        Serial.println("O/B ERROR");
        digitalWrite(lcdlight, HIGH);
        lcd.clear();
        lcd.print("O/B ERROR");  //display error message on lcd
        lcd.setCursor(0,1);
        lcd.print("RESETTING");
        delay(1000);
        for(int count = 9; count >= 0; count = count - 1){
          lcd.setCursor(15,1);
          lcd.print(count);     //count down from 10
          delay(1000);
        }
        setpoint = 50;        //reset setpoint at 50.
        displtimeon = millis();
      }

      //turn on humidifier relay if below setpoint  --------RELAY CONTROL
      //RELAY MODULE IS ACTIVE LOW
      if(DHT.humidity <= setpoint - 3 and syson == true){  //if humidity is 3% lower than setpoint
        Serial.println("humidifier ON, fan OFF");
        digitalWrite(humidifier, LOW);  //turn on humidifier
        digitalWrite(fan, HIGH);
      }
      else if(DHT.humidity >= setpoint + 3 and syson == true){  //if humidity is 3% above setpoint
        Serial.println("humidifier OFF, fan ON");
        digitalWrite(humidifier, HIGH);  //turn on fan
        digitalWrite(fan, LOW);
      }
      else{
        Serial.println("all off");  //if humidity is within 3% of setpoint
        digitalWrite(humidifier, HIGH);  //turn both off
        digitalWrite(fan, HIGH);
      }
      //delay(700);  //un-comment for serial debugging

      Serial.print("setpoint = ");
      Serial.println(setpoint);

      //delay(700);  //un-comment for serial debugging
    }

    /*  WIRING DIAGRAMS
     https://66.media.tumblr.com/98426b566744beacdd42bc0221092b76/tumblr_pvr0u8kvZy1yrmjh9o1_1280.png
     */

title: Help with debugging code

Answers: 1

body:
You have installed the Adafruit DHT library via the Arduino library manager

[![Adafruit library][1]][1]

The source code does not work with that library. It is written to use the DHT library written by Rob Tillaart, named [DHTLib](https://github.com/RobTillaart/Arduino/tree/master/libraries/DHTlib). That library is not included in the Library Manager of the Arduino IDE. Instead, you have to download [the library as a ZIP file](https://lastminuteengineers.com/libraries/DHTlib.zip) and install it via Sketch / Include Library / Add .ZIP library.

[![How to install][2]][2]

I don't know why you have changed the source code in the meanwhile. Using DHTLib with the source code of [revision 1](https://arduino.stackexchange.com/revisions/72003/1) of your question works fine. In the meanwhile you have tried to adapt the code to match the Adafruit library, which eventually might be ok as well after some hard work. I suggest rolling back to the code of revision 1 and installing the correct library.

  [1]: https://i.stack.imgur.com/QCuJx.png
  [2]: https://i.stack.imgur.com/AnEM4.png


body:
Thank you for reading my post. I have been stuck on this for several weeks now! I am trying to turn ON/OFF a DC motor from Arduino IOT Cloud. I have set up the cloud and added the switch. Everything works well with an LED: it lights on and off as needed, but the motor does not turn on or off. Below is the circuit I have set up.

[![Circuit Design][1]][1]

My circuit specs are as follows:

 1. I'm not using a UNO as the image illustrates, rather I'm using an [Arduino MKR WiFi 1010][2], but the connections of the pins are exactly the same: LED at PIN 3 and Motor at 7.
 2. The diode I am using is [1N4001][3].
 3. The transistor I'm using is [TIP120][4].
 4. The motor I'm using is [5V DC Motor][5].
 5. 270 Ohm resistor on the transistor circuit and 220 Ohm on the LED circuit.

The Arduino code I made is as follows:

```
#include "thingProperties.h"

#define LED_PIN 3
#define MOTOR_PIN 7

void setup() {
  pinMode(LED_PIN, OUTPUT);
  pinMode(MOTOR_PIN, OUTPUT);

  setDebugMessageLevel(2); // For debugging of cloud integration
  Serial.begin(9600);
  delay(1500);

  initProperties(); // initialize cloud properties
  ArduinoCloud.begin(ArduinoIoTPreferredConnection); // Connect to cloud
}

void loop() {
  ArduinoCloud.update(); // Update cloud background services
}

void onMotorChange() {
  if (motor) {
    // Motor & LED ON
    digitalWrite(LED_PIN, HIGH);
    digitalWrite(MOTOR_PIN, HIGH);
  } else {
    // Motor & LED OFF
    digitalWrite(LED_PIN, LOW);
    digitalWrite(MOTOR_PIN, LOW);
  }
}
```

All my setup seems to be be correct, but it just is not working. I have researched a lot but to no avail. I have tested with a different motor just to be sure, but it also does not work. I'm not sure where I have made a mistake.

Please help me. Thank you very much.

  [1]: https://i.stack.imgur.com/4jDRa.png
  [2]: https://www.seeedstudio.com/ARDUINO-MKR-WiFi-1010-p-46.html
  [3]: https://www.amazon.com/Switching-Rectifier-14-Electronic-Assortment/dp/B07BTY8FD2/ref=sr_1_5?keywords=1N4001 DIODE&qid=1576622652&sr=8-5
  [4]: https://www.amazon.com/Bridgold-TIP120-Darlington-Bipolar-Transistor/dp/B07LG2C3MY/ref=sr_1_1?keywords=TIP120 60V 5A NPN Darlington Bipolar Power Transistor TO&qid=1576622562&sr=8-1
  [5]: https://www.amazon.com/gp/product/B07P18SQSR/ref=ppx_yo_dt_b_asin_title_o00_s02?ie=UTF8&psc=1

title: Arduino MKR 10100 control DC Motor

Answers: 2

body:
The TIP120 is a poor choice because of the approximate 10% - 14% voltage drop across it. Try the circuit with a logic level, low Rds MOSFET.

For a more in-depth answer, please see this answer: https://electronics.stackexchange.com/a/388468/165322

body:
Okay i managed to solve it, the issue was actually my circuit wiring. Below is an image with the correct setup for the transistor or MOSFET.

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

I have changed the TIP120 to RFP30N06LE as [VE7JRO][2] suggested:

> The TIP120 is a poor choice because of the approximate 10% - 14% voltage drop across it. Try the circuit with a logic level, low Rds MOSFET.

but that with the circuit in question does not work. I have not tested the circuit attached with this answer using a TIP120 but i suspect it would work as well.
Finally i added a 9V battery as [jsotola][3] suggested:

> never use an arduino as a power supply ... there is a good chance that the arduino will become an expensive fuse

but i have not tested using the 5V Arduino pin again i suspect it would work as well.

## Bonus: ##
If anyone was wondering how i made these images i used [TinkerCAD][4]

Thank you all

Hope this Helps!

  [1]: https://i.stack.imgur.com/JOEGk.png
  [2]: https://arduino.stackexchange.com/users/37523/ve7jro
  [3]: https://arduino.stackexchange.com/users/40318/jsotola
  [4]: https://www.tinkercad.com


body:
I have been able to get the current time from an NTP server and set what appears to be an internal clock using the `configTime()` function from the ESP32 core.  I can then get the current time with the function `getLocalTime()`.

I would like to be able to set the time returned by `getLocalTime()` from user input rather than from an NTP server.  I would also like to be able to update the GMT Offset without needing to reconnect to the server.

How do I interact with the clock value used by `getLocalTime()`? Is there documentation for this clock somewhere?

-----

per request the `SimpleTime` example from the ESP32 [install][1]:

    #include <WiFi.h>
    #include "time.h"

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

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

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

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

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

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

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

    void loop()
    {
      delay(1000);
      printLocalTime();
    }

  [1]: https://randomnerdtutorials.com/installing-the-esp32-board-in-arduino-ide-windows-instructions/

title: Set the wall clock time or change GMT offset without ntp server?

Answers: 1

body:
The functions configTime and getLocalTime are from ESP32 core file [esp32-hal-time.c][1]. This wraps the ESP32 SDK functions. You can use the SDK functions to set the time and zone. They work with the RTC peripheral of the ESP32.

You can use setTimeZone to set the time zone.

The time.h is standard C time library. The ESP32 SDK makes it to work with the built in RTC ([reference][2]). To set the time it gets complicated. You would have to use undocumented SDK [time functions][3].

  [1]: https://github.com/espressif/arduino-esp32/blob/f41beb92bf4434f52209bd15655c1b2f2447447f/cores/esp32/esp32-hal-time.c
  [2]: https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/system/system_time.html#get-current-time
  [3]: https://github.com/espressif/esp-idf/blob/master/components/newlib/time.c


body:
I am trying to program a Teensy 3.2 to act as a lightsaber controller. My code works perfectly but I can't select a port. How should I fix this problem?

Here is my code:

    /* Presented without warranty, guarantee and support.
        By Bob Clagett - I Like To Make Stuff

       This is the code to accompany the lightsaber project at http://www.iliketomakestuff.com/make-lightsaber/
       Expected hardware is listed in post (Teensy 3.2, Prop Shield, DotStar LEDs)

       This is functional v1 of this code.  Lots more I want to add to it including crash detection/sounds.
       This code is dirty, bulky, poorly documented and ugly but I finally got it all functional.
       Cleanup to come later in v2.
    */

    #include <SerialFlash.h>
    #include <Wire.h>
    #include <SPI.h>
    #include <SD.h>

    // GUItool: begin automatically generated code

    // GUItool: end automatically generated code

    #include <Adafruit_DotStar.h>
    #include <NXPMotionSense.h>

    NXPMotionSense imu;
    NXPSensorFusion filter;

    int motionThreshold = 2;

    float lastPitch = 0, lastRoll = 0, lastHeading = 0;

    int buttonState = HIGH;
    int bladeState = 0; //0 off, 1, fading up, 2 on, 3 fading down
    int fadeStep = 0;
    int fadeStepSize = 6;
    int selectedColor = 0;
    int lastSelectedColor = 0;
    bool isAnimating = 0;
    bool bladeOn = 0;
    long lastDebounceTime = 0;  // the last time the output pin was toggled
    long debounceDelay = 50;
    int lastButtonState = HIGH;
    int pendingPress = 0;

    //BC = Blade Color
    int BCbuttonState = HIGH;
    long BClastDebounceTime = 0;  // the last time the output pin was toggled
    long BCdebounceDelay = 50;
    int BClastButtonState = HIGH;
    int BCpendingPress = 0;
    int pendingColorPress = 0;

    #define COLOR_BUTTON_PIN 1
    #define POWER_BUTTON_PIN 0
    #define COLOR_ORDER BGR
    #define CHIPSET     APA102
    #define NUMPIXELS    252

    #define BRIGHTNESS  100
    #define FRAMES_PER_SECOND 70

    #define PROP_AMP_ENABLE 5
    #define FLASH_CHIP_SELECT 6
    #define LED_BUFFER_SELECT 7

    #define VOLUME_POT 15

    #define LED_PIN    7
    Adafruit_DotStar strip = Adafruit_DotStar(
                               NUMPIXELS, DOTSTAR_BRG);

    int outputValue = 0;
    int presetColors[] = {0x0000FF, 0x00FF00, 0xFF0000, 0xFFFFFF};
    int totalPresetColors = (sizeof(presetColors) / sizeof(int));
    int selectedColorIndex = 0;

    int swingSounds = 4;
    int lastSwingSound = swingSounds;

    int clashSounds = 0;
    void setup() {
      delay(500); // sanity delay
      imu.begin();
      filter.begin(100);
    #if defined(__AVR_ATtiny85__) && (F_CPU == 16000000L)
      clock_prescale_set(clock_div_1); // Enable 16 MHz on Trinket
    #endif

      strip.begin(); // Initialize pins for output
      strip.show();  // Turn all LEDs off ASAP

      pinMode(POWER_BUTTON_PIN, INPUT);
      pinMode(COLOR_BUTTON_PIN, INPUT);
      pinMode(LED_PIN, OUTPUT);
      digitalWrite(POWER_BUTTON_PIN, HIGH);
      digitalWrite(COLOR_BUTTON_PIN, HIGH);
      digitalWrite(LED_PIN, LOW);

      Serial.begin(9600);
      // wait up to 3 seconds for the Serial device to become available
      long unsigned debug_start = millis ();
      while (!Serial && ((millis () - debug_start) <= 3000))
        ;

      Serial.println ("Start prop shield RAW player");
      SPI.begin();
      // Enable the amplifier on the prop shield
      pinMode(PROP_AMP_ENABLE, OUTPUT);
      digitalWrite(PROP_AMP_ENABLE, HIGH);
      pinMode(LED_BUFFER_SELECT, OUTPUT);
      digitalWrite(LED_BUFFER_SELECT, HIGH);

      // Audio connections require memory to work.  For more
      // detailed information, see the MemoryAndCpuUsage example

      // Set initial volume

      // Start SerialFlash
      if (!SerialFlash.begin(FLASH_CHIP_SELECT)) {
        while (1)
        {
          Serial.println ("Cannot access SPI Flash chip");
          delay (3000);
        }
      }

    }

    void powerUpBlade() {

      isAnimating = 1;
      bladeState = 1;
      Serial.println("Turn on blade");
      bladeOn = 1;

    }

    void powerDownBlade() {
      //animate DOWN

      bladeState = 3;
      fadeStep = NUMPIXELS;
      isAnimating = 1;
      Serial.println("Turn off blade");

      bladeOn = 0;
    }

    void bladeIsOn() {

    }
    //nothing needed here unless adding animation

    void bladeIsAnimatingUp() {
      //Serial.println("bladeIsAnimatingUp");
      int midpoint = NUMPIXELS / 2;
      int newSection = fadeStep + fadeStepSize;
      for ( int j = fadeStep; j < newSection; j++) {
        strip.setPixelColor(j, selectedColor);
        strip.setPixelColor(NUMPIXELS - j, selectedColor);
      }
      Serial.println(newSection);
      fadeStep = newSection;

      if (fadeStep >= midpoint + fadeStepSize) {

        fadeStep = NUMPIXELS;
        isAnimating = 0;
        bladeState = 2;
        //      delay(200);
        Serial.println("blade up complete");

      }
    }

    void bladeIsAnimatingDown() {
      //Serial.println("bladeIsAnimatingDown");
      int midpoint = NUMPIXELS / 2;
      int newSection = fadeStep - fadeStepSize;
      for ( int j = fadeStep; j > newSection; j--) {

        strip.setPixelColor(j - midpoint, 0x000000);

        strip.setPixelColor(midpoint + NUMPIXELS - j, 0x000000);
      }
      //Serial.println(fadeStep);
      fadeStep = newSection;

      if (fadeStep <= midpoint - fadeStepSize) {
        fadeStep = 0;
        isAnimating = 0;
        bladeState = 0;
      }
    }

    void detectMotion() {
      float ax, ay, az;
      float gx, gy, gz;
      float mx, my, mz;
      float roll, pitch, heading;

      if (imu.available()) {
        // Read the motion sensors
        imu.readMotionSensor(ax, ay, az, gx, gy, gz, mx, my, mz);

        // Update the SensorFusion filter
        filter.update(gx, gy, gz, ax, ay, az, mx, my, mz);

        // print the heading, pitch and roll
        roll = filter.getRoll();
        pitch = filter.getPitch();
        heading = filter.getYaw();

        // does it need a time threshold too?

        float headingDiff = abs(lastHeading - heading);
        float pitchDiff = abs(lastPitch - pitch);
        if (lastHeading != 0) {
          if (pitchDiff > motionThreshold || headingDiff > motionThreshold) {
            //cyle through swing sounds
            lastSwingSound++;
            if (lastSwingSound > swingSounds) {
              lastSwingSound = 1;
            }
            String swingFile = "saberswingX.raw";

            char charBuf[50];
            swingFile.toCharArray(charBuf, 50);
            triggerSwing(charBuf);  // needs sequence to iterate through
          }
        }
        lastHeading = heading;
        lastPitch = pitch;
      }

    }
    void loop() {
      // Add entropy to random number generator; we use a lot of it.
      // random16_add_entropy( random() );

      //handle color selector button
      int BCreading = digitalRead(COLOR_BUTTON_PIN);

      if (BCreading != BClastButtonState) {
        // reset the debouncing timer
        BClastDebounceTime = millis();
      }

      if ((millis() - BClastDebounceTime) > BCdebounceDelay) {
        if (BCreading != BCbuttonState) {
          BCbuttonState = BCreading;

          if (BCbuttonState == HIGH) {
            nextColor();
          }
        }
      }
      BClastButtonState = BCreading;

      selectedColor = presetColors[selectedColorIndex];
      if (selectedColor != lastSelectedColor && bladeState != 0) {
        Serial.print("COLOR CHANGE");
        Serial.println(selectedColorIndex);
        for ( int j = 0; j < NUMPIXELS; j++) {
          strip.setPixelColor(j, selectedColor);
        }
      }
      lastSelectedColor = selectedColor;

      //handle blade on/off

      int reading = digitalRead(POWER_BUTTON_PIN);
      //debounce
      if (reading != lastButtonState) {
        // reset the debouncing timer
        lastDebounceTime = millis();
      }

      if ((millis() - lastDebounceTime) > debounceDelay) {
        if (reading != buttonState) {
          buttonState = reading;
        }
      }
      lastButtonState = reading;

      if ( pendingPress == 1 && buttonState != LOW) {
        buttonState = HIGH;
        pendingPress = 0;
        Serial.print("execute pending blade press");

        if (bladeOn) {
          powerDownBlade();
        } else {
          powerUpBlade();
        }
      }

      if (buttonState == LOW && !isAnimating) {
        Serial.println("BLADE BUTTON IS PRESSED");
        pendingPress = 1;
      }
      switch (bladeState) {
        case 0:
          //blade is off
          break;
        case 1:
          //blade is animating up
          bladeIsAnimatingUp();
          break;
        case 2:
          //blade is on
          bladeIsOn();
          break;
        case 3:
          //blade is animating down
          bladeIsAnimatingDown();
          break;
      }
      SPI.beginTransaction(SPISettings(10000000, MSBFIRST, SPI_MODE0));
      digitalWrite(LED_PIN, HIGH);  // enable access to LEDs
      strip.show();                     // Refresh strip
      digitalWrite(LED_PIN, LOW);
      SPI.endTransaction();   // allow other libs to use SPI again

      delay(10);

      if (bladeState == 2) {
        detectMotion();
      }

    }
    void nextColor() {
      selectedColorIndex++;
      if (selectedColorIndex >= totalPresetColors) {
        selectedColorIndex = 0;
      }
    }
    void triggerSound(const char *filename) {

    }
    void triggerSwing(const char *filename) {

    }

    void startHum() {
      //Serial.println("startHum");

    }

title: Why is my "port" button on the toolbar greyed out?

Answers: 0


body:
    tcommand=(pwm_value-480.0)/8.22;
    flapmag=(pwm_value-880)/41.0+10;
In this piece of code used in arduino radio control aircraft, I don't understand why PWM value is subtracted and divided like this. This is not my code, it came from [here][1]. Any explanation would be of great help. I have read about PWM but all have different explanations.

    //Arduino servo flap system
    //copyright Steve Morris 10-25-16
    #include <Servo.h>
    volatile int pwm_value = 0;
    volatile int prev_time = 0;
    static int servo_comm1 = 0;
    static int servo_comm2 = 0;
    volatile int flapangle1 = 0;
    volatile int flapangle2 = 0;
    volatile int millisold = 0;
    int millinow = 0;
    float dt = 0;
    float flapmag = 0;
    static float flapdeg = 0;
    float tcommand = 0;
    float floattime = 0;
    float temp = 0;
    float glide_deg = -10.0;
    static int pwm_value_temp = 0;
    float omegadot = 0.0;
    float thetadot = 0.0;
    static float omega = 0.0;
    static float theta = 0.0;
    static float k0 = 1.0;
    static float k2 = 10.0;
    static float servo_zero1 = -4;
    static float servo_zero2 = 0;

    Servo myservo1, myservo2; // create servo object to control a servo

    void setup() {
      //Serial.begin(115200);
      // when pin D2 goes high, call the rising function
      attachInterrupt(0, rising, RISING);
      myservo1.attach(5); // attaches the servo on pin 5 to the servo object
      myservo2.attach(6); // attaches the servo on pin 6 to the servo object
    }
    void loop() {

      millinow = millis();
      floattime = millinow / 1000.0;
      dt = (millinow - millisold) / 1000.0;
      millisold = millinow;

      tcommand = (pwm_value - 480.0) / 8.22;
      omegadot = k0 * tcommand - k2 * omega;
      thetadot = omega;
      flapdeg = sin(theta);
      theta = theta + omega * dt;
      omega = omega + omegadot * dt;

      flapmag = (pwm_value - 880) / 41.0 + 10;
      flapdeg = flapmag * sin(theta); //variable amplitude+freq

      flapangle1 = (int)((30.0 - flapdeg + servo_zero1) * 2.0 + 25.0);
      flapangle2 = (int)((30.0 + flapdeg + servo_zero2) * 2.0 + 25 .0);

      if (pwm_value > 930) {
        servo_comm1 = flapangle1;
        servo_comm2 = flapangle2;
      }

      //Glide Lock
      if (pwm_value < 910) {

        servo_comm1 = (int)((30.0 - glide_deg + servo_zero1) * 2.0 + 25.0);
        servo_comm2 = (int)((30.0 + glide_deg + servo_zero2) * 2.0 + 25.0);

      }

      myservo1.write(servo_comm1); // tell servo to go to position in variable 'pos'
      myservo2.write(servo_comm2); // tell servo to go to position in variable 'pos'

      //Serial.println(servo_comm1);
      //Serial.println(floattime);
      //Serial.println(dt);
      //Serial.println(flapangle);
      //Serial.println(flapdeg);
      //Serial.println(temp);
      //Serial.println(tcommand);
      //Serial.println(pwm_value);

    }

    void rising() {
      attachInterrupt(0, falling, FALLING);
      prev_time = micros();
    }

    void falling() {
      attachInterrupt(0, rising, RISING);
      pwm_value = micros() - prev_time;
    }

  [1]: https://www.rcgroups.com/forums/showthread.php?2765781-Arduino-Servo-Flap-System/page6

title: Why are the PWM variables in this RC code snippet handled this way? What are the magic numbers?

Answers: 1

body:
There is not enough context to be certain, but given the variable names I can assume that this is code from a sketch that receives information from an RC controller and is intended to control parts of some form of flying craft.

So with that in mind, let's take this line:

    flapmag=(pwm_value-880)/41.0+10;

I assume that this is to calculate the amount the flaps should be extended or retracted.

RC controllers, or rather the receivers that pick up the signals, usually output a PWM signal (square wave with a variable duty cycle) where the duty cycle is directly related to the position of the joystick.

A joystick is usually zero in the center and goes plus or minus for up and down (or right and left). But you can't have a negative PWM value, since that makes no sense (how can you have a signal that is off for *less* that 0% of the time?!).  So the output is "offset" by a certain amount (that's not quite true - actually the joystick is 0 for fully down, and 100% for fully up, with "0" being somewhere in the middle, so the offset is applied by the joystick, not the receiver, but that really doesn't matter for us right now).

So we have a signal that is at any time somewhere between 0% and 100%, with "zero" being somewhere in the middle.  What actual value the "100%" is, or exactly where "zero" is, can vary depending on many many factors, so we'll just use "100" for the maximum, and "50" for the middle "zero" offset.

The first thing you want to do, then, is remove that "zero" offset. And that is as simple as subtracting it.  With our example numbers above, if you subtract the "zero" offset of "50" from the incoming signal it now goes between -50 and +50 instead of 0 and 100. That now relates much better to how a joystick appears - 0-50 in an upwards direction (+) and 0-50 in a downwards direction (-).

And that is exactly what is happening with `pwm_value-880` in your code.  The middle "zero" value of 880 is being subtracted from the incoming joystick position to give you an "up" or "down" value that is positive or negative respectively.

Next comes the division.  This scales the incoming value to the right size for the device you are driving. In our example we have a ±50 signal. But what if our flaps require a ±10 signal to give the correct movement range. So simply dividing the value by 5 will change ±50 into ±10. That's exactly what the `/41.0` is doing - scaling the result to fit the range of the target device.

Then there's one final `+10` in there. This simply adds a small offset to the result. You can think of this as a "trim" value. It sets the actual "zero" point of the target device - in this case when the joystick is centered it means the flaps are set to a +10 position.

As to how the `pwm_value` itself is created, that is usually done through capturing the rising and falling edges of the incoming waveform from the receiver and timing how long the signal is in the HIGH or LOW state. That may be performed by some unspecified library.


body:
Hello I am i need of a piece of code that lets me invert a PWM signal of two PWM pins on the due. Example D1 will be 101010 and D2 will be 010101. Is it possible?

Im pretty limited in my options because, doing it externally is not an option because there will be a time where a change in mode is needed and both pins will be sending signal independently. Manually pulling the pins High and Low is also not an option for me because this will make the code blocking other codes.

title: How to create an inverted PWM on the Due via software

Answers: 1

body:
Not using the Arduino API, no. But you can by direct manipulation of the SAM3X8E registers.

You should study section 38 of [the datasheet](https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf), where it mentions in the list of facilities:

> * Independent Complementary Outputs with 12-bit Dead-Time Generator (Also Called Dead-Band or Non-Overlapping Time) for Each Channel


body: I'm using an Arduino MKR GSM 1400. I know this board uses the Atmel SAMD21 and the SAMD21 supports half-duplex (USART with full-duplex and single-wire half-duplex configuration). My question is, how can I configure one of the SERCOMs to use it as half-duplex (use one pin for rx and tx)?

title: Half-duplex for Atmel SAMD21

Answers: 2

body:
> Up to six Serial Communication Interfaces (SERCOM), each configurable
> to operate as either:
>
>  -   USART with full-duplex and single-wire half-duplex configuration
>  -   I2C up to 3.4 MHz
>  -   SPI
>  -   LIN slave

It is an error in the overview of the SAM D21 features in the datasheet. The SERCOM is half-duplex for I2C. USART can't be configured half-duplex.

see [Application Note about SERCOM configuration][1]

> 1 Introduction to Serial Communication Interfaces (USART, I2C, and
> SPI)
>
> ... The exchange of data can be half-duplex or fullduplex depending on
> the serial module specification. ...
>
> 1.1 USART
>
> ... It is full-duplex in operation. ...
>
> 1.2 I2C
>
> ... It is half-duplex in communication. ...

[1]: https://www.microchip.com/wwwAppNotes/AppNotes.aspx?appnote=en590861

body:
You can use USART in half duplex mode.

SERCOMx.PAD0 or SERCOMx.PAD2 are available for this. Refer to document "AT03256: SAM D/R/L/C Serial USART (SERCOM USART) Driver" section "10. SERCOM USART MUX Settings".

Below is a piece of code for ATXMEGA32E5, SERCOM0, PAD0. I am tested - it works:

Pull-up will help keep the line at 1 when the device’s transmitter is turned off and there is no other transmitter on the line, or it has not turned on yet. In the GPIO setup procedure:

    // PA08 - SERCOM0/PAD[0]
    PORT->Group[0].PINCFG[8].bit.PULLEN=1;   // Pull Enable
    PORT->Group[0].PINCFG[8].bit.PMUXEN=1;    // Peripheral Multiplexer Enable
    PORT->Group[0].PMUX  [4].bit.PMUXE=0x02;  // PMUX function C - SERCOM0/PAD[0]

In the SERCOM setup procedure, configure TX and RX on one pad:

    while(SERCOM0->USART.SYNCBUSY.reg & 0x07) { ; }
    SERCOM0->USART.CTRLA.bit.TXPO = 0x00; // SERCOM PAD[0] Transmit Data Pinout
    while(SERCOM0->USART.SYNCBUSY.reg & 0x07) { ; }
    SERCOM0->USART.CTRLA.bit.RXPO = 0x00; // SERCOM PAD[0] is used for data reception

If at the time of your transmission both the receiver and the transmitter are turned on at the same time, you will hear your echo.

When you get up for reception, do not forget to turn off your transmitter so that it does not interfere with reception:

    SERCOM0->USART.CTRLB.bit.TXEN=0x00; while(SERCOM0->USART.SYNCBUSY.bit.CTRLB ) { ; }
    SERCOM0->USART.CTRLB.bit.RXEN=0x01; while(SERCOM0->USART.SYNCBUSY.bit.CTRLB ) { ; }

Before transmitting, do not forget to turn on the transmitter:

    SERCOM0->USART.CTRLB.bit.TXEN=0x01; while(SERCOM0->USART.SYNCBUSY.bit.CTRLB ) { ; }
    SERCOM0->USART.CTRLB.bit.RXEN=0x00; while(SERCOM0->USART.SYNCBUSY.bit.CTRLB ) { ; } // If you don't want to receive your own transmission

Hope it helps.


body:
My main goal is to use connect the **HC-SR04** ultrasonic sensor with **ESP8266**.

Problem is, HC-SR04 works with **5V** while the ESP8266 works with **3.3V**
In order to solve this, idea would be to use a logical level converter.

I bought some of this [3.3V 5V TTL Bi-directional Logic Level Converter(s)][1] a good while ago, and thought they would fit best for this project.

**Here's my setup**

- 5V from arduino
- 3.3V from digital power supply
- GND connected together
- **Nothing** connected to TX0 (HV side)
- Voltmeter connected to TX1 (LV side), **still getting a 3.3V**

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

**Here's a closer look at the breadboard connections**
[![enter image description here][3]][3]

Am I doing something wrong ? Any suggestions would be appreciated !

  [1]: https://www.banggood.com/3_3V-5V-TTL-Bi-directional-Logic-Level-Converter-p-949438.html?cur_warehouse=CN
  [2]: https://i.stack.imgur.com/ktAWZ.jpg
  [3]: https://i.stack.imgur.com/8tdB4.jpg

title: Level shifting 5V <-> 3.3V

Answers: 3

body:
No, you're not doing anything wrong.  Those simple MOSFET level shifters work by having both sides pulled up by resistors to their respective power supplies. When one side gets pulled low by a digital signal that LOW is mirrored to the other side of the MOSFET.

If you connect your TX0 pin to GND you will see the TX1 pin go to 0V.

body:
Edit: Forget the post above if you just want to know how your board is working. Your board is a retired Spurkfun product - clone.

Here you can see the schematics and all info about your board:

https://learn.sparkfun.com/tutorials/retired---using-the-logic-level-converter

<b>Original post</b>:

The module you got, use the BSS138 MOSFET.
The circuit is easy, and how @Majenko said, it has just 2 pullups:
See https://electronics.stackexchange.com/questions/367052/replace-bss138-with-ao3400a-in-level-shifter-circuit

[![level shifter][1]][1]

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

But this board is really strange: what means TX0, TX1, RX0, RX1 on the same MOSFET? It is better if you can measure it to be sure how to connect the sensor to the TX.

But there is a better way to solve it: Since you just have 1 input to your ESP, why not use 2 resistors?
5V--- 1k --- 2k --- GND
And connect the ESP input between the 2 resistors? It is even faster, because the MOSFET need up to 20ns to change state.

body:
Check this out:
https://learn.sparkfun.com/tutorials/bi-directional-logic-level-converter-hookup-guide/all
This article gives a comprehensive explanation about the bi-directional logic level converter and it's connection in a circuit.


body:
I want
When,

 - light=0, ir=0 then output will pin 8 high & pin 12 low.

 - light=0, ir=1 then output will pin 8 high & pin 12 high.

 - light=1, ir=0 then output will pin 8 low & pin 12 low.

 - light=1, ir=1 then output will pin 8 low & pin 12 low (This statement
   does not work).

Please find the code & suggest me, if any modification is needed.

    void setup() {

        pinMode(8,OUTPUT); //logic output.
        pinMode(12,OUTPUT); //logic output.
        pinMode(2, INPUT); //value input.
        pinMode(4, INPUT); //value input.

        Serial.begin(9600);
    }

    void loop() {

        int light = digitalRead(2); //value input.
        int ir = digitalRead(4); //value input.

        if (light == LOW && ir == LOW)
        {

          digitalWrite(8, HIGH);
          digitalWrite(12, LOW);
          delay(2000);

        }

        if (light == LOW && ir == HIGH)
        {

          digitalWrite(8, HIGH);
          digitalWrite(12, HIGH);
          delay(2000);

        }

        if (light == HIGH && ir == LOW)
        {

          digitalWrite(8, LOW);
          digitalWrite(12, LOW);
          delay(2000);

        }

        if (light == HIGH && ir == HIGH) //This condition does not work.
        {

          digitalWrite(8, LOW);
          digitalWrite(12, LOW);
          delay(2000);

        }

        digitalWrite(8, LOW);
        digitalWrite(12, LOW);
        delay(2000);

    }

title: Can't get actual output when, both input logic is high

Answers: 2

body:
You can simplify your requirements somewhat by splitting your inputs up.

> light=0, ir=0 then output will pin 8 high & pin 12 low.
>
> light=0, ir=1 then output will pin 8 high & pin 12 high.

If `light` is 0 then pin 8 is high. AND `ir` is echoed to pin 12.

> light=1, ir=0 then output will pin 8 low & pin 12 low.
>
> light=1, ir=1 then output will pin 8 low & pin 12 low

If `light` is 1 then both pins 8 and 12 are low, and you don't care what `ir` does, since it doesn't have any effect on the outputs.

So your structure could look more like:

    if (light == 0) {
        digitalWrite(8, HIGH); // 8 will always be high with light == 0
        digitalWrite(12, ir); // echo the ir value to pin 12
    } else {
        digitalWrite(8, LOW); // if light is 1 then everything
        digitalWrite(12, LOW);// is low regardless of ir.
    }

body:
Note this is not an answer to the question (I don't see any problem initially), but to clean the code it might help to debug it (using print statements as Sim Son suggests).

Instead of all the `if` statements, check when pin 8 and pin 12 needs to be HIGH:

     pin 8:  (light == LOW && ir == LOW)
     pin 12: (light == LOW && ir == LOW)  or (light == LOW && ir == HIGH)

For pin 12, the condition can be rewritten as

     pin 12: (light == LOW) || (ir == LOW or ir == HIGH)

which is equal to

     pin 12: light == LOW

So now you can change the code from the `loop` function to:

    void loop()
    {
       digitalWrite(8 , (light == LOW && ir == LOW) ? HIGH : LOW);
       digitalWrite(12, (light == LOW             ) ? HIGH : LOW);
       delay(2000);

       digitalWrite(8, LOW);
       digitalWrite(12, LOW);
       delay(2000);
   }

the x ? : z statements means: if x is true, do y, else z.

The last three statements are fixed (copied from your code).

Now we can even further reduce it, by removing the duplicated code

    void loop()
    {
       processLeds((light == LOW && ir == LOW), (light == LOW));
       processLeds(False                      , False         );
    }

    void processLeds(int conditionLed8, int conditionLed12)
    {
        digitalWrite( 8, conditionLed8  ? HIGH : LOW);
        digitalWrite(12, conditionLed12 ? HIGH : LOW);
        delay(2000);
    }

You pass the condition when led 8 and 12 have to be high or log to a function, which sets the LEDs.

Now you can also use much less print statements for finding your problem.


body:
I'm working with Arduino and getting some strange errors. qsorting is not sorting correctly.

    //using this libraries
    #include <ESP8266WiFi.h>
    #include <inttypes.h>

    //the red struct is

    typedef struct {
        int32_t rssi;
        int id;
    } red;

    //Here is my compare function
    int compare (const void * a, const void * b)
    {
      yield();
      red *redA = (red *)a;
      red *redB = (red *)b;
      //Serial.printf("redA->rssi: %d, redB->rssi: %d\n",redA->rssi,redB->rssi);
      //Serial.flush();

      return redA->rssi > redB->rssi ? 1 : (redB->rssi < redA->rssi ? -1 : 0);
      //return ( redB->rssi - redA->rssi );
    }

    void showNetworks(){
      int n = WiFi.scanNetworks(false,false);
      red listOfRedes[n];

      for (int i = 0; i < n; i++) // ...initialize it
      {
        yield();
        listOfRedes[i].rssi = WiFi.RSSI(i);
        listOfRedes[i].id = i;
        Serial.printf("%d: RSSI%d\n", i, listOfRedes[i].rssi);
        Serial.flush();
      }
      Serial.printf("salio\n");
      Serial.flush();
      qsort (listOfRedes, n, sizeof(red), compare);
      Serial.printf("ordeno\n");
      for (int i = 0; i < n; i++) // ...initialize it
      {
        yield();
        Serial.printf("%d: RSSI:%" PRId32 "\n", listOfRedes[i].id, listOfRedes[i].rssi);
      }
    }

and this is the output i get

    0: RSSI-69
    1: RSSI-65
    2: RSSI-72
    3: RSSI-50
    4: RSSI-60
    5: RSSI-87
    6: RSSI-87
    7: RSSI-79
    8: RSSI-80
    9: RSSI-88
    10: RSSI-74
    11: RSSI-77
    12: RSSI-78
    13: RSSI-83
    14: RSSI-79
    15: RSSI-60
    16: RSSI-85
    17: RSSI-86
    18: RSSI-66
    19: RSSI-88
    20: RSSI-80
    21: RSSI-74
    22: RSSI-81
    23: RSSI-87
    salio
    ordeno
    4: RSSI:-60
    1: RSSI:-65
    0: RSSI:-69
    3: RSSI:-50
    18: RSSI:-66
    15: RSSI:-60
    2: RSSI:-72
    10: RSSI:-74
    11: RSSI:-77
    21: RSSI:-74
    19: RSSI:-88
    20: RSSI:-80
    22: RSSI:-81
    23: RSSI:-87
    12: RSSI:-78
    5: RSSI:-87
    6: RSSI:-87
    7: RSSI:-79
    8: RSSI:-80
    9: RSSI:-88
    13: RSSI:-83
    14: RSSI:-79
    16: RSSI:-85
    17: RSSI:-86

As you can see the sorting is not OK and I don't get why.
Thank you in advance and sorry for my poor English.

title: qsort is not really sorting

Answers: 1

body:
In your program there is this line of code:

      return redA->rssi > redB->rssi ? 1 : (redB->rssi < redA->rssi ? -1 : 0);

Which appears to return a 1 if A is greater then B other wise it will return a 0.  This code can not tell the difference between A < B and A == B.  Consider altering this line of code to allow returning 1 for A > B, 0 for A == B and -1 for A < B:

      return redA->rssi > redB->rssi ? 1 : (redA->rssi < redB->rssi ? -1 : 0);


body:
Printing structure variables, I get default values. What is wrong with my code?

```
struct SCENARIO
{
  int Lamp_Pin = -1;
  int PB_Pin = -1;
} ;

SCENARIO  _red;
SCENARIO  _yellow;
SCENARIO  _white;
SCENARIO  _stop;
SCENARIO btns[4] = { _red,  _yellow, _white, _stop};

void setup()
{
  _stop.Lamp_Pin = 8;
  _stop.PB_Pin = 4;

 ///// initializing other 3 objects i.e. red & white & yellow
 ////
for (int i = 0; i < 4; i++)
  {
    Serial.print(i);Serial.print(":");
    Serial.print(btns[i].Lamp_Pin);Serial.print(":");
    Serial.println( btns[i].PB_Pin );
    //pinMode(  btns[i].Lamp_Pin, OUTPUT);
    //pinMode(  btns[i].PB_Pin, INPUT);
  }
}
```
The image below shows what I get. It seems I have not initialized the variables!

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

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

title: Declaring and using array of structures in Arduino

Answers: 2

body:
The problem is that a struct is handled as a value type, not as a reference type.

This means that a copy of `_stop` is made and put in `btns` (`btns[3]` actually).

So what you need to do is putting pointers into the `btns` array:

    SCENARIO* btns[4] = { &_red, &_yellow, &_white, &_stop};

The symbol * denotes a pointer, and & means the address of a variable (so it points to the variable and is not a copy).

Now when you change `_stop`, also `btns[3]` which points to `_stop` will show the correct initialized value.

For printing you should use:

    Serial.println( (*btns[i]).LampPin);Serial.print(":");
    Serial.println( (*btns[i]).PB_Pin );

Because *btns[i] is a pointer, but because this is a very often used feature, a special notation can be used:

    Serial.print(btns[i]->Lamp_Pin);Serial.print(":");
    Serial.println( btns[i]->PB_Pin);

body:
In this line:

    SCENARIO btns[4] = { _red,  _yellow, _white, _stop};

you are making 4 copies of the structures and placing them in an array.

Instead you should either create the array directly with the values:

    SCENARIO btns[4] = {
        {-1, -1},
        {-1, -1},
        {-1, -1},
        {8, 4}
    };

And only use the array, or use pointers in the array:

    SCENARIO *btns[4] = { &_red,  &_yellow, &_white, &_stop };

and then access the entries as pointers:

    Serial.print(btns[i]->Lamp_Pin);
    Serial.print(":");
    Serial.println( btns[i]->PB_Pin );