message:
cannot convert 'bool' to 'PinStatus' for argument '2' to 'void digitalWrite(pin_size_t, PinStatus) on Arduino Uno Rev 2 Wifi not working

I am a newbie to micro controllers and struggling to figure out how to fix this issue. When using an older Arduino micro controller it works fine, but when I use a new board (Arduino Uno Rev 2 Wifi) it gives me this error:

    cannot convert 'bool' to 'PinStatus' for argument '2' to 'void digitalWrite(pin_size_t, PinStatus)'

At this line :

    digitalWrite(pin_enable_line, !digitalRead(pin_enable_line));

Library I am using is: `ReceiveOnlySoftwareSerial`.

body:
The `digitalRead` method doesn't return a Boolean value. It returns an Integer.

From what I remember inside Arduino.h values of `LOW` and `HIGH` are defined as being simply Integer `0` and `1`.

    #define HIGH 0x1
    #define LOW 0x0

I think that was changed to an Enum called `PinStatus` but Enum can be treated as an Integer.

This means that you have to store results of `digitalRead` inside Integer variable.

    int value = digitalRead(8);

It was designed that way to easily cast values between Integer and Boolean. By (very smart) design choice Integer value of `0` (`LOW`) will be cast to `false` and every other value (for example `1` or `HIGH`) will be cast to `true`.

The operator `!` (Boolean NOT) can be used only with Boolean variables so the compiler needs to perform several "implicit casts". When it's smart enough it will assume you are know what you are doing and it will add the cast by itself.

By reading the error I see that the issue is happening when compiler tries to convert Boolean value into Integer. So this is implicitly evaluated correctly as a Boolean value

    !digitalRead(pin_enable_line)

But when you try to put it inside a place for PinStatus you get the exception

    cannot convert 'bool' to 'PinStatus'

Try adding an "explicit cast" to PinStatus:

    digitalWrite(pin_enable_line, (PinStatus)!digitalRead(pin_enable_line));

It should fix the issue.
But I suggest splitting the code into several lines and adding a temporary variable. It makes debugging much easier. Trust the code optimizer that's built into the compiler. It will understand what you want to do and actual machine code will be the same.

  [1]: https://en.wikipedia.org/wiki/Code_smell


sender: user

message:
How to filter the power supply for an Arduino in a vehicle (car, motorcycle)?

I want to use an Arduino (maybe Nano, maybe MEGA) in my motorcycle (a new KTM with lots of electronics).
I checked my test circuit (with the MEGA) and it uses about 100mA (with 5V connected to the 5V pin).

Edit: the bike has a 12v battery and when it's on the generator pushes this up to about 14.3v.

For my first tests I used a 3 terminals DC/DC Regulator with output 5V for the Arduino power supply. If the ignition is on the Arduino works. As soon as I start the bike the Arduino restarts every couple of seconds.

Currently I used the BP5293 DC/DC Regulator because it has 2% precision. Currently I don't have any capacitors on the input or output terminals of that regulator.

I guess I have the following options:

a) Use the BP5293 and add capacitors on the input and/or output terminals. In the datasheet an output capacitor of about 10-330uF is recommended. For the input it recommends a capacitor but without any value given.

b) Use another regulator to 5V

c) Use a regulator to i.e. 7V and then connect that to the Arduino power input and let the Arduino do the filtering of the input.

What is the proper solution and what are suitable values for the capacitors?

I have 100nF ceramic capacitors and Low ESR electrolyte capacitors with 6.3V, 16V and 35V from 68uF up to 3300uF in stock. Obviously I could just try but I prefer to know how it should be done.

sender: assistant

body:
The solution depend on what causes the reset.

It might be EMI interference on the RESET, in this case a stronger pull-up might help. The standard pull-up for nano is 1kohm which should be enough but if you use a clone the value might be higher.

If the reset comes from power drops then only a higher capacitor on the regulator input would not be enough since you also have other consumers on the 12V line that will suck the energy stored in the input capacitor.

Feed the capacitor and the regulator input through a diode, anode to 12v, cathode to capacitor/regulator. This will stop the energy stored in the capacitor to go back to the 12V line.


message:
Triggering an ultrasonic sensor

I made a smart blind stick for my class project. It uses an ultrasonic sensor to detect obstacles and I was asked this question in VIVA...

Why is it necessary for giving a digital high for 10 μS on the trigger (`Trig`) pin of an ultrasonic sensor ?

Why 10 μS only?

I changed it to 5 μS then to 20 μS and to 50 μS and it still works fine! Why so?

body:
The specification1 says (emphasis is mine):

>  using IO trigger distance, the high signal to ***at least*** 10us.

So, longer than 10 μS is not a problem.

With respect to less than 10 μS, well 5 μS may also work, but it is out-of-spec and therefore not guaranteed to work and so may not always work correctly, or as expected.

From [Source 1][1]:

