body:
I have a BLUno bluetooth arduino based on uno.

the logic kind of works, I am connecting ok to the phone, getting and sending messages via blue tooth

but with the serial data, Im having problems using it, and with the logic.

I want to have the option to turn ON/OFF some RGB LEDs, the problem is that the state is sometimes erratic.

here the code

    int redLED = 2;
    int greenLED = 4;
    int blueLED = 3;

    static bool redRunning;
    static bool greenRunning;
    static bool blueRunning;
    static bool freq = 34;

    void setup() {
      Serial.begin(115200);               //initial the Serial
      Serial.write("started");

      pinMode(redLED, OUTPUT);
      pinMode(greenLED, OUTPUT);
      pinMode(blueLED, OUTPUT);

      digitalWrite(redLED, HIGH);
      digitalWrite(greenLED, HIGH);
      digitalWrite(blueLED, HIGH);

      redRunning = false;
      greenRunning = false;
      blueRunning = false;
      freq = false;
    }

    void loop()
    {

      if (Serial.available() > 0)
      f{
    String s = Serial.readStringUntil('\n');

    //    String s = Serial.readStringUntil("#");   // Until CR (Carriage Return)
    //    s.replace("#", "");
        Serial.println("s:" + s);

    if (s == "red_ON")
    {
      redRunning = true;
    }

    if (s == "red_OFF")
    {
      redRunning = false;

    }  if (s == "green_ON")
    {
      greenRunning = true;

    }  if (s == "green_OFF")
    {
      greenRunning = false;

    }  if (s == "blue_ON")
    {
      blueRunning = true;

    }  if (s == "blue_OFF")
    {
      blueRunning = false;

    }

     }

     //

      if (redRunning) {
    //    Serial.println("redRunning");

    digitalWrite(redLED, LOW);
    delay(125);
    digitalWrite(redLED, HIGH);
    delay(125);
      }

      if (greenRunning) {
    //    Serial.println("greenRunning");

    digitalWrite(greenLED, LOW);
    delay(125);
    digitalWrite(greenLED, HIGH);
    delay(125);
      }

      if (blueRunning) {
        //    Serial.println("blueRunning");

        digitalWrite(blueLED, LOW);
        delay(125);
          digitalWrite(blueLED, HIGH);
        delay(125);
      }

      if (!redRunning && !greenRunning && !blueRunning) {
        digitalWrite(redLED, HIGH);
        digitalWrite(greenLED, HIGH);
        digitalWrite(blueLED, HIGH);
      }

       }

So what is the proper way to handle state? so the LED stay blinking? but also can turn off all LEDs
also if I can turn LEDs combined, at the moment, I'm turning on one, then the other,

All these problems come from not understanding how to handle state internally, and manage changes that come via serial.

title: Turn RGB blinker via serial

Answers: 2

body:
I think you are handling the state quite well, but if you spend some time to some other topics, I'm sure you get it working:

1. Instead of `delay`'s everywhere, use just one at the end, and make sure you handle all state before that delay. This means that you set all your states the way you want, that single `delay` gives a much easier sketch to analyze.

2. Split your sketch in separate parts (within the `loop` function):
   - Read serial input
   - Adjust states according to your serial input
   - Adjust states according to time (for blinking purposes)
   - Set the GPIO pins for the LEDs based on that state
   - Delay
Regarding the states, you use now 3 'running' states, one for each color, this is good. Probably it's easier to keep these variables attached to the serial input (so if you get "green_ON", greenRunning is always `true`, else `false`. So you don't need to always set them to `false` in the beginning of the `loop` function, just once during declaration or within `setup`.

Than you make another (global) variable that defines if (any) LED is in HIGH state (if it WOULD be running) of LOW. This variable you change every 125 ms (or whatever speed you like). You can flip this variable every 125 ms (`ledsOn = !ledsOn`).

So you get something like (# = pseudo code), for red only, rest is similar:

in global:

    bool redRunning = false;
    bool ledsOn = false;

in `loop`:

    // Read serial input
    # Read input

    // Set states
    # if serial data Red On is received
       redRunning = true;
    # if serial data Red Off is received
       redRunning = false;

    ledsOn = !ledsOn;

    // Set LEDs
    digitalWrite(redLED, redRunning && ledsOn ? HIGH : LOW);

    // Delay
    delay(125);

body:
Here is some untested code that uses a non-blocking timer to flash the leds.

```

uint8_t redLED   = 2;
uint8_t greenLED = 4;
uint8_t blueLED  = 3;

static uint8_t redRunning   = HIGH;   // leds off at start
static uint8_t greenRunning = HIGH;
static uint8_t blueRunning  = HIGH;

// static bool freq = 34;             // not sure what this is

void setup() {
  Serial.begin(115200);               // initialize the Serial
  Serial.write("started");

  pinMode(redLED,   OUTPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(blueLED,  OUTPUT);

  digitalWrite(redLED,   HIGH);       // leds off
  digitalWrite(greenLED, HIGH);
  digitalWrite(blueLED,  HIGH);

//freq     = false;
  tick     = false;                   // time interval signal
  ledState = false;                   // state of led display

  static uint32_t ledTicker = millis();
}

void loop() {

  if (millis() - ledTicker >= 125) {             // Once every 125 ms
    ledTicker = millis();
    tick = true;                                 // set the tick flag
    ledState = !ledState;                        // changes state at every tick
  }

  if (Serial.available() > 0) {
    String s = Serial.readStringUntil('\n');

//  String s = Serial.readStringUntil("#");      // Until CR (Carriage Return)
//  s.replace("#", "");
    Serial.println("s:" + s);

    if (s == "red_ON"   )  redRunning   = LOW ;  // sometimes, this format is easier to read
    if (s == "red_OFF"  )  redRunning   = HIGH;

    if (s == "green_ON" )  greenRunning = LOW ;
    if (s == "green_OFF")  greenRunning = HIGH;

    if (s == "blue_ON"  )  blueRunning  = LOW ;
    if (s == "blue_OFF" )  blueRunning  = HIGH;
  }

  //
  if (tick) {                                    // 125 ms passed, so update the leds
    tick = false;                                // reset tick so that leds change only once every tick

    if (ledState) {                              // state of leds at this tick
   digitalWrite(redLED  , redRunning  );
      digitalWrite(greenLED, greenRunning);
      digitalWrite(blueLED , blueRunning );
    }
    else {                                       // all off this time around
      digitalWrite(redLED  , HIGH);
      digitalWrite(greenLED, HIGH);
      digitalWrite(blueLED , HIGH);
    }
  }
}
```


body:
My issue is fairly simple to describe but I have no idea what the problem could be. So I got my FONA 3G and immediately after taking it out of the box, I connected the battery and I wired up my FTDI board (aka USB to serial converter), and then I plugged it into my USB port to try and establish communication. I just tried the most basic at command AT(using PuTTy). You're supposed to get an OK in response but the FONA doesn't appear to even notice that I'm trying to talk to it. I type AT and press enter and nothing happens at all.

The issue is most certainly not my FTDI board, I'm very experienced communicating with wifi modules and other GSM modules using PuTTy. So please don't be concerned with the setup. That's 100 percent definitely not the problem.

I was able to send AT commands after plugging the module into my laptop directly using the module's USB input, but there is still some issue with its UART. I haven't been able to send or receive any communications directly from RX and TX. It wont respond to any programs I load up onto my arduino. Its like the UART is asleep.

If you have experience with FONA 3G, please speak up and tell me what steps you took to get the UART to respond. What should the status indicator look like before its ready to receive commands? Any knowledge you have about the FONA3G module would be helpful.

As a side note, the FONA3G has a chip number. It is SIM5320a. I don't know if that helps. Most people know it as FONA 3G.

title: Problem communicating with GSM module which is a Fona 3G from adafruit

Answers: 1

body: All right. Thanks to those of you who posted comments. It turned out to be an issue with the baud rate! Its always the simple stuff. Adafruit said this thing has auto baud meaning you can use any baud rate but they are wrong. It requires 115200 to work properly. Also I'd like to point out that there was nothing wrong with my setup. Sometimes you should trust the person when they say their setup is 100 percent fine.


body:
For a project I am trying to understand SPI.

The final project I will use this in, is for reading the SPI from a car radio.

That Radio writes to address 0x80 of a DDRAM LCD display. MY intent is to read for a write to this address and if the bits are correct replace waht is being written.

IE Radio says write the letter E to 0x80, using a mega2560 read this and then interject a different letter then write to the radio screen. So the radio is a master with the Mega and LCD as daisy chained slaves.

I'm using the base code from for [writing to the screen][1]. This was written to fully replac ethe radio so i'm trying to mimic the radio using an UNO as Master and the screen using a Uno as a slave.

I've got the demo working from [circuits4you.com][2]

I'm trying to modify it to use the same STI settings as seen in the base radio replacement code i'll be modifying for my final project. I know this code writes correctly to the screen. The problem is that the code uses SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE3)); as its designed to replace the radio functions.

I'm trying to get that line to work on the 2 UNO's im bench testing with so I can make the mega a slave in the final project.

SPI MASTER Code

```#include <SPI.h>

void setup (void) {
   Serial.begin(9600); //set baud rate to 115200 for usart
   digitalWrite(SS, HIGH); // disable Slave Select
   SPI.begin ();

}

void loop (void) {
    SPI.beginTransaction(SPISettings(9600, MSBFIRST, SPI_MODE3));

   char c;
   digitalWrite(SS, LOW); // enable Slave Select
   // send test string
   for (const char * p = "Hello, world!\r" ; c = *p; p++)
   {
      SPI.transfer (c);
      Serial.println(c);
   }
   digitalWrite(SS, HIGH); // disable Slave Select
   delay(2000);
   SPI.endTransaction();
}
```
The problem seems to arise from the SPI.attachInterrupt() not being compatible with the SPI.beginTransaction is this correct and is there a way around it?

SPI SLAVE Code

