message:
Serial.write printing blank values

I've got an Adafruit Bluefruit NRF52 hooked up to the Adafruit BNO055 9-axis orientation sensor, but when I use Serial.write to send the data, serial monitor displays blank values only. The scroll bar drops so something I definitely appearing, it just seems to be empty.

Serial.print works fine, but I cannot use this for my application, as it uses too much memory.

I'm gathering 3 axis of absolute orientation plus 3 axis of acceleration (6 floats in total) plus a three digit number representing the calibration of each sensor.

Each line should look something like

    303 68.69   4.19    -2.19   -0.12   0.14    -0.40

My code:

    void displayCalStatus(void)
    {

      uint8_t system, gyro, accel, mag;
      system = gyro = accel = mag = 0;
      bno.getCalibration(&system, &gyro, &accel, &mag);

      /* Display the individual values */
      Serial.write(gyro);
      Serial.write(accel);
      Serial.write(mag);
      Serial.write("\t");
    }

    void loop()
    {
      imu::Vector<3> accel = bno.getVector(Adafruit_BNO055::VECTOR_LINEARACCEL);

      /* Get a new sensor event */
      sensors_event_t event;
      bno.getEvent(&event);

      displayCalStatus();

      /* Display the floating point data */
      Serial.write(event.orientation.x);
      Serial.write("\t");
      Serial.write(event.orientation.y);
      Serial.write("\t");
      Serial.write(event.orientation.z);
      Serial.write("\t");

        /* Display the floating point data for Linear Acceleration */
      Serial.write(accel.x());
      Serial.write("\t");
      Serial.write(accel.y());
      Serial.write("\t");
      Serial.write(accel.z());
      Serial.write("\n");
    }

body:
**Problem 1:**

You wish to send/display on the *Serial Monitor* the `int` and `float` values generated by your sensor, but `Serial.print()` uses too much memory.

**Solution 1:**

Optimize your sketch to use less memory.

----------

**Problem 2:**

`Serial.write()` doesn't cause the values to show up on Serial Monitor, but *something* is getting sent, because I see scrolling activity.

**Solution 2:**

`Serial.write()` sends raw bytes, whereas `Serial.print()` converts a variable to a string (or series of ASCII bytes) and sends that string. For example, `Serial.write(65)` sends `A` to the Serial Monitor because the ASCII value of `A` is `65`; `Serial.print(65)` sends `65` to the Serial Monitor because it converts the numeric value `65` into a string containing the character `6` and the character `5`, and sends that string to Serial Monitor.

The Serial Monitor expects only ASCII data. You are using Serial Monitor for development/debugging, but your final application does not require ASCII, only to transmit the numbers.

`Serial.write()` comes in a few forms. One is `Serial.write(val)` which sends a single byte (named `val`, of type `byte` or compatible). Another is `Serial.write(buf, len)` which sends a series of `len` bytes, starting at the address of memory pointed by by `buf`. (This is often when `buf` is an array of bytes, so `buf` points to the first element of the array.)