> [![Timing diagram#1][2]][2]

From [Source 2][3]:

> [![Timing diagram#2][4]][4]

----

As to why must it be 10 μS, well that is *probably* (at a guess) down to the design of the logic upon the silicon and the resultant propagation delay through the logic gates. Most, if not all, logic ICs specify a minimum amount of time required for a signal level, in order to allow the signal to propagate through the transistors that make up the logic, so that they switch correctly. PN junctions require a finite time for the electrons and holes to move, and when there are a number of them in sequential stages, that time is multiplied by the number of stages that the signal needs to propagate through. That is a very simplified way of looking at it.

To confirm this, you would need to speak to either the designers, or take a look at the mask used to fabricate the IC. Test simulations were probably run during the design phase, and they suggested a minimum trigger pulse of 10 μS. The figure could also be arrived at by simply looking at the design and counting the number of stages and multiplying that by the propagation delay per stage.

However, as Valbhav points out, the HC-SR04 is controlled by a STM8 (actually it is a STC11F), and after having looked at the [STM8 programming manual][5], it is more related to instruction cycles. The `Trig` pin is, I assume, an interrupt, and from section **3.2 CPU registers**

> When an interrupt occurs, the CPU registers (CC, X, Y, A, PC) are pushed onto the stack.
>This operation takes 9 CPU cycles and uses 9 bytes in RAM

So, 9 CPU cycles just *begin to* to service the interrupt, and then however many needed to actually do the rest. I can't find any timing diagrams in the Programming Manual which would show the minimum interrupt signal length.  This information, is however in the [Reference Manual][6]

The length of a CPU cycle will obviously depend upon the clock frequency., which according to this schematic, from [An Ultrasonic Shortcut – Getting the HC-SR04 Transducer Up and Running Fast!][7], is 4 MHz:

[![HC-SR04 schematic][8]][8]

So, 10 μS is 40 CPU cycles.

----

1 Sources for downloading HC-SR04 pdf datasheet:

 - [Source 1][1]
 - [Source 2][3]

> ### HC-SR04 Specifications
>
>  - Working Voltage: DC 5V
>  - Working Current: 15mA
>  - Working Frequency: 40Hz
>  - Max Range: 4m
>  - Min Range: 2cm
>  - Measuring Angle: 15 degree
>  - Trigger Input Signal: 10µS TTL pulse
>  - Echo Output Signal Input TTL lever signal and the range in proportion
>  - Dimension 45 * 20 * 15mm

  [1]: https://www.electroschematics.com/wp-content/uploads/2013/07/HCSR04-datasheet-version-1.pdf
  [2]: https://i.stack.imgur.com/vaaML.png "Timing diagram#1"
  [3]: https://www.electroschematics.com/wp-content/uploads/2013/07/HC-SR04-datasheet-version-2.pdf
  [4]: https://i.stack.imgur.com/pmS4c.png "Timing diagram#2"
  [5]: https://www.st.com/content/ccc/resource/technical/document/programming_manual/43/24/13/9a/89/df/45/ed/CD00161709.pdf/files/CD00161709.pdf/jcr:content/translations/en.CD00161709.pdf
  [6]: https://www.st.com/content/ccc/resource/technical/document/reference_manual/9a/1b/85/07/ca/eb/4f/dd/CD00190271.pdf/files/CD00190271.pdf/jcr:content/translations/en.CD00190271.pdf
  [7]: https://www.electroschematics.com/13975/an-ultrasonic-shortcut-getting-the-hc-sr04-transducer-up-and-running-fast/
  [8]: https://i.stack.imgur.com/So1mD.jpg "HC-SR04 schematic"


message:
Fan regulator control from Arduino

I'm trying to control my ~230 V fan from the Arduino.

Can anyone say the best possible ways to design a fan regulator that can be controlled by the Arduino using a low cost design.

body:
Its not exactly what you are looking for but it will help [Arduino-controlled-light-dimmer-The-circuit](https://www.instructables.com/id/Arduino-controlled-light-dimmer-The-circuit/).

Here is the sample project in which TRIAC is used with arduino for controlling the flow of current to the light. In your case Light or better we can say load is FAN. This will help you in controlling the FAN Speed. Relay only act as switch and it won't control FAN Speed.


body:
Finally i found it as a product available [here][1]
with the thyristor circuit and *electrical-contactless* ***servo (PWM or ANALOG input) motor*** ( to drive the input) will helps to drive the output from 0 to 220V. **smooth fan regulator can also do this with servo motor and without any external electrical component requirement** . If it is not efficient way with low cost design command or answer your way.  :-).

  [1]: https://robu.in/product/3000w-thyristor-scr-voltage-regulator-temperature-dimmer-speed-light-ac-220v/?gclid=Cj0KCQjw4-XlBRDuARIsAK96p3DJsjbkwTyPaNCDEJwJh2sTK-GFBiYKZua3WaEDRh4wZRD5LO1xS1kaAhuWEALw_wcB


body:
To control AC power for inductive load (motor) a Triac is used. The concept is called [phase cutting][1]. It works for a resistive load (heater) too.

[This module][2] is designed for phase cutting. It contains a zero crossing detector and a Triac. The control is done in MCU. The zero crossing detector is wired to an interrupt pin. The control signal for the Triac is wired to an output pin. In external interrupt function you set a timer interrupt to send a pulse to the Triac after some microseconds. Longer off time results in less power for the motor.

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

At 50 Hz AC, one pulse is 10 milliseconds. To cut a part of AC wave out, activate the Triac gate for 20 microseconds after 0 to 10 milliseconds. Triac turns self off the AC line at next zero crossing.

Robotdyn has [a library][4] for the module.

**EDIT**:

I bought the Robotdyn AC dimmer module to use it in my AC heater regulation project and I tested it with a incandescent light bulb and a fan. ([video on youtube][5])

The library by Robotdyn works, but it is designed to control many dimmers and uses a timer interrupt every 12 microseconds (yes, micros). The library sets the interrupts over MCU registers.

I wrote an arduino fade-in/out sketch using TimerOne library to demonstrate phase cutting with this module.

    #include <TimerOne.h>

    const byte INTERRUPT_PIN = 2;
    const byte TRIAC_PIN = 4;
    const byte TRIAC_PULSE_MICROS = 30;

    const int FADE_MAX = 9800;
    const int FADE_MIN = 2000;

    volatile bool triacOn;
    volatile int period = FADE_MIN; // microseconds cut out from AC pulse

    int fadeAmount = 10;

    void zeroCrossing() {
      triacOn = false; // triac tuns off self at zero crossing
      Timer1.setPeriod(period); // to call triacPulse() after off period
    }

    void triacPulse() {
      if (triacOn) { // stop pulse
        digitalWrite(TRIAC_PIN, LOW);
        Timer1.stop();
      } else { // start pulse
        digitalWrite(TRIAC_PIN, HIGH);
        triacOn = true;
        Timer1.setPeriod(TRIAC_PULSE_MICROS);
      }
    }

    void setup() {
      pinMode(TRIAC_PIN, OUTPUT);
      attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), zeroCrossing, RISING);
      Timer1.initialize();
      Timer1.attachInterrupt(triacPulse);
    }

    void loop() {
      period = period + fadeAmount;
      if (period <= FADE_MIN || period >= FADE_MAX) {
        fadeAmount = -fadeAmount;
      }
      delay(25);
    }

**EDIT 2** version with triac activated by 'pwm' pin

    const byte TRIAC_PIN = 9;
    const byte ZC_EI_PIN = 2;

    unsigned long topMicroseconds = 9700; // 10000 micros is between zero crossings
    int prescaler = 8;
    byte prescalerBits = _BV(CS11); // 8

    void zeroCrossing() {
      TCNT1 = 0; // reset the timer counter
    }

    void setup() {
      Serial.begin(115200);
      Serial.println("START");

      attachInterrupt(digitalPinToInterrupt(ZC_EI_PIN), zeroCrossing, RISING);

      pinMode(TRIAC_PIN, OUTPUT);
      uint32_t topPeriod = ((F_CPU / 1000000)* topMicroseconds) / prescaler ;
      ICR1 = topPeriod;
      OCR1A = topPeriod + 1; // full off
      // WGM mode 14 - Fast PWM w/TOP=ICR1
      TCCR1A = _BV(WGM11) | _BV(COM1A0) | _BV(COM1A1);
      TCCR1B = _BV(WGM13) | _BV(WGM12) | prescalerBits;
    }

    void loop() {
      if (Serial.available()) {
        unsigned long microseconds = Serial.parseInt();
        Serial.find("\n");
        uint32_t period = ((F_CPU / 1000000)* microseconds) / prescaler ;
        OCR1A = period;
      }
    }

on SAMD it is possible to setup this to start the timer on external interrupt over event, without an interrupt function. then the CPU of the MCU is not involved in phase cutting after the initial configuration of the peripherals

**EDIT 3:**

The TriacDimmer library version 1.1.0 for AVR Arduinos available in Library Manager works good with this dimmer. Fun fact: It uses timer1's input capture on pin 8 instead of external interrupt on pin 2 or 3.

  [1]: https://en.wikipedia.org/wiki/Phase-fired_controller
  [2]: https://robotdyn.com/ac-light-dimmer-module-1-channel-3-3v-5v-logic-ac-50-60hz-220v-110v.html
  [3]: https://i.stack.imgur.com/PMHdv.gif
  [4]: https://github.com/RobotDyn/AC-Light-Dimmer-Module-1-Channel-3.3V-5V-logic-AC-50-60hz-220V-110V
  [5]: https://www.youtube.com/watch?v=3gH2Eg5rLE0


body:
There is also the issue of isolation here, to keep the controller side from being connected to the mains for reasons of noise and safety.  The previous posters' comments about doing this with triacs or mosfets, and phase angle control are all true.  It is nearly impossible to control the speed of a single phase induction motor.   Anyway, the most elegant solution is to get a 3 phase fan motor and a variable frequency drive with low-voltage DC control input.  Run the pwm output from the Arduino through an opto-isolator (drive the internal led).  Use the DC reference on the speed control to power the output of the opto-isolator.  Run that through an rc lowpass filter to the speed control voltage input.  I think you could get out of this for around 200$US. Check surpluscenter.com.  there are many motors and drives out there.
-Hugh


message:
Is there a way to have the LED switch on after 10 readings or say a minute?

I am using Arduino for a RFID project where the LED must switch on after either 12 readings of the tag or 2 minute, the tag reading happen every 10 seconds. I can't seem to figure out a way to have the LED switch on only after the above mentioned conditions.

I have tried doing various if loop much to my failure, below is the code I am currently using:

    #include <RFID.h>
    #include <SPI.h>
    #define SS_PIN 10
    #define RST_PIN 9
    #define LED_PIN A0

    RFID rfid(SS_PIN, RST_PIN);
    int serNum[5];
    String cardno;
    int interval = 15000; // millisec
    long now = 0;
    long lasttime = millis();
    // change Reader ID to your name
    String readerID = "Reader_001";

    void setup() {
      Serial.begin(9600);
      SPI.begin();
      rfid.init();
      pinMode(A0, OUTPUT);
    }

    void loop() {
      now = millis();
      if (now > lasttime + interval) {
        lasttime = now;
        Serial.print(readerID);
        Serial.print(":");
        Serial.println("I am alive");
      }
      if (rfid.isCard()) {
        if (rfid.readCardSerial()) {
          lasttime = now;
          cardno = String(rfid.serNum[0]) +
                   String(rfid.serNum[1]) +
                   String(rfid.serNum[2]) +
                   String(rfid.serNum[3]) +
                   String(rfid.serNum[4]);

          Serial.print(readerID);
          Serial.print(":");
          Serial.println(cardno);
        }
      }
      rfid.halt();
      delay(10000);
    }

The expected outcome is the LED switching on after 2 minutes of contact between the tag and the reader.

body:
You want to light the LED, when the same chip was read 12 consecutive times. So I would suggest something like this:

Inside your `void loop()` function you use the `millis()` coding style (refer to the `BlinkWithoutDelay` example, that comes with the Arduino IDE) to scan every 10s for a chip. Then you add a counter variable to count, how often the same chip was scanned. If this counter variable is >=12, you turn on the LED. If a different chip was scanned, you set the counter to 1 (since this chip was now scanned 1 time). This leads to a code something like this:

    #define READ_INTERVAL 10000
    int read_counter = 0;
    unsigned long read_timestamp=0;
    String last_identifier="";
    void loop(){
        if(millis()-read_timestamp>READ_INTERVAL){
            // Read the chip
            if(card_identifier == last_identifier)
                read_counter++;
            else
                read_counter = 1;
            if(read_counter>=12){
                digitalWrite(LED_PIN, HIGH);
            }
        }
    }

Be sure to use `unsigned long` with the `millis()` function, to prevent it from overflowing to a negative value.


message:
Optimizing for speed using const, static, constexpr etc in a function

In an ISR I want to keep things quick. At the same time I want to limit variable scope. Storage space is not a factor.

I have this line:

    const char trigs[] = "aAbBcCdDeEfFgGhHiIjJ";

When this is global, the resulting compile stats show:

    Sketch uses 3418 bytes (10%) of program storage space.
    Global variables use 431 bytes (21%) of dynamic memory.

When it's inside the function (to limit scope) I get:

    Sketch uses 3470 bytes (10%) of program storage space.
    Global variables use 431 bytes (21%) of dynamic memory.

The extra program space is 52 bytes, which is more than the size of the variables, so there must be extra code in there. That might be something to do with initialization checks... but why? Isn't a `const` already known? If there's a difference in where it's stored, why doesn't global variable space change?

If I prefix this as `static const` I'm back to the first behavior `(3418 / 431)`.

So the immediate answer is just to use `static const`, I suppose. But I'm still curious what's going on. Can someone elucidate?

body:
`const char trigs[]` is an auto - it's allocated on the stack at function entry time - and must be initialized at each invocation. The literal used to do that is stored in globals space, which is why the globals allocation doesn't change.

`static const char trigs[]` is allocated in globals space and used in place. The symbols' scope is still local, though, so `trigs[]` isn't visible outside the function.

So why does code space increase by 52 bytes? That seems a lot for copying a string from place to another. So I'll take a guess that the need to copy a string loads a library module that includes it and a few other functions as well.


message:
Why can't I switch off the LED immediately using this sketch?

I hope the LED can fade out a period of time. Also, I hope I can switch off the LED immediately when it is fading, but I only can fade out.

    const int buttonPin = 2;
    const int ledPin = 9;
    const int fadingDelay = 20000;
    int buttonState = 0;
    boolean fadingState = false;
    void setup() {

    // initialize the LED pin as an output:
      pinMode(ledPin, OUTPUT);
      // initialize the pushbutton pin as an input:
      pinMode(buttonPin, INPUT);
    }
    void loop() {
      // read the state of the pushbutton value:
      buttonState = digitalRead(buttonPin);

      // check whether the button was pressed
      if (buttonState == HIGH) {
        buttonState = LOW;
        // check the current LED status (on/off)
        if (fadingState == false) {
          // turn on the LED
            for (int i = 255; i >= 0; i -= 5) {
              if (buttonState == HIGH && fadingState == true) {
              analogWrite(ledPin, 0); //immediately off
              i=-1;
              }
            analogWrite(ledPin, i);
                 delay(fadingDelay);

        }
        fadingState = false;  // save the current LED state (on/off)
      }
    }
    }

body:
I can't see anywhere where you are assigning `fadingState as true`.I can't understand this part

    if (fadingState == false) {
          // turn on the LED
            for (int i = 255; i >= 0; i -= 5) {
              if (buttonState == HIGH && fadingState == true) {
              analogWrite(ledPin, 0); //immediately off
              i=-1;
              }
        analogWrite(ledPin, i);
        delay(fadingDelay);
        }

If you are entering in a `if` condition with statement `fadingState as false`. Then in `for loop` you are having a `if condition` in which `statement` is `fadingState == true`.If you are entering in as a False then why are you looking for True Condition.

Then if you manage to sort that add `break;` in that `if` condition so that when LED turns OFF you will exit that `for Loop`.

And Here you are setting the button state as low `buttonState = LOW` if first If condition, then in that nested `if` without reading the `buttonState` you still looking for it as `HIGH`.


message:
ArduinoJSON v6 - Passing buffer as function parameter

I'm new to ArduinoJSON - so perhaps it is a newbie's question.... but I wish to pass a `StaticJsonDocument` into a function as a parameter ( later on it should be implemented in a library ).

exmaple below shows `test_1` what I wish to obtain, but by duplicating `StaticJsonDocument`, which I don't want to do.

How can `test_1` should be written (as I tried in `test_2`)?

    #include <ArduinoJson.h>

    StaticJsonDocument<200> doc;

    void createJSON() {
            doc["sensor"] = "gps";
            doc["time"] = 1351824120;

            JsonArray data = doc.createNestedArray("data");
            data.add(48.756080);
            data.add(2.302038);

            // Generate the minified JSON and send it to the Serial port.
            serializeJson(doc, Serial);
            Serial.println("JSON is created:");

            // Generate the prettified JSON and send it to the Serial port.
            serializeJsonPretty(doc, Serial);

    }

    bool test_1(StaticJsonDocument<100> _doc){
            serializeJson(_doc, Serial);
            return true;
    }

    bool test2(const JsonObject& _doc){
            Serial.println("HI");
            serializeJson(_doc, Serial);
    }

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

            createJSON();
            test_1(doc);

    }

    void loop() {
            // not used in this example
    }

body:
The `StaticJsonDocument` is a template class. The template value in <> is here only the size of the internal buffer, but every size used generates a different class. (memory usage!)

To have the parameter of the function take an `StaticJsonDocument` version instance, it must be the same version or a common base class. In this case the base class is `JsonDocument`.

If you don't use the reference symbol `&` the parameter is copied. In this case `StaticJsonDocument<200> _doc` or `JsonDocument _doc` would create a copy and that copy would be modified in the function. The object used as parameter value would be unchanged - empty.

So use

    void test2(const JsonDocument& _doc) {
      Serial.println("HI");
      serializeJson(_doc, Serial);
    }


message:
How to get average of 16bit ADC readings?

I have an [Adafruit ADS1115 analog-to-digital converter][1], configured in single ended mode. I want to average over 3 sensor readings to increase the reading stability.

      //initialize variables
      int16_t rawData, ambient;
      int i=0;

      // start loop
      while(i<3) {
          rawData = ads.readADC_SingleEnded(0); //read from ADC
          // divide sensor reading by three
          // (doing so after summation will lead to an overflow)
          rawData=rawData/3;
          Serial.println(rawData); // print data to serial for debugging (OK)
          ambient+=rawData;
          i+=1;
          delay(100);
          Serial.println("I LIVVVVEEE"); // print text to serial for debugging (OK)
      }

      // Print signal (NOT OK)
      Serial.print("Ambient is ");
      Serial.println(ambient);

The "rawData" is printed correctly on the serial monitor. However, the value for "ambient" can be crazy: the resulting output is over an order of magnitude higher. Somehow, the summation doesn't seem to be performed correctly.

  [1]: https://learn.adafruit.com/adafruit-4-channel-adc-breakouts/arduino-code

body:
If you are trying to average out three sensor ADC reading first you need to store and add them all then divide it by 3.

     int16_t rawData =0;
     int32_t avg=0,ambient=0;
      int i=0;

     while(i<3) {
          rawData = ads.readADC_SingleEnded(0); //read from ADC
          // divide sensor reading by three
          // (doing so after summation will lead to an overflow)
         Serial.println(rawData); // print data to serial for debugging (OK)
         avg += rawData;
          i++;
          delay(100);
          Serial.println("I LIVVVVEEE"); // print text to serial for debugging (OK)
      }
      abmient = avg /3;
      avg = 0;
      // Print signal (NOT OK)
      Serial.print("Ambient is ");
      Serial.println(ambient);


body: You forgot to initialize `ambient` to zero, so it got whatever happened to be in that place of memory when it got instantiated. Some unpredictable, seemingly random data.


message:
Sending mouseX and mouseY from Processing to Arduino

I'm new to serial communication and trying to send `mouseX` and `mouseY` from Processing to Arduino. Serial monitor doesn't show anything.

**Processing code:**

    import processing.serial.*;
    Serial port;
    void setup() {
      size(500,300);
      port = new Serial(this , Serial.list()[0], 9600);
    }

    void draw() {
       text("X Y mouse",250,50);
       if (port.available() > 0) {
        port.write(str(mouseX)+' '+str(mouseY));
       }
    }

**Arduino code:**

    int x = 0;
    void setup() {
      Serial.begin(9600);
    }

    void loop() {
      if (Serial.available() > 0) {
        x = Serial.read();
        Serial.print("I received: ");
        Serial.println(x);
      }
    }

when I close Processing window and enter "ok" in Arduino serial monitor I see:
[![enter image description here][1]][1]

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

body:
Since you can't use the serial monitor to "see" the incoming data from Processing, here are 2 test sketches that may help you determine if data is received on the Arduino.

Upload the Arduino sketch first. Leave the serial monitor **closed**. Now run the Processing sketch.

I'm using `frameRate(1)` in the Processing sketch to send the data once per second, so the mouse X/Y values in the Processing window will be slow to update.

You should see the LED on the Arduino flash on then off quickly as the data is received. If you have a I2C LCD available, you could connect it to the Arduino and print out the incoming data.

As chrisl mentions in the comments, there is still much work to be done to get the raw data in the format you require.

**Arduino**

    int x = 0;
    const byte ledPin = 2;

    void setup(){
      Serial.begin(9600);
      pinMode(ledPin, OUTPUT);
    }

    void loop(){
      if(Serial.available() > 0){
        x = Serial.read();
        digitalWrite(ledPin, HIGH);
      }
      else{
        digitalWrite(ledPin, LOW);
      }
    }

**Processing**

    import processing.serial.*;
    Serial port;
    void setup() {
      size(500,300);
      background(148);
      try{
        port = new Serial(this , Serial.list()[0], 9600);
      }
      catch(Exception e){
        System.err.println(e);
        e.printStackTrace();
      }
      frameRate(1);
    }

    void draw() {
      background(148);
      //@chrisl comment: Finish your data, that you send with \n (newline).
      port.write(str(mouseX)+' '+str(mouseY) + "\n");
      text(mouseX,250,50);
      text(mouseY,250,70);
    }

**EDIT**

Here is a second Arduino sketch that will display the mouse X/Y values sent from Processing on a LCD. You could change the Processing sketch's `frameRate()` value to 10.

    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>

    char inputBuffer[32 + 1];

    LiquidCrystal_I2C lcd(0x27, 16, 2);

    void setup(){
      Serial.begin(9600);
      lcd.init();
      lcd.backlight();
    }

    void loop(){
      if(Serial.available() > 0){
        lcd.print("                ");
        Serial.readBytesUntil('\n', inputBuffer, 32);
        lcd.setCursor(0, 0);
        lcd.print(inputBuffer);
        memset(inputBuffer, 0, sizeof(inputBuffer));
      }
    }


message:
Ethernet Shield: Maximum speed

Looking at this shield here: https://store.arduino.cc/arduino-ethernet-shield-2

It states that "Connection speed: 10/100Mb". However from looking at various forums it appears that no one can get much more than 300Kb/sec with this device?

Can anyone explain what causes this limitation and how to overcome it? If its SPI that is the bottleneck is there some alternative? I am looking to get speeds of 6 mega bytes per second or more using a TCP connection.

I am extremely new to all this so apologies if I've missed something extremely obvious here. I also had a look at bluetooth/wifi shields but it appears they seem to also have some similar throughput issues. USB looked like it could work but is extremely complex for a newbie.

body:
It's not just the SPI what limits overall speed. You also need some proccessing power, and AVR based Arduinos lacks of it. It all depens what do you want to do with data.

If you need some serious processing power, it might be better to use something much more powerfull, like raspberry PI with real operating system. You can even run some web server at the speeds you can't even imagine with Arduino with the ethernet shield


body:
A guy on this forum reports achieving 100 Kbyte/sec with a W5100 ethernet shield, which would be 800 kbit/sec:

https://forum.arduino.cc/index.php?topic=555957.0


message:
Using an external header file

I have a project that is part of a larger repository, and shares header files with non-Arduino C programs.

I know that it's possible to use these headers by copying them to the libraries folder, or the sketch folder, but I would rather use them with a relative path (which seems to not work), so I can avoid copying files around for every repository clone or update.

Is there a solution that doesn't involve moving/copying the header file?

EDIT:
Although there is no full solution for this question,
I have since found that using the [PlatformIO][1]
IDE instead solves the problem.

  [1]: https://platformio.org/

body:
You can use header files with an absolute name, like:

    #include "c:\Temp\x.h"

Another way that might help is to make the include path like:

    #include "q:\x.h"

And use Windows to map driver letter Q to the path you need.


body:
I tried to do this, and looked into it, a few years ago, but it doesn't appear to be possible to do what you want to do. This guy was having the same issue, [#include statement with relative path][1].

Seems like either Michel's suggestion or copying them (which *is* a pain) will work, from [Can I include a header file that is not a library?][2]:

> If the include file is part of a single Sketch, instructions are
> here... [http://www.arduino.cc/en/Hacking/BuildProcess][3] [[new
> link][4]]
>
> If the include file is meant to be shared by multiple Sketches then...
>
>  - Close the Arduino IDE
>  - Navigate to the `{Arduino}\hardware\libraries` directory
>  - Create a subdirectory.  I suggest something like `MyCommon`.
>  - In the new subdirectory, create a header file.  I suggest something like `MyCommon.h`.
>  - Open the new header file, edit it as you wish, and save it
>  - Open the Arduino IDE
>  - Create or open a Sketch
>  - Add a `#include` to the top of the Sketch that references your new include file

----

This is ***why*** relative paths are not supported, from [Re: how to include header file from previous folder?][5]

> Enable verbose mode when compiling. Navigate to the Testing.cpp file that is created from the Testing .ino file. Go up one level. Do you see the files you are trying to include?

and from [Re: how to include header file from previous folder?][6] (emphasis is mine)

> The reason for having you go look at the something
> like/AppData/Local/Temp/build<a lot of characters>/sketch folder was
> to make you think about what the build process is doing, and maybe
> think that you could google Arduino + Build to get more details.
>
> The IDE copies your sketch, and stuff #included by your sketch to a
> build directory.
>
> If you #include <header.h>, the file header.h, and everything else in
> the directory it is in, will be copied to the build directory, too.
>
>
> If you #include "header.h", the file header.h, and everything else in
> the directory it is in, will be copied to the build directory, too.
>
> The difference between <> and "" is where the header.h file is looked
> for. "" looks in the current directory. <> looks in the library
> directories.
>
> If the token between the <> or the "" is not found in the appropriate
> folder, you are not told that; nothing gets copied, though.
>
> But, **that explains why relative names are useless**. A sketch directory
> might contain a file called header.h. It will not contain a file
> called ..\header.h, because ..\header is NOT a valid file name.
>
> Note that I did NOT say that ..\header.h is not a valid NAME. I said
> that it is not a valid FILE NAME.
>
> Only file names between the <> or "" are possible, as far as the IDE
> is concerned.
>
> If you do not like that, you are free to not use the IDE.

Finally from [Re: How to specify a path to a specific header file?][7]

> The Arduino system has some severe limitations in its ability to work sensibly with the file system - can be a real PITA.

  [1]: https://forum.arduino.cc/index.php?topic=110950.0
  [2]: http://forum.arduino.cc/index.php?topic=37371.msg276056#msg276056
  [3]: http://www.arduino.cc/en/Hacking/BuildProcess
  [4]: https://github.com/arduino/Arduino/wiki/Build-Process
  [5]: https://forum.arduino.cc/index.php?topic=405797.msg2791119#msg2791119
  [6]: https://forum.arduino.cc/index.php?topic=405797.msg2792289#msg2792289
  [7]: https://forum.arduino.cc/index.php?topic=496614.msg3388572#msg3388572


body: BTW, If you create multiple libraries in **libraries** folder, you can use relative reference path i.e in all Header files, you can use `#include "..\mylib2\xxxx.h`.


message:
How to get 3v3 pins on Arduino Mega Sensor shield v2.0?

I am using Arduino mega and a sensor shield (picture attached below). I need to connect three different wires to 3.3 V input. Can anybody suggest how can I achieve the same? What voltage do the VCC pins of all digital and analog pins on the sensor shield have?

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

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

body:
They are all 5V as the Mega2560 uses 5 V logic.  However, there is a `3V3` pin at the bottom, second pin from the left, that you could use:

[![Mega sensor shield][1]][1]

However, unfortunately, the pin isn't protruding *above the shield*, so you'll have to make an ugly solder link to the top of the pin. Either that, or remove the row of pins and replace with a female header (carefully avoiding the `SD card` pins):

[![Female header pins][3]][3]

---

As an aside, the [Iteaduino MEGA 2560][4] works at 3V3 but unfortunately the Mega shield that you have won't fit it.

[![Iteaduino MEGA 2560][5]][5]

The Uno equivalent of your shield will fit it though:

[![Uno sensor shield][6]][6]

  [1]: https://i.stack.imgur.com/l5Kz7.jpg "Mega sensor shield"
  [2]: https://i.stack.imgur.com/aaFub.jpg
  [3]: https://i.stack.imgur.com/DO6Sd.png "Female header pins"
  [4]: https://www.itead.cc/wiki/Iteaduino_MEGA_2560
  [5]: https://i.stack.imgur.com/TySaZ.png "Iteaduino MEGA 2560"
  [6]: https://i.stack.imgur.com/RFxKs.jpg "Uno sensor shield"


message:
tty doesn't list ttyUSB0 so arduino doesn't list serial ports

Okay so lsusb gives
Bus 002 Device 019: ID 1a86:7523 QinHeng Electronics HL-340 USB-Serial adapter

dmesg|grep 'ttyUSB' gives

[63723.589107] usb 2-1: ch341-uart converter now attached to ttyUSB0

but tty lists only /dev/pts/0 although in /dev there is a ttyUSB0 file (or whatever it is because vim says its not a file)

I can use cu -l /dev/ttyUSB0 -s 9600 and transmit to arduino nano as the rx LED blinks. On starting arduino I get the "java.lang.NullPointerException thrown while loading gnu.io.RXTXCommDriver" error.

System: Linux Mint 19.1 Tessa (64 bit)

body: Sorry, I was using the software center to get arduino IDE and that didn't work well. Downloading the official IDE from arduino.cc worked without hassle. Lesson learnt: Not all linux distros have package repos as up-to-date as Arch. :P


message:
STM32YYXX chip series is not defined in boards.txt

The STM32YYXX chip series is not defined in `boards.txt`? How can I solve this? I am using Windows 10 with Arduino IDE 1.6.6

body:
###Overview

Following the guide [Getting Started][1] on the STM32 page on Github: [Arduino core support for STM32 based boards][2]:

> This repo is available as a package usable with [Arduino Boards
> Manager][3].
>
> Use this link in the "Additional Boards Managers URLs" field:
>
> [`https://github.com/stm32duino/BoardManagerFiles/raw/master/STM32/package_stm_index.json`][4]
>
> For full instructions on using the "Boards Manager", see the [Getting
> Started][5] page.

Thanks to Juraj's [comment][6] for the tip

> this is not the current STM boards package. ST Microelectronic took over the development [github.com/stm32duino/Arduino_Core_STM32][2] [stm32duino.com/viewtopic.php?f=16&t=4671][7]

###Step by Step

The process is as follows (screenshots from OS X, but on Windows/Linux the process is the same):

Adding the URL in the preferences dialog (one URL per line)

> [![STM32 - Additional Boards Manager URLs][8]][8]

Boards Manager menu

> [![STM32- Boards Manager menu][9]][9]

Boards Manager dialog

> [![STM32 - Boards Manager][10]][10]

Boards Manager dialog - STM32 Core Boards installed

> [![STM32 - STM32 Cores selected][11]][11]

Boards Manager dialog - Boards installing

> [![STM32 - STM32 Cores installing][12]][12]

Boards Manager dialog - Boards installed

> [![STM32 - STM32 Cores installed][13]][13]

Here are the newly installed boards in the menu

> [![STM32 - Boards Manager added boards][14]][14]

As a comparison, these are the boards installed using the deprecated manual process described below:

> [![STM32 - Manually added boards][15]][15]

----

###Deprecated method

From [STM32 - installation][16]

> ###Prerequisites
>
>If your STM32 board does not have a bootloader yet and you want to be able to program it over USB, you'll have to upload
> the STM32duino bootloader to flash memory. See [Burning the
> bootloader][17].
>
> ###Arduino and Arduino_STM32
>
>  - Download and install the official [Arduino IDE][18]. Versions 1.6.10 till 1.8.5 have been reported to work fine.
>   - If you already have the Arduino IDE installed and it's a newer version, see the [Boards Manager package][19] method of installation.
>      - Note: this method is deprecated and not supported in forum!
>  - Run Arduino IDE, and open the menu **Tools -> Boards -> Boards Manager**. Install the "Arduino SAM Boards" package (includes the
> Arduino Due) from the list of available boards. This installs compiler
> support for ARM Cortex-M3.
>  - Download a zip file containing the Arduino STM32 files from [here][20].
>  - Unzip the content of the zip file, and place the Arduino_STM32 folder to `[Arduino sketches folder]/[hardware]/[Arduino_STM32]`.
> Create the '`hardware`' folder if it does not exist yet.
>
> Example how the path should look like:
> `C:\Users\<user>\Documents\Arduino\hardware\Arduino_STM32`

---

As an aside, for anyone using OS X, from [Installation on OSX][21]

> ###Installation on OSX
>  - `Arduino_STM32` folder must be placed inside
> `~/Documents/Arduino/hardware` (note. if the hardware folder doesn't
> exist you will need to create it)
>  - So you should get `~/Documents/Arduino/hardware/Arduino_STM32`
>  - Note.  DFU util binaries
> have now been added to the repo, in `tools/macosx/dfu-util`, so there is
> no longer a need to install Homebrew to then install `dfu-util`, or to
> compile `dfu-util` from source.

  [1]: https://github.com/stm32duino/Arduino_Core_STM32#getting-started
  [2]: https://github.com/stm32duino/Arduino_Core_STM32
  [3]: https://www.arduino.cc/en/guide/cores
  [4]: https://github.com/stm32duino/BoardManagerFiles/raw/master/STM32/package_stm_index.json
  [5]: https://github.com/stm32duino/wiki/wiki/Getting-Started
  [6]: https://arduino.stackexchange.com/users/37622/juraj
  [7]: http://stm32duino.com/viewtopic.php?f=16&t=4671
  [8]: https://i.stack.imgur.com/huCZ3.png "STM32 - Additional Boards Manager URLs"
  [9]: https://i.stack.imgur.com/9TNTA.png "STM32- Boards Manager menu"
  [10]: https://i.stack.imgur.com/sRmCN.png "STM32 - Boards Manager"
  [11]: https://i.stack.imgur.com/B7AwL.png "STM32 - STM32 Cores selected"
  [12]: https://i.stack.imgur.com/4jVJN.png "STM32 - STM32 Cores installing"
  [13]: https://i.stack.imgur.com/8h3np.png "STM32 - STM32 Cores installed"
  [14]: https://i.stack.imgur.com/vDwJu.png "STM32 - Boards Manager added boards"
  [15]: https://i.stack.imgur.com/HbFWW.png "STM32 - Manually added boards"
  [16]: https://wiki.stm32duino.com/index.php?title=Installation
  [17]: https://wiki.stm32duino.com/index.php?title=Burning_the_bootloader
  [18]: http://arduino.cc/en/Main/Software
  [19]: https://wiki.stm32duino.com/index.php?title=Boards_Manager_package
  [20]: https://github.com/rogerclarkmelbourne/Arduino_STM32/archive/master.zip
  [21]: https://wiki.stm32duino.com/index.php?title=Installation_on_OSX


message:
Need help with wire connections and code

I am currently working on a keypad door lock mechanism (Similar to this project, [Keypad door lock][1]).

The issues with the code I have is that the keypad attached to my board does not allow me to type the full password. Only the first value displayed on the LCD screen moves but no value is excepted. Also the buttons used to open and close the servo motor do not operate as intended.

Fritzing diagram

[![Fritzing diagram][2]][2]

Photo of breadboard

[![Photo of breadboard][3]][3]

Below is the code I currently have:

    //LCD config
    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    LiquidCrystal_I2C lcd(0x27, 20, 4);

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

    //Variables
    int mot_min = 90;   //min servo angle  (set yours)
    int mot_max = 180; //Max servo angle   (set yours)
    int character = 0;
    int activated = 0;
    char Str[16] = {' ', ' ', ' ', ' ', ' ', ' ', '-', '*', '*', '*', ' ', ' ', ' ', ' ', ' ', ' '};
    //               0    1    2    3    4    5    6    7    8    9    10   11  12    13   14  15

    //Pins
    Servo myservo;
    int buzzer = 11;   //pin for the buzzer beep
    int external = 12; //pin to inside open
    int internal = 13; //pin to inside close

    //Keypad config
    const byte ROWS = 4; //four rows
    const byte COLS = 4; //four columns
    //define the cymbols on the buttons of the keypads
    char hexaKeys[ROWS][COLS] = {
      {'1', '4', '7', '*'},
      {'2', '5', '8', '0'},
      {'3', '6', '9', '#'},
      {'A', 'B', 'C', 'D'}
    };
    byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
    byte colPins[COLS] = {9, 8, 7, 6}; //connect to the column pinouts of the keypad

    //initialize an instance of class NewKeypad
    Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

    void setup() {
      myservo.attach(10); //attach the servo to pin D10
      pinMode(buzzer, OUTPUT);
      pinMode(external, INPUT);
      pinMode(internal, INPUT);
      //Init the screen and print the first text
      lcd.init();
      lcd.backlight();
      lcd.clear();
      lcd.print("    PASSWORD");
      lcd.setCursor(0, 1);
      lcd.print("      -***     ");
      //put the servo in the close position first
      myservo.write(mot_min);

    }

    void loop() {
      ///////////////EMERGENCY OPEN/CLOSE/////////
      if (digitalRead(external) == LOW) // if (digitalRead(external))
      {
        myservo.write(mot_max);
        lcd.clear();
        lcd.setCursor(2, 0);
        lcd.print("INSIDE  OPEN");
        activated = 2;
        analogWrite(buzzer, 240);
        delay(250);
        analogWrite(buzzer, 200);
        delay(250);
        analogWrite(buzzer, 180);
        delay(250);
        analogWrite(buzzer, 250);
        delay(250);
        analogWrite(buzzer, LOW);

        lcd.clear();
        lcd.setCursor(4, 0);
        lcd.print("WELLCOME");

        lcd.setCursor(2, 1);
        lcd.print("ELECTRONOOBS");

        lcd.clear();
        lcd.setCursor(3, 0);
        lcd.print("DOOR  OPEN");
        lcd.setCursor(2, 1);
        lcd.print("ELECTRONOOBS");
        delay(500);

      }

      if (digitalRead(internal) == LOW) // if (digitalRead(internal))
      {
        myservo.write(mot_min);
        activated = 0;
        character = 0;
        Str[6] = '-';
        Str[7] = '*';
        Str[8] = '*';
        Str[9] = '*';
        Str[10] = ' ';
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print("    PASSWORD");
        lcd.setCursor(0, 1);
        lcd.print(Str);
      }

      ///////////////KEYPAD OPEN/CLOSE////////////
      char customKey = customKeypad.getKey(); //this function reads the presed key

      if (customKey != NULL) { // if (customKey)

        if (character == 0)
        {
          Serial.println(customKey);
          Str[6] = customKey;
          lcd.clear();
          lcd.setCursor(0, 0);
          lcd.print("    PASSWORD");
          lcd.setCursor(0, 1);
          lcd.print(Str);

        }

        if (character == 1)
        {
          Serial.println(customKey);
          Str[7] = customKey;
          lcd.clear();
          lcd.setCursor(0, 0);
          lcd.print("    PASSWORD");
          lcd.setCursor(0, 1);
          lcd.print(Str);

        }

        if (character == 2) {
          {
            Serial.println(customKey);
            Str[8] = customKey;
            lcd.clear();
            lcd.setCursor(0, 0);
            lcd.print("    PASSWORD");
            lcd.setCursor(0, 1);
            lcd.print(Str);

          }

          if (character == 3)
          {
            Serial.println(customKey);
            Str[9] = customKey;
            lcd.clear();
            lcd.setCursor(0, 0);
            lcd.print("    PASSWORD");
            lcd.setCursor(0, 1);
            lcd.print(Str);

          }

          if (character == 4)
          {
            Serial.println(customKey);
            Str[10] = customKey;
            activated = 1;

          }
          character = character + 1;
        }

        if (activated == 1)
        {
          /*Change your password below!!!
            Change each of Str[6], Str[7], Str[8], Str[9]*/

          // if (Str[10] = 'A' && ...)
          if (Str[10] == 'A' && character == 5 && Str[6] == '3' && Str[7] == '0' && Str[8] == '0' && Str[9] == '7' )
          {
            myservo.write(mot_max);
            lcd.clear();
            lcd.setCursor(4, 0);
            lcd.print("ACCEPTED");
            activated = 2;
            analogWrite(buzzer, 240);
            delay(250);
            analogWrite(buzzer, 200);
            delay(250);
            analogWrite(buzzer, 180);
            delay(250);
            analogWrite(buzzer, 250);
            delay(250);
            analogWrite(buzzer, LOW);
            delay(1000);

            lcd.clear();
            lcd.setCursor(4, 0);
            lcd.print("WELLCOME");
            delay(500);
            lcd.setCursor(2, 1);
            lcd.print("ELECTRONOOBS");
            delay(1000);

            lcd.clear();
            lcd.setCursor(3, 0);
            lcd.print("DOOR  OPEN");
            lcd.setCursor(2, 1);
            lcd.print("ELECTRONOOBS");

          }
          else
          {
            lcd.clear();
            lcd.setCursor(1, 0);
            lcd.print("PASSWORD ERROR");
            lcd.setCursor(3, 1);
            lcd.print("TRY  AGAIN");
            analogWrite(buzzer, 150);
            delay(3000);
            analogWrite(buzzer, LOW);
            character = 0;
            Str[6] = '-';
            Str[7] = '*';
            Str[8] = '*';
            Str[9] = '*';
            Str[10] = ' ';
            activated = 0;
            lcd.clear();
            lcd.setCursor(4, 0);
            lcd.print("PASSWORD");
            lcd.setCursor(0, 1);
            lcd.print(Str);
          }
        }
        if (activated == 2)
        {
          if (customKey == 'B' )
          {
            myservo.write(mot_min);
            activated = 0;
            character = 0;
            Str[6] = '-';
            Str[7] = '*';
            Str[8] = '*';
            Str[9] = '*';
            Str[10] = ' ';
            lcd.clear();
            lcd.setCursor(0, 0);
            lcd.print("    PASSWORD");
            lcd.setCursor(0, 1);
            lcd.print(Str);

          }
        }
      }
    }

To re-iterate, With this code now the LCD screen displays `PASSWORD` but when I enter the password into the keypad only the first number changes value and it does not move to the second value.

  [1]: http://www.electronoobs.com/eng_arduino_tut11.php
  [2]: https://i.stack.imgur.com/Rk9Wi.png "Fritzing diagram"
  [3]: https://i.stack.imgur.com/kzU5p.jpg "Photo of breadboard"

body:
You would appear to have an excess of `{` here:

    if (character ==2) {
    {    <<<< Remove this

and then remove the excess `}` at the end of the code.

It would seem that this is affecting the logic of your code, as you've ended up inadvertently grouping some `if`s within another `if`.

---

To avoid this type of situation, you need to be much more consistent with your code style (i.e. formatting/indentation).

Either use:

    if (character ==2) {

or

    if (character ==2)
    {

but *don't mix them*. Otherwise you'll end up in a right old muddle.

If you keep your coding style consistent, then you'll see, in a flash, something that is out of place - merely by quickly scrolling through the code.

---

In addition, use the `Tools ► Auto Format` menu item in the Arduino IDE to correctly format your code and make it easy to read.


message:
Using Pro Micro without soldering pin

I'm a total newbie. I bought a Pro Micro but I didn't know that it can't be used, if you don't solder things in his holes.
I found this picture on Google:[![enter image description here][1]][1]

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

And it seems that exists those stuffs (green and white) to test the circuit before soldering.

Do you know where can I buy them? Or do you know their name?

Thanks.

body:
Perhaps you are looking for items [like these][1] from from a well established seller adafruit.com.  However, what you are proposing is not cheap when compared to soldering.  I would recommend you [learn soldering][2] as it will likely be the way you want to assemble your final Arduino project.

  [1]: https://www.adafruit.com/product/2617
  [2]: https://learn.adafruit.com/adafruit-guide-excellent-soldering/tools


body:
If you're just getting started and are not comfortable with soldering I would suggest getting one of the larger boards that has headers on it. (An Uno or a Mega, for example). You can use one of those and a breadboard to experiment without having to solder at all.

MicroCenter (A US retailer) sells 100% compatible Arduino Mega 2560 knockoffs for $10 US.

I suggest using a board like that when you are first starting out. (And learn how to solder. It's very useful for electronics repair and various other things.)


message:
What sensor do I use to measure the intensity of direct sunlight?

I'm trying to measure how bright the day is on a particular day to see how it affects plant growth. The brightest sun can be [120,000 lux][1]. It possible to measure such a large brightness? What sensor do I use?

The best options I've found is the [BH1750FVI][2] since its sheet says, "[i]t is possible to detect min. 0.11 lx, max. 100000 lx"

However, it still doesn't go high enough.

**Note:** I live "only" 3,494 km (2171 miles) from the equator, and it can get fairly bright here.

  [1]: https://en.wikipedia.org/wiki/Daylight
  [2]: https://www.mouser.com/ds/2/348/bh1750fvi-e-186247.pdf

body:
You can use a photo resistor. It is also known as an  LDR (Light dependent resistors) and here is a great tutorial to do just that. You can also find a conversion from the 8-bit analog value to lumens if you wish. Here is a tutorial:

https://www.instructables.com/id/Measuring-Light-Using-Light-Sensor/

You can also use a LUX which is the advanced version of a LDR. Here is a tutorial:

https://www.instructables.com/id/How-to-Measure-LUX-With-Arduino/


body: What about SiLabs SI11xx Sensors? Some of them are designed for direct sunlight.


message:
error when trying to upload code to esp8266

Sketch uses 344,292 bytes (32%) of program storage space. Maximum is 1,044,464 bytes.
Global variables use 32,276 bytes (39%) of dynamic memory, leaving 49,644 bytes for local variables. Maximum is 81,920 bytes.
error: Failed to open COM1
error: espcomm_open failed
error: espcomm_upload_mem failed

*********************************
please help me to fix this issue.

body:
Try holding down the flash button when uploading the code to the board.

The ESP8266 and the ESP32 need certain buttons held down to open the COM port to upload code.


message:
Byte text file to array

I'm trying to display a bitmap on gLCD 128x64, I stored the bitmap into txt file `1.txt` in a SD card this is a part of bit map  as following:

0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x80, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0,
0xC0, 0xC0, 0x80, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00.......

 I want to convert the content of this text into array:
`Unsigned char logo[]` with making a split on "`,`".

Any help please

body:
The most efficient way is to read the file byte-by-byte into a small character array until you get a comma or the end of file - ignoring any characters that aren't of interest (line feeds, etc).

Then for each chunk that you read you then convert it to an integer.

For example (untested):

    char temp[5] = {0}; // should be more than enough
    int pos = 0;
    int bno = 0;

    const char *hexchars = "0123456789abcdefABCDEFx";

    while ((int ch = myFile.read()) >= 0) {
        if (ch == ',') { // We found a comma
            logo[bno++] = strtoul(temp, NULL, 16); // Base 16 conversion
            pos = 0;
            temp[0] = 0;
        } else if (strchr(hexchars, ch) != NULL) {
            if (pos < 4) {
                temp[pos++] = ch;
                temp[pos] = 0;
            }
        }
    }

Of course, you have to know how big the `logo` array has to be beforehand.

One does, though, have to ask "Why are you storing a graphical logo as a textual representation of binary data" in the first place?  It would be far easier to just store it as a simple binary file and read the data directly into the `logo` array with a single `File::read(void *buf, size_t nbyte);` function call.  Using text as an intermediate format is both wasteful and needlessly increases complexity massively.


message:
compare char receive from Slave writer to Master reader with I2C

Im trying to send data from slave (writer) to master (reader) then compare it to declared 'char p[]' to turn on the lights but somehow i cant make it work.

    ////master reader

        #include <Wire.h>

    int LED = 13;
    char p[] = "YES...";

    void setup() {
      pinMode(LED, OUTPUT);
      Wire.begin();        // join i2c bus (address optional for master)
      Serial.begin(9600);  // start serial for output

    }

    void loop() {
      Wire.requestFrom(8, 6);    // request 6 bytes from slave device #8

      while (Wire.available()) { // slave may send less than requested
        char c= Wire.read(); // receive a byte as character

      Serial.print(c);         // print the character

      if(c == p){

      digitalWrite(LED, HIGH);   // turn the LED on (HIGH is the voltage level)

        }else{

      digitalWrite(LED, LOW);   // turn the LED on (HIGH is the voltage level)

              }

      }

      delay(1500);

**Slave**

    //////////////     Slave       ///////////////////////

        #include <Wire.h>

    const int pingPin = 8; // Trigger Pin of Ultrasonic Sensor
    const int echoPin = 9; // Echo Pin of Ultrasonic Sensor

    void setup() {
      Serial.begin(9600); // Starting Serial Terminal
      Wire.begin(8);                // join i2c bus with address #8

    }

    void loop() {
       long duration, inches, cm;
       pinMode(pingPin, OUTPUT);
       digitalWrite(pingPin, LOW);
       delayMicroseconds(2);
       digitalWrite(pingPin, HIGH);
       delayMicroseconds(10);
       digitalWrite(pingPin, LOW);
       pinMode(echoPin, INPUT);
       duration = pulseIn(echoPin, HIGH);
       inches = microsecondsToInches(duration);
       cm = microsecondsToCentimeters(duration);
       Serial.print(inches);
       Serial.print("in, ");
       Serial.print(cm);
       Serial.print("cm");
       Serial.println();
       delay(1500);

    if( inches <= 4){

      Wire.onRequest(requestEvent); // register event
       Serial.print("Obstacle detected");
       Serial.println();
      }
      else
      {

      Wire.onRequest(requestEvent1); // register event
       Serial.print("Nothing Detected");
       Serial.println();

        }

    }

    // function that executes whenever data is requested by master
    // this function is registered as an event, see setup()
    void requestEvent() {

      Wire.write("YES..."); // respond with message of 6 bytes
      // as expected by master
    }
    void requestEvent1() {

      Wire.write("NO...."); // respond with message of 6 bytes
      // as expected by master
    }

    long microsecondsToInches(long microseconds) {
       return microseconds / 74 / 2;
    }

    long microsecondsToCentimeters(long microseconds) {
       return microseconds / 29 / 2;
    }

body:
 1. Improve you indentation.
 2. If you want to compare two strings use `strcmp` function for that.
 3. Your master part has some brackets left in your `void loop()` function, correct them.
 4. In I2C you are receiving one `byte` at time. You should receive data till the last `byte` in received.
 5. You should have some identification in your message, which is you are sending from slave to master indicating that this is last character. It helps you come out of Data reception loop in Master side.


message:
Esp8266 not responding to GET request from Android app created using MIT App Inventor

I hope I am posting this question in the right section.
I am making a Smart Home Project for my college semester finals. I am using an Atmega328p microcontroller along with an ESP8266 (Esp 01). The Atmega328p controls all the sensors and actuators and sends the data to Esp01 via serial communication.

I have created a web server on the Esp01 which I plan to access by creating an app using MIT App Inventor. My GET request is of the format "http://192.168.43.42/4" where the digit at the end is data I want to send to the server and the response I get from the server is of the format "12&0&34.8" where the '&' is used to separate different values.

My problem is , when I access the server from Chrome in my laptop I get the desired response but when I access it using the App , I get an error "Error 1101 :Cannot find the specified URL". The Esp01 is connecting to a hotspot from my phone and I have checked the IP assigned to the Esp01 to ensure my GET request is correct.

The code for Esp01 in Arduino IDE is here : https://gist.github.com/TheMagicSmoke/467d6227d670697464038056e22f302d

The blocks for the app made in App Inventor is below:
[![enter image description here][1]][1]

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

The GET request URL when entered from Chrome in laptop returns a blank page at first but upon refreshing Chrome I get the desired response I told earlier. And in the app , I have used a timer which queries the server with the same GET request every 2 seconds. But when I open the App the error keeps on popping up. Please suggest me a solution, I have googled this without any success.

  [1]: https://i.stack.imgur.com/Q1RJX.png
  [2]: https://i.stack.imgur.com/hBwur.png

body:
I have found out the solution to this problem. The code that I had written in the Arduino IDE for the Esp8266 was not correct for handling the GET request.  It only accepted data as a simple Web Server and not as a HTTP server. I am posting the modified code below .

https://gist.github.com/TheMagicSmoke/adaae1e4d92f258c88184c8690e68f08


message:
Transmit image file thougth the TX TR serial line

I have a digital camera with a USB port for image dowload from the camera SD card.

I will like to be able to capture this image files store in the camera SD card using the Arduino  TX TR lines (serial) then transmit this image file to the computer from the USB connection from Arduino to Computer.

The reason need this scenario responds to that the camera dissables the shutter when sensing a USB cable conneted to computer. I do not knwo why this happens but I suspect is an underdeveloped feature of the camera.

Basically, I will like to use Arduino as a USB hub for external devices but at the same time to power down the line when no longer need the device using the Arduino TX and TX line . This will give tha camera a sense that the camera is been unplugged.

<!-- 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/civGW.png)

<!-- End schematic -->

body:
You cannot. The TX and RX lines are UART. UART is *not* USB. USB is a very complicated protocol, and you need a proper understanding of how it works. It's not a simple serial protocol like UART.

Add to that the fact that the Arduino can in no way handle the amount of data involved in video, and you're already on a non-starter.


message:
Servo motor not working properly with arduino

I have some problem with my fyp, which is auto serving of food using train.

I have 4 servo motors, first servo motor's function is to connect the track to table no.1, and second motor for table no.2 and third and fourth motor for table no.3.

All the motors are performing well at first time..
but when I reset and give command for second or third table, motors behavior changes and they start rotating in arbitrary directions which are not defined in code.
but sometimes it works good and sometimes motors are not performing as expected.

I have check all the grounds and powers. they are all good.

Please help me, as I have my final submission in two days.

The code is given below..
Please check and tell me if I have a logical error in my code or any other issue regarding to hardware also tell me is their any cache in arduino, which I need to clean or something like that.

    #include <Servo.h>

    Servo motor;  // create servo object to control a servo
    // twelve servo objects can be created on most boards

    const int button1 = A1;
    const int button2 = A2;
    const int button3 = A3;

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

    int buttonState1 = 0;
    int buttonState2 = 0;
    int buttonState3 = 0;

    void setup() {

      pinMode(button1, INPUT);
      pinMode(button2, INPUT);
      pinMode(button3, INPUT);

      servo1.attach(9);
      servo2.attach(11);
      servo3.attach(6);
      servo4.attach(5);

      Serial.begin(9600);
    }

    void loop() {

      buttonState1 = digitalRead(button1);
      buttonState2 = digitalRead(button2);
      buttonState3 = digitalRead(button3);

      if (buttonState1 == HIGH) {
        int pos1 = 180;
        int pos2 = 180;
        int pos3 = 90;
        int pos4 = 90;

        for (int pos2=90; pos2 <= 180; pos2 += 1) {
          servo2.write(pos2);
          delay(0);
        }
        for (int pos1=90; pos1 <= 180; pos1 += 1) {
          servo1.write(pos1);
          delay(50);
        }

        while (pos1 >= 0 && pos2 >= 0 && pos3 >= 0 && pos4 <= 180) {
    //      servo1.writeMicroseconds (1000);

    //      servo1.write(pos1);
    //      servo2.write(pos2);
          servo3.write(pos3);
          servo4.write(pos4);
          delay(200000);                // 500ms delay
        }

      }
      else if (buttonState2 == HIGH) {

        int pos5 = 90;
        int pos6 = 0;

        for (int pos5=90; pos5 >= 0; pos5 -= 1) {
          servo1.write(pos5);
          delay(0);
        }
        for (int pos6=90; pos6 >= 0; pos6 -= 1) {
          servo2.write(pos6);
          delay(50);
        }

        while ( pos6 <= 180 && pos5 <= 180) {

    //      servo2.write(pos6);
    //      servo1.write(pos5);
          delay(200);
        }
    //      while ( pos5 <= 180) {
    //        servo1.write(pos5);
    //        delay(200);
    //      }

      }
      else if (buttonState3 == HIGH) {
        int pos9 = 90;
        int pos10 = 180;
        int pos11 = 0;
        int pos12 = 180;

        for (int pos10=90; pos10 <= 180; pos10 += 1) {
          servo2.write(pos10);
          delay(0);
        }
        for (int pos9=90; pos9 >= 0; pos9 -= 1) {
          servo1.write(pos9);
          delay(0);
        }
        for (int pos11=90; pos11 >= 0; pos11 -= 1) {
          servo3.write(pos11);
          delay(30);
        }
        for (int pos12=90; pos12 <= 180; pos12 += 5) {
          servo4.write(pos12);
          delay(50);
        }

        while ( pos9 <= 180 && pos10 >= 0 && pos11 >= 0 && pos12 >= 0) {

    //      servo1.write(pos9);
    //      servo2.write(pos10);
    //      servo3.write(pos11);
    //      servo4.write(pos12);
    //      delay(200);
        }
    //      while ( pos9 <= 180) {
    //        servo1.write(pos9);
    //        delay(200);
    //      }
      }

    }

body:
I think reason for which you are not getting the expected result is because of you `while loops` in you `if condition`.

As you loops doesn't have any termination condition. In case of `first button` pressed you will get what you want because you have only single not terminating while loop, while in you Case of `button 2 and button 3` there are two while loop's and both are not terminating.

In that case if you logic goes in first while loop, then it never comes out of it and won't go for second loop.

I don't know what are you up to so can't suggest on logic changes, but add termination in while loop might get you expected results.


message:
Class help - Same Object types seem to mix values with each other

I'm having issues with two objects of the same class type. I have a LED class, which has functions to fade in and out, a LED. In my code, I create two objects of this class, and on the board, I fade them in and out.

Code is in my FadingLED.h file, which I #include.

I instantiate these classes - and then in my setup(), I call an Init function on the classes to initialise them and pass all the parameters I need.

And then in the loop, I just keep calling an Update method, which internally, uses Millis() to handle updating the brightness of the LED.

But I think I am having cross contamination of the objects. Because if I trigger them both to fadein and out at the same time, only the first LED fades. If I stagger them, the 2nd LED works, but it's timing seems to be out. It seems like maybe I'm somehow mixing member variables within the class. I'm new to this, so it's probably an obvious fault?

My calling code:

    // This #include statement was automatically added by the Particle IDE.
    #include "Buzzer.h"
    #include "FadingLED.h"

    // Pins being used by devices.
    int LED1_PIN = A4;
    int LED2_PIN = A5;
    int PIR_PIN = 3;
    int BUZZER_PIN = 0;

    // Instantiate the objects
    FadingLED LED_1;
    FadingLED LED_2;
    Buzzer buzzer;

    // Setup global variables.
    bool AllStill = true;

    // Setup.
    void setup() {
        // Initialise the two LEDs
        LED_1.Init(LED1_PIN, 500, 0, true);
        LED_2.Init(LED2_PIN, 500, 250, true);
        // Set the PIR pinmode.
        pinMode(PIR_PIN, INPUT);
        Particle.publish("Device","Board initialised", PUBLIC);
        buzzer.Beep(100, 2200);
    }

    // Function to check if movement has been detected.
    bool CheckMovement() {
        // Read the pin value.
        int val = digitalRead(PIR_PIN);

        // Has a new movement been detected?
        if(val==true && AllStill==true) {
            buzzer.Beep(200, 2200);
            AllStill = false;
            Particle.publish("Device", "Movement Detected", PUBLIC);
        }
        AllStill = !val; // All still is false if we have movement.

        return val != 0;
    }

    void loop() {
        // Check for moment.
        bool val = CheckMovement();
        // Update connected devices.
        LED_1.Update(val);
        LED_2.Update(val);
        buzzer.Update();
    }

And then the class it's self.

    /*
     * A class that manages a fading LED. This needs to be on PWM pin.
     */
    class FadingLED {
      int             delayedStart = 0;               // Period to wait before starting.
      int             ledPin = -1;                    // The pin to control - Note, as we're fading, we must use an ANALOG pin.
      long            fadePeriod = 0;                 // The time to do a full light and dim cycle.
      unsigned long   previousMillis = 0;             // The previous millis value.
      bool            debug = false;                  // Should we output stuff?
      float           fadeChangeGap = 0;              // Calculated gap between brightness changes.
      unsigned long   firstMillis = -1;

    public:
      void Init(int LedPin, int FadePeriod, int DelayedStart, bool Debug) {
        ledPin = LedPin;
        fadePeriod = FadePeriod;
        delayedStart = DelayedStart;
        debug = Debug;
        pinMode(ledPin, OUTPUT);
        Particle.publish("Debug", "LED Initialised on " + String(ledPin) + ", Fade Period is " + String(fadePeriod) + ", Start Delay is " +  String(delayedStart), PUBLIC);
      }

      void Update(bool isOn) {

          // Get the current millis since the board was started.
          unsigned long currentMillis = millis();

          // Is this the first time this code is running?
          if(firstMillis == -1)
            firstMillis = currentMillis; // Set the first time this class was run.

          // Adjust the current time to be based on the current time since the object was created.
          currentMillis = currentMillis - firstMillis;

          // Calculate the difference bwteen the last update and now.
          unsigned long diff = currentMillis - previousMillis;

          int brightness = 0;

          // Check if we have a delay set. If so, don't light up yet.
          if(delayedStart > 0 && currentMillis < delayedStart) {
            Particle.publish("LED", "In Delay Start...", PUBLIC);
             previousMillis = currentMillis;
            return;
          }

          // Map the difference which is betweem 0 and the cycle time, to a value between 0 and 512.
          // Map the difference, which is between 0 and the fade period, to a value between 0 at 512.
          int b = map(diff, 0, fadePeriod, 0, 512); // 512, as we'll brighten to 256, then then fade from 256 to 512.

          // Check if we should be bringtning, or fading...
          if(b > 255) {
            brightness = 255 - (b-255);
          }
          else
          {
            brightness = b;
          }

          if(isOn == false) {
            brightness = 0;
          }
          // Set the brightness.
          analogWrite(ledPin, brightness);

          // And then save the timestamp.
          if(currentMillis - previousMillis >= fadePeriod) {
             previousMillis = currentMillis;
          }
      }
    };

Is there an error with how I am defining the class (I'd expect to use the 'new' keyword, but don't). Maybe in the class it's self, there is a way to say the field are private to that object only?

If I try:

    FadingLED LED_1 = new FadingLED();

I get:

> conversion from 'FadingLED*' to non-scalar type 'FadingLED' requested

Any assistance or advice would be great.

body:
I combined the `FadingLED` class with your "calling code" sketch, then removed the references to libraries that I don't have. The first error I received was regarding the seven lines of code immediately under the **"class FadingLED {"** line.

My answer will only address the issues with the way the class is written. As Jot and Michel Keijzers have mentioned in their comments to your question, there may be other issues that need to be fixed.

The following sketch uses a slightly modified version of the `FadingLED` class. There are 2 constructors. One is a "no argument" constructor, and the other accepts 4 arguments. Both constructors call the private function `initStuff()` to initialize other variables, pinModes, etc.

    /*
     * A class that manages a fading LED. This needs to be on PWM pin.
     */
    class FadingLED {

      private:

        int             delayedStart;     // Period to wait before starting.
        int             ledPin;           // The pin to control - Note, as we're fading, we must use an ANALOG pin.
        long            fadePeriod;       // The time to do a full light and dim cycle.
        unsigned long   previousMillis;   // The previous millis value.
        bool            debug;            // Should we output stuff?
        float           fadeChangeGap;    // Calculated gap between brightness changes.
        unsigned long   firstMillis;

        void initStuff(){
          previousMillis = 0;
          fadeChangeGap = 0;
          firstMillis = -1;
          pinMode(ledPin, OUTPUT);
          //Particle.publish("Debug", "LED Initialised on " + String(ledPin) + ", Fade Period is " + String(fadePeriod) + ", Start Delay is " +  String(delayedStart), PUBLIC);
        }

      public:

        FadingLED(): delayedStart(0), ledPin(-1), fadePeriod(0), debug(false){
          initStuff();
        }

        FadingLED(int LedPin, int FadePeriod, int DelayedStart, bool Debug):
          delayedStart(DelayedStart),
          ledPin(LedPin),
          fadePeriod(FadePeriod),
          debug(Debug){
          initStuff();
        }

        void Update(bool isOn) {

            // Get the current millis since the board was started.
            unsigned long currentMillis = millis();

            // Is this the first time this code is running?
            if(firstMillis == -1)
              firstMillis = currentMillis; // Set the first time this class was run.

            // Adjust the current time to be based on the current time since the object was created.
            currentMillis = currentMillis - firstMillis;

            // Calculate the difference bwteen the last update and now.
            unsigned long diff = currentMillis - previousMillis;

            int brightness = 0;

            // Check if we have a delay set. If so, don't light up yet.
            if(delayedStart > 0 && currentMillis < delayedStart) {
              //Particle.publish("LED", "In Delay Start...", PUBLIC);
              previousMillis = currentMillis;
              return;
            }

            // Map the difference which is betweem 0 and the cycle time, to a value between 0 and 512.
            // Map the difference, which is between 0 and the fade period, to a value between 0 at 512.
            int b = map(diff, 0, fadePeriod, 0, 512); // 512, as we'll brighten to 256, then then fade from 256 to 512.

            // Check if we should be bringtning, or fading...
            if(b > 255) {
              brightness = 255 - (b-255);
            }
            else
            {
              brightness = b;
            }

            if(isOn == false) {
              brightness = 0;
            }
            // Set the brightness.
            analogWrite(ledPin, brightness);

            // And then save the timestamp.
            if(currentMillis - previousMillis >= fadePeriod) {
               previousMillis = currentMillis;
            }
        }
    };

    // This #include statement was automatically added by the Particle IDE.
    //#include "Buzzer.h"
    //#include "FadingLED.h"

    // Pins being used by devices.
    int LED1_PIN = A4;
    int LED2_PIN = A5;
    int PIR_PIN = 3;
    int BUZZER_PIN = 0;

    // Instantiate the objects
    FadingLED LED_1(LED1_PIN, 500, 0, true);
    FadingLED LED_2(LED2_PIN, 500, 250, true);
    //Buzzer buzzer;

    // Setup global variables.
    bool AllStill = true;

    // Setup.
    void setup() {
        // Set the PIR pinmode.
        pinMode(PIR_PIN, INPUT);
        //Particle.publish("Device","Board initialised", PUBLIC);
        //buzzer.Beep(100, 2200);
    }

    // Function to check if movement has been detected.
    bool CheckMovement() {
        // Read the pin value.
        int val = digitalRead(PIR_PIN);

        // Has a new movement been detected?
        if(val==true && AllStill==true) {
            //buzzer.Beep(200, 2200);
            AllStill = false;
            //Particle.publish("Device", "Movement Detected", PUBLIC);
        }
        AllStill = !val; // All still is false if we have movement.

        return val != 0;
    }

    void loop() {
        // Check for moment.
        bool val = CheckMovement();
        // Update connected devices.
        LED_1.Update(val);
        LED_2.Update(val);
        //buzzer.Update();
    }


message:
Where this function is defined?

This is the code for timer example in esp8266..(got from a website)

My doubt is where the function   timer1_enable(TIM_DIV16, TIM_EDGE, TIM_SINGLE)  is defined ??
I am look in Ticker.cpp, but not found.
<!-- language-all: lang-cpp -->

    #include < ESP8266WiFi.h>
    #include < Ticker.h >

    Ticker blinker;

    #define LED 2  //On board LED

    //=======================================================================
    void ICACHE_RAM_ATTR onTimerISR(){
        digitalWrite(LED,!(digitalRead(LED)));  //Toggle LED Pin
        timer1_write(600000);//12us
    }

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

        pinMode(LED,OUTPUT);

        //Initialize Ticker every 0.5s
        timer1_attachInterrupt(onTimerISR);
        timer1_enable(TIM_DIV16, TIM_EDGE, TIM_SINGLE);
        timer1_write(600000); //120000 us
    }

    void loop()
    {
    }

body:
Those functions have nothing to do with the Ticker library. Those functions are defined in the [ESP8266 core](https://github.com/esp8266/Arduino/blob/master/cores/esp8266/core_esp8266_timer.cpp).

The example you cite has this at the top of it:

> Hardware Timer0 is used by WiFi Functions. We can use only Timer1. **Use of timer instead of Ticker** gives advantage of precision timing and You can get timer interrupt in micro seconds.

Note the use of "instead of Ticker" there. That says that the code below has nothing to do with Ticker.


message:
Multiple slave(sender) to one master (receiver)

I beg your help to my project
I wish to send the data from slave to master but only one data is receive out of two slaves.

    //master

    #include <Wire.h>

    void setup() {
      Wire.begin();        // join i2c bus (address optional for master)
      Serial.begin(9600);  // start serial for output

    }

    void loop() {
      Wire.requestFrom(8, 1);    // request 6 bytes from slave device #8

      while (Wire.available()) { // slave may send less than requested
        char c= Wire.read(); // receive a byte as character
        char q= Wire.read();

      Serial.print(c);         // print the character
      Serial.print(q);
      }

      delay(1500);
    }

////slave 1

    #include <Wire.h>

    void setup() {
      Serial.begin(9600); // Starting Serial Terminal
      Wire.begin(8);                // join i2c bus with address #8
    }

    void loop(){
      Wire.onRequest(requestEvent); // register event

      delay(1500);
    }
    void requestEvent() {

      Wire.write('Q');
      Serial.println("Sent");
    }

////slave 2

    #include <Wire.h>

    void setup() {
      Serial.begin(9600); // Starting Serial Terminal
      Wire.begin(8);                // join i2c bus with address #8
    }

    void loop() {
      Wire.onRequest(requestEvent); // register event

      delay(1500);
    }
    void requestEvent() {

      Wire.write('Y');
      Serial.println("Sent");
    }

body:
You cannot have 2 devices with the same address at the I2C bus. If they both try to send at the same time with different data, the data will either get corrupted, or one of the slaves will stop to send. You cannot request data from more than 1 device at once with I2C.

You have to give the slaves different addresses. Then you have to do the requests sequentially, first a request (with the corresponding read) to the first slave and after that is done, you can start a second request (with the corresponding read).

---

Besides that, the reading code is not good. You are testing in the condition of the `while` loop, if there is anything to read (which can be only 1 byte), but then you read 2 bytes. In your case you only have to read 1 byte, since you also request only 1 byte. In the case, when you request more than 1 byte, you can either check, if there are enough bytes in the buffer (with something like `if(Wire.available()>=2)` ), or you can just work through the buffer byte by byte (with `while(Wire.available()){ data = Wire.read();}` , note the single read in the while loop).


message:
Getting gibberish serial port until button is pressed, plus the button is turning the leds off instead of on

I'm connecting a button to ESP8266.
Connection goes like this:
3v to one side of button, other side connected with GND and pin number 2 (no resistor).

Every time I connect the ESP both built in LED's stay on until I press the button, they turn off until I let go (even though code states otherwise).
Plus, When I monitor the serial, gibberish runs while ignoring my print commands, until I press the button then the serial stops outputting altogether.

When I run the serial without the button, everything works fine.
Am I connecting it wrong, or is the button damaged, or any other problem source?
Thanks in advance.

EDIT: I added the pinMode(BTN_PIN, INPUT_PULLUP) to take the resistor role; to the code, still not helping.

body:
When pin 2 is connected to ground as you have done it puts the chip into an invalid boot mode. It will be spewing out messages at 74880 baud complaining about the boot mode being invalid.

You must not connect pin 2 to ground. It must, at boot time, be connected to 3.3V through a resistor (which is should be provided by the board for you if you use a development board not a bare module).

By connecting the button between 3.3V and GND you are causing a short circuit that removes the power from the module and risks damaging the power supply on your board.

The proper way of wiring a button is to use:

    pinMode(2, INPUT_PULLUP);

and then connect the GPIO pin to ground *through* the button.

The `INPUT_PULLUP` acts like the required pullup resistor keeping the input HIGH while "idle", and the button connects the input to GND when you want to "activate" it, making it LOW.

Those are the only connections you should make.  If you want to use an external resistor *instead of* the internal one with `INPUT_PULLUP`, then that goes between the input pin and 3.3V.

Never ever cause 3.3V to be directly connected to GND.


message:
Using 18650 batteries with a 3.7v to 5v boost converter

I'm looking to set up a 1-meter strip of WS2812B LEDs (60 LEDs) with an off-the-shelf RF LED controller with a remote. The LEDs want a 5V supply - I've tried running them off 3.7v but the colour accuracy goes out the window and they start flickering and doing all sorts of other nonsense.

To work around that I'm considering using a DC boost converter like one of these [pololu](https://www.pololu.com/product/2564) ones. I'll wire up a couple 18650 batteries in parallel to supply the voltage and my plan is to hook them up to the LEDs via the boost converter.

Idiot question time: is it safe to wire the boost converter directly to the output terminals of the battery/batteries and take the 5V off the +5v pin using a common ground? Or am I doing something dumb?

Also, I'm not 100% sure how to go about charging this setup. One option would be to put the batteries in cases and use an external charger with replaceable cells.

Would it make more sense to get [one of these](https://www.adafruit.com/product/2465)? This should be able to handle both charging AND stepping up the voltage, am I right?

body:
> is it safe to wire the boost converter directly to the output terminals of the battery/batteries and take the 5V off the +5v pin using a common ground?

Yes. That is the normal way of using them.

> Also, I'm not 100% sure how to go about charging this setup. One option would be to put the batteries in cases and use an external charger with replaceable cells.

That is the simplest option, yes. You shouldn't charge Li-Poly / Li-Ion batteries whilst using them - the load messes with the charge termination detection and can cause your batteries to over-charge and explode.

> Would it make more sense to get one of these? This should be able to handle both charging AND stepping up the voltage, am I right?

That gets around the problem of charging while running, yes. A proper charger like that should bypass the battery when charging so the load is running from the incoming charge power rather than the battery.

One option you haven't considered though is to *not* use step-up.  Step-up is harder to manage with heavy loads. As you can see that first step-up module you link to has an upper limit of only 1.2A.  If you have 60 LEDs per meter, and 1 meter of LED strip, that's a maximum of 3.6A (60 * 0.02 * 3) which is 3x what that module can provide.

A better solution would be to use two batteries in *series*, not parallel, to give you about 7.2V. Then you can use a step-down switching regulator to give you your 5V and have far higher current limits.  Looking for a "UBEC" or "SBEC" in a model RC supplier shop is usually a good bet. For example:

* [Turnigy 5A (8-26v) SBEC for Lipo
](https://hobbyking.com/en_us/turnigy-5a-8-26v-sbec-for-lipo.html)
* [HobbyKing™ HKU5 5V/5A UBEC](https://hobbyking.com/en_us/hobbykingtm-hku5-5v-5a-ubec.html)

These are all designed for use with two or more LiPoly batteries in series.


message:
HX711 Soft WDT Reset

I am using the following code to check if the value is 0 e.g there is no weights placed and if so, it will ignore this value and do nothing with it. The code runs correctly but keeps outputting the following:

> Soft WDT reset
>
> >>>stack>>>
>
> ctx: cont sp: 3ffffd70 end: 3fffffc0 offset: 01b0 3fffff20:  00000050
> 00000000 31310010 36323439   3fffff30:  00000000 00000000 00000010
> 00000001   3fffff40:  3ffee408 00000000 00000000 40202927   3fffff50:
> 4022dff2 a0000000 bf2cc404 3ffe84dc   3fffff60:  3ffee408 bf2cc404
> 3ffee408 40202962   3fffff70:  3ffeeb9c 40202c00 3ffee408 40202996
> 3fffff80:  3ffee448 bf2cc404 3ffee408 40202664   3fffff90:  3fffdad0
> fffe2d7e 3ffee448 3ffee4b0   3fffffa0:  3fffdad0 00000000 3ffee480
> 40203848   3fffffb0:  feefeffe feefeffe 3ffe8514 40100a41
> <<<stack<<<

If I remove if(reading < 0.01){ the code runs fine. What could be causing this?

    #include "HX711.h"
    #include <ESP8266WiFi.h>
    #include <ESP8266HTTPClient.h>

    #define DOUT  D3
    #define CLK  D2
    const char* ssid = "Curtis";
    const char* password = "password";

    HX711 scale(DOUT, CLK);
    float calibration_factor = -118470; //-7050 worked for my 440lb max scale setup
    void joinwifi(){
        WiFi.begin(ssid, password);
      Serial.println();
      Serial.print("Connecting");
       while (WiFi.status() != WL_CONNECTED)
      {
        delay(500);
        Serial.print(".");
      }
      Serial.println("success!");
      Serial.print("IP Address is: ");
      Serial.println(WiFi.localIP());
    }
    void setup() {
      Serial.begin(9600);
      joinwifi();
      Serial.println("HX711 calibration sketch");
      Serial.println("Remove all weight from scale");
      Serial.println("After readings begin, place known weight on scale");
      Serial.println("Press + or a to increase calibration factor");
      Serial.println("Press - or z to decrease calibration factor");
      scale.set_scale();
      scale.tare(); //Reset the scale to 0
      long zero_factor = scale.read_average(); //Get a baseline reading
      Serial.print("Zero factor: "); //This can be used to remove the need to tare the scale. Useful in permanent scale projects.
      Serial.println(zero_factor);
    }
    void loop() {
      while (WiFi.status() == WL_CONNECTED)
      {
        scale.set_scale(calibration_factor); //Adjust to this calibration factor
        float reading = scale.get_units(1);
        if(reading < 0.01){
          Serial.print("no need");
           Serial.println();
        }
        else{
          Serial.print("Reading: ");
          Serial.print(reading);
          Serial.print(" lbs"); //Change this to kg and re-adjust the calibration factor if you follow SI units like a sane person
          Serial.print(" calibration_factor: ");
          Serial.print(calibration_factor);
          Serial.println();
          if(Serial.available())
          {
            char temp = Serial.read();
            if(temp == '+' || temp == 'a')
              calibration_factor += 10;
            else if(temp == '-' || temp == 'z')
              calibration_factor -= 10;
          }
        }
      }
      while (WiFi.status() != WL_CONNECTED)
      {
        joinwifi();
      }

    }

body:
Because your code is all running in a `while` inside your loop (which is redundant - loop() loops, hence its name), and you have no delays or `yield()` calls, you are not giving the watchdog the required kick that it needs to stay alive.

Either remove your whiles and turn them into ifs instead, or add `yeild()` calls inside your `while` loops.


message:
ESP-12F responds only to a few basic AT commands

I previously read a few guides and tutorials about the ESP8266 and i just started using the ESP-12F module as i think that it is a terrific replacement for Arduino with the added benefit of Wi-Fi. I only have the module itself which is basically a metal casing so, i wired up the ESP-12F module according to this schematic.[![ESP-12 module wire connections][1]][1]

My USB-TTL board is operating at 3 V for its VCC and also for the TX and RX logic levels. I use Arduino IDE 1.8.9 (i made sure that i am using the latest stable version) and then set the COM port to the USB-TTL RS232 connected to the ESP12F and typed "AT" and got a response "OK". Then, i tried, "AT+RST" and got a big bunch of text which proved that there is successful communication with the ESP module. But then, i tried to connect the ESP-12F to my Wi-Fi network, so i entered: AT+CWJAP_CUR="SSID","password" replacing the SSID and password with my own and it gave the response "ERROR", so i tried the old format AT+CWJAP="SSID","password" and again i got "ERROR". So, what am i doing wrong? How to fix this? I was thinking that maybe the firmware on my ESP is old and needs to be updated, so i entered "AT+GMR" and i got this info:

    19:07:27.560 -> ready
    19:07:27.560 -> AT+GMR
    19:07:27.560 -> AT version:1.2.0.0(Jul  1 2016 20:04:45)
    19:07:27.560 -> SDK version:1.5.4.1(39cb9a32)
    19:07:27.560 -> Ai-Thinker Technology Co. Ltd.
    19:07:27.560 -> Dec  2 2016 14:21:16
    19:07:27.560 -> OK

Do i need to update my module to be able to connect it to my Wi-Fi? If yes, how? I want to update it as safely as possible as this is my only ESP module and i don't want to inadvertently damage it.

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

body:
You can't connect to an access point until you put the module into Station mode.

    AT+CWMODE=1

That will put it in STA mode.  You can alternatively make it an access point (AP mode) with:

    AP+CWMODE=2


message:
avrdude: stk500_getsync(): not in sync: resp=0xyy ... where to find the response values?

Last week I retried some of my Arduinos and one Mega was working without a problem, but two Uno's didn't work anymore. The error I got was something like:

    avrdude: stk500_getsync(): not in sync: resp=0xyy

Where yy where all different kind of values (I cannot copy/paste it as I'm not near the Arduino's).

Does anybody know where to find a document what the response values mean?

body:
They don't mean anything.

AVRDude sends a packet, and expects a certain response. When it gets something that it's not expecting it tells you it's "out of sync", and tells you what the actual response was it got. That is, what byte it received over the serial port.  That could be something that your sketch is sending, or complete garbage if you're communicating with a floating serial input, or anything at all.


message:
I have a problem with my nano arduino and the nrf24l01 as receiver

Hello I have a problem with my nano arduino and the nrf24l01 as receiver . I'm trying to upload my code to my board, but it say that my code have this mistake:

Receiver:45:10: error: void value not ignored as it ought to be

exit status 1
void value not ignored as it ought to be

the complet code is:

    #include <nRF24L01.h>
    #include <RF24.h>
    #include <RF24_config.h>

    //Receiver Code (Hand)

    #include <Servo.h>    //the library which helps us to control the servo motor
    #include <SPI.h>      //the communication interface with the modem
    #include "RF24.h"     //the library which helps us to control the radio modem

    //define the servo name
    Servo myServo1;
    Servo myServo3;
    Servo myServo4;
    Servo myServo2;
    Servo myServo5;

    RF24 radio(9,10);     /*This object represents a modem connected to the Arduino.
                          Arguments 9 and 10 are a digital pin numbers to which signals
                          CE and CSN are connected.*/

    const uint64_t pipe = 0xE8E8F0F0E1LL; //the address of the modem,that will receive data from the Arduino.

    int msg[5];

    void setup(){

      //define the servo input pins
      myServo1.attach(15); //A1
      myServo2.attach(16); //A2
      myServo3.attach(17); //A3
      myServo4.attach(18); //A4
      myServo5.attach(19); //A5

      radio.begin();                    //it activates the modem.
      radio.openReadingPipe(1, pipe);   //determines the address of our modem which receive data.
      radio.startListening();           //enable receiving data via modem
      }

    void loop(){
      if(radio.available()){
        bool done = false;
        while (!done){
        done = radio.read(msg, sizeof(msg));

        myServo1.write(msg[2]); //A1
        myServo2.write(msg[4]); //A2
        myServo3.write(msg[3]); //A3
        myServo4.write(msg[1]); //A4
        myServo5.write(msg[0]); //A5
        }
      }
    }

and the problen is here:

  done = radio.read(msg, sizeof(msg));

I don't know hoy to make that comes out as a code. I'm sorry.
I'm trying to program a bionic hand but i have just started to work with arduino boards and their respective prongram. If someone can help me I would be very grateful. thanks

body:
`radio.read()` does not return a value.  You can't assign "no value" to a boolean.

If `radio.available()` is true then `radio.read()` *will* succeed. There is no need to test if it worked or not.