```
include <SPI.h>
char buff [50];
volatile byte indx;
volatile boolean process;

void setup (void) {
   Serial.begin (9600);
   pinMode(MISO, OUTPUT); // have to send on master in so it set as output
   SPCR |= _BV(SPE); // turn on SPI in slave mode
   indx = 0; // buffer empty
   process = false;
   SPI.attachInterrupt(); // turn on interrupt

}

ISR (SPI_STC_vect) // SPI interrupt routine
{
   byte c = SPDR; // read byte from SPI Data Register
   if (indx < sizeof buff) {
      buff [indx++] = c; // save data in the next index in the array buff
      if (c == '\r') //check for the end of the word
      process = true;
   }
}

void loop (void) {

   if (process) {
      process = false; //reset the process
      Serial.println (buff); //print the array on serial monitor
      indx= 0; //reset button to zero
   }

}
```

  [1]: https://github.com/TonyChatfield/S1-RX8-AC-Display-controller/blob/master/rx8_display_beta_3.0.ino
  [2]: https://circuits4you.com/2019/01/03/arduino-spi-communication-example/

title: UNO SPI slave read from UNO SPI Master beginTransaction

Answers: 1

body: Okay so I have got this working now. It seems that it was the Slave not understanding the data mode. I found the SPI.setDataMode() it is listed as Do not use in the reference guide on Arduino.com but its worked spot on for me.


body:
 I came accross this code for writing data into EEPROM in arduino. Why is `void printTemp();`, `void clearEEPROM();` and `void writeTemp();` functions are mentioned in global declaration? How will this help?
```cpp
#include <EEPROM.h>

#define SAMPLE_TIME 2000  //The time between each EEPROM write function call in ms

int tempPin = 0;      //the ADC pin
int printPin = 2;     //the print button pin
int erasePin = 4;    //the erase button pin

int address = 0;      //EEPROM address counter

unsigned long timer;

float conv_coeff = 0.0;   //coefficient for converting from 0-1024 to 0-5 range

void printTemp();
void clearEEPROM();
void writeTemp();

void setup(){
  Serial.begin(115200);     //start the serial connection as always
  conv_coeff = 5.0/1024.0;  //find the coefficient to do the conversion
  timer = millis();         //millis() returns the time since program start in ms
}

void loop(){
  if(millis()-timer > SAMPLE_TIME)  //check if it's time to do a temp sensor sample
  {
    writeTemp();
    timer = millis();
  }

  if(!digitalRead(printPin))  //check if print button is pressed
  {
    printTemp();
    delay(500);
  }

  if(!digitalRead(erasePin)) //check if erase button is pressed
  {
    clearEEPROM();
    delay(500);
  }

  delay(1);
}

void printTemp()
{
  for (int i = 0 ; i < EEPROM.length() ; i++) {
    byte value = EEPROM.read(i);                //read EEPROM data at address i
    if(value != 0)                              //skip "empty" addresses
    {
      float temp = value*conv_coeff;            //convert ADC values to temperature
      temp = (temp - 0.5)*100;                  //take care of the offset

      Serial.println(temp);
    }
  }
}

void clearEEPROM()
{
  for (int i = 0 ; i < EEPROM.length() ; i++) {
    if(EEPROM.read(i) != 0)                     //skip already "empty" addresses
    {
      EEPROM.write(i, 0);                       //write 0 to address i
    }
  }
  Serial.println("EEPROM erased");
  address = 0;                                  //reset address counter
}

void writeTemp()
{
  byte value = analogRead(tempPin);     //read sensor value

  EEPROM.write(address, value);         //write value to current address counter address

  Serial.print("Sensor value stored at address ");
  Serial.println(address);

  address++;                      //increment address counter
  if(address == EEPROM.length())  //check if address counter has reached the end of EEPROM
  {
    address = 0;              //if yes: reset address counter
  }
}
```

title: Why is function mentioned in global declaration?

Answers: 2

body:
Those are called *function prototypes*.  They mean "These functions exist somewhere else".  That "somewhere else" could be later on in the same file, or a different file entirely.

Usually these kind of things are provided by header (`.h`) files, or are automatically created (for functions in the INO file) by the IDE and hidden from you, so you never really see them. But if you're not using the IDE then you need to have them so your code (which is parsed linearly) knows that these functions exist before the parser comes across them.

body:
Originally, C (from which C++ inherited the bulk of its syntax) was compiled by a single-pass compiler: the compiler only got one look at the code.

A multi-pass compiler could look over the code and collect function definitions in one pass, then in a later pass, compile the code that calls those functions, or detect errors in those calls, if there are any.

A single pass compiler couldn't do that so it needs either the function or its prototype to appear before any code that uses calls it, for the compiler to have that same information when it needs it.

The prototype provides the function's name, the number and types of its arguments, and the type of value it returns, which is what the compiler needs to confirm and compile a function call or to issue a diagnostic message if the call doesn't match the prototype.


body:
I'm working on big Arduino project that involves lots proprietary libraries. Ergo, we need test scripts to ensure each library works. Is there a testing framework for Arduino similar to CPPUnit, JUnit, Cunit, etc.? It should preferable also have the ability to simulate an Arduino.

EDIT: By "Arduino Simulator" I only want something that allows observation of local variables, global variables, the different register values (at a minimum the INPUT/OUTPUT status of the pins, what is being inputted or outputted), and fake inputs into the various pins. This way, only the Arduino itself needs to be simulated, not the external hardware components like LEDs, buttons, real time clocks, motors etc.

title: Is there a test framework for Arduinos?

Answers: 1

body:
> It should preferable also have the ability to simulate an Arduino.

As said in the comments, only simulating the Arduino is mostly not enough, because you would also need to simulate all the connected components. Just simulating the Arduino is a rather hard task. You can find Arduino simulators, but they always only support a rather small collection of additional hardware (mostly things like switches, LEDs, buzzers, ...). I guess the proprietary libraries, that you use, are for connecting to some extra devices (maybe are also proprietary), which will be rather complex. These devices will most likely not be supported by any of the Arduino simulators.

Also: Arduino is a beginner and fast prototyping platform. The ones, that do professional things like designing a product (which are mostly the ones, that need such test suites), will fastly move away from the Arduino platform to program an abstraction layer lower directly on the AVR platform. So why would those people need a test suite for Arduino?

Simulating electronic circuits can be really difficult, so you won't see a program, that can handle all of your circuit, including the complex parts like sensors with communication interface. That means, that you can only test your circuit and the corresponding code (which interacts with the circuit) in the real hardware. Some IDEs (like PlatformIO) might give you the possibility, to write test sketches, but you would still need to upload them to the real hardware and observe the results yourself.

Code, that is independent from the Arduino hardware, could be unit tested on the PC, but that is mostly not the case, since Arduino/microcontrollers are so hardware near. Of course, you could write mocking code for the Arduino parts, but that is often even more tedious, than just using the hardware.

---

As no real Arduino testing framework exists, you are down to writing own testsketches and using a good IDE (not the Arduino IDE) to organize them.


body:
I have a project which runs on an ESP8266 and one functionality is to do nothing else but to read what comes in from a HC-05 Bluetooth adapter via SoftwareSerial and outputs the read data to the HardwareSerial TX pin. Vice versa, the same is done with what kind of data comes in via HardwareSerial's RX pin and is output to the HC-05 via SoftwareSerial. I use this cheap serial-to-bluetooth adapter, to flash a device where the stock adapter would cost me 100$ or more.

On the surface, the code still runs fine, as most of the time no errors occur. But after some handshake data is transmitted and the flashing begins with larger blocks of data (100+ bytes), the device I'm talking to quits the communication. I can't really figure out why because I don't have access to its internals, but when I flash the ESP8266 with a binary of my software that is about a year old, the communication is much more stable and most of the flash procedures work fine.

I have checked my code and it is basically the same as a year ago, except for the SoftwareSerial constructor and the .begin statement which changed a while ago. But other than that, there is nothing much I can see.

Of course it could be changes inside the EspSoftwareSerial library or even the framework. I was using 2.3.3 until a while ago, but I can't recall which version of EspSoftwareSerial I used a year ago. I tried 2.3.3 for the framework and 5.0.4 for EspSoftwareSerial via configuration in platformio.ini, but to no avail.

Is there anything known about changes in behaviour in EspSoftwareSerial or in relation to the framework that I shoudl consider?

Here's the relevant code:
```
void handle_bluetooth() {

//  SoftwareSerial BtSerial(2, 0, false, 256);
  SoftwareSerial BtSerial;

  if (!webServer.authenticate(http_user, http_pass)) {
    return webServer.requestAuthentication();
  }

  unsigned long timeout = millis();
  uint16_t idx = 0;
  uint8_t bt_read = 0;
  uint8_t bt_write = 0;
  uint16_t crc_result = 0;
  boolean need_flash = false;
  boolean fw_poll = false;
  boolean fw_memory = false;
  uint8_t model_no = webServer.arg(0).toInt();

  String message = "";
  if (model_no > 0) {
    message.concat(F("Emulating model no. "));
    message.concat((String)model_no);
  }
  webServer.send(200, "text/html", message);

//  BtSerial.begin(38400);
  BtSerial.begin(38400, SWSERIAL_8N1, 2, 0, false, 256);

  telnetClient.println(F("Starting Bluetooth mode..."));
  while (timeout + 300000 > millis()) {

    while (BtSerial.available() > 0) {
      bt_read = BtSerial.read();
      if (bt_read == 0x02 || idx > sizeof(rx_msg)) {
        idx = 0;
      }

      telnetClient.print(to_hex(bt_read));
      telnetClient.print(F(" "));
      rx_msg[idx] = bt_read;
      if (bt_read == 0x03) {
        telnetClient.println();
        crc_result = decodeMsg(idx+1);

        if (rx_msg[3] == 0x27 && model_no > 0) {
          fw_poll = true;
          fw_memory = false;
          telnetClient.println(F("FW request detected."));
        }
        if (rx_msg[3] == 0x25 && rx_msg[4]+rx_msg[5]+rx_msg[7] == 0 && (rx_msg[6] == 4 || rx_msg[6] == 4)) {
          fw_poll = true;
          fw_memory = true;
          telnetClient.println(F("FW memory request detected."));
        }

        if (rx_msg[3] == 0x64) {
          telnetClient.println(F("BT-Address detected:"));
          for (int x=4; x<10; x++) {
            if (CMD[x]!=rx_msg[x]) {
              need_flash = true;
              CMD[x] = rx_msg[x];
            }
            telnetClient.print(to_hex(CMD[x]));
            telnetClient.print(F(" "));
          }
          telnetClient.println();
        }
      }
      Serial.write(bt_read);
      idx++;
      timeout = millis();
      yield();
    }

    while (Serial.available() > 0) {
      BtSerial.write(bt_write);
      if (bt_write == 0x03) {
        telnetClient.println();
      }
      yield();
    }
  }
  telnetClient.println(F("Exiting Bluetooth..."));
  BtSerial.flush();
  BtSerial.end();
  Serial.begin(38400);
  while (Serial.read() >= 0) {    // flush the receive buffer
    yield();
  };
}

uint16_t decodeMsg(uint16_t idx) {
  uint16_t counter = 0;
  uint16_t i = 0;
  while (i < idx) {
    if (rx_msg[i] == 0x1B) {
      rx_msg[counter] = rx_msg[i + 1];
      rx_msg[counter] = rx_msg[counter] - 0x20;
      i++;
    } else {
      rx_msg[counter] = rx_msg[i];
    }
    i++;
    counter++;
  }
  if (crc8(rx_msg, counter - 2, 1) != rx_msg[counter - 2]) {
    telnetClient.print(F("CRC error in message received: "));
    telnetClient.print(to_hex(crc8(rx_msg, counter - 2, 1)));
    telnetClient.print(F("/"));
    telnetClient.print(to_hex(rx_msg[counter - 2]));
    telnetClient.print(F("/"));
    telnetClient.println(to_hex(counter));
    return 0;
  } else {
    return counter;
  }
}

```