If you wanted to send the 4 bytes of a `float` using `Serial.write()`, you could call:

    Serial.write(&(event.orientation.x), sizeof(event.orientation.x);

As an alternative, you can use *bit shifting* to send one byte at a time of the 4-byte float:

    Serial.write((byte)((event.orientation.x & 0xFF000000) >> 24);
    Serial.write((byte)((event.orientation.x & 0x00FF0000) >> 16);
    Serial.write((byte)((event.orientation.x & 0x0000FF00) >>  8);
    Serial.write((byte)((event.orientation.x & 0x000000FF)      );

On the receiving end, you need to reconstruct your float by doing the reverse.

But you have multiple 4-byte values to send, in rapid repeating loop, so what happens if your receiver and transmitter get out of sync? Then you might want to put in a "flag" value to indicate the start of a sequence of data and a different flag for the stop of a sequence of data. What happens if your start or stop "flag" value actually shows up as one of the bytes you send as part of a real data byte? Then you need to find some way to modify the "real" data so that it's not to be construed as a flag.

This looks to be getting complicated now? Fortunately, these problems have existed and been solved for decades. Unfortunately, there is no consensus on the best or right way.

I did a quick search and found this arduino library that facilitates packet-based serial communication:

https://github.com/bakercp/PacketSerial

Perhaps that can help you take a bundle of numbers and send them reliably to some other system. I don't know that library in particular, and there are probably others that do something similar. This one claims to be compatible with the PySerial, COBS, and SLIP modules for dealing with packetized serial data communications.


sender: user

message:
Deep Sleep NodeMCU with Door Sensor

I have a very simple code of door sensor (magnetic) which gives results in 1 & 0 format. But I want to run the NodeMCU only when a door is open or close. Rest of time I want to keep it in deep sleep mode. Here is my code looks like :

    int doorClosed = 1;

    #define REED_SWITCH D5

    void setup() {
      // put your setup code here, to run once:

      Serial.begin(115200);
      pinMode(BUILTIN_LED, OUTPUT);
      digitalWrite(BUILTIN_LED, HIGH);

      pinMode(REED_SWITCH, INPUT_PULLUP);
    }

    void loop() {
      // put your main code here, to run repeatedly

       Serial.println(digitalRead(REED_SWITCH));

        if ((digitalRead(REED_SWITCH) == HIGH) && (doorClosed == 1))
        {
          Serial.println("DOOR OPEN!!");
          doorClosed = 0;
          digitalWrite(BUILTIN_LED, LOW);
          ESP.deepSleep(0);
        }
        else if ((digitalRead(REED_SWITCH) == LOW) && (doorClosed == 0))
        {
          Serial.println("DOOR CLOSED!!");
          doorClosed = 1;
          digitalWrite(BUILTIN_LED, HIGH);
          ESP.deepSleep(0);
        }
        delay(500);
    }

Here I am able to put the NodeMCU in deep sleep. But it never wakes up. How can I wake up my chip. After attaching the D0 with RST, I don't event get Serial Logs. I am not sure what kind of behaviour is this. If someone can help me to fix this code will be great!

Thank you!

sender: assistant

body:
According to this [guide][1]:

> The RST pin of the ESP8266 is always HIGH while the ESP8266 is
> running. However, when the RST pin receives a LOW signal, it restarts
> the microcontroller.
>
> If you set a **Deep Sleep timer** with the ESP8266, once the timer ends,
> GPIO 16 sends a LOW signal. That means that GPIO 16 when connected to
> RST pin can wake up the ESP8266 every time the timer ends.

The only way to wakes up ESP8266 from deep sleep mode **without timer** is set a LOW signal on RST pin.

Example without timer:

    ESP.deepSleep(0);

Connect D0 (GPIO 16) to RST is available only when ESP8266 is in sleep mode **with timer**.

Example with 30sec timer:

    ESP.deepSleep(30e6);

In your case, you can use deep sleep with timer and connect Door sensor to D0 and will act as switch between the RST and D0.

  [1]: https://randomnerdtutorials.com/esp8266-deep-sleep-with-arduino-ide/


body:
My response is late but herewith my experience that may be of help to others.

NodeMcu in deep sleep will wake-up from external source on receiving a pulse from high to low on the RST pin.

An ADXL345 accelerometer raises an interrupt HIGH on sensing motion and remains high until (I2C) READ to prevent multiple devices from interfering with each other

The following post was instrumental in my finding a solution

https://electronics.stackexchange.com/questions/158015/how-to-turn-continuous-signal-into-a-short-pulse-using-logic-gates


message:
Lines not pulsed fast enough (?))

Should this code pulse the PB3 and PB4 pins (MOSI and MISO of an Arduino Uno) at 2ms interval ?

    #include <avr/io.h>

    int main(void)
    {

    //  for (byte i = 0; i < 32; i++)
    //    pinMode(i, INPUT);

      DDRB |= (1 << PB4);
      DDRB |= (1 << PB3);
    //  pinMode(PB4, OUTPUT);
      while (1)
      {
        PORTB &= ~(1 << PB4);
        PORTB &= ~(1 << PB3);
      //  digitalWrite(PB4, LOW);
    //      __asm__ __volatile__("nop");
    //      __asm__ __volatile__("nop");
    //      __asm__ __volatile__("nop");
    //      __asm__ __volatile__("nop");
    //      __asm__ __volatile__("nop");
    //      __asm__ __volatile__("nop");
    //      __asm__ __volatile__("nop");
    //      __asm__ __volatile__("nop");
    //    delayMicroseconds(10000);
        delay(1);
        PORTB |= (1 << PB4);
        PORTB |= (1 << PB3);
      //  digitalWrite(PB4, LOW);
    //    delayMicroseconds(10000);
        delay(1);

      }
    }

If used for SPI MOSI can do 1 MHz just fine - so my logic analyzer says. MISO would not behave when used by SPI. MISO works in other non-SPI scenario: I am able to use the Arduino for in-system programming other AVR boards.

But the code above pulses neither MISO nor MOSI, as pointed out by the same logic analyzer in the same setup. Should it?

**update**

There has been some issue with the board. Changed it and all works fine now, regardless of using `int main()` alone or also calling `init()` as per @Majenko 's answer

body:
The code *content* works fine while compiled as an Arduino program - that is, using the proper `setup()` and `loop()` structure:

    void setup() {
        DDRB |= (1 << PB4);
        DDRB |= (1 << PB3);
        while (1) {
            PORTB &= ~(1 << PB4);
            PORTB &= ~(1 << PB3);
            delay(1);
            PORTB |= (1 << PB4);
            PORTB |= (1 << PB3);
            delay(1);
        }
    }

    void loop() {
    }

However the same code will *not* work when using it in `main()`. This is simply because `delay()` will never work. Normally `main()` calls `init()` which then configures TIMER0 to generate the `millis()` and `micros()` count used for the `delay()` functions.

So either use `setup()` and `loop()` instead of `main()`, or make your program call `init()` before anything else:

    int main() {

     init();

        DDRB |= (1 << PB4);
        DDRB |= (1 << PB3);
        while (1) {
            PORTB &= ~(1 << PB4);
            PORTB &= ~(1 << PB3);
            delay(1);
            PORTB |= (1 << PB4);
            PORTB |= (1 << PB3);
            delay(1);
        }
        return 0;
    }


message:
Assign and control Digital pin from String

Here is modified version of Blink example

    #define D8  13

    String p = "D8";

    // the setup function runs once when you press reset or power the board
    void setup() {
      // initialize digital pin LED_BUILTIN as an output.
      pinMode(D8, OUTPUT);
    }

    // the loop function runs over and over again forever
    void loop() {
      byte pin[2];
      p.getBytes(pin, sizeof(pin));

      digitalWrite(D8, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);                       // wait for a second
      digitalWrite(D8, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);                       // wait for a second
    }

D8 defined above is a byte of length 2. So LED turns on/off if I mention D8 on digitalWrite(D8, HIGH). Similarly I am getting the same byte D8 from `String p = "D8"`, and converting it into byte of length 2, but assigning `pin` to digitalWrite(pin, HIGH/LOW) doesn't works. Has anyone tried something similar before ? any help would be appreciated :)

body:
C and C++ programs get compiled in multiple passes through various programs/steps. One of the first is the *C Preprocessor*, which handles the `#define` *preprocessor directive*.

It's basically a big find/replace function. After the preprocessor is done, anywhere you had `D8` outside of a string literal, would have the value `13`. It's not a variable or a string -- it's simply the number 13.

But the `String` `p`, which has content `"D8"` doesn't get replaced by the `#define` directive because it's part of a string, and the preprocessor doesn't modify strings in that way.

Also, `p` converted to a `byte` array of length 2 does not have anything like `13` as the value. It has `0x44` and `0x38` (or, in decimal, `68` (ASCII `'D'`) and `56` (ASCII `'8'`)). Disregarding that `digitalWrite()` and `pinMode()` do not accept byte arrays, only bytes, you are passing in a byte that doesn't represent pin 13.

If you want to assign the pin via a string, then you would need to use programming to examine the string and pick the right byte value, and each possible value would have to be explicitly enumerated and checked for.


message:
How do you remove dependencies from a library?

I'm writing a library for a project i created, but it depends on the Neopixel library from adafruit. I want to remove this dependency and have my library be a stand-alone library.

Is there a way to run a ws2811 chip without the neopixel or similar library?

body:
The [Adafruit Neopixel library][1] is licensed under GPL v3. You can fork a copy of this library into your own code and modify it to suit your own requirements, but if you distribute your code, your compiled project, or a product containing the library or any portion of it, you must ensure you follow the rules of the license by which the library is governed. Those terms of license may include release of the source code if you use any portion of the licensed library in a product. Opinions differ on the exact meaning of GPL v3 with libraries.

You should be able to copy the library into your own codebase and strip out the color-specific routines, put in your own application-specific data-setting routines, but use the same underlying protocol implementation.

  [1]: https://github.com/adafruit/Adafruit_NeoPixel


message:
Did not find fingerprint sensor :( Arduino Mega 2560 Adafruit Fingerprint Sensor

I'm getting the following error when I try to enroll fingerprints using the Arduino Mega 2560 microcontroller along with a Fingerprint Scanner:

> Did not find fingerprint sensor :(

The exact devices I'm using are as shown in the links below:

https://www.gearbest.com/development-boards/pp_70487.html?lkid=11637831
https://www.gearbest.com/boards-shields/pp_009769796663.html?wid=1433363

My circuit connection is:

- (Green) TX  => Pin 0 [PWM]

- (White) RX => Pin 1 [PWM]

//It doesn't respond when connected to 5V, it only heats up

- (Red) VCC  => 3.3v

- (Black) GND => GND

The connection is illustrated below:

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

The code is shown below:

    #include <Adafruit_Fingerprint.h>

    // On Leonardo/Micro or others with hardware serial, use those! #0 is green wire, #1 is white
    // uncomment this line:
     #define mySerial Serial1

    // For UNO and others without hardware serial, we must use software serial...
    // pin #2 is IN from sensor (GREEN wire)
    // pin #3 is OUT from arduino  (WHITE wire)
    // comment these two lines if using hardware serial
    //#include <SoftwareSerial.h>
    //SoftwareSerial mySerial(10, 11);

    Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

    uint8_t id;

    void setup()
    {
      Serial.begin(9600);
      while (!Serial);  // For Yun/Leo/Micro/Zero/...
      delay(100);
      Serial.println("\n\nAdafruit Fingerprint sensor enrollment");

      // set the data rate for the sensor serial port
      finger.begin(57600);

      if (finger.verifyPassword()) {
        Serial.println("Found fingerprint sensor!");
      } else {
        Serial.println("Did not find fingerprint sensor :(");
        while (1) { delay(1); }
      }
    }

    uint8_t readnumber(void) {
      uint8_t num = 0;

      while (num == 0) {
        while (! Serial.available());
        num = Serial.parseInt();
      }
      return num;
    }

    void loop()                     // run over and over again
    {
      Serial.println("Ready to enroll a fingerprint!");
      Serial.println("Please type in the ID # (from 1 to 127) you want to save this finger as...");
      id = readnumber();
      if (id == 0) {// ID #0 not allowed, try again!
         return;
      }
      Serial.print("Enrolling ID #");
      Serial.println(id);

      while (!  getFingerprintEnroll() );
    }

    uint8_t getFingerprintEnroll() {

      int p = -1;
      Serial.print("Waiting for valid finger to enroll as #"); Serial.println(id);
      while (p != FINGERPRINT_OK) {
        p = finger.getImage();
        switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image taken");
          break;
        case FINGERPRINT_NOFINGER:
          Serial.println(".");
          break;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          break;
        case FINGERPRINT_IMAGEFAIL:
          Serial.println("Imaging error");
          break;
        default:
          Serial.println("Unknown error");
          break;
        }
      }

      // OK success!

      p = finger.image2Tz(1);
      switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image converted");
          break;
        case FINGERPRINT_IMAGEMESS:
          Serial.println("Image too messy");
          return p;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          return p;
        case FINGERPRINT_FEATUREFAIL:
          Serial.println("Could not find fingerprint features");
          return p;
        case FINGERPRINT_INVALIDIMAGE:
          Serial.println("Could not find fingerprint features");
          return p;
        default:
          Serial.println("Unknown error");
          return p;
      }

      Serial.println("Remove finger");
      delay(2000);
      p = 0;
      while (p != FINGERPRINT_NOFINGER) {
        p = finger.getImage();
      }
      Serial.print("ID "); Serial.println(id);
      p = -1;
      Serial.println("Place same finger again");
      while (p != FINGERPRINT_OK) {
        p = finger.getImage();
        switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image taken");
          break;
        case FINGERPRINT_NOFINGER:
          Serial.print(".");
          break;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          break;
        case FINGERPRINT_IMAGEFAIL:
          Serial.println("Imaging error");
          break;
        default:
          Serial.println("Unknown error");
          break;
        }
      }

      // OK success!

      p = finger.image2Tz(2);
      switch (p) {
        case FINGERPRINT_OK:
          Serial.println("Image converted");
          break;
        case FINGERPRINT_IMAGEMESS:
          Serial.println("Image too messy");
          return p;
        case FINGERPRINT_PACKETRECIEVEERR:
          Serial.println("Communication error");
          return p;
        case FINGERPRINT_FEATUREFAIL:
          Serial.println("Could not find fingerprint features");
          return p;
        case FINGERPRINT_INVALIDIMAGE:
          Serial.println("Could not find fingerprint features");
          return p;
        default:
          Serial.println("Unknown error");
          return p;
      }

      // OK converted!
      Serial.print("Creating model for #");  Serial.println(id);

      p = finger.createModel();
      if (p == FINGERPRINT_OK) {
        Serial.println("Prints matched!");
      } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
        Serial.println("Communication error");
        return p;
      } else if (p == FINGERPRINT_ENROLLMISMATCH) {
        Serial.println("Fingerprints did not match");
        return p;
      } else {
        Serial.println("Unknown error");
        return p;
      }

      Serial.print("ID "); Serial.println(id);
      p = finger.storeModel(id);
      if (p == FINGERPRINT_OK) {
        Serial.println("Stored!");
      } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
        Serial.println("Communication error");
        return p;
      } else if (p == FINGERPRINT_BADLOCATION) {
        Serial.println("Could not store in that location");
        return p;
      } else if (p == FINGERPRINT_FLASHERR) {
        Serial.println("Error writing to flash");
        return p;
      } else {
        Serial.println("Unknown error");
        return p;
      }
    }

I used the Adafruit Fingerprint library found here:

https://github.com/adafruit/Adafruit-Fingerprint-Sensor-Library

I also soldered the wires from the sensor onto Male Pin Headers for greater connection stability.

All I get is the fingerprint sensor blinking continuously which makes me think it's not faulty but when I try to run the enroll code I get the error message highlighted above.

I also tried connecting using the Software Serial approach like below but that wasn't the solution either:

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(10, 11);

What could be the problem? Is my connection and code okay? Anyone have an idea on how to fix this?

The heat occurs on the encircled area below:
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/fn5wj.png
  [2]: https://i.stack.imgur.com/EhdCJ.jpg

body:
Thanks for your responses @HavocRC and @Juraj

I've successfully come to the following working parameters that I have tested and have given positive results:

> **When using Arduino Mega 2560 with the SFG Demo, we use:**
>
> (Green) TX  => Pin 1
>
> (White) RX => Pin 0
>
> (Red) VCC  => 5V
>
> (Black) GND => GND
>
>
> **When using Arduino Mega 2560 with the Adafruit Library, we use:**
>
> **Using Hardware Serial Port (Serial1) [Recommended]**
>
> (Green) TX  => Pin 19
>
> (White) RX => Pin 18
>
> (Red) VCC  => 5V
>
> (Black) GND => GND
>
> //Note that you'll comment out the Software Serial initialization
>
> //as directed by the code in the Adafruit Library
>
>     #define mySerial Serial1
>
>
> **When using Arduino Mega 2560 with the Adafruit Library, we use:**
>
> **Using Software Serial**
>
> (Green) TX  => Pin 10
>
> (White) RX => Pin 11
>
> (Red) VCC  => 5V
>
> (Black) GND => GND
>
> //The order of the PINs in the code is
>
>     SoftwareSerial mySerial(10, 11);

In the process of testing I also used an older version of Arduino IDE, version 1.0.5 which may have helped to get the sensor working (just a hunch). It turns out the sensor only works with 5V although it heats up a bit (not to fiery levels at a go but I wouldn't leave it turned on if I was away from my laptop for a while).

By the way, for the SFG Demo to work, upload the 'blank' example first, close Arduino and then run SFG Demo. If it works then your fingerprint scanner is in working order.

For the hardware Serial options you can also use alternative PINs as follows:

> **Serial2 on pins 17 (RX) and 16 (TX)**
>
> **Serial3 on pins 15 (RX) and 14(TX)**

Links

http://www.adafruit.com/datasheets/SFGDemoV2.0.rar

https://www.arduino.cc/en/main/OldSoftwareReleases

https://www.arduino.cc/reference/en/language/functions/communication/serial/


message:
Can Arduino Uno R3 board remove chip on the board

First off, got my Elegoo Uno board as Christmas gift, so this is all new to me.

Here is my problem, I built an motor project and the chip has been programmed. Can I remove the chip from the Uno board?

Or can I placing a new chip onto the Uno board?

Best regards.

body:
It depends, if the chip has not been soldered, but placed in an IC (DIP) socket, than you can remove the programmed chip, and use it in another circuit and place another (same) IC in the IC socket of the Uno to be reprogrammed.

You also could desolder it, but I would not advice that; also most of the Uno's having a soldered IC use SMD instead of DIP.

Also, to replace the IC, you need to install a bootloader on the IC to be placed in the new Arduino (thanks for the addition Roberto Lo Giacco).

Below is a version with DIP that easily can be replaced, hence the big IC and the socket:

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

Below is a version with SMD that cannot easily be replaced, hence the small IC without a socket:

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

  [1]: https://i.stack.imgur.com/48UrM.jpg
  [2]: https://i.stack.imgur.com/oKCui.jpg


body:
Yes, you can pull the DIP chip off the board, and use it elsewhere. It will require a 16 MHz crystal and two 22pF caps (or a 16MHz resonator), at least three 0.1uF (aka 100nF) caps (connect one each from VCC, AVCC, AREF to gnd - do not connect Aref to VCC), a 10K resistor from Reset to Vcc.

If you have a  hot air rework station and decide to pull off the SMD part, that chip has two VCC pins, so another 0.1uF cap is needed.


message:
Calling external function from a class function

I'll try to explain my need:

1. I have a generic library I created, called `myIOT.h`.
2. This class have a pre-configured  MQTT and wifi setup.
3.  Inside this library there is a `mqtt_callback` function, for all generic commands, such as `boot_time` and `connection_status`.
4. BUT, this library serves in several of my iot device's code, that each one has a few more mqtt commands, that is tailored just for s specific device, and I looking for a way that `iot.mqtt_callback(ext_mqtt_func)` will get as parameter a local ( which belong to the sketch and not to the library ), that will have the additional code needed.

I'll try to explain more clearly:

    void myIOT::mqtt_callback(ext_mqtt_func){
    if (a == true ) {
    do something

    };

    else {

    ext_mqtt_func()); // calling another fucntion that belongs to sketch and not library

    }

body:
Yes, you can do it.

You pass function pointer as function parameter.

See this stackoverflow question:

https://stackoverflow.com/questions/2582161/c-function-pointer-as-parameter


message:
Dynamic allocation/ Pointer to Pointer to update an Array containing parameter

`topicArray` defined as follows:

    const char* msgTopic = "Home/Messages";
    const char* groupTopic = "Home/All";
    char* deviceName = deviceTopic;
    const char* topicArry[2] = {deviceTopic, groupTopic};

But `deviceTopic` can be changed during code run, and I wish that `topicArray` containg `deviceTopic` will have the correct value after `deviceTopic` has changed.

What is the right way doing so ?

body:
You may try something like this:

    const char* topicArry[2] = {NULL, groupTopic};
    const char** const pDeviceTopic = &topicArry[0];
    #define deviceTopic (*pDeviceTopic)

Arguably not very elegant, but now when you assign, e.g.

    deviceTopic = msgTopic;

you are actually writing into `topicArry[0]`.


message:
Attempting to read random string from SD card

I was wondering if anyone knew how to read in a random string from a file named "PhraseList.csv" or "PhraseList.xlsx" (whatever is easier)? There is a list of 10k.

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

    File myFile;

    void setup()
    {

     // Open serial communications and wait for port to open:
      Serial.begin(9600);
       while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }

      Serial.print("Initializing SD card...");

      if (!SD.begin(chipSelect)) {
        Serial.println("initialization failed!");
        return;
      }
      Serial.println("initialization done.");

      // re-open the file for reading:
      myFile = SD.open("PhraseList.xlsx");
      if (myFile) {
        Serial.println("PhraseList.xlsx":);

        // read from the file until there's nothing else in it:
        while (myFile.available()) {
         Serial.write(myFile.read());
        }
        // close the file:
        myFile.close();
      } else {
       // if the file didn't open, print an error:
        Serial.println("error opening Phrase List");
      }
    }

    void loop()
    {
     // nothing happens after setup
    }

body:
Reading an individual string from a list in a file is not a simple operation. Well, it's "simple", but takes a lot of work.

It's not possible to say "Get me line number 2984 from the file" with a normal text file.  You, instead, have to get each line in turn, discarding the ones you don't want, until you get to line 2984.

A better way would be to create custom "indexed" file format with a file header structure describing the rest of the file.  That header structure would contain (amongst other possible things) the offset within the file of each string it contains.

For example you may choose to have the simplest arrangement - a list of 32 bit integers (4 bytes each), each one a simple offset from the start of the file for the string that corresponds to the same number, and have the strings NULL terminated in the file.

Such as:

    00000000: 0c000000 17000000 22000000 53747269  ........"...Stri
    00000010: 6e67206f 6e650053 7472696e 67207477  ng one.String tw
    00000020: 6f005374 72696e67 20746872 656500    o.String three.

The idea with this now is you can seek in the file to "String no * 4" and read 4 bytes as an `unsigned long` (arranged *little endian*, like the Arduino uses), then use that value to do another seek. From there you can read bytes until you hit `\0`, at which point you know you have finished the string.

In the example above the string "String one" is located at offset 12 within the file.  That's 0x0C in hexadecimal, or 0x0c 0x00 0x00 0x00 as a little-endian 32-bit integer.  That's the first 4 bytes in the file.  So you read those, interpret them as a 32-bit integer (12), then seek to that location in the file to get your string.

    void readString(int num) {
        // Seek to the index entry
        myFile.seek(num * 4);

        // Read the index entry
        unsigned long offset = 0;
        myFile.read(&offset, 4);

        // You might want to add some sanity checking here

        // Seek to where the index points to
        myFile.seek(offset);

        // Read each character until you get a NULL.
        char c = myFile.read();
        while (c > 0) {
            Serial.write(c);
            c = myFile.read();
        }
        Serial.println();
    }


message:
Am I able to set up a code where I can have two ways of turning something on?

I am pretty new to Arduino.

I've created a code with the help of many YouTube tutorials to control a servo with a button. I decided it has gotten a little un-exciting so I've been trying to add a sound sensor module to it so that if you clap or whatever, it will control the servo in the same way the servo did. Is it possible to control the servo with the button *and* the sound sensor so that I have to ways of turning on the servo at the same instance.

The code I currently have just runs the servo constantly and does not stop, you'll probably see what I mean when I attach the code below.
I'm just looking for help on this issue as I don't have a lot of experience with this, but my guess is it is not possible.

<!-- language: lang-cpp -->

        #include <Servo.h>;

        const int buttonPin = 8;
        int soundSensor = 2;
        Servo servo;

        int buttonState = 0;

        void setup()
        {
          servo.attach(3);
          servo.write(80);

          pinMode(buttonPin, INPUT);

          pinMode (soundSensor, INPUT);
        }

        void loop() {
          int statusSensor = digitalRead (soundSensor);

          if (statusSensor == 1)
          {
            servo.write(0);
            delay(1000);
            servo.write(180);
            delay(500);
          }
          else
          {
            servo.write(80);
          }

          buttonState = digitalRead(buttonPin);
          if (buttonState == HIGH)
          {
            servo.write(80);
          }
          if (buttonState == LOW)
          {
            servo.write(0);
            delay(1000);
            servo.write(180);
            delay(500);
          }
        }

body:
Just cobled this together,
untested but should give you some hints in the right direction.

In the main loop it checks the condition of the button and also the sound detector.
If either are active it sets a bool to true.
at the end of the loop, if either are true it calls the servo function that then powers the servo.
hopefully you will be able to pull this apart to add more triggers

    #include <Servo.h>;

    const int buttonPin = 8;
    int soundSensor = 2;
    Servo servo;

    int buttonState = 0;
    int statusSensor = 0;

    bool runServo = false;  // bool setting to start the servo

    void setup()
    {
      servo.attach(3);
      servo.write(80);

      pinMode(buttonPin, INPUT);
      pinMode (soundSensor, INPUT);
    }

    void loop() {
      statusSensor = digitalRead (soundSensor);
      buttonState = digitalRead(buttonPin);

        runServo = false;  // start of loop reset the runServo flag

      if (statusSensor == 1)
      {
        runServo = true;
      }

      if (buttonState == HIGH)
      {
        runServo = true
      }

      if (runServo == true)
      {
        servoFunction();//call the servoFunction code
      }

    };

    void servoFunction(){
        servo.write(0);
        delay(1000);
        servo.write(180);
        delay(500);

    }

Spriggsy


message:
Keyboard.h: No such file or directory - Arduino pro micro (leonardo)

I've just bought a new pro-micro and I want to simulate some keyboard inputs with it, the thing is the Arduino IDE (version 2:1.0.5) can't seem to find neither HID.h or Keyboard.h libraries. The steps to reproduce the problem are:

- plug the device using usb cable on the pc
- Open arduino ide
- try to compile my code
- it fails with the error

>test_keyboard.ino:27:22: fatal error: Keyboard.h: No such file or directory
compilation terminated.

The code is:

    #include <Keyboard.h>

    void typeKey(int key)
    {
      Keyboard.press(key);
      delay(50);
      Keyboard.release(key);
    }

    /* Init function */
    void setup()
    {
      // Begining the Keyboard stream
      Keyboard.begin();

      delay(400);

      //Keyboard.press(KEY_LEFT_GUI);

      Keyboard.press(KEY_CTRL);
      Keyboard.press(KEY_ALT);
      Keyboard.press(KEY_T);

      Keyboard.releaseAll();

      delay(100);

      Keyboard.print("echo 'hello world'");

      typeKey(KEY_RETURN);

      delay(100);

      // Ending stream
      Keyboard.end();
    }

    /* Unused endless loop */
    void loop() {}

By the way, I'm running this on linux, after pluging it and running `lsusb` on terminal I got:
  `Bus 002 Device 071: ID 2341:8036 Arduino SA Leonardo (CDC ACM, HID)`

body:
The Keyboard functions were moved into their own library in Arduino IDE 1.6.6/Arduino AVR Boards 1.6.9. In previous Arduino AVR Boards versions, those functions were part of the core library and there was no Keyboard library or Keyboard.h. Since you're using a very outdated version of the Arduino IDE, you don't have a Keyboard library, thus the error. There are two options to solve this problem:

- Remove the line `#include <Keyboard.h>` from your sketch.
- Update to a modern version of the Arduino IDE. Note that when you install the Arduino IDE via `sudo apt-get install arduino`, [you end up with the very outdated IDE version](https://github.com/arduino/Arduino/pull/2703) you're using. I recommend always installing the official Arduino IDE downloaded from https://www.arduino.cc/en/Main/Software.

----
For anyone wanting to write code that's backwards compatible with old IDE versions, you can do this:

<!-- language: lang-cpp -->

    #if ARDUINO > 10605
    #include <Keyboard.h>
    #endif

----
Reference: https://github.com/arduino/Arduino/pull/3304


body:
Don't hang around in the stone age, step forward to 2019 and join us with the newest Arduino IDE.

Do you use the newest linux version, for example Ubuntu 18.10?

Remove all arduino related packages from the repositories.
Be sure to remove the package librxtx-java.
You don't need to install Java, jdk, openjdk, jre or any of those.
If you use snap, remove the Java and Arduino from the snap as well.

When you have used such an old version, I suggest to delete the hidden `.arduino15` folder from your HOME folder.

Perhaps you have downloaded libraries that are now included with the Arduino IDE. You could check the "libraries" folder (in the same folder as the folders of your projects) and delete unused libraries.

Download the Arduino IDE [from the arduino.cc website][1].
The 32-bit version for a 32-bit linux system, and the 64-bit version for a 64-bit linux system.
Unpack it somewhere in under your HOME folder. You can make a shortcut to the file "arduino" and run the shortcut.
Don't make changes to the stardard Arduino system files (the Arduino IDE that you have downloaded and unpacked). Sometimes it is needed to make changes to the files in the hidden `.arduino15` folder.

  [1]: https://www.arduino.cc/en/Main/Software


message:
Can the IDE handle a 32khz main clock?

I read somewhere that having the main clock be 32768Hz messes not only with micros() and millis(), but with some other stuff too. Is this true? Will I have to forgo the Arduino IDE to program for an avr running at 32768Hz?

body:
Yes, things will break. The main culpret is this:

    #define clockCyclesPerMicrosecond() ( F_CPU / 1000000L )

With any value below 1000000 the result of that calculation will be 0.

That means code like `micros()` will break, since it uses:

    return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());

64/0 is ... um ... yes... And whatever that ends up being is then multiplying the tick count. So ... the result of `micros()` is ... um ... yes...

In fact, when trying to compile anything you get (certainly on UECIDE):

    • Error at line 103 in file wiring.c:
        ‣ division by zero [-Werror=div-by-zero]

Since that's erroring when compiling code there's not a lot you can do about it.

However, one idea does spring to mind - one that is a little "crazy" I guess.

* Set your boards.txt entry to 3276800Hz

The calculations will all then be valid - however, they will all be *out by a factor of 100*.

With the board actually running at 32768, and the API thinking it runs at 3276800, all you need to do is use values 100x less than you would normally in your calculations.

For instance, to delay 1 second you'd use `delay(10);` instead of `delay(1000);`.  Or you'd multiply the return value of `millis()` by 100 to get the real number of milliseconds.

Baud rates will have to be 100x faster - so use `Serial.begin(960000);` instead of `Serial.begin(9600);`.

Of course, the `clockCyclesPerMicrosecond()` is not geared towards working with values like 3276800, and `F_CPU/1000000L` will result in `3` not `3.2768` as you'd like, so timing calculations will be a little bit off. You may need to tweak things like baud rates accordingly to compensate.


message:
Can I control 4 DC Brushless motors with arduino uno and Adafruit motor shield?

I need to control 4 DC brushless motors. I have no experience with arduino or coding. After some research the cleanest setup seems to be using the Adafruit motor shield, however the motors I'm using have 5 wires. Can I still make this work? I envision the motors being connected to the shield via the negative and positive power wires, but what do I do with the rest?  Thank you in advance.

body:
You don't need the motor shield at all. The motor you link to has its own driver built in.

According to the connection table on the page you link to:

* Red wire to +24V
* Green wire is for sensing the RPM - you can ignore it
* Yellow wire is the direction select - connect to any GPIO
* Black wire is ground - connect to 24V GND *and* Arduino GND.
* Blue wire is PWM control. Connect to any PWM output on the Arduino

Note that the motor will probably spin immediately power is applied until your sketch tells it to stop by driving the PWM output LOW (or 0% duty cycle).  There appears to be a 15-25kΩ (typical) pullup resistor on that pin, so adding a smaller pulldown resistor (say 1kΩ) on it should force it to be off until you turn it on.


message:
Array is affecting digitalread values

i want to turn on an led with two buttons. If either of the buttons is pressed i want the led to turn on while the button is pressed and stay off if nothing is pressed. i have two sets of code, they both do the same thing, but the second set of code causes the led to stay in the on position even when nothing is being pushed and i dont understand why.. i am using pulldown resistors on both the buttons.

This is the first set of code that works properly:

    class Button {

      public:

        int pin;
        int state;
        int location;
        int Speed;
        int Direction;
        int active;
        int prevstate;

        Button(int pin1, int state1, int location1, int active1, int previousState)
        {
          pin = pin1;
          state = state1;
          location = location1;
          active = active1;
          prevstate = previousState;
        }
    };

    Button button(7,0,0,0,0);
    Button button2(8,0,0,0,0);
    Button buttons[2] = {button, button2};

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

    void loop() {
       if (digitalRead(button2.pin) == HIGH){
                 digitalWrite(ledPin, HIGH);
              } else {
              // turn LED off:
              digitalWrite(ledPin, LOW);
              }
           if (digitalRead(button.pin) == HIGH){
                 digitalWrite(ledPin, HIGH);
              } else {
              // turn LED off:
              digitalWrite(ledPin, LOW);
              }
    }

this is the code i want to use but it is not working.. the led stays in the on position:

    void loop(){
      for (int i = 0; i<sizeof(buttons); i++){
        if(digitalRead(buttons[i].pin) == HIGH){
              digitalWrite(ledPin, HIGH);
              } else {
              // turn LED off:
              digitalWrite(ledPin, LOW);
              }
        }
    }

also if i change

    if(digitalRead(buttons[i].pin) == HIGH)

to

    if(digitalRead(buttons[0].pin) == HIGH)

the code works for the first or second button alone in the array.. but not both???

body:
I have to disagree that your first sketch is working. I suppose that a very fast blinking led seems to be "on".

When you describe what should happen in a logic way, then you can put that into code.

The logic is: The led is on, if at least one of the buttons is pressed.
In other words: The led is off, if no button is pressed, else the led is on.

This logic has as a result that the led stays on if a second button is pressed and after that the first button is released. I assume this is okay.

For **two buttons** it is possible to check both conditions.

    if (digitalRead(button.pin) == HIGH || digitalRead(button2.pin) == HIGH)
      digitalWrite(ledPin, HIGH);
    else
      digitalWrite(ledPin, LOW);

Or test for LOW:

    if (digitalRead(button.pin) == LOW && digitalRead(button2.pin) == LOW)
      digitalWrite(ledPin, LOW);
    else
      digitalWrite(ledPin, HIGH);

For **multiple buttons**, a `bool` can be used or the number of pressed buttons can be counted.

A fixed number for the array size is easy and has less chance for a mistake:

    #define BUTTONS_COUNT 2

It is also possible to use `sizeof()`. The total size has to be divided by the size of one element:

    int count = 0;
    for (int i = 0; i<sizeof(buttons)/sizeof(Button); i++) {
      if (digitalRead(buttons[i].pin) == HIGH) {
        count++;
      }
    }

    if (count == 0)
      digitalWrite(ledPin, LOW);
    else
      digitalWrite(ledPin, HIGH);


body:
You seem to have made 4 button objects: button, button2, and buttons[2]. buttons[0] and buttons[1] are full button objects whose first member, .pin, is initialized to the addresses of `button` and `button2`, respectively. This is probably not what you intended.

Did you mean to create:

    Button buttons[2] = {
       {7,0,0,0,0},
       {8,0,0,0,0}
    };

, an array of two initialized button objects?


message:
How do I make a Servo Stop if it Hits Resistance?

I am trying to make a device which will turn a turn key with a servo.

However, I want it to stop turning the turn key if the resistance is too great (meaning it is locked and will not ever turn).

How do I do this? Would I just tell it to turn and then have it turn back after a time (because if it is locked or not it should be done within that time)?

I do not want to damage my servo by having it try to turn something that it can't turn.

I am using an Arduino Uno and the library "Servo.h". The servo being used is a Batan S1123.

body:
The best way is use external feedback. Hall sensor for example.
200-250ms after using servo check status of hall sensor


body:
You could either:

 1. Use a limit-switch to sense that the servo has completed it move. If it doesn't complete it a reasonable time, return it to its original position. Or,

 2. Measure the motor current by putting a low value resistor inline with the ground side of the motor's power supply. With one of the A/D pins, measure the voltage on the motor side of the resistor, which increases with motor current. You'll need to have figured out how much current the motor draws when operating normally. If the motor stalls, your controller could sense that by seeing that current increase. Pick a value (try 150%, for example) of over-current as an indicator that the motor is stalled, and return it to its original position.

The first way is easier to implement but possibly lets the motor stall while you wait for the expected move time to expire. The second way lets you detect stalling and take action immediately.


body: I suggest detecting the current flowing through the servo or using a potentiometer to detect whether the servo is moving. You could also put a clutch between the servo and the key, but then you wouldn't know the angle of the key at any given time.


body:
It depends on what kind of failure you expect. If you're afraid the motor may break your linkage (the gears, cranks, belts, whatever you have in place), you have to react very fast, and it's only feasible with a current measurement. That would require sensing the current and reacting very quickly on over-current to be effective.

If you know for a fact that your linkage can withstand the stall torque of the motor, you just have to worry about overheating the motor. Such a protection can be done with a position sensor or a limit switch if you happen to have one. You could even implement a protection with no sensors at all: drive the motor for just long enough to do its job and then stop: either it will turn the key or it won't, but it won't overheat if stalled for a second or two.


message:
How to handle concurrent HTTP request when using interrupt

I'm trying to make a door sensor with a reed switch. Each time the there is a change, the ESP8266 sends an HTTP request to web service.

Unfortunately, the ESP8266 serial monitor dumps a huge stack trace when I'm approaching the magnet to the reed switch:

    Exception (9):
    epc1=0x40104b14 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000003 depc=0x00000000

    ctx: sys
    sp: 3fffeb20 end: 3fffffb0 offset: 01a0

    >>>stack>>>
    3fffecc0:  00000002 00000006 3ffefdc4 40227108
    3fffecd0:  3ffefa74 00000002 00000014 401004e4
    3fffece0:  3ffeffbc 3ffeffc0 00000006 00000001
    3fffecf0:  402253bc 00000000 00000010 00000000
    3fffed00:  00000000 4bc6a7f0 81cac083 00000000
    3fffed10:  00000000 00000000 4bc6a7f0 00000000
    3fffed20:  40104d40 0037d809 3ffeecd0 00000000
    3fffed30:  3ffee520 3ffeecd0 3ffeffbc 40224398
    3fffed40:  00000000 00200085 40201578 00001388
    3fffed50:  3ffeecd0 00000000 00000050 00000050
    3fffed60:  00000000 3fffedd0 3ffefd34 402032e5
    3fffed70:  1301a8c0 00000031 3ffeebbc 402039cc
    3fffed80:  3ffeedb8 000000ef 000000ef 00000020
    3fffed90:  ffffffff 00000050 3fffedd0 40202d5c
    3fffeda0:  40204738 1301a8c0 40204738 1301a8c0
    3fffedb0:  3ffe8a64 00000005 000...

I think it's because the ESP8266 tries to make concurrent HTTP calls...
How can I solve this?

Here is the code:

    // https://www.instructables.com/id/Arduino-Software-debouncing-in-interrupt-function/
    // #include "util/atomic.h"
    #include "ESP8266WiFi.h"
    #include "ESP8266HTTPClient.h"
    #include "Wire.h"

    const char* ssid = "****";
    const char* pass = "****";
    const byte interruptPin = 5;
    long debouncing_time = 50; //Debouncing Time in Milliseconds
    volatile unsigned long last_micros;
    const char* host= "192.168.1.19";
    const char* doorStates[2] = {"closed", "opened"};

    void connection()
    {
      // Establish a WIFI connection
    }

    void setup()
    {
      Serial.begin(115200);
      connection();
      pinMode(interruptPin, OUTPUT);

      // Attaching interrupt
      attachInterrupt(digitalPinToInterrupt(interruptPin), handleInterrupt, CHANGE);
    }

    void loop()
    {
      delay(1000);
    }

    void handleInterrupt() {
      if ((long)(micros() - last_micros) >= debouncing_time * 1000) {
        int val = digitalRead(interruptPin);
          notify(val);
      }
      last_micros = micros();
    }
    // Make HTTP Call to web service
    void notify(int val)
    {
      WiFiClient client;
      const String frontDoorState = doorStates[val];
      String url = "http://192.168.1.19/alarm/front-door/state/" + frontDoorState;
      client.connect(host, 80);
        client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                     "Host: 192.168.1.19\r\n" +
                     "Connection: close\r\n\r\n");
                     client.stop();
    }