title: Unreliable EspSoftwareSerial Bluetooth transmission for longer read/writes on ESP8266

Answers: 0


body: I would like to save data that I am receiving from API calls in a char array. The problem is the data is around 80KB however my Arduino IoT 33 has 32KB of memory. It will save data in a char array that 25000 bytes however when I go to 30000 or above the Arduino freezes. When I copy-paste the entire data to a char array without specifying the size it works fine, however, when receiving data over API in chunks of 10KB it won't save the entire 80KB. Is there a way to go around this? A response will be appreciated.

title: Arduino Nano IoT 33 Char Array size constraints

Answers: 1

body:
You can use the flash memory of the SAMD21 MCU used on the Nano 33 IoT, if you don't write too often. Flash memories have a limited count of write-erase cycles. It is guarantied for 10000 writes.

For Arduino SAMD boards like the Nano 33 IoT you can use the [FlashStorage library][1]. The library is in the Library Manager.

  [1]: https://github.com/cmaglie/FlashStorage


body:
I'm trying to read data from MH-Z19B sensor to NodeMCU v2 board with a simple circuit like this.

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

Some key points, which could be not that obvious from picture:
 - sensor has separate power supply of 4 AAs, providing ~5,5V
 - sensor's TX connected to GPIO15 (TX D2) of NodeMCU
 - sensor's RX connected to GPIO13 (RX D2) of NodeMCU

And here is my sketch:

```
const byte readCommand[] = {0xFF, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79}; // according to datasheet
unsigned char response[9];

void setup() {
  // according to datasheet, sensor uses 9600 baud, 8 databits and 1 stopbit
  // with parity NONE, which I believe corresponds to default config SERIAL_8N1
  Serial.begin(9600);
}

void loop() {

    //  ... check if it is time to measure

    Serial.swap(); // switch to sensor

    Serial.write(readCommand, sizeof(readCommand));

    memset(response, 0, sizeof(response));

    int attempts = 5;
    int available = Serial.available();
    while(available < sizeof(response) && attempts > 0) {
        delay(100);
        attempts--;
        available = Serial.available();
    }

    Serial.readBytes(response, sizeof(response));

    Serial.swap(); // switch back to console

    // print out the response in hex
    for (int i = 0; i < sizeof(response); i++) {
      Serial.print(String(response[i], HEX));
      Serial.print("   ");
    }

    // ...process the response according to protocol
}

```

**The Problem**

For some reason after sending command to serial I get an answer exactly the same as command is although the structure of answer expected to be different. Of course datasheet says nothing about situations like this.
Expectation
```
ff 86 .. .. 0 0 0 0 CRC
```
Reality (same bytes I sent as a command)
```
ff   1   86   0   0   0   0   0   79
```

Other notes:
 - I got exactly the same when tried to use `SoftwareSerial` with D1 & D2 pins
 - connecting TX to RX respectively on both sensor and MCU results in reading failure
 - I tried to pull everything while available from serial, there are only my expected 9 bytes
 - my soldering skills are far from ideal, but I'm pretty sure tx/rx on the sensor are connected properly

I'm new to all this stuff, so it is completely possible that there is ridiculously silly, but crucial mistake, so would appreciate any help on this. And I understand that sensor also has additional interfaces to obtain the value, but as I mentioned I'm a newbie and wanted to familiarize myself with UART as this is something new for me.

**UPD 1**:
I didn't use level conversion for sensor output as datasheet says:
[![enter image description here][2]][2]
Assuming this I thought that sensor provides logical level conversion itself. Did I get it wrong?

**UPD 2**:
I got back to proper TX - RX connection just to check out what is going on exactly to describe that "reading failure" problem with more details. It seems that `Serial.available()` returns 0 after I send command so this loop gets stopped after 5 attempts:
```
while(available < sizeof(response) && attempts > 0)
```

  [1]: https://i.stack.imgur.com/42cKt.jpg
  [2]: https://i.stack.imgur.com/qoP7I.png

title: NodeMCU v2 with MH-Z19B CO2 sensor UART read problem

Answers: 1

body:
It says in your description that you have the Rx connected to Rx and the Tx connected to Tx.  That's backwards.  What one transmits the other needs to receive.  When you have a conversation with someone, do you talk into their mouth and listen to their ears?  You should have Rx-Tx and Tx-Rx.

You also need to be sure that it is OK to feed a 5V Tx into that Rx pin.  On some ESP8266 boards it is and on most it isn't.  If you don't have one of the boards that specifically has circuitry built in to handle 5V inputs then you will fry your NodeMCU


body:
I have an arduino program that only does serial communications with a little bit of math, and I am writing another one to communicate with it on a second arduino.  For testing purposes I was hoping I could run the serial only program on my desktop.  I know it is possible to run on a raspberry pi but I have never done that.  Can I do something similar on windows?  If not, can anybody recommend the easiest way to do this with a regular C++ program that would require very little editing? Here is a copy of my code if it's helpful.  It basically increments a variable up and down between 0 and 100.

```
int pos = 60;
bool flag=0;
int dly=50;
int vel=0;

const int buttonPin =  12;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);

Serial.begin(115200);
}

void loop() {
    dly=50;
    buttonState = digitalRead(buttonPin);
    if (buttonState==0)dly=12;
    Serial.print(vel); //speed
    Serial.print(",");
    Serial.println(pos); //position
    delay(dly);
    if (pos==30)flag=1;
    if (flag==1) pos+=1;
    if (pos==100)flag=0;
    if (flag==0) pos-=1;
    vel=1000/dly;
    if (flag==0) vel*=-1;

}
```

title: How compile an Arduino program for a desktop PC

Answers: 3

body:
It depends on what exactly you wanna test. I guess you want to run the "Serial & math only" sketch on the PC, while communicating over Serial (via USB) with the other real Arduino. It can be done, but you would have to change quite a lot. The Serial libraries for a PC are different than for an Arduino. Also you cannot simply compile Arduino code for a PC, they are totally different devices.

Mostly the Serial code is better tested with the real hardware, by checking, what actually is send. You can do this by connecting to the Arduino over Serial/USB with a corresponding program (Arduino Serial Monitor, Putty, ...), so that you can test the functionality by hand. Or write a simple test sketch for the second Arduino.

For testing the math part, you could relatively easy write a so called unit test on the PC. A unit test tests a confined code part without or only with few dependencies. Most math is the same on Arduino and PC (as long as you use variables of the same size and type). So you could put all the math code into a function, which does not contain Arduino specific code, like `Serial` code. Just the math. Then you can copy that function into the source code of a C++ PC programm and use it, to test the math function unit without involving the Arduino.

A further option would be using an Arduino Simulator. But keep in mind, that these simulators can never be as good as the real hardware and you can see differences in the behavior of simulated and real Arduinos. Though it should work, as long as your program is simple and does not rely on too much outer hardware or events. Your current program is simple enough, so that a simulator should be able to work with it.

All in all: Testing your code outside of the real Arduino mostly only makes sense, when you have a complex program, that does not involve Arduino specific code, which would need the hardware to work. If your project is not very complex, you are mostly better off with testing directly with the real hardware.

body:
If you want to run the Arduino sketch on your desktop, you just have to
implement the Arduino core library for your PC.

It may not be as bad as it sounds. If your program makes only minimal
use of the Arduino core, you may implement only the parts you really
need. For example, this partial implementation is enough to run your
program:

```c++
#include <cstdint>
#include <iostream>
#include <unistd.h>  // for usleep()

using std::cout;
using std::endl;

#define INPUT_PULLUP 2

void pinMode(uint8_t, uint8_t) {}

uint8_t digitalRead(uint8_t) { return 0; }

void delay(int t) { usleep(t * 1000UL); }

struct {
    void begin(int) {}
    template<typename T> void print(T x) { cout << x; }
    template<typename T> void println(T x) { cout << x << endl; }
} Serial;

int main()
{
    void setup();
    void loop();
    setup();
    for (;;) loop();
}
```

I tested this on Linux, by simply appending your program right below
this. If you are using Windows, you will have to replace the `usleep()`
function with the appropriate Windows call (and `<unistd.h>` with the
appropriate header). The serial stream goes to the standard output. You
may redirect it to the USB serial port if you wish (trivial to do in
Linux, I assume it should be doable on Windows). You may also want to
replace `digitalRead()` with something that simulates a more realistic
user interaction.