body:
Simple: don't do HTTP requests in the interrupt.

It's usually bad to do anything heavy like that in an interrupt.  Instead you should just set a flag in the interrupt (`volatile bool`) and examine that flag in `loop()`.

    volatile bool sendNotification = false;
    volatile int notifyVal = 0;

    void loop() {
        if (sendNotification) {
            notify(notifyVal);
            sendNotification = false;
        }
    }

    void handleInterrupt() {
        if ((long)(micros() - last_micros) >= debouncing_time * 1000) {
            notifyVal = digitalRead(interruptPin);
            sendNotification = true;
        }
        last_micros = micros();
    }


message:
Can't upload sketch - avrdude: butterfly_recv(): programmer is not responding

I'm trying to upload a Blink example to run on a pro-micro (leonardo) but it is not working anymore (it was just working yesterday).

Steps to reproduce:

- Plug the device in USB port
- Open Blink example in Arduino IDE (version 1.8.8)
- Select the port and board accordingly to Arduino Leonardo
- Compile and try to upload it.

The code compile successfully but when uploading it just halts. The ide console displays:

> avrdude: error: programmer did not respond to command: exit bootloader
>
> Forcing reset using 1200bps open/close on port /dev/ttyACM0 PORTS
> {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } /
> {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
> PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, }
> / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } =>
> {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS
> {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } /
> {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
> PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, }
> / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } =>
> {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS
> {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } /
> {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {}
> PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, }
> / {/dev/ttyACM0, } => {} PORTS {/dev/ttyACM0, } / {/dev/ttyACM0, } =>
> {} Uploading using selected port: /dev/ttyACM0
> /home/fabio/Downloads/pacotes/arduino-1.8.8/hardware/tools/avr/bin/avrdude
> -C/home/fabio/Downloads/pacotes/arduino-1.8.8/hardware/tools/avr/etc/avrdude.conf
> -v -patmega32u4 -cavr109 -P/dev/ttyACM0 -b57600 -D -Uflash:w:/tmp/arduino_build_350609/Blink.ino.hex:i
>
> avrdude: Version 6.3-20171130
>          Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
>          Copyright (c) 2007-2014 Joerg Wunsch
>
>          System wide configuration file is "/home/fabio/Downloads/pacotes/arduino-1.8.8/hardware/tools/avr/etc/avrdude.conf"
>          User configuration file is "/home/fabio/.avrduderc"
>          User configuration file does not exist or is not a regular file, skipping
>
>          Using Port                    : /dev/ttyACM0
>          Using Programmer              : avr109
>          Overriding Baud Rate          : 57600
>          AVR Part                      : ATmega32U4
>          Chip Erase delay              : 9000 us
>          PAGEL                         : PD7
>          BS2                           : PA0
>          RESET disposition             : dedicated
>          RETRY pulse                   : SCK
>          serial program mode           : yes
>          parallel program mode         : yes
>          Timeout                       : 200
>          StabDelay                     : 100
>          CmdexeDelay                   : 25
>          SyncLoops                     : 32
>          ByteDelay                     : 0
>          PollIndex                     : 3
>          PollValue                     : 0x53
>          Memory Detail                 :
>
>                                   Block Poll               Page                       Polled
>            Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
>            ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
>            eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
>            flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
>            lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
>            hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
>            efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
>            lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
>            calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
>            signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00
>
>          Programmer Type : butterfly
>          Description     : Atmel AppNote AVR109 Boot Loader
>
> Connecting to programmer: .avrdude: butterfly_recv(): programmer is
> not responding
>
> avrdude: butterfly_recv(): programmer is not responding

A strange behavior I noticed is each time I plug the device again in the usb port different leds are light up, some times only RX, sometimes only TX and sometimes none (the power led is always on)

What could be happening here? Can it be the problem on the hardware?

body:
I have successfully solved this a year ago and I am trying to remember how I did it. So while it's fresh in my head this thing has to do with the bootloder.

The first and most obvious thing you can do is try to doubletap the reset and ground contact. Double tapping it will force the Arduino to reset and start in the bootloader for 8 seconds.

This is how I managed to install the driver for my pro-micro, it wouldn't install unless you did it when Arduino was in bootloader mode. But this strategy doesn't work for the code upload for some reason although many people claim it was the only thing that helped.

Another thing that could maybe help is clearing the Arduino's cache. When I was trying to compile a year ago, after many attempts I had to clear the pro-micro with another Arduino once in a while (you may need this later on). *[thebusybee's note: I never heard about a cache in AVR micros. If a sketch is uploaded it will be flashed into the non-volatile memory overwriting all that was at its place before.]*

Something else I remembered (if this is the case it would make things very problematic for me) is the USB cable. Again before my 1 year break I remembered that uploading the sketch for me only worked with 1 out of like 15 micro-USB cables I had (the one that's the shortest and thickest). That cable is broken now so I can't really check this unless I start researching microUSB cables right this instant.

Finally it may be the system. If nothing works try uploading the sketch from another preferably clean system.

Anyway, I hope you solve this because I am trying to solve the same issue.

Good luck


body:
I experienced the same frustrating issue for days. It was Ubuntu.

The fix was also so easy: sudo apt purge modemmanager

Until I discovered it, I suffered headache for days.

The auto upgrader may cause issues with this command. It can be solved
with the following command:

sudo dpkg-reconfigure -plow unattended-upgrades

At the first prompt, choose not to download and install updates.
Then reboot.


message:
How to drive N channel gate correctly from Adafruit Feather pinout?

I am learning how to create a soft latch power switch, using an N channel mosfet.

Currently, I have this:

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

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

<!-- End schematic -->

The idea is (so far) that I can turn it on with the switch, the Arduino immediately brings the power control high (ensuring the FET stays on), and brings that same pin low after 1.5s (simulating a timed shutdown).

However; when the power control goes low, I still see about 1.8v in the power control line (I'm presuming its floating?), which leaves this particular FET partially open.

If I disconnect the power control line from the MCU, I get the behaviour I expect. I can touch the power control to +ve and the FET will switch on.  If I lift the control line from +ve, the FET closes the gate, due to the pull down resistor.

I'm struggling to understand why the FET works in isolation, but does not work when connected to the MCU output pin.  The pinMode is OUTPUT.

FET (3055VL): https://www.onsemi.com/pub/Collateral/MTP3055VL-D.PDF

Here's the test code I'm using.
It simply flashes a build in LED 10 times then does a power off.

    int ledPIN = 17;
    int controlPin = 11;
    int lDelay = 150;

    bool shouldBeUp = true;

    void setup()
    {
      pinMode(ledPIN, OUTPUT);
      pinMode(controlPin, OUTPUT);
      digitalWrite(controlPin, HIGH);
    }

    void loop()
    {
      if (shouldBeUp) {
        for (int i = 0; i < 10; i++)
        {
          digitalWrite(ledPIN, LOW); // on
          delay(lDelay);
          digitalWrite(ledPIN, HIGH); // off
          delay(lDelay / 2);
        }

        // Leave the LED low
        digitalWrite(ledPIN, LOW);
        digitalWrite(controlPin, LOW);
        shouldBeUp = false;
      }
    }

Any help is appreciated! Thank you :)

body:
Your problem is that the GPIO pin is referenced to ground - and the MOSFET is isolating that ground.

You need instead to switch the power not the ground - and for that, you use a P-channel MOSFET.

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

<!-- End schematic -->

To hold the power on you now set the GPIO LOW instead of HIGH.

If you need to switch a higher voltage than the operating voltage of the MCU you will need to add another N-channel MOSFET to pull down the P-channel's gate.


message:
how can I upload a hex file to an arduino uno?

I have a Rostock Max 3d with an Arduino Uno as the controller. The OEM has a firmware version I would like to upload, but it is in the hex file format.

I have looked all over the Arduino IDE, but did not found a way to upload a hex file to the Arduino. I tried using AVRDUDE, but the Arduino only communicates with my PC when I set the "Programmer" to AVRISP. I have uploaded other codes for blink, and hello_world, but haven't been able to compile the firmware source. I was hoping I could just use the hexfile included in the firmware package.

My OS is Linux.

body:
I recommend looking at the arduino IDE files located at **"(install path)/hardware/arduino/avr/"** (on windows anyway, I should assume the same on linux).

I am unsure if the following files have the .txt extension on them, but if not use just the file name.

----------

Open and look in "boards.txt" and find the associated entries starting with "**uno.**" keeping this file open.

Next open "platform.txt" looking for the entries "**tools.avrdude**" (the avrdude part comes from boards.txt "uno.upload.tool" entry) and copy into a new text editor the value of "**tools.avrdude.upload.pattern**" you can fill in the parameters later.

With the command you copied replace the following:

from platform.txt

 - "**{cmd.path}**" = "**tools.avrdude.cmd.path**"
 - "**{config.path}**" = "**tools.avrdude.config.path**"
 - "**{upload.verbose}**" = "**tools.avrdude.upload.params.verbose**"
 - "**{upload.verify}** = "**tools.avrdude.upload.verify**"

now from boards.txt

 - "**{build.mcu}**" = "**uno.build.mcu**"
 - "**{upload.protocol}** = "**uno.upload.protocol**
 - "**{{serial.port}**" = Your serial port (according to research something like **/dev/ttyS0**)
 - "**{upload.speed}**" = "**uno.upload.speed**"
 - "**{build.path}**" and "**{build.project_name}** = path to file you are trying to upload

So with the above set out for me to upload a program to an Arduino uno I would use something like the following in windows:

assuming install path was "C:\Arduino\"
> "C:\Arduino\hardware\tools\avr\bin\avrdude.exe" "-CC:\Arduino\hardware\tools\avr\etc\avrdude.conf" -v -patmega328p -carduino "-PCOM1" -b115200 -D "-Uflash:w:C:\MyArduinoProject\build.hex:i"

for linux it could possibly be (I really am unsure):

assuming install path was "/opt/Arduino/"
> "/opt/Arduino/hardware/tools/avr/bin/avrdude" "-C/opt/Arduino/hardware/tools/avr/etc/avrdude.conf" -v -patmega328p -carduino "-P/dev/ttyS0" -b115200 -D "-Uflash:w:/usr/MyArduinoProject/build.hex:i"

----------

The above should work for you, I have previously written my own program to upload a hex file to the Arduino utilizing the above commands and avrdude.


body:
I use a standalone programmer that uploads a .hex file from an SD card via the ICSP interface.

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

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


body:
I think you can use this software http://www.mediafire.com/file/tx2l85gsdkpf5d4/HEXtoArduino_V1.0.0.zip/file
[![enter image description here][1]][1]

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


body:
I found the definitive answer to this.

1. Start Arduino IDE
2. To to File...Preferences...
3. Turn on Show verbose output during: [X] upload (image 1 below)
4. Upload a sketch to your Arduino Uno
5. I used the sample blink sketch and saw the following (image 2 below):

**AVRDude: is used to upload**

You want that first line shown in white --- when you expand it you'll see that it is the entire line of code that is used to upload the HEX file of your program to the Uno.

The entire command on my computer looks like the following:

    C:\Users\<username>\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude -CC:\Users\<username>\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:C:\Users\<username>\dev\arduino\STK2UPDI\build\blink.ino.hex:i

I'm going to break this down into a few lines:

First, it's the full path to the avrdude exe.
Then it is passing the -C argument with the full path to the `avrdude.conf` file

`c:\longpath\avrdude -C C:\avrdude.conf`

Then a bunch of params to set up avrdude properly:
`-v -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:`

And finally the full path to the HEX file you want to upload

`c:\longpath\blink.ino.hex:i`

**All You Have To Do**

All you have to do is take that extremely long line and replace the full-path to the hex file to be your target HEX file and then run the entire command and you'll see something **like what is shown in image 3 below**.

**Image 1**

[![verbose output][1]][1]

**Image 2**

[![upload info][2]][2]

**Image 3**
[![upload success][3]][3]

  [1]: https://i.stack.imgur.com/7zllb.png
  [2]: https://i.stack.imgur.com/hykpi.png
  [3]: https://i.stack.imgur.com/O7KUL.png


message:
ESP-8266 stopped working due to possibly faulty perfboard layout

I have been following [this tutorial](http://www.deviceplus.com/how-tos/arduino-guide/esp8266-setup-tutorial-using-arduino/) to set up my ESP8266. I have also recreated on a perfboard the circuit provided in the tutorial, and I intend to use this perfboard circuit in my project.

The problem arises when I plug my ESP into the perfboard and try to talk to it through the serial monitor. When using a baud rate of 115200, the ESP responds to commands but in a garbled format. Also, the blue LED stays on after powerup for increasingly long periods of time. Now the blue LED is always on and the ESP no longer responds to any commands, except when reset and asked for the startup firmware info. I suspect that the ESP is now broken but am not sure how to check.

Also note that the ESP was working fine on a breadboard at 9600 baud, prior to the blue LED incident. Now it won't work with the breadboard either.

All commands were sent with newline and carriage return.

Is the ESP8266 broken? Could there be something wrong with my perfboard circuit? The circuit is rather dense and contains wiring for several other components in addition to the ESP-8266.

body: It turns out the real culprit was the `AT+IPR=9600` command bricking the board. The board was "fixed" by obtaining the [firmware](https://github.com/espressif/ESP8266_NONOS_SDK) and flashing it to the board using `esptool.py`. Download the repo's source code, navigate to the directory `bin/at/`, and see the file `README.md` to see which addresses to flash the different parts to.


message:
Precise On/Off control for IR LED

My goal is to be able to send/receive IR messages in my own custom format and send messages ~10 bytes long. My message object will get serialized down to individual bits, which are transmitted by turning the IR LED on/off at specific timings of my choosing to represent logical ones and zeros. From what I've seen, an IR LED can be turned on/off in either a while loop or as a PWM signal in order to transmit the message. I'm under the assumption the only thing gained by using a PWM signal is that the work there is done on a timer callback and let other code run seemingly simultaneously. For simplicity, I opted for the while loop approach.

The issue I am seeing is one of two. Either the receiver is not reading the timings right, or the transmitter is not turning the LED on/off as fast as I would expect.

For the example code below, the IR LED is turned on for 600 microseconds, and off for 300. (Eventually, my custom messages will be built up using something along these lines.) However, as you can see in the Sample Outputs below the receiver is not seeing the IR signal as on or off for anywhere near that amount of time.

Not sure if this is a setup issue, or something else. The two Arduino boards I'm using are both Arduino Pro ATmega328p boards. For the board sending the IR signal, Pin 6 goes to a 330 Ohm resistor, then to the LED, then to ground. The IR Receiver on the other board has no resistors, just direct connections to pins. When reading the IR signals, I hold the receiver a few centimeters away from the LED.

My questions are:

  1. Is this a viable setup? Should this work? Or am I all wrong in my assumptions and need to look some other way of doing this?
  1. Is my assumption about turning the LED on/off with a while loop vs. a PWM signal true? Or should I remove the loop concept and only use a PWM signal.

IR Transmit Code:
```
#define IRpin          6

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

void loop() {
  //LED On
  PORTD |= (1 << IRpin);
  delayMicroseconds(600);

  //LED Off
  PORTD &= ~(1 << IRpin);
  delayMicroseconds(300);
}
```

IR Receive Code (taken from an online example, only modifications are to output text):
```
#define IRpin_PIN      PIND
#define IRpin          2

// the maximum pulse we'll listen for - 65 milliseconds is a long time
#define MAXPULSE 65000
#define RESOLUTION 20

uint16_t pulses[300][2];  // pair is high and low pulse
uint8_t currentpulse = 0; // index for pulses we're storing

void setup(void) {
  Serial.begin(9600);
  Serial.println("Ready to decode IR!");
}

void loop(void) {
  uint16_t highpulse, lowpulse;  // temporary storage timing
  highpulse = lowpulse = 0; // start out with no pulse length

  while (IRpin_PIN & (1 << IRpin)) {
    // count off another few microseconds
    highpulse++;
    delayMicroseconds(RESOLUTION);

    // If the pulse is too long, we 'timed out' - either nothing
    // was received or the code is finished, so print what
    // we've grabbed so far, and then reset
    if ((highpulse >= MAXPULSE) && (currentpulse != 0)) {
      printpulses();
      currentpulse = 0;
      return;
    }
  }
  // we didn't time out so lets stash the reading
  pulses[currentpulse][0] = highpulse;

  // same as above
  while (! (IRpin_PIN & _BV(IRpin))) {
    // pin is still LOW
    lowpulse++;
    delayMicroseconds(RESOLUTION);
    if ((lowpulse >= MAXPULSE)  && (currentpulse != 0)) {
      Serial.println("Breaking - Hit max Pulse Low");
      printpulses();
      currentpulse = 0;
      return;
    }
  }
  pulses[currentpulse][1] = lowpulse;

  // we read one high-low pulse successfully, continue!
  currentpulse++;
}

void printpulses(void) {
  uint32_t totalMicroseconds = 0;
  for (uint8_t i = 0; i < currentpulse - 1; i++) {
    Serial.print("On(");
    Serial.print(pulses[i][1] * RESOLUTION , DEC);
    Serial.print(");");
    Serial.println("");
    Serial.print("   Off(");
    Serial.print(pulses[i + 1][0] * RESOLUTION , DEC);
    Serial.println(");");

    totalMicroseconds += pulses[i][1] * RESOLUTION;
    totalMicroseconds += pulses[i + 1][0] * RESOLUTION;

    if (i % 8 == 0) {
      Serial.println("");
    }
  }

  Serial.print("On(");
  Serial.print(pulses[currentpulse - 1][1] * RESOLUTION, DEC);
  Serial.print(");");
  totalMicroseconds += pulses[currentpulse - 1][1] * RESOLUTION;

  Serial.println("");
  Serial.print("Total Microseconds: ");
  Serial.println(totalMicroseconds, DEC);
}
```

Sample Outputs:
```
Ready to decode IR!
On(20);
   Off(62064);

On(0);
   Off(12060);
On(360);
   Off(1860);
On(440);
   Off(8940);
On(20);
   Off(15460);
On(80);
   Off(25672);
On(40);
Total Microseconds: 127016
On(40);
   Off(6740);

On(300);
   Off(6740);
On(20);
   Off(8520);
On(40);
   Off(6740);
On(1540);
   Off(15720);
On(40);
   Off(34860);
On(20);
Total Microseconds: 81320

On(3000);
   Off(35384);

On(40);
   Off(14180);
On(1220);
   Off(54440);
On(980);
Total Microseconds: 109244

On(200);
Total Microseconds: 200
On(20);
   Off(29160);

On(60);
   Off(26700);
On(60);
   Off(22880);
On(20);
   Off(2928);
On(20);
Total Microseconds: 81848
```

body:
I ended up also asking this question at electronics.stackexchange.com. I know that's frowned upon, but the topic really did toe the line between being an Arduino subject or electronics.

To summarize the accepted answer, no IR messages cannot be sent/received the way I thought. The IR LED needs to be on/off at a frequency that matches what the receiver is set to be able to receive. Generally 38kh. So On for 13 microseconds, then Off for 13 microseconds. Then repeat.

https://electronics.stackexchange.com/questions/417387/precise-on-off-control-for-ir-led/417391


message:
Please Correct my Delay Code without using delay();

This is my `loop()`function:

    if(Serial.read() == 't') {
      tarestate = true;
    }

    while(tarestate == true) {
      timeNowTare = mills();
      if(mills() - timeNowTare >= 3000) {
        Serial.println("Tare");
      }
      tareState = false;
    }

Where `tareStare` is a boolean, `timeNowTare` is a long.

I need to print on serial:

> Tare

three seconds after I enter "t" into serial.

With everything I have tried to date, the program either stops or tares immediately after entering “t”.

EDIT: Thanks to everyone who responded with answers.
The solution was simply to move the timeNowTare = true; declaration up to the Serial.read() if statement. I also changed the while loop to an if statement because it seemed to make my code run quicker.

[![final code][1]][1]

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

body:
Move `timeNowTare = millis();` inside first `if`:

    if (Serial.read() == 't') {
      tareState = true;
      timeNowTare = millis();
    }

and `tareState = false` inside second `if`:

    while (tareState) {
      if (millis() - timeNowTare >= 3000) {
        Serial.println(F("Tare"));
        tareState = false;
      }
    }


body:
The easiest solution is to just use `delay()`:

<!-- language-all: lang-c++ -->

    if (Serial.read() == 't') {
        delay(3000);
        Serial.println(F("Tare"));
    }

What? You said “no `delay()`”? OK, then just write your own
implementation of `delay()` and inline it in place of the actual call to
`delay()`:

    if (Serial.read() == 't') {
        uint32_t timeNowTare = millis();
        while (millis() - timeNowTare < 3000) continue;  // wait
        Serial.println(F("Tare"));
    }

This seems to be more or less what you attempted. You write a `while`
loop that blocks the program for three seconds. It is also what leoc7's
answer does.

However, doing so is completely foolish. Why would you write your own
version of `delay()` when the Arduino core provides you with a well
tested one? Why would you want to avoid the standard `delay()` in the
first place?

It turns out there is a very good reason to avoid `delay()`. The reason
is that `delay()` _blocks_ your program for the entire delay duration.
If your code needs to be responsive to some external inputs (as any non
trivial program at some point needs), this means within that time window
the program will be completely unresponsive. The bad thing about
`delay()` is not the implementation (there is no point in replacing it
with your own), it's the fact that it blocks your program. If you
replace `delay()` by your own blocking code you have won nothing.

The real solution is to think in terms of a finite state machine. Either
the program is running in “tare mode” or not. The possible state
transitions are:

* upon reading a `'t'` on the serial port, you enter tare mode and take
  note of the current time
* if you are already in tare mode and three seconds have elapsed since
  you entered that mode, then you print out `"Tare"` and exit tare mode.

Here is a straight forward implementation of such state machine:

    static bool tare_mode = false;
    static uint32_t tare_start_time;  // meaningful only in tare_mode
    if (Serial.read() == 't') {
        tare_mode = true;
        tare_start_time = millis();
    }
    if (tare_mode && millis() - tare_start_time >= 3000) {
        Serial.println(F("Tare"));
        tare_mode = false;
    }

Now you can add more code to `loop()` and this extra code will never be
blocked by your “tare” feature.


message:
C: No communication to a connected serial port?

I'm trying to connect to an arduino Mega At2560 unit connected via usb serial port in my linux based PC.
Using C code, I'm trying to send and receive simple text strings, just I'm able to send and receive on both sides.

On arduino:

    int incomingByte = 0;    // for incoming serial data

    void setup() {
        Serial.begin(19200);    // opens serial port, sets data rate to 9600 bps
    }

    void loop() {
      // send data only when you receive data:
      if (Serial.available() > 0) {

        // read the incoming byte:
        incomingByte = Serial.read();

        // say what you got:
        Serial.print((char)incomingByte);
      }

    }
basically just a loop that checks if there is serial data, and if so reads it and prints it back. there's a (char) conversion so I'll see right away the sent data is what I got back (linux side)

For the linux code I use the pretty standard code for opening a port which I found [here][1]

I call the Arduino "Table" as it will eventually operate a moving table through USB commands.

C file:

    #include "TableFunctions.h"

    bool connected=false;
    int fd;
    char *portname;

    int set_interface_attribs (int fd, int speed, int parity)
    {
            connected=false;
            struct termios tty;
            struct termios tty_old;
            memset(&tty, 0, sizeof tty);
            if (tcgetattr (fd, &tty) != 0)
            {
                    printf("PC: Error %d from tcgetattr  \n", errno);
                    return -1;
            }
            tty_old = tty;

            cfsetospeed (&tty, (speed_t)B19200);
            cfsetispeed (&tty, (speed_t)B19200);

            //tty.c_cflag |= B19200;
            tty.c_cflag     &=  ~PARENB;            // Make 8n1
            tty.c_cflag     &=  ~CSTOPB;
            tty.c_cflag     &=  ~CSIZE;
            tty.c_cflag     |=  CS8;

            tty.c_cflag     &=  ~CRTSCTS;           // no flow control
            tty.c_cc[VMIN]   =  1;                  // read doesn't block
            tty.c_cc[VTIME]  =  5;                  //
            tty.c_cflag     |=  CREAD | CLOCAL;     // turn on READ & ignore ctrl lines
            cfmakeraw(&tty);
            tcflush( fd, TCIFLUSH );

            if (tcsetattr (fd, TCSANOW, &tty) != 0)
            {
                    printf("PC: Error %d from tcsetattr  \n", errno);
                    return -1;
            }
            return 0;
    }

    void set_blocking(int fd, int should_block)
    {
            struct termios tty;
            memset(&tty, 0, sizeof tty);
            if (tcgetattr (fd, &tty) != 0)
            {
                    printf("PC: Error %d from tggetattr  \n", errno);
                    return;
            }

            tty.c_cc[VMIN]  = should_block ? 1 : 0;
            tty.c_cc[VTIME] = 10;            // 0.5 seconds read timeout

            if (tcsetattr (fd, TCSANOW, &tty) != 0)
                    printf("PC: Error %d setting term attributes  \n", errno);
    }

    void OpenSerialPort()
    {
        char *portname = "/dev/ttyACM0";

        printf("PC: Opening port to table \n");

        int fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);

        usleep(2000000);
        if (fd < 0)
        {
            printf("PC: Error %d opening %s: %s  \n", errno, portname, strerror(errno));
            return;
        }

        set_interface_attribs(fd, B19200, 0);  // set speed to 19,200 bps, 8n1 (no parity)
        set_blocking(fd, 0);                // set no blocking
        printf("PC: Connected\n");
        connected = true;
    }
    void PrepareWriteCommand(int numberOfCommands, const char *commands[numberOfCommands])
    {
        if(connected) //check if arduino still connected
        {
            for(int i = 0; i<numberOfCommands; i++) //go through commands
            {
                int bufferSize = strlen(commands[i]); //get the buffer size needed for this command
                char charArray[bufferSize]; //helper char array
                memcpy(charArray,commands[i],bufferSize);//copy command to the char array
                charArray[bufferSize]=0; //make sure there is a stop symbok at the end
                WriteSerialPort(charArray); //command is ready to be sent, send it.
            }
        }
    }
    int WriteSerialPort(const char *buffer)
    {
        printf("PC: Now writing: ");
        int n_written = 0; //how many bytes were written

        n_written = write(fd, buffer, strlen(buffer)); //write the command and return how many bytes were written

        printf("\n");

        //check bytes send and return ouput (error, nothing or x bytes sent)
        if(n_written<0)
        {
            printf("PC: Error %d from %s \n",errno, strerror(errno));
        }
        else if(n_written == 0)
        {
            printf("PC: Nothing was written  \n");
        }
        else
        {
            printf("PC: Written %i bytes  \n", n_written);
        }

    }

    int ReadSerialPort(char *buffer, unsigned int buff_size)
    {
        //check if arduino still connected
        if(connected)
        {
            //read the serial data
            if(read(fd,buffer,buff_size))
                return sizeof(buffer); //return how much bytes were read
            else
            {
                //else print nothing received
                printf("PC: Arduino not Connected (ReadSerialPort) \n");
            }
        }
    }

in OpenSerialPort I basically open a new fd, and call the functions that set the communication settings.
I use PrepareWriteCommand to make sure commands input from users are with a stop symbol and send them to WriteSerialPort where I use write() and print how many bytes were sent.

H file:

    #include <errno.h>
    #include <fcntl.h>
    #include <termios.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <unistd.h>
    #include <stdbool.h>

    #define MAX_DATA_LENGTH 256

    int set_interface_attribs (int fd, int speed, int parity);
    void set_blocking(int fd, int should_block);
    void OpenSerialPort();
    void PrepareWriteCommand(int numberOfCommands, const char *commands[numberOfCommands]);
    int WriteSerialPort(const char *buffer);
    int ReadSerialPort(char *buffer, unsigned int buff_size);

Main:

    #include "TableFunctions.h"
    #include <stdio.h>
    #include <stdlib.h>
    int main(int argc, char *argv[])
        {
            char output[MAX_DATA_LENGTH]; //char array to hold arduino output
            int received = 0; // check if read() got any bytes
            const char* commands[]={"test"}; //test command

            OpenSerialPort(); // open serial port

            PrepareWriteCommand((sizeof(commands)/sizeof(commands[1])),commands); //prepare command for sending

            usleep(500000); //wait for arduino response

            while(true)
            {
                ReadSerialPort(output,MAX_DATA_LENGTH);//check serial port for response
                if(strlen(output)>0) //if anything received
                {
                    printf("PC: received %i\n",received); //if yes, how many bytes
                    printf("PC: %s\n",output); //and what was received
                    usleep(500000);
                }
                else if(strlen(output)<=0) //else print nothing received
                {
                    printf("PC: Nothing received\n");
                }
            }
            return 0; //finish program
        }

I tried tweaking the tty flags settings with no success. Each time I run the C code I see the arduino resets (and after opening a new fd I give it some time for bootloading) but no communication is sent between the two.

Output:

    PC: Opening port to table
    PC: Connected
    testPC: Now writing:
    PC: Written 4 bytes

    PC: received 0
    PC:
Any help with understanding why the C code can't communicate with the Arduino will be highly appreciated!

  [1]: https://stackoverflow.com/questions/6947413/how-to-open-read-and-write-from-serial-port-in-c

body:
Problem was in OpenSerialPort(). I set another variable fd which is local, thus given priority. then when OpenSerialPort() is done, it is deleted, and the global fd remain unset. This is why I can't send anything from or to the PC.

Thanks.


message:
Simultaneous button reading?

I'm currently working on a project that requires that I simultanously check the state of two buttons. Each button HIGH state is assigned to one if loop. Here's the basic concept:

```
void loop() {
  S1_State = digitalRead(S1_Pin);
  S2_State = digitalRead(S2_Pin);
  ButtonPRESSED = false;

  P1_Time = random(2000, 5000);
  delay(P1_Time);
  digitalWrite(P1_Pin, HIGH);

  while(ButtonPRESSED == false) {
    if (S1_State == HIGH) {
       Serial.print("Player 1 wins");
       Serial.print("");
       digitalWrite(P1_Pin, LOW);
       ButtonPRESSED = true;
       delay(5000); }
    if (S2_State == HIGH) {
       Serial.print("Player 2 wins");
       Serial.print("");
       digitalWrite(P1_Pin, LOW);
       ButtonPRESSED = true;
       delay(5000); }
```
The problem is that checking for the button states this way requires that the S1_State loop _has to be read before the S2_State loop_, thus giving player 1 an advantage. Although I'm not sure how pronounced this issue is in practice, it certainly was noticable when I was first trying this project out through python code on a Pi through similar means.

Is it possible check the conditions to both if loops simultanously? If not, are there other ways to circumvent this problem?

body:
I think you want after a random time, a 'Start' LED to be lit, and whoever presses his/her button first wins.

There are some problems in your sketch:

- It seems even when a button is pressed to early, the button is still taken into account. You should check for this 'cheating'. So check directly after the 'start' LED is lit, that no buttons are pressed. If so, that player loses.
- Assuming the players are honest, you check for their buttons, which probably the first iteration it will not be pressed (that would be an immediate reaction speed). However, than you wait 5 seconds; probably both players pressed their buttons, and you check the button of the first player first. It will help, if you change the delay to 1 ms, or even remove it completely.

Untested proposal:

    int playerXWon = 0; // No player won yet, 1 = player 1 wins, 2 = player 2 wins, 3 = draw

    void loop()
    {
       // Delay for a random time.
       P1_Time = random(2000, 5000);
       delay(P1_Time);

       CheatCheck();

       if (playerXWon == 0)
       {
          // Start
          digitalWrite(P1_Pin, HIGH);

          checkFirstPress();
       }
    }

    void CheatCheck()
    {
       // Check if a player did not press its button too early.
       // (Btw, it does not matter if the player presses and release its button before the LED goes on.
       S1_State = digitalRead(S1_Pin);
       S2_State = digitalRead(S2_Pin);

       if (S1_State == HIGH)
       {
          else if (S2_State == HIGH)
          {
             PlayerWin(3);
          }
          else
          {
             PlayerWin(2);
          }
       }
       else
       {
          if (S2_State == HIGH)
          {
             PlayerWin(1);
          }
       }
    }

    void checkFirstPress()
    {
       // Whoever presses first wins.
       while (playerXWon == 0)
       {
          S1_State = digitalRead(S1_Pin);
          S2_State = digitalRead(S2_Pin);

          if (S1_State == HIGH)
          {
             if (S2_State == HIGH)
             {
                PlayerWin(3);
             }
             else if (S1_State == HIGH)
             {
                PlayerWin(1);
             }
          }
          else if (S2_State == HIGH)
          {
             PlayerWin(2);
          }
       }
    }

    void playerWins(int player)
    {
       switch (player)
       {
       case 1:
          Serial.print("Player 1 wins\n");
          break;

       case 2:
          Serial.print("Player 2 wins\n");
          break;

       case 3:
          Serial.print("Both players win\n");
          break;

        default:
           assert(NULL); // Programming error
           break;
       }

       playerXWon = player;

       digitalWrite(P1_Pin, LOW);
    }


body:
There is a very easy solution to your problem, and it's called "interrupts".

The processes inside `loop` method are executed synchronously, so always one read will be done before second one, and always one check will be done before a second one (even if they are inside one `if` statement)

Fortunately there is a way of simulating asynchronous behavior in ATmega. It's called "external interrupt". You can setup ATmega inside Arduino to stop processing `loop` method and instead immediately run a different method whenever a voltage on one of the pins change. You are "interrupting" execution of `loop`  hence the name "interrupt". In Arduino Uno this can be done (only) on pins 2 and 3.

https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/

I made a little model i Tinkercad

[![Arduino with two push buttons][1]][1]

Whenever you push left button PIN2 of the Arduino gets shorted to ground.
Whenever you push right button PIN3 of the Arduino gets shorted to ground.

And now my source code

    void setup()
    {
      pinMode(2, INPUT_PULLUP);
      pinMode(3, INPUT_PULLUP);

      interrupts();
      attachInterrupt(digitalPinToInterrupt(2), Player1ButtonPress, FALLING);
      attachInterrupt(digitalPinToInterrupt(3), Player2ButtonPress, FALLING);

      Serial.begin(9600);
    }

    void Player1ButtonPress() {
      Serial.println("Player 1 wins");
    }

    void Player2ButtonPress() {
      Serial.println("Player 2 wins");
    }

    void loop()
    {
     //nothing here
    }

And now some explanation.
In `setup` we first setup PIN2 and PIN3 as "input with pullup resistor". In our design this means that when button is not pressed those pins will have 5V on them, but as soon as the buttons are pressed voltages go down to 0V. Then we make sure that `interrupts` are turned on (they are on by default, but I like to show everyone who is reading the code that I will be using them) and then we do some `attachInterrupt` magic. We make that a "falling edge" (change from 5V to 0V) on PIN2 and PIN3 will immediately run methods `Player1ButtonPress` and `Player2ButtonPress`.

When I was playing with buttons they worked perfectly.

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

And a word about possible cheating. Keeping the button pressed does not create a "falling edge" (voltage on a pin is constantly 0) so if you only add some global variables with info when game starts and who won. Then add some conditions in the two methods responsible for interrupts. You can then use the `loop` method to start the game, and show result.

  [1]: https://i.stack.imgur.com/rUWxP.png
  [2]: https://i.stack.imgur.com/6L7e8.png


body:
Instead of using the high level digitalRead() function access the low level port registers. See [this documentation.][1]

A port register is one byte and each bit represents one of the digital inputs on the arduino.

Do something like this:

    pin_status = PIND; //Input port D (pins 0-7)
    button_1 = bitRead(pin_status, 2); // digital pin 2
    button_2 = bitRead(pin_status, 3); // digital pin 3

The values are read simultaneously so it is possible to have a tie.

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


body:
I was not sure about posting this as an answer, since it is basically some more considerations on the three existing answers (for reference, they are Michel Keijzers's one - using digitalRead -, Craig's one - read the PIND variable at once -, Filip Franik's one - use interrupts), but it became quite long and so a single comment could not fit all of this.

What you and the other answerers wrote is in theory correct. Checking the button of player 1 before player 2 gives an advantage to player one. What you lack is... How much advantage?

Mechanical actions (such as the pressing of a button) have a time duration that is around 50ms*.

Since I assume your application is a reaction time tester, human reaction times are around 250ms.

Moreover mechanical buttons have "bounces". Typical debounce times are in the range 20-100ms. You can avoid this by just checking the first edge.

A player gets an advantage if he is awarded as winner even if the button was pressed at the same time.

----------

_* I tried to find a source for this, but I was not able to get some data. I tried with an online stopwatch and pressing the two spacebars (notebook and USB keyboard) roughly at the same time, obtaining results around 75ms. This is not a real value, so if someone has some measured values or estimations feel free to comment

----------

Now, let's assume you properly coded your program so that you check for ties and avoid delays, since these will greatly affect the following measurements.

**In the `digitalRead` case** you are executing this series of actions:

 1. Read status of pin 1 - 3.6us
 2. Read status of pin 2 - 3.6us
 3. Check the statuses and decide who won - some tens of instructions (about 1us)
 4. Loop - a couple instructions (0.5us)

The 60 instructions comes from [this thread][1] (3.6us = 57.8 instructions @16MHz); as for the others it's a rough measurement. Let's assume that the function actually samples the pin at the very end of the function.

Now, since you are checking for ties, if both buttons get pressed during phases 3, 4 or 1 you will get a tie (since both buttons will be read as pressed). If both buttons get pressed during phase 2, button 2 will be marked as pressed and button 1 not, thus giving advantage to that player. The time when this happens is about 3.6us long. So you are giving a 3.6us advantage to button 2 player.

**In the PIND case** you are reading the buttons exactly at the same time. The advantage is thus 0.

**In the interrupt case** when both EXT0 and EXT1 interrupts are triggered at the same time EXT0 gets executed, since it is before in the ISR. Consequently the player pressing the button on EXT0 has one interrupt checking cycle of advantage. I admit I do not know how often the inputs are checked for the EXT interrupt, but I assume it performs a check every clock cycle (consequently the advantage is 62.5ns).

----------

Now, let's sum up the advantage

 - digitalRead: 3.6us
 - PIND: 0
 - interrupt: 62.5ns

The solution is pretty obvious to me, and it is... Don't care! Even in the worst case scenario you are four order of magnitude faster than your phenomenon. You are giving one player a 4us advantage in a 250ms game (0.0016% of advantage). I'm pretty sure that the mechanical differences between the two buttons (maybe one is a bit stiffer, or has a slightly higher size, or has a slightly lower contact) affect the reading much more than this.

In the end, with this kind of setup you will reasonably be able to have an accuracy that is at most some tens of milliseconds. With other measurement setups (maybe optically based) you can go as low as 1ms. Adding 4us of advantage to one player will not influence the result.

Try to focus on the rest of the program, and for this problem use whichever solution you find more understandable.

NOTE: This is based on the assumption that a proper program is developed, with tie checks  and no delays and so on. The program as you wrote in the question is not ok from this point of view (as it is now it will stay in the loop forever; if you change `Sx_State` to `digitalRead` it will become roughly fair - something like 4us of advantage to player one and 3.8us of advantage to player two)

  [1]: https://forum.arduino.cc/index.php?topic=337578.0


body:
I have to concur with frarugi87 here. The few microseconds taken by
`digitalRead()` are completely inconsequential for your application. But
let me add that, even if your players were super-humans capable of
sub-millisecond reaction times, you are not giving an advantage to any
of them if you alternatively check button 1, then button 2,
then button 1, and so on. The reason is that, in the small time
window between reading button 1 and reading button 2, you give
an advantage to player 2: he will win if both buttons are pressed
simultaneously. In the following time window (between checking
button 2 and button 1) the same advantage goes to
player 1.

The net result is that the game has a tiny amount of randomness: if both
buttons are pressed simultaneously, the result is seemingly random. But
again, the chances of this happening are so tiny that it makes no sense
to worry about it.

Here is how I would determine the winner. I think this code makes clear
that we are alternatively checking button 1, then button 2,
then button 1...

<!-- language: lang-c++ -->

    int find_winner()
    {
        for (;;) {
            if (digitalRead(S1_Pin) == HIGH)
                return 1;
            if (digitalRead(S2_Pin) == HIGH)
                return 2;
        }
    }


message:
Do I need a pull-up/down resistor for button LED circuit?

When reading up on how to make a circuit that turns an LED on when a button is held down, I keep finding people saying a pull up or down resistor must be involved, to avoid the flickering state of the LED seen with a floating pin. There's also code being implemented, where the state of a pin is read and monitored as the button is pressed down or left raised. What I don't understand, is why this is all necessary. Surely it isn't, considering the circuit below allows the button to be pressed with the LED turning on/off depending on the state of the button.

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

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

I made this circuit before drawing it online, and it works exactly as intended. No need for a pull up/down resistor or any code. I must be missing something here, can anyone please explain? It works perfectly with a buzzer as well.

Many thanks.

body:
The circuit you have made is only using Arduino as a 5V power source. You aren't using any GPIO pins to read the state of the button or to control the LED by an output pin. You've just made a plain-old circuit with a button and LED in series with a power source.

Often for a button-controlling-LED sketch, you will have a button connected between GND and an I/O pin defined as an `INPUT_PULLUP`, which means the Arduino will be able to read the state of the pin as `HIGH` (5V) or `LOW` (0V). The `PULLUP` part indicates that when the button is not completing the circuit between GND and the pin, a weak voltage is applied to get it up to 5V. In this way it's not "floating" at an unspecified voltage, but is being actively driven to 5V. When you press the button, the input pin is shorted to GND.

A pull-up resistor causes an otherwise un-driven pin to go to logic `HIGH`. A pull-down resistor causes an otherwise un-driving pin to go to logic `LOW`.

In the case of a pull-up resistor, reading a logic `LOW` means the button is pressed, which is kind of the reverse of your circuit operation, so in your sketch code, you would look for `LOW` to turn on the LED.