Keep in mind that the sizes of the basic data types can be different on
the Arduino and on the PC. On an AVR-based Arduinos, `int` and pointers
are 16 bits while `long` is 32 bits. This is an “IP16” data model. An
ARM-based Arduino would typically be ILP32, whereas a 64-bit PC is LP64,
unless it runs Windows, in which case it's LLP64. This can make a
difference, especially if some of your calculations are prone to
overflow with the smaller data models.

------------------------------------------------------------------------

**Edit**: I recently stumbled upon [NCORE, a native core for
Arduino][ncore]. It may be a good fit for what you are trying to do.
From the page description:

> The native core allows you to compile and run Arduino sketches on the
> PC, generally with no modification. It provides native versions of
> standard Arduino functions, and a command-line interpreter to give
> inputs to your sketch that would normally come from the hardware
> itself.

[ncore]: https://github.com/maniacbug/ncore

body:
There is also [arduino_ci](https://github.com/ianfixes/arduino_ci), a framework for running unit tests against an Arduino library (maybe also sketch) on your computer. It contains mock implementations of most Arduino functions and some libraries, and gives the unittest control of things like Serial buffers and I/O pin values.

For your example, you could maybe write a unittest that just use stdin/stdout as a serial port and then connect two of these programs together, or maybe you could generalize your communication code a bit into an object and then instantiate that twice.


body:
I have a cosplay project where I'm creating a "Megaman" aka Rockman type of arm cannon (it's actually based on DC's Cyborg). Anyhoo, I've been weighing options like using 3xAA alks or 4xAA nicd (or otherwise 1.2V)--inclcuding various combinations of less or more cells with a voltage regulator; boost up or step down as appropriate.

there are 4 lighted segments (15 leds of WS2812B x 4). I also of course have to power the Arduino Nano as well. I'm flexible on led brightness so I'm just going to tune it [code it] to whatever looks adequate for my purpose. I am aware of the 50ma draw of these units at full brightness

My original plan was to just keep it easy (read lazy) and use 3 AA alks per 2 segments, and another 3 so the nano can have it's own supply. So 9 cells in total (without any additional regulation). Before you judge me--weight, volume, and especially area are definitely big factors in my decision.

So that's a long way to get to my actual question. Has anyone used these new types of USB rechargeable batteries? They seem to have the best of both worlds with the power of an alkaline but the consistency and sustainability of a NiMH /NiCD as they have internal regulators that produce a steady 1.5v (until they don't--which I'm more than cool with)

Short of having a properly regulated 5v power supply, are these a good option if I want to be slightly more responsible than throwing in whatever other AAs I have lying around? They definitely check the box on my space/mass requirements. I'm sure they do fine with most consumer electronics, but as far as arduino and any other custom/hobby 4.5-5v applications how reliable are these? Even if you haven't used them before I'd be curious of your thoughts. I'm a novice at best when it comes to elec engineering.

Yes, they are expensive. Thanks all!

examples:
https://www.amazon.com/Rechargeable-Batteries-Quick-Charge-Integrated-Protection/dp/B07F27PK2M/ref=sr_1_5?crid=1RTQUCZYG4KBM&dchild=1&keywords=usb+aa+batteries+1.5v&qid=1588280164&sprefix=usb+aa,aps,242&sr=8-5

https://www.amazon.com/Blackube-Rechargeable-Batteries-Lithium-1500mAh/dp/B07D9K2H9H/ref=sr_1_11?dchild=1&keywords=usb+aa+batteries+1.5v&qid=1588282813&sr=8-11

title: Rechargeable USB "AA" Batteries. Has anyone used them?

Answers: 1

body:
Those "batteries" are actually a 3.7V¹ ~750mAh Lithium rechargeable cell with a 1.5V switching regulator and 5V charge circuit built in.

In about the same space as one of those, if you throw away the charge circuit and switching regulator, you can get a single 18650 Lithium rechargeable cell at 3.7V¹ (nominal) and three times the capacity. Two of those plus a small 5V switching regulator² would give you more power capacity and longer run time in a smaller space than the equivalent voltage of these strange "batteries".

----
¹ Nominal

² Use a good one with a Li-Ion battery protection circuit and maybe a built in 2S charger too for convenience


body:
I've been using an Arduino Nano 33 BLE to communicate with my PC over the BlueFruit LE Friend's UART characteristic. Using the default ArduinoBLE library, I'm able to connect to the BlueFruit from the Nano 33 as a central device, and write to the BlueFruit and have it show up in a serial terminal. I can get the Nano 33 to read from the Bluefruit as well, by sending a Characteristic.read() request and a subsequent Charcterisitc.readValue() command. Subscribing to the rx characterisitic on the Nano 33 does NOT work, however, even though the Bluefruit's info page says that the rx characterisitc (address 0x0003) is capable of Notify. I need to be able to subscribe, so that I can use the characteristic.valueUpdated() function to know when new data is available. Here is the relevant code:

    if (peripheral.connect()) {
    Serial.println("Connected");
    } else {
    Serial.println("Failed to connect!");
    return;
    }

    // discover peripheral attributes
    Serial.println("Discovering attributes ...");
    displayNum('A');
    if (peripheral.discoverAttributes()) {
      Serial.println("Attributes discovered");
      displayNum(-1);
    } else {
      Serial.println("Attribute discovery failed!");
      peripheral.disconnect();
      displayError('A');
      return;
    }

    // retrieve the TX characteristic
    BLECharacteristic txCharacteristic = peripheral.characteristic("6e400002-b5a3-f393-e0a9-e50e24dcca9e");
    BLECharacteristic rxCharacteristic = peripheral.characteristic("6e400003-b5a3-f393-e0a9-e50e24dcca9e");

    // make sure BlueFruit UART characteristics have been loaded properly are of
    // proper format
    if (!txCharacteristic) {
      Serial.println("Peripheral does not have TX characteristic!");
      peripheral.disconnect();
      return;
    } else if (!txCharacteristic.canWrite()) {
      Serial.println("Peripheral does not have a writable TX characteristic!");
      peripheral.disconnect();
      return;
    }
    if (!rxCharacteristic) {
      Serial.println("Peripheral does not have RX characteristic!");
      peripheral.disconnect();
      return;
    } else if (!rxCharacteristic.canSubscribe()) {
      Serial.println("rxCharacteristic is not subscribable!");
      peripheral.disconnect();
      return;
    } else if (!rxCharacteristic.subscribe()) {
      Serial.println("rxCharacteristic subscription failed!");
      peripheral.disconnect();
      return;
    }
What's strange is that Characteristic.canSubscribe() method returns true, and it is only when I actually try to subscribe that my error message is triggered. This code is also basically taken directly from the ArduinoBLE SensorTag example, so I'm not sure if this is an issue with the Arduino library or the Bluefruit, so any input would be appreciated.

title: Subscribing to Bluefruit LE Friend with ArduinoBLE not working

Answers: 0


body:
I am using the PCA9865 to light a led

**My circuit** [![enter image description here][1]][1]

**Arduino to PCA9865**
A5 > SLC A4 > SDA 5V > 5V GND > GND and
5 volts from a battery

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

**My code:**

    #include <Wire.h>
    #include <Adafruit_PWMServoDriver.h>

    // called this way, it uses the default address 0x40
    Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

    void setup()
    {
      pwm.begin();
      pwm.setPWMFreq(60);  //~60 Hz updates
    }

    void loop()
    {
      int pin = 0;
      pwm.setPWM(pin, 4096, 0);
    }

**the led does not light**

  [1]: https://i.stack.imgur.com/QgMwO.png
  [2]: https://i.stack.imgur.com/AkRGy.jpg

title: Arduino Turn on a led with the PCA9865

Answers: 1

body:
As written in the comments check resistor/led AND make sure you get power/GND to the terminal on the PCA board as this is needed for powering servos/leds/motors hanging on the board. I use about 10 on my layout and they are fantastic for powering all kind of appliancies. I patched the lib but in your case this is overkill. Instead of

 void setPWM(uint8_t num, uint16_t on, uint16_t off);

you could also try

 void setPin(uint8_t num, uint16_t val, bool invert=false);

but that is not the problem here

**EDIT**

Thanks for the foto now its clear why not. You have to connect A4 (UNO SCA) -  SCA (PCA9865)  AND A5 (UNO SCL) - SCL (PCA9865) see diagram:

[![UNO to PCA9865][1]][1]

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


body:
I have an ATMEGA16 lying around that was in an old robot I'd bought. It was in a socket, so I pulled it out and was thinking of using [this page](url=https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard) to use it with Arduino IDE. Is there a way for me to backup the chip's current state, so as to be able to restore it if I mess up?
I don't have an SPI programmer with me, but I do have a Arduino Uno available at hand

title: Backup an ATMEGA16

Answers: 1

body:
A [detailed how to is here](https://hardwarefun.com/tutorials/use-arduino-as-an-isp-programmer-to-program-non-arduino-avr-microcontrollers) its for the ATMega16 but check connections with the circuit diagram.
[![Flash ATMEGA16 with UNO][1]][1]

Use this command for backup of flash

     avrdude -c avrisp2 -p m16 -P /dev/ttyUSB0 -b 115200 -U flash:r:Old_flash_backup_file.hex:h

Backup EEPROM (just in case there is something stored there)

    avrdude -c avrisp2 -p m16 -P /dev/ttyUSB0 -b 115200 -U eeprom:r:eeprom_backup_file.hex:h

and this for writing the new bootloader / backup back

     avrdude -c avrisp2 -p m16 -P /dev/ttyUSB0 -b 115200 -U flash:w:New_BootLoader.hex:i -v

and this for EEPROM writing back

    avrdude -c avrisp2 -p m16 -P /dev/ttyUSB0 -b 115200 -U eeprom:w:new_eeprom_file.hex:h

As your avr-dude outputis

    lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00

there seems to be no lock on the chip. As you are on LINUX when reading youhave tospecify the format :h hex when reading

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


body:
I am new to Arduino and I have the following:

    int     delaynum;
    char    cval[12];

    void setup()
    {
     Serial.begin(9600);
     Serial.print("Enter Number");
     Serial.flush();

     int i=0;
     while(i<12)
     {
      if(Serial.available()>0)
      {
        char ch=Serial.read();
        if(ch>='0'&&ch<='9')
        {
          cval[i]=ch;
          i++;
        }
        else
        {
          cval[i]=0;
          delaynum=atoi(cval);
          break;
        }
      }
     }
    }
    void loop()
    {
       Serial.println(delaynum);
       exit(0);
    }

The code output in virtual bread board:(i Entered 100)

[![Output 1][1]][1]

But when i remove `Serial.flush()` The output like (i Entered 100)

[![Output 2][2]][2]

I am Expecting the output:

Enter Number (I want to enter number 100 after the output)

100

Why the code not working ?

I am using Arduino IDE with virtual bread board(ATMega328p)

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

title: Serial.flush() in arduino

Answers: 1

body:
Not knowing what virtual breadboard does on a normal Arduino it would do the following:

Serial.flush() clears the buffer  and this needs some time normaly you wait minimum for around 100 ms to write/read to that buffer again.
As your code runs in setup (so just once) the serial is not available as its still flushing and so your result.

As the name setup says this should only be used to setup HW/SW but not to run routines as you may get all sorts of weird results.
 If you use "\n" aka newline terminators in your communication you can go for them and flushing would be only necessary if the connection is interrupted and you have to resend data.

**EDIT**

>     Waits for the transmission of outgoing serial data to complete.

If you send a character, it is placed in a buffer for transmission. It takes time for each character to be sent because serial is slow. Once it is in the buffer, it will be sent automatically in the background while the program immediately moves on to the next statement. This is done so the program won't waste time waiting for characters to be sent.

flush() is a way to wait for it to be sent, instead of immediately moving on in the user program.

So after calling flush() you can be sure that all data has been sent, and the buffer is empty. So in your case where you placed it it makes no sense.


body: I need to know the IP address of ESP32 on the local network(without printing ip on serial monitor ). The idea is to do mDNS or UDP broadcast to send the IP to the android application. The app will then use that IP to do the communication. Is there someone who has already done it?

title: how to get esp32 ip address ,which is being connected to local network

Answers: 1

body:
You don't. You configure mDNS (as you already suggested in your question...!) and the client device then queries mDNS to find the device by the name you allocated it.

Look at the ESPmDNS library examples for how to use mDNS.

Edit: if you really want the IP, you can do `WiFi.localIP()` (station mode) or `WiFi.softAPIP()` (access point mode).


body:
I have an Adafruit Metro Mini board that I am using. After soldering the board and accessories to a perfboard the FTDI chip is overheating, the COM port will not show up on the PC, and the 3V pin does not produce any power while the board is plugged in.

Is there a way to fix this? Have I nuked my board?

title: Adafruit Metro Mini FTDI chip overheating

Answers: 2

body:
> Is there a way to fix this?

Yes. Undo whatever short circuit you have created with your soldering.

> Have I nuked my board?

Possibly, possibly not. Most likely the short is making the regulator go into thermal shutdown and no lasting damage has been caused. But you can't be sure.

body: The 3.3V output of the FTDI chip might be shorted to Gnd, or overloaded by your circuit. Start by checking that.


body:
I have been working on an [Arduin Uno Rev2][1] project for a while now. I have been developing using my MacBook, downloading code through the USB jack running it, monitoring the serial output on my MacBook, etc.

The Arduino is being powered from my MacBook through the USB jack which is also carrying the serial output back to the MacBook.

But now I want to make this project portable. IE: instead of powering it off a wire from my Macbook, I want to power it off a battery. So I followed [these instructions #4][2] and connected up a 9V battery to the VIN pin.

At first it seemed to work. But very soon started noticing great instability. There are many serious problems I need to solve working off this battery:

 1. As soon as I connect up the battery, I loose the Serial Monitor connection (even though the USB cable is still connected). So I can no longer see what's going on inside the Arduino for debugging purposes. Why? How can I continue to see the Serial Monitor? Is there a way to see the serial output from somewhere other than the USB jack?
 2. I can tell by the lights on the board and by the behavior of the outputs that the software is malfunctioning. But I can't tell exactly why (because of #1). Why would changing the power source cause this?
 3. I know that the VIN pin needs 7-12 volts. The battery I plugged in is a new 9V battery. But what happens as it wears down? Does it still push 9 volts? Or does the voltage drop? Can I tell my Arduino to stop functioning if the voltage drops below acceptable levels? Because ceasing altogether is better than malfunctioning.
 4. I have read that I need to ensure that the current from the battery remains around 500mA. But how can I measure that in hardware/software? This ties back into question #3.

  [1]: https://store.arduino.cc/usa/arduino-uno-wifi-rev2
  [2]: https://www.technobyte.org/2016/07/power-up-the-arduino-uno/

title: Problems running Arduino project off a 9V battery

Answers: 1

body:
> As soon as I connect up the battery, I loose the Serial Monitor connection (even though the USB cable is still connected). So I can no longer see what's going on inside the Arduino for debugging purposes. Why? How can I continue to see the Serial Monitor? Is there a way to see the serial output from somewhere other than the USB jack?

Probably because although the voltage is high enough to cut off the power from the USB port it's not got enough current to run the main MCU properly.

> I can tell by the lights on the board and by the behavior of the outputs that the software is malfunctioning. But I can't tell exactly why (because of #1). Why would changing the power source cause this?

Because 9V batteries can't provide enough current.

> I know that the VIN pin needs 7-12 volts. The battery I plugged in is a new 9V battery. But what happens as it wears down? Does it still push 9 volts? Or does the voltage drop? Can I tell my Arduino to stop functioning if the voltage drops below acceptable levels? Because ceasing altogether is better than malfunctioning.

No. The voltage drops rapidly to about 8V then down and down and down until it's below what the regulator can regulate. You can see this curve in any battery datasheet.

> I have read that I need to ensure that the current from the battery remains around 500mA. But how can I measure that in hardware/software? This ties back into question #3.

That's nonsense. The current demands will be whatever the circuit needs at any moment in time. There will be an upper limit to that demand (defined by your circuit and what you are doing at any one time - the *peak* current draw) and your power source has to be able to provide *at least* that amount of current.  If you try to draw more current than the battery can handle then the output voltage will drop to a level where it can no longer power the circuit properly. It is at this point you get "brownouts" and the board resets randomly and strange unpredictable things happen.

**In short: never use a 9V battery for an Arduino project. It's fine for vert low power operations, which take careful design, but for general use stay away from them. Also the Arduino's built-in regulator is a very inefficient and will waste about 25%-40% of a 9V batteries power before you even begin. Instead you should use a more efficient switching regulator to provide 5V directly to the 5V pin (or USB port) from suitable higher capacity batteries (such as AA cells).**

----

As a comparison here's some typical battery discharge graphs comparing alkeline AA to PP3 (9V). These are both Duracell Ultra.

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

As you can see the PP3 drops its voltage very rapidly even under a light load. Under a "heavy" load (what would be considered a very light load to an AA) it tumbles away to next to nothing in no time at all.

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


body:
I am trying to generate a square pulse with a fixed delay of 5 second between pulses and varying width of the pulse. The code I wrote so far generates a sequence of pulses every 5 seconds. Is it possible to generate one pulse (with varying width) every 5 seconds instead? Could you please help me with it?

```c++
const int pin =  11;

int i  = 0;

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

void loop() {
    i = random(0 , 255);
    analogWrite(pin, i); // turn on LED
    delay(5000);
}
```

title: Pulse generator with varying width

Answers: 1

body:
Simple but not fully accurate:

- Turn on LED
- Delay for the amount of pulse width (e.g. 20)
- Turn off LED
- Delay 5000 ms - pulse width (20) thus 4980 in this example

However, since turn on/off a LED will also take some time, this will take slightly more than 20 + 4980 = 5000 ms.

Thus better is:

- Set time to a variable (use `millis` function).
- Turn on LED
- Wait until time >= pulse width
- Turn off LED
- Wait until time >= 5000


body:
I have created my first LED project with a hand made 4X4 LED matrix. The cathodes are joined horizontally to make the rows and the anodes are joined vertically to make the columns the columns. It is controlled by a shift register with the cathodes (rows) connected to pins 0-3 and the anodes (columns) connected to pins 4-7 of the register controlled from an Arduino Nano.

It all works but I have hit upon a limitation that I have not seen in the various videos and tutorials about making LED matrices so I suspect I am missing something.

This code will light up the bottom left LED which I will call position (0,0).

    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B00011110 );
    digitalWrite(latchPin, HIGH);

This code will light up the LED at position (1,1), so one up and one to the right.

    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B00101101 );
    digitalWrite(latchPin, HIGH);

If I then combine the two as below:

    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, B00111100 );
    digitalWrite(latchPin, HIGH);

it of course lights up 4 LEDs: (0,0),(0,1),(1,0) and (1,1).

This feels like a limitation of wiring the LEDs in this way because once you power a row in a given column, you cannot unpower it in subsequent columns or vice versa. i.e. lighting (X,Y) and (A,B) means that you cannot have (X,B) and (A,Y) unlit.

However, in the videos I have seen that accompany tutorials on how to make similarly constructed matrices, I can see them lighting up in ways I can't replicate.

How can I light up an LED at positions (0,0) and (1,1) without also lighting up (0,1) and (1,0)?

Is this possible with this configuration?

title: Individually addressing LEDs in a multiplexed matrix

Answers: 1

body:
Thanks to [KIIV][1] in the comments I figured it out. Apparently the trick is to rapidly switch between columns or rows without ever having two on at the same time.

With the below code running in the main loop it appears that (0,0) and (1,1) are lit at the same time even though they are actually switching rapidly.

    void loop()
    {
      digitalWrite(latchPin, LOW);
      shiftOut(dataPin, clockPin, MSBFIRST, B00011110 );
      digitalWrite(latchPin, HIGH);
      digitalWrite(latchPin, LOW);
      shiftOut(dataPin, clockPin, MSBFIRST, B00101101 );
      digitalWrite(latchPin, HIGH);
    }

  [1]: https://arduino.stackexchange.com/users/23841/kiiv


body:
In my setup, I've got a number of ESP8266 devices around my home controlling various devices like my boiler and some lights.

They're all controlled by a central smart hub on a Raspberry Pi with a static's IP address.

This works great, but I'm increasingly concerned of the security implications of this. Communication between the Pi and the various ESP8266s is currently done over HTTP, with all the commands simply in the URL the Pi requests from the web servers.

As such, anyone on my network could theoretically control these smart devices using a simple `curl` request.

Whilst I have a strong Wi-Fi password, and am using WPA2 encryption, I would feel much more comfortable if communication with the ESP8266s was controlled in some way. E.g. in the same sort of way you can only connect to an SSH server using public key encryption if you have the right private key.

Is something like this possible to implement on an ESP8266? I've done some searching and only found articles about HTTPS which doesn't seem like it would solve my problem.

Thanks in advance,
Rocco

title: Securing ESP8266 connections

Answers: 1

body:
The simplest method is to encrypt your communication channel using some secret key.  You could use the built-in AES encryption functionality, which would mean that only people that know the key could encrypt a request in such a way that the device at the other end could decrypt it.

You would think that SSL (HTTPS) would do the job, but that only provides interception security, not authentication. Of course for even more security you can combine both HTTPS *and* AES encryption.  One for overall encryption, and the other for encryption-based authentication.


body:
I have a very small test project running on an Attiny85 (set to internal 8MHz).

Everything works when powering the circuit from an Arduino (3.3 or 5.0 volt). But when changing the  power to a 18650 battery with a voltage of around 4.0v the Attiny85 still works, because the LED blinks, but nothing is coming through via the UART. What could be the reason for this?

    #include <SendOnlySoftwareSerial.h>
    #define PHOTO_RESISTOR_PIN A1
    #define UART_TX_PIN 0
    #define LED_PIN 1

    SendOnlySoftwareSerial esp(UART_TX_PIN);

    void setup() {
      esp.begin(9600);
      pinMode(PHOTO_RESISTOR_PIN, INPUT);
      pinMode(LED_PIN, OUTPUT);
      pinMode(UART_TX_PIN, OUTPUT);
    }

    void loop() {
      digitalWrite(LED_PIN, HIGH);
      int light = analogRead(PHOTO_RESISTOR_PIN);
      esp.println(light);
      delay(1000);
      digitalWrite(LED_PIN, LOW);
      delay(1000);
    }

[![circuit][1]][1]

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

title: Attiny85 SoftwareSerial not working on battery power

Answers: 1

body:
Unless you connect the ground of your ATTiny to the ground of your USB UART interface there is no circuit for the electrons to flow around.

It works when powered from the computer because everything shared the same ground connection.


body:
I'm using Windows 10, Arduino 1.8.12 (Windows Store 1.8.33.0)

I have an Arduino MEGA 2560 and a red LED connected to pin 4.

```
#define RED 4
#define GREEN 2

void setup() {
  analogWrite(GREEN,  0);
  analogWrite(RED,  100);
}

void loop() {

}
```
This code lights up the red LED.
[![led on][1]][1]
However, when I write 1 to the GREEN pin `analogWrite(GREEN,  1)`, the red LED goes off. I'm expecting the red LED to stay on.
```

#define RED 4
#define GREEN 2

void setup() {
  analogWrite(GREEN,  1);
  analogWrite(RED,  100);
}

void loop() {

}

```

[![LED off][2]][2]

The red LED stays on when both written values are the same, e.g.
```
  analogWrite(GREEN,  25);
  analogWrite(RED,  25);
```

I also found that adding some "garbage" code at the beginning fixes the issue. I wasn't able to get the garbage into a simpler form without both pins shutting off.
```

#define RED 4
#define GREEN 2

void setup() {
  // GARBAGE BEGIN ===
  unsigned long t = millis();
  const unsigned long period = 10;
  float progress = float(t % period)/period;
  float r = progress * 0;
  // GARBAGE END ===

  analogWrite(GREEN,  100 + r);
  analogWrite(RED,  50 + r);
}

void loop() {

}
```

[![two leds on][3]][3]

**Update:** Thanks all for your comments. Setting the pinMode to output did not fix the issue. However, changing the function declaration to `__attribute__((optimize("-O0"))) void setup() {` fixed the issue. `-O1` also works, but `-O2` fails.

  [1]: https://i.stack.imgur.com/1RJUt.jpg
  [2]: https://i.stack.imgur.com/SStZY.jpg
  [3]: https://i.stack.imgur.com/rleHS.jpg

title: MEGA 2560: Simple program - One analogWrite turns off the other

Answers: 1

body:
As you are using using ArduinoIDE >=1.8.10 its an "optimization" problem by the compiler for the Mega try to replace the line

     void setup()

with

     void setup() __attribute__((optimize("-O0")));

// also -O1 works the default -Os and -O3,-O4 not

Actually the problem is not the IDE version but the included AVR boards package version.<br>  You can install any AVR boards package in any IDE with Boards Manager. Last good AVR boards package is 1.6.21. If your compiler (tool chain) shows 7.03 in the output window you  are affected. I have examples where the compiler even optimizies the loop away, which ends in funny results - I dont know wether other boards are also affected but the MEGA is for sure.


body:
I have a project where I read 2 sensors using an esp32 and also have an web server. I can connect using mobile phone and display the page where I see info about the sensors (using web sockets to update the info on the page very quickly ) and also send some commands back to esp32. Is working fine, just the issue that when I am connected to esp I don t have internet on my phone anymore (which is a normal thing:) ).
My question is if I can achieve same but using bluetooth instead wifi ? Is there any way to have a "web page" using bluetooth ?
Thank you

title: Web page using bluetooth?

Answers: 3

body:
No. There is no such facility in Bluetooth to provide such a feature.  That's not to say that technically it can't be done, there just isn't any software (a web browser) that would support it.

Instead you would need to use a Bluetooth-enabled app on the smartphone to communicate with the ESP32 over Bluetooth and display the data / provide control natively.  Such an app would probably have to be written by you since it would be specific to the way you are working, unless you can find a generic app that lets you design an interface for your project and then communicate using a documented protocol that you would then have to implement on the ESP32.

----

An alternative is to just reverse everything. Instead of having your phone connect to the ESP32 then connect to a webserver on it just have the ESp32 connect to your phone when your phone is set to WiFi Hotspot mode. You can still then get your phone to connect to the webserver on the ESP32, and your phone also has mobile internet. If course, if you are wanting internet through a WiFi connection for your phone then you can't do that. However, your ESP32 can then just also connect to your WiFi router so there is nothing to change on your phone. You just browse to the webserver on the ESP32 through your local WiFi network.

body:
Program your ESP32 to connect to your wifi - it then gets its own IP address on your LAN (e.g. 192.168.1.123 ) - then connect to your ESP from your phone (or anything else on your LAN).

Have you tried micropython? Works amazing on esp32 - makes everything super easy

body:
There is an experimental feature called the [Web Bluetooth API][1]. You could host a single file on a Webserver which then interacts via Bluetooth with your ESP. Keep in mind that aside from localhost you have to use https as protocol. [Here][2] is a Tutorial that shows how you can read and write to Bluetooth caracteristics using JavaScript.

  [1]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Bluetooth_API
  [2]: https://developer.chrome.com/articles/bluetooth/


body:
I have a Controllino Mega running a code that rotates a stepper one revolution CW, and one revoluction CCW.
I need the program to run, just when a signal is received from an HMI that I have connected to the Controllino via ethernet.
This is my first time using modbus. I have seen some examples using the modbus library, and I know I have to declare the variables in void setup, but don't know how many variables I need and if they  have to be analog or digital. I don't know either how to read those variable within void loop.

        #include <SPI.h>
        #include <Controllino.h>
        #include <Ethernet.h>
        #include "MgsModbus.h"

        MgsModbus Mb;

        const int pul = 46;  // pin 46 to PUL -
        const int dir = 47;  // pin 47 to DIR -

        void setup ()
         {

            byte mac[] = {0x90, 0xA2, 0xDA, 0x0E, 0x94, 0xB5};
            IPAddress ip(10, 7, 4, 17);
            IPAddress gateway(10, 7, 4, 17);
            IPAddress subnet(255, 255, 255, 0);
            Ethernet.begin(mac, ip, gateway, subnet);
            delay(5000); // Time to open the terminal
            Serial.begin(9600);

            pinMode (pul, OUTPUT);
            pinMode (dir, OUTPUT);
         }

         void loop()
         {

     Mb.MbsRun();

       digitalWrite(dir, HIGH);
      /*Turns the motor 400 steps*/
      for (int i = 0; i < 400; i++)
      {
        digitalWrite(pul, HIGH);
        delayMicroseconds(1000);
        digitalWrite(pul, LOW);
        delayMicroseconds(1000);
      }

     delay(1000);

      digitalWrite(dir, LOW);
    /*Turns the motor 400 steps*/
      for (int i = 0; i < 400; i++)
      {
        digitalWrite(pul, HIGH);
        delayMicroseconds(1000);
        digitalWrite(pul, LOW);
        delayMicroseconds(1000);
      }

    delay(1000);

     }

title: Modbus programming

Answers: 0


body:
I have a bunch of 3D arrays in the following form:

    byte lines[][4][2] {
                         { {B00000000, B11110000 },
                           {B00000000, B11110000 },
                           {B00000000, B11110000 },
                           {B00000000, B11110000 } },
                         { {B11110000, B00000111 },
                           {B00000000, B11111000 },
                           {B00000000, B11111000 },
                           {B00000000, B11111000 } },
    // continues for numerous elements
                        }
They are a bunch of values to push out to a pair of shift registers controlling an LED matrix. Each array is essentially an animation that plays across the LED matrix.

I would like to put my collection of arrays into an array so I can iterate through them. I know I can just combine them into one big array but the code is already opaque and I would at least like to keep separate named arrays so I can sequence and rearrange a series of animations by rearranging a series of named arrays in another array rather than one massive array of opaque binary values.

I want to do something like this

    sometype* sequence[] = { lines, circles, squares } ;
or if that's not possible then:

    sometype* sequence[3];
    sometype[0] = lines;
    sometype[1] = circles;
    sometype[2] = squares;

Can I do this or some approximation thereof? If so what is "sometype"? I can't figure out how to say "an array of pointers to 3d byte arrays" or whatever it is I am trying to do. What is the syntax for deeclaring the array and dereferencing the pointers?

title: An array of existing arrays

Answers: 2

body:
Yes, you can ( both ways )

You need

    typedef byte sometype[4][2];

However, you'll probably need the size of lines, circles, etc. , which is lost by a pointer.

One way might be an end marker (A special element, indicating there are no more)
Another might be a

    struct sometype {
      size_t n;
      byte [][4][2] data;
    } lines ;

IMO, even 2D arrays are reaching the limits of human intelligence, and I'd prefer even more user defined types:

    typedef byte Pattern[4][2]; // or a more appropriate name

    Pattern lineArray[] {
                 { {B00000000, B11110000 },
                   {B00000000, B11110000 },
                   {B00000000, B11110000 },
                   {B00000000, B11110000 } }
              , { {B11110000, B00000111 },
                   {B00000000, B11111000 },
                   {B00000000, B11111000 },
                   {B00000000, B11111000 } }
    };

    typedef struct {
      size_t count;
      Pattern* data;
    } PatternCollection;

    PatternCollection lines = {sizeof(lineArray)/sizeof(Pattern), lineArray };

    PatternCollection sequence[] = {lines /* , circles, squares */ }; // if you ever need to iterate them

body:
Try this:

```c++
byte (*sequence[])[4][2] = { lines, circles, squares } ;
```

**Explanation**: The identifiers `lines`, `circles` and `squares` decay
to pointers to the first element of each array. Their decayed types are
then “pointer to array of length 4 of array of length 2 of byte”. This
type could be declared as

```c++
typedef byte (*pointer_to_2d_array)[4][2];
```

The sequence is then an array of this type, which can be declared as

```c++
pointer_to_2d_array sequence[] = { ... };
```

or, if you appreciate the obscure elegance of the C syntax, as in the
beginning of this answer.


body:
I have

    char c;

where

    int bt_available = Serial2.available();
    if (bt_available) {
      c = Serial2.read();
    }

and later in the code I try to

    strcat(some_char_array, c);

and it gives me this error

> initializing argument 2 of 'char* strcat(char*, const char*)' [-fpermissive]<br>
error: invalid conversion from 'char' to 'const char*' [-fpermissive]

My best guess why the error appears would be that strcat can only accept strings and char arrays, but not single characters, so a solution I can think of would be to create a char array like *char test[1]* where *test[1] = '\0'* and then *test[0] = c* but I'm not sure if that's the best way to go about the problem and if that's a solution. Does 'const char*' mean 'char[]'?

P.S I read Majenko's blog thingy and I'm turning all Strings to char arrays and it's a bit of suffering :P

title: strcat gives error when I try to add a char to a char array

Answers: 1

body:
A `char` is a single character. A `char *` and a `char[]` are both arrays of characters (more correctly `char *` is a pointer to an array of characters).

`strcat` expects two arrays or pointers to arrays of characters. If you want to add a single character you can either fool the compiler into thinking that the character is an array of characters of size 1 (but it lacks the required NULL termination) or manually manipulate the target array.

For the former you could use `strncat` and casting:

    strcat(some_char_array, &c, 1);

That gives you a pointer to the character, which is as far as the compiler is concerned, indistinguishable to a pointer to an array of characters. You use the "n" variant of strcat  to limit it  to just one character (plus an added NULL character) so it doesn't rely on the missing NULL termination.

For the second you could do:

    int n = strlen(some_char_array);
    some_char_array[n] = c;
    some_char_array[n+1] = 0;

That just sets the Nth character in the target array to whatever is in c, then adds a new NULL termination character to the end.


body:
Can anyone help me connecting arduino mega to D1 Wemos Mini serially? Please let me know most efficient and easy steps to setup a communication.

Using that following tutorial:

https://engineeringprojectshub.com/serial-communication-between-nodemcu-and-arduino/amp/

Following is the circuit diagram:
https://i.stack.imgur.com/oOKwL.png

title: Serial communication arduino mega and D1 Wemos Mini

Answers: 1

body:
Apart from ensuring you're wiring TX -> RX and connecting all grounds, you can use [SerialTransfer.h][1] to automatically packetize and parse your data for inter-Arduino communication without the headace. The library is installable through the Arduino IDE and includes many examples.

Here are the library's features:

> This library:
>
>  - can be downloaded via the Arduino IDE's Libraries Manager (search "SerialTransfer.h")
>  - works with "software-serial" libraries
>  - is non blocking
>  - uses packet delimiters
>  - uses consistent overhead byte stuffing
>  - uses CRC-8 (Polynomial 0x9B with lookup table)
>  - allows the use of dynamically sized packets (packets can have payload lengths anywhere from 1 to 254 bytes)
>  - can transfer bytes, ints, floats, and even structs!!

Example TX Arduino Sketch:

    #include "SerialTransfer.h"

    SerialTransfer myTransfer;

    void setup()
    {
      Serial.begin(115200);
      Serial1.begin(115200);
      myTransfer.begin(Serial1);
    }

    void loop()
    {
      char buff[] = "hi";

      myTransfer.txObj(buff, sizeof(buff));
      myTransfer.sendData(sizeof(buff));
      delay(100);
    }

Example RX Arduino Sketch:

    #include "SerialTransfer.h"

    SerialTransfer myTransfer;

    void setup()
    {
      Serial.begin(115200);
      Serial1.begin(115200);
      myTransfer.begin(Serial1);
    }

    void loop()
    {
      if(myTransfer.available())
      {
        char buff[40];

        myTransfer.rxObj(buff, sizeof(buff));

        Serial.println("New Data: ");
        Serial.write(buff, sizeof(buff));
        Serial.println();
      }
      else if(myTransfer.status < 0)
      {
        Serial.print("ERROR: ");

        if(myTransfer.status == -1)
          Serial.println(F("CRC_ERROR"));
        else if(myTransfer.status == -2)
          Serial.println(F("PAYLOAD_ERROR"));
        else if(myTransfer.status == -3)
          Serial.println(F("STOP_BYTE_ERROR"));
      }
    }

  [1]: https://github.com/PowerBroker2/SerialTransfer


body: I noticed that the TomThumb.h font included in the Adafruit GFX library has characters that have different widths, which is a problem for me because I'm doing text processing that requires characters to have the same dimensions (width and height). I also noticed that the TomThumb.h font misses some characters (such as ') and so on. I need a way to create/edit fonts for the Adafruit GFX (where I'm using the Adafruit_ST7735 on a 1.8" TFT Display). I've looked around the internet but I couldn't find anything decent.

title: How to create and edit fonts for the Adafruit GFX library?

Answers: 3

body:
One possible solution you might already have: There’s a small utility called `fontconvert` that’s part of the Adafruit GFX library. The source code is installed by default together with the Adafruit GFX library in `Arduino/libraries/Adafruit_GFX_Library/fontconvert` You need Linux to compile it from the provided source code. It also compiles and runs on a Raspberry Pi.

It takes care of converting TrueType fonts (completely or partially) to Adafruit GFX format. There’s some documentation on compiling and using it in the fontconvert directory.

body:
I found an online editor that can parse Adafruit GFX font headers, modify, and export the result to create a new font header.  It works very well.  May be a bit late to help OP, but for anyone else looking...

It uses regexes to extract info from the header files, so it's pretty strict on following the layout of GFX font headers provided by Adafruit.

webpage: https://tchapi.github.io/Adafruit-GFX-Font-Customiser/
github: https://github.com/tchapi/Adafruit-GFX-Font-Customiser

body:
I have used this website to generate various fonts, sizes, etc. with success.

http://oleddisplay.squix.ch/#/home


body:
I recently created a project that involves the control of three SG90 servo motors. I started off by controlling this through the 5V output pin of the Arduino Uno, with the Arduino powered through the barrel plug with a 9V mains power supply.

However, the servos couldn't perform the full 180° sweep, it would appear to be due to the high torque at the end of the motion for my application.

I then switched to powering the servos separately to the Arduino using four AA batteries in series. I now had no issues with the servos stalling and could perform the full sweep.

I am not sure why this is though?

Four AAs in series will result in 6V, which is not that different to the 5V Arduino output pin? And it seems the current is the issue with servo stalling? and surely the number of batteries makes no difference to this as connected in series it stays the same? Is the current of the AA battery just higher than the 5V Arduino output pin?

Any help would be greatly appreciated, I'd really like to have a better understanding of this.

title: External vs arduino power supply for servo motors?

Answers: 0


body:
Probably something easy but I’ve not resolved it.

I’m extracting data from a JSON string and all the values are correct accept for two.

They are referring to two date time values and are in milliseconds.

One is the date refreshed and the other is date updated.

Problem is they are both very large and I’m having difficulty assigning them in the IDE.

One is 1588447162117 which is showing as 020-05-02 20:19:53.948  on the dashboard using the JSON.

Here is the code I have thus far to get the data from JSON:

    #include <ArduinoJson.h>

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

      const char* input = "{TotalCases:3308678,TotalCasesToday:4458,TotalDeaths:234123,TotalDeathsToday:293,TotalRecovered:1042991,TotalTerritories:124,CurrentUpdatedMS:1588312648603,CurrentChangedMS:1588312648603}";

      StaticJsonDocument<512> doc;

      DeserializationError err = deserializeJson(doc, input);

      if (err) {
        Serial.print("Error: ");
        Serial.println(err.c_str());
        return;
      }

      unsigned long TotalCases = doc["TotalCases"];
      unsigned long TotalCasesToday = doc["TotalCasesToday"];
      unsigned long TotalDeaths = doc["TotalDeaths"];
      unsigned long TotalDeathsToday = doc["TotalDeathsToday"];
      unsigned long TotalRecovered = doc["TotalRecovered"];
      unsigned long TotalTerritories = doc["TotalTerritories"];
      unsigned long CurrentUpdatedMS = doc["CurrentUpdatedMS"];
      unsigned long CurrentChangedMS = doc["CurrentChangedMS"];

      Serial.print("Total Cases: ");
      Serial.println(TotalCases);
      Serial.print("Total Cases Today: ");
      Serial.println(TotalCasesToday);
      Serial.print("Total Deaths: ");
      Serial.println(TotalDeaths);
      Serial.print("Total Deaths Today: ");
      Serial.println(TotalDeathsToday);
      Serial.print("Total Recovered: ");
      Serial.println(TotalRecovered);
      Serial.print("Total Territories: ");
      Serial.println(TotalTerritories);
      Serial.print("Update time in ms:");
      Serial.println(CurrentUpdatedMS);
      Serial.print("Change time in ms:");
      Serial.print(CurrentChangedMS);
    }

    void loop()
    {

    }

    **Serial monitor output**

    Total Cases: 3308678
    Total Cases Today: 4458
    Total Deaths: 234123
    Total Deaths Today: 293
    Total Recovered: 1042991
    Total Territories: 124
    Update time in ms:0
    Change time in ms:0

Should be good to manipulate it once I can work with it in a variable.

Thanks for any input,

Shane

title: Large number into variable

Answers: 1

body:
I didn't try myself, but just by looking at the docs I suggest you try:

1. Adding
   ```c++
   #define ARDUINOJSON_USE_LONG_LONG 1
   ```
   at the top of the sketch, before including ArduinoJson.h.

2. Declare `CurrentUpdatedMS` and `CurrentUpdatedMS` as either
   `unsigned long long` or `uint64_t`.

**Edit**: To answer the question in the comment:

> When you said you looked at the docs where did you check?

I had to follow a (not so simple) path: [Deserialization tutorial][1] →
[JsonDocument::operator[]][2] → [JsonVariant][3] →
[JsonVariant::as<T>()][4]. This last page states that the method
`as<unsigned long long>()` “may require ARDUINOJSON\_USE\_LONG\_LONG”.
Unfortunately, the macro is not linked, so I have to search for it and
found [`ARDUINOJSON_USE_LONG_LONG`][5].

[1]: https://arduinojson.org/v6/doc/deserialization/
[2]: https://arduinojson.org/v6/api/jsondocument/subscript/
[3]: https://arduinojson.org/v6/api/jsonvariant/
[4]: https://arduinojson.org/v6/api/jsonvariant/as/
[5]: https://arduinojson.org/v6/api/config/use_long_long/


body:
I'm trying to understand Arduino with push buttons. But I can't get the test project I'm working on to work as how I want it to do.

Basically what I'm trying to do with the codes below is to make the push button either start or stop the servo motor. But so far, I couldn't get it to work. I'm also wondering why the servo motor won't run on loop? I tried several approach, but I couldn't get it working.

What am I missing here? Thanks.

By the way, I'm a beginner.

```
#include <Servo.h> //Servo Library.

int servoPin = 3; //Servo to Pin 2.
int led = 4; // LED to Pin 4.
int buttonState = 0;
int lastButtonState = 0;

Servo ServoOne; //Servo object created.

void setup() {
  Serial.begin(9600);
  ServoOne.attach(servoPin);
  pinMode(led, OUTPUT);
  pinMode(2, INPUT);
}

void loop() {
  buttonState = digitalRead(2);
  if (buttonState != lastButtonState) {
   servoRun();
  }
  lastButtonState = buttonState;
}

void servoRun() {
  if (buttonState != lastButtonState) {
    if (buttonState == HIGH) {
      Serial.println("Running.");
      ServoOne.write(0); //Servo resets to 0 degrees.
      digitalWrite(led, LOW); //LED turns on.
      delay (1000);
      ServoOne.write(90); //Servo turns to 90 degrees.
      digitalWrite(led, HIGH); //LED turns on.
      delay (1000);
      ServoOne.write(180); //Servo turns to 180 degrees.
      digitalWrite(led, LOW); //LED turns on.
      delay (1000);
      ServoOne.write(90); //Servo turns to 90 degrees.
      digitalWrite(led, HIGH); //LED turns on.
      delay (1000);
      ServoOne.write(0); //Servo resets to 0 degrees.
      digitalWrite(led, LOW); //LED turns on.
    } else {
      Serial.println("Off.");
      ServoOne.write(0);
      digitalWrite(led, LOW);
    }
  }
}
```

Edit:
I tried this new approach, but I can't get the button state change saved.

```
#include <Servo.h> //Servo Library.

//Constant.
const int pswitch = 2; //Switch to Pin 2.

//Variables.
int servoPin = 3; //Servo to Pin 3.
int led = 4; //LED to Pin 4.
int newState; //Current switch state.
int oldState = LOW; //Previous switch state.

Servo ServoOne; //Servo object created.

void setup() {
  Serial.begin(9600);
  ServoOne.attach(servoPin);
  pinMode(led, OUTPUT);
  pinMode(pswitch, INPUT_PULLUP);
}

void loop() {
  newState = digitalRead(pswitch);

  if (oldState == LOW && newState == HIGH) {
    Serial.println("ON and running.");
    ServoOne.write(90);
    digitalWrite(led, HIGH);
    delay(1000);
    ServoOne.write(0);
    digitalWrite(led, LOW);
    delay(1000);
    ServoOne.write(90);
    digitalWrite(led, HIGH);
    delay(1000);
    ServoOne.write(180);
    digitalWrite(led, LOW);
    delay(1000);
    ServoOne.write(90);
    digitalWrite(led, HIGH);
    delay(1000);
  } else {
    Serial.println("OFF.");
    delay(1000);
  }
  oldState = newState;
}
```

title: Start / Stop Motor Run with Button State Change

Answers: 0


body:
I have the following really simple code. On every iteration it'll read the first pin, and if it's high - do some serial IO. Then do the same with the second pin. Nice and simple, works during my tests.

My concern is that (in production), the digital pulse I'm receiving (and trying to mimic during testing) would be too quick for the arduino to read. So, for example, the race condition could be:

 1. *First pin is low* Read first pin - result is low.
 2. *First pin is now high* Read second pin - result is low.
 3. *Fist pin now low again* Read first pin - result is low again (missed the 'high')

How much of an 'edge case' is this? Am I worrying about something that's likely to be a non-issue here? In production, each single pulse would represent a significant amount of product (I multiply it elsewhere) - so even skipping one could throw my data off.

    boolean count1High = false;
    boolean count2High = false;
    int count1 = 7;
    int count2 = 8;
    int a = 1;
    void setup() {
      pinMode(count1, INPUT);
      pinMode(count2, INPUT);
      Serial.begin(9600);
    }

    void loop()
    {
      if (digitalRead(count1) == HIGH)
      {
        if (!count1High)
        {
          count1High = true;
          a++;
          Serial.println(a);
        }
      }
      else
      {
        count1High = false;
      }

      if (digitalRead(count2) == HIGH)
      {
        if (!count2High)
        {
          count2High = true;
          a++;
          Serial.println(a);
        }
      }
      else
      {
        count2High = false;
      }
    }

EDIT:
------

I know best approach here might be to attach an interrupt but I've been advised to avoid serial IO from within interrupts, I don't see an alternative here.

title: How long does my digital pulse need to be for it to be read?

Answers: 3

body:
This is exactly the reason interrupts were invented. They can respond a lot faster than a simple digital read. By "a lot" I mean orders of magnitude.

When an interrupt is triggered your interrupt handler for that interrupt executes. If another interrupt occurs whilst your interrupt handler is running the interrupt controller remembers it and the interrupt handler for that interrupt will execute as soon as the previous one is finished.

So you won't miss that pulse while the other pulse is processing.

However note that you shouldn't use Serial in interrupts, since Serial itself uses an interrupt internally to control the transmission, so transmission can't happen properly if your interrupt is already running. So instead your interrupt routine should just set a flag which you then check for in your main loop. You then benefit from the ability to notice a pulse while processing another pulse and still be able to use Serial. In fact, if you arrange it right, you can recognise and remember a pulse on the *same* input as the one you're currently processing.

body:
**It depends** where the signal comes from and on other code in your sketch.

Typically, a sketch is rather way too fast for a mechanical switch, and you have to debounce it.

If your fear to lose events is _realistic_, interrupts are the way to go. But an ISR is some very special code: You won't do more than collect the information that there was an event. And you have to assert your main sketch won't interfere with the ISR.

body:
As explained by Majenko's answer, you should detect the pulses from an
interrupt and print the result from the regular code. However, instead
of just setting a flag in the interrupt handler, I suggest you instead
_count_ the pulses within the handler. This will make the handler a tiny
bit slower, which is often something you want to avoid. However, the
extra overhead is really tiny, and you gain the ability to count
not only pulses that are short but also pulses that are closely spaced.

There is, however, something to be aware of when sharing a variable
between interrupt code and regular code. If the variable cannot be read
in a single CPU instruction (which is the case of an `int` on an
AVR-based board), there is some risk that the value gets changed in the
middle of you reading it. To void this problem, you have to disable
interrupts when reading the variable from regular code.

Here is an implementation of this strategy highlighting this point:

```c++
const uint8_t intPin1 = 2;
const uint8_t intPin2 = 3;

// This is volatile because it is shared between interrupt context
// and regular code.
volatile unsigned int sharedCount = 0;

// Interrupt handler.
void countPulse() { sharedCount++; }

// A variable shared with interrupt context should be accessed from
// regular code with interrupts disabled, in order to avoid race
// conditions.
unsigned int getCount() {
    noInterrupts();
    unsigned int countCopy = sharedCount;
    interrupts();
    return countCopy;
}

void setup() {
    pinMode(intPin1, INPUT);
    pinMode(intPin2, INPUT);
    attachInterrupt(digitalPinToInterrupt(intPin1), countPulse, RISING);
    attachInterrupt(digitalPinToInterrupt(intPin2), countPulse, RISING);
    Serial.begin(9600);
}

void loop() {
    static unsigned int previousCount = 0;
    unsigned int count = getCount();
    if (count != previousCount) {
        Serial.println(count);
        previousCount = count;
    }
}
```

Note that if the pulses come very fast, you may miss _printing_ the
value, but you will not miss _counting_ it (up to some limit, of
course). Thus you may see non-consecutive numbers being printed.