# Question
Title: ADC value changing after changing Timer1 value in program
I'm writing a code where `analogRead()` reads ADC value from load. After reading ADC value, if it is not in range, I need to manipulate Timer1 value. Which is also getting changed. But, after changing the Timer value, if the load value again gets restored, ADC doesn't show the same value again, but shows some other value.

Please refer below code:

```
#include <TimerOne.h>

int LED = 13;
int IN0 = 12;
int IN1 = 11;
int OUT1 = 10;
int OUT2 = 9;
int OUT3 = 8;
int OUT4 = 7;
//float A0;
//int OUT5 = 6;
const float refvolt = 5.0;
int volts = 0;
byte tempL_flag = 0;
float samples, loadval, avgacs, acsvaluef =0;
float refval = 2.0;
bool lflag=0;
unsigned long count = 0;

void setup()
{
    pinMode(IN0, INPUT);
    pinMode(IN1, INPUT);
    pinMode(OUT1, OUTPUT);
    pinMode(OUT2, OUTPUT);
    pinMode(OUT3, OUTPUT);
    pinMode(OUT4, OUTPUT);
    pinMode(LED, OUTPUT);
    pinMode(A0, INPUT);
    //digitalWrite(OUT3, LOW);
    Timer1.initialize(370000);
    Serial.begin(9600);
}

word ADC_READ(byte sample, byte tim, byte CH)
{
    word adcdata;
    word avrdata;
    word abcdata;
    byte i;

    for(i=0; i<sample; i++)
    {
        adcdata = 0;
        adcdata = analogRead(CH);
        avrdata = avrdata + adcdata;
        delay(tim);
    }
    return(avrdata/sample);
}

void flash_L()
{
    digitalWrite(LED, !digitalRead(LED));
    digitalWrite(OUT4, !digitalRead(OUT4));

    if (digitalRead(OUT4)==1)
    {
        loadval = ADC_READ(10, 10, A5);
        Serial.println(loadval);

        if(loadval < refval)
        {
            Timer1.initialize(185000);
        }
        else
        {
            tempL_flag = 1;
        }
        return;
    }
}

void loop() {

    delay(2000);

    if(digitalRead(IN0)==1)
    {
        Timer1.attachInterrupt(flash_L);
    }
    else if(digitalRead(IN0)==0)
    {
        digitalWrite(LED, LOW);
        digitalWrite(OUT4, LOW);
    }
}

```

# Answer
> ADC doesn't show the same value again

You are not reading the ADC correctly, so `ADC_READ()` can return anything. See the comments in the code:

```
word ADC_READ(byte sample, byte tim, byte CH)
{
    word adcdata;  // not needed
    word avrdata;  // not initialized
    word abcdata;  // not used
    byte i;
    for (i = 0; i < sample; i++)
    {
        adcdata = 0;  // useless
        adcdata = analogRead(CH);
        avrdata = avrdata + adcdata;
        delay(tim);
    }
    return (avrdata/sample);
}

```

The big issue is `avrdata` not being initialized. Its initial value is whatever was left there (in the stack or some CPU registers) by the code that ran before. The value returned by the function is then hard to predict and depends on what the rest of the program is doing.

The other remarks I left in the comments are not that problematic, although they are revealing of some lack of attention to detail. Same for some badly named variables. Here is how I would implement this function:

```
word ADC_READ(byte samples, byte time, byte channel)
{
    word sum = 0;
    for (int i = 0; i < samples; i++)
    {
        sum += analogRead(channel);
        delay(time);
    }
    return sum/samples;
}

```
> 1 votes

---
Tags: arduino-uno, timers, analogread, adc
---


title: Arduino PID controller for Triac

text:
# Question
Title: Arduino PID controller for Triac
I am designing a new soldering station which will use a 24 V ac soldering iron.

I started to make some research and I designed a few steps of the soldering station. I will use a 24Vac/100VA toroidal transformer. I will use a 24V/50W soldering iron with K type thermocouple. For the thermocouple I will use a LM358 amplifier. Please have a look at the attached schematic and code. The code is not ready yet and I need some help in making the connection between the PID library and output in the code. The voltage on the soldering iron looks like: https://ibb.co/CMF1gQ0 If I rotate the pot, nothing happens on the screen of the scope.

https://ibb.co/vdDRmnJ

I wrote a few lines of code but I don't know how to make the connection between the PID library functions and the interruption function and the other variables in my code.

Please have a look at the code and at the schematic and tell me what you think... I am waiting for your help.

```
#include <PID_v1.h>

int AC_LOAD = 1;    // Output to Opto Triac pin
double set_value = 0;
double input = 0;
double output = 0;

PID aaa_PID(&input, &output, &set_value, 1, 0.05, 0.25, DIRECT);

void setup()
{
  aaa_PID.SetOutputLimits(0, 128);
  aaa_PID.SetMode(AUTOMATIC);
  pinMode(AC_LOAD, OUTPUT);// Set AC Load pin as output
  attachInterrupt(0, zero_crosss_int, RISING);  // Choose the zero cross interrupt # from the table above
}

//the interrupt function must take no parameters and return nothing
void zero_crosss_int()  //function to be fired at the zero crossing to dim the light
{
  // Firing angle calculation : 1 full 50Hz wave =1/50=20ms
  // Every zerocrossing thus: (50Hz)-> 10ms (1/2 Cycle)
  // For 60Hz => 8.33ms (10.000/120)
  // 10ms=10000us
  // (10000us - 10us) / 128 = 75 (Approx) For 60Hz =>65
  int dimtime = (75*output);    // For 60Hz =>65
  delayMicroseconds(dimtime);    // Wait till firing the TRIAC
  digitalWrite(AC_LOAD, HIGH);   // Fire the TRIAC
  delayMicroseconds(10);         // triac On propogation delay (for 60Hz use 8.33)
  digitalWrite(AC_LOAD, LOW);    // No longer trigger the TRIAC (the next zero crossing will swith it off) TRIAC
}

void loop()  {
  int set_point = analogRead(A1);
  set_point = map(set_point, 0, 1023, 150, 400);
  int in = analogRead(A0);
  input = map(in, 0, 550, 25, 400);
  set_value = set_point;
  aaa_PID.Compute();

}

```

# Answer
> 1 votes
> I need some help in making the connection between the PID library and output in the code

PID calculates the value of `output` and it is used in `int dimtime = (75*output);`.

The `aaa_PID` object gets the reference to variable `output` with `&` so when the PID algorithm sets the output value it sets the value of this variable in your sketch.

`output` should be `volatile double output = 0;` because it is used in interrupt.

EDIT 2:

I hope you wired the zero crossing detector to pin 2, because that is the pin for external interrupt 0. And don't use pin 1 for Triac, it is wired to USB chip too.

EDIT: Your code stays too long in interrupt. You exit the interrupt only in the time after firing the TRIAC and the next zero crossing.

In this Arduino SE answer I offer two sketches which demonstrate Triac control. This is one of them:

```
#include <TimerOne.h>

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

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

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

int fadeAmount = 10;

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

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

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

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

```

the other uses direct registers access o AVR.

EDIT 3: mike's oscilloscope output of the sketch above: https://www.youtube.com/watch?v=dnfy\_EsPlVI

EDIT 4: the PID outputs high values for high power and small values for lower power. but the Triac period is the off time. so the period should be something like `period = 11000 - (75 * output)`

here are the input and output values of mike's code based on this answer (blue is temperature, red is output for the Triac period):

The PID control gets smoother over time as it finetunes its parameters, but I think a simple PID has some problems with the sine relation between the output (time) and the resulting heating power.

# Answer
> 1 votes
I see several issues here.

The most serious is in the wiring of the Arduino. The first argument of `attachInterrupt()` is an interrupt number. On the Uno, “interrupt 0” is wired to the pin “digital 2”. This is where you should connect the output of the zero-crossing detector (ZERO\_OUT).

Then, as noticed by Juraj, there is the issue of the interrupt handler taking too long to execute. This is generally considered bad practice, and it has some negative consequences on the working of the Arduino core like, e.g., the `millis()` function will be completely off. I do not think, however, that this is a serious issue for you. There is one single time-critical bit in your program, which is the generation of the triac trigger pulses. You really do not care about `millis()` or any other time-related things. Thus, at least for the initial version of the program, I would not care too much, and just let the interrupt handler delay as needed.

The third issue has been noted by chrisl in a comment: there is a race condition with both the main program and the interrupt handler accessing the same `output` variable. Race conditions are a nasty kind of bug because usually things work fine “most of the time” and then fail at unexpected times. I would not recommend, however, to run `myPID.Compute()` with interrupts disabled: that may throw off the timing of your triac pulses. Instead, compute the delay required by the interrupt, save it to a temporary variable, then copy it to a variable shared with the handler. Only the copy needs to be done with interrupts disabled, and that takes only a handful of CPU cycles:

```
// Variable used by zero_crosss_int().
// Do not forget the `volatile' qualifier.
volatile int dimtime;

void loop() {
    // PID and associated computations.
    set_value = map(analogRead(A1), 0, 1023, 150, 400);
    input = map(analogRead(A0), 0, 550, 25, 400);
    aaa_PID.Compute();
    int tmp_dim_time = 75*output;

    // Critical section executed with interrupts disabled.
    noInterrupts();
    dimtime = tmp_dim_time;
    interrupts();
}

```

---

**Edit**: If things do not work, you should try to debug piece by piece. Sending debug messages to the serial port should help, although serial communication is likely to be significantly slowed down by the long-running interrupt handler. As an alternative, you can use the triac control pulses as a debug aid, maybe with the heating element unplugged. For example:

* In `loop()`, set `dimtime` to a value proportional to `set_value`. Turn the pot and look at the FIRING\_PULSE signal. Does the pulse width vary proportionally to the pot position? Is it in sync with the Vin zero-crossings?
* Set `dimtime` proportional to `input`. Heat the thermocouple by some external means. Does FIRING\_PULSE vary as expected?
* Set `dimtime` proportional to `output`, but keep the heating element unplugged. How does the pulse change as you move the pot or heat the thermocouple?

---
Tags: potentiometer, analog-sampling, pid
---


title: writing mqtt payload to spiffs file

text:
# Question
Title: writing mqtt payload to spiffs file
I'm trying to write the payload of a MQTT message into a file in the SPIFFS file system of my esp32 board. I've tried this:

```
if(file.print((long)payload)) {
   Serial.println("File was written");
}else {
   Serial.println("File write failed");
}

```

payload is a byte\* and file was opened in the setup() function like:

```
File file;
if(!SPIFFS.exists("/testfile")){
  file = SPIFFS.open("/testfile", "r+");
}

```

I always get an error when writing to it telling me that the file write failed. Is this the correct approach for what I'm trying to accomplish?

# Answer
> 1 votes
Use `file.write(payload, length);` for byte array. `length` should be the count of payload bytes, not the size of the payload array.

`print` and `write` return the count of bytes written. It is not meaningful to use the return value as boolean.

# Answer
> 0 votes
Open the file in the loop or the subroutine, but not in setup as file is then a local var to setup

In your code it should be

```
file = SPIFFS.open("/testfile", "a"); // a ... append

```

> a Open for appending (writing at end of file). The file is created if it does not exist. The stream is positioned at the end of the file.

r+ positions stream at the beginning of the file

and to get lines you can afterwards analyze you should use

```
if(file){
   file.println("Your MQTT payload");
   Serial.println("File was written");
   file.close();
} else {
    Serial.println("File write failed");
}

```

and do not forget to close after the operation.
**EDIT**
As reaction to the comments here a "clean solution" as a function:

```
bool writeLog(const char fileName[],  char payloadMqtt[]) {
  File logFile = SPIFFS.open(fileName, "a");
  if (!logFile)  {
        Serial.println("logFile open failed");
    return false;
  }
  else {
    //Write data to file
    Serial.println("writing Data to logFile");
    logFile.print(payloadMqtt);
    logFile.close();
    return true;
  }
}

```

You call it with:

```
writeLog("/myfilepath", payload);

```

and can also be used like

```
if (writeLog("/myfilepath", payload)) Serial.println("Log save success");
else Serial.println("Log save failure");

```

Hope this helps to understand the nature of SPIFFS/LittleFS/SD operations

---
Tags: mqtt, spiffs
---


# Question
Title: My LED toggeling doesn't work the way I want
I want to do LED toggeling so I wrote this:

```
int led=13, button=12;

void setup()
{
    // put your setup code here, to run once:
    pinMode(led,OUTPUT);
    pinMode(button,INPUT);
}

void loop()
{
    // put your main code here, to run repeatedly:
    if(digitalRead(button)==HIGH && digitalRead(led)==LOW)
    {
        digitalWrite(led,HIGH);
    }

    if(digitalRead(button)==HIGH && digitalRead(led)==HIGH)
    {
        digitalWrite(led,LOW);
    }
}

```

But It doesn't work well, sometimes I need to press the button many times in order to turn on or of...and some times with just one press.

I saw this video but I didn't understand it well: https://www.youtube.com/watch?v=aMato4olzi8&t=415s

Anyway I don't know why my way doesn't work well.

# Answer
There are a few problems with your approach.

1. You seem to have the button backwards. You should wire a button so that it is between the pin and ground. This way it should read LOW when pressed, not HIGH. It should also have pinMode(pin, INPUT\_PULLUP) instead of INPUT. With the button wired the way you have it to read HIGH then you will need an extra resistor for each button. With it wired the right way where it reads LOW then it needs nothing extra.
2. If the first if statement is true and the button is pressed and it turns on the led, what do you think are the chances that you are fast enough to get your finger off the button in the 62.5 nanoseconds it takes to get to that next if statement? It's not going to happen, so the button is still pressed there and now the led is on so this line turns it right back off. Only in the rare case where you happen to get your finger off the button at just the right instant will the led stay lit. To solve this, look at the "State Change Example" that comes with the IDE. It shows how to keep track of the last state of the button in a variable so you can act only once when the button actually changes state.
3. Once you get that worked out you will notice that it seems like for every time you press your button it registers tens of presses. This is switch bounce. That's a term you should google. The contacts are making and breaking contact really fast in the in-between pushed and not-pushed state. But you need to get the first two issues solved before you worry about bounce.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Generate 5VDC signal when external sensor input changes from high to low
I am new to arduino. I have a project in which I need an arduino to generate a +5VDC signal in response to a *change* *of* *status*, (high/5VDC To low/ground) from an external source.

The external source is a stand alone receiver/transmitter set which outputs +5VDC when the transmitter is out of range and ground when the transmitter is within range.

The goal is to have the arduino output +5VDC (triggering a series of events) only when the TX is within range of the RX (signal voltage is GRND vs. +5vDC). The series of events are controlled via a stand alone event controller which is initiated by a +5VDC signal courtesy of the arduino.

I already have a RX/TX set which outputs +5VDC when the the TX is absent and GROUND when the TX is within range. I also have the event controller. I only need the arduino solution.

I have an arduino UNO but I am open to other option if needed.

Solution: give me +5VDC when signal voltage (from receiver) is low (ground).

If anyone could point me in the right direction it would be greatly appreciated. This is my first arduino project so I have much to learn.

Best regards

# Answer
> 1 votes
This is literally the simplest Arduino program possible. I can't believe you couldn't find an example of making one pin HIGH when another goes LOW.

```
void setup(){
  pinMode(yourInputPin, INPUT_PULLUP);
  pinMode(yourOutputPin, OUTPUT);
}

void loop(){
  if(digitalRead(yourInputPin) == LOW){
     digitalWrite(youOutputPin, HIGH);
  }
  else {
     digitalWrite(yourOutputPin, LOW);
  }
}

```

All you need to do is supply the appropriate pin numbers.

# Answer
> 1 votes
Why waste an Arduino on such a paltry job? Here's a circuit that has just 3 components in it that does what you want:

simulate this circuit – Schematic created using CircuitLab

It's basically a NOT gate (you can use an actual NOT gate, like a 74HC04 if you like) where the output is the opposite of the input. You could even remove R2 if you like - that just prevents the input floating when there's no valid signal detected.

This form of gate is called *RTL* \- Resistor-Transistor Logic, and is one of the simplest logic gate arrangements there is.

---
Tags: input, signal-processing
---


title: Arduino Uno SD card storage

text:
# Question
Title: Arduino Uno SD card storage
I am interested in storing accelerometer data to an SD card. Since power consumption is the main consideration of my project, it is important to do as few writes to the SD as possible, because the SD requires much current, and also takes long to be written, keeping my MCU from sleeping.

1. The data to be stored are about 50 bits of data at 10Hz, so I need to store 500c bits per second, or around 63 bytes per second. The arduino uno EEPROM is 1024 bytes, which could give me around 16 seconds of data stored before having to access my SD card. However I have seen that the EEPROM has limited write cycles (100000). So each byte can be written 100000 times, which gives us a total of 1000\*100000=100000000 bytes to be written.As a result, with writing there 63 bytes per second, that would give me 1587301 seconds=441hours=18days of EEPROM lifetime, which is unacceptable. Is this correct?
2. If (1) is correct and using internal eeprom is not a possible solution, what other recommendations do you have? Is there an alternative to SD storage, that requires less power and less writing time, so that it is cheaper power-wise? The total storage should be around 200MB.

# Answer
> 2 votes
Regarding 1, it's true that EEPROM has limited write cycles. Mostly it can be much more, but it's only guaranteed upto that number, so I can imagine you don't want taking the risk to be lucky.

Regarding 2, other solutions could be external SRAM, which can be much more than just 1 KB, but also adds some extra components, thus cost and more important power. When that SRAM is full (can be many KBs), you can transfer it to the SD card.

Another (added) improvement you might think of (if you did not already) is data compression (trying to store the 50 bits in less bits), but this will cost some 'computing' power.

# Answer
> 0 votes
To start with power consumption rules an Arduino UNO out so you will need some device capable of (deep) sleep mode. Devices like ESP8266 or ESP32. The table below shows the differences between each mode (information from the ESP8266 datasheet).

```
Item                 Modem-sleep        Light-sleep       Deep-sleep
Wi-Fi                   OFF          OFF            OFF
System clock             ON         OFF             OFF
RTC                     ON          ON              ON
CPU                     ON          Pending         OFF
Substrate current     15 mA        0.4 mA          ~20 uA
Avg. current (DTIM = 1) 16.2 mA     1.8 mA            –
Avg. current (DTIM = 3) 15.4 mA     0.9 mA            –
Avg.current (DTIM = 10) 15.2 mA     0.55 mA

```

These modules have around 4MB flash which yoi could use for storage of data (SPIFFS/LittleFS) so 1MB for programs and 3MB for on board storage, after that you save to SD and fill up the onboard FS again or you send the data via WLAN to an online storage or database or to a server in your network (depending on your scenario) These devices cost as much as an Arduino UNO clone (5-7$) and can be programmed with the same IDEs as Arduinos and in the same (extern C/)C++ derivate. So if power consumption is an issue look at those IoT devices

---
Tags: arduino-uno, power, sd-card, eeprom
---


# Question
Title: Node.js cannot recognize characters from the serial port
The following script prints everything fine, it recognizes integers from the serial port, but cannot recognize characters. The if statement does not work with characters. I have tried both == and === in the if statement

```
var SerialPort = require('serialport')
var Readline = SerialPort.parsers.Readline
var serialPort = new SerialPort('/dev/ttyAMA0', {//ttyAMA0
  baudRate: 9600
})

var parser = new Readline()
serialPort.pipe(parser)
parser.on('data', function (data) {
if(data === 'c'){/// c is not recognized
  console.log('data received: ' + data)
}

})
serialPort.on('open', function () {
  console.log('Communication is on!')
})

```

The Arduino code is as follows:

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(12, 13); // RX, TX
int x = 0;
int y = -30000;
int z = 0;
String data;
char command = 'q';
int left = 0;
int right = 0;
int left_pwm = 0;
int right_pwm = 0;

void setup() {
  mySerial.begin(9600);     // opens serial port, sets data rate to 9600 bps
  Serial.begin(9600);
  }
void loop() {//map and compass data
if (y==30000) {
 mySerial.println('c');
 delay(5);
 mySerial.println(299);
 delay(5);
 z = -25000;
 }

 if(z==30000){
 mySerial.println('lon');
 delay(5);
  mySerial.println(529);
  delay(5);
  mySerial.println('lat');
 delay(5);
   mySerial.println(522);
          y = -30000;
    }
  y++; z++;

  if (!mySerial.available()) {
    return;
  }

  data = mySerial.readString();
   sscanf(data.c_str(), "%c%01d%01d%03d,%03d", &command, &left, &right, &left_pwm, &right_pwm);

  if (command == 'n') { // we got a navigation command
    // update the GPIO accordingly, this only happens once after a new 'n' command has been received
    Serial.print(command);
    Serial.print(left);
    Serial.print(right);
    Serial.print(left_pwm);
    Serial.print(",");
    Serial.println(right_pwm);
    }

    }////end loop

```

# Answer
> 0 votes
If you use the line parser in Nodejs, it does not remove all line ending characters. I think (though I currently cannot cite it), that only the `'ņ'` character is removed from the string. But `Serial.println()` sends `"\r\n"` as line ending. That means, that your string is "c\r", which is not equal to "c".

By using the `trim()` method of the String type, you can remove all white space from start and end of the string, including line ending characters like `'\r'`.

---
Tags: arduino-uno, serial, programming, c, node.js
---


# Question
Title: Why is function mentioned in global declaration?
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?

```
#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
  }
}

```

# Answer
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.
> 2 votes

# Answer
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.
> 1 votes

---
Tags: arduino-uno, arduino-ide, functions
---


# Question
Title: UNO SPI slave read from UNO SPI Master beginTransaction
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. 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

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

```

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
   }

}

```

# Answer
> 1 votes
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.

---
Tags: arduino-uno, spi
---


# Question
Title: Arduino Nano IoT 33 Char Array size constraints
I would like to save data that I am receiving from API calls in a char array. The problem is that the data is around 80 kB, and my Arduino IoT 33 only has 32 kB of memory.

It will save data in a char array up to 25000 bytes, but when I go to 30000 bytes or above the Arduino freezes. When I copy-paste the entire data to a char array without specifying the size it works fine, but when receiving data over the API in chunks of 10 kB it won't save the entire 80 kB. Is there a way around this?

# Answer
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. The library is in the Library Manager.
> 0 votes

---
Tags: wifi, array, memory, arduino-nano-33-iot
---


# Question
Title: STM32 and SDFat - Can't create file in directory in SD
I'm using the SdFat.h library on a STM32 and I can successfully create a file in the root directory using *SD.open("test.txt", FILE\_WRITE);* but my code fails to create *SD.open("DATA/data\_test.txt", FILE\_WRITE);* in a directory. Here's the piece of code that successfully creates a file in the root:

```
String final_book_name = upload_book_name + ".txt";
if (SD.exists(final_book_name.c_str())) {
  SD.remove(final_book_name.c_str());
}
tft.println(final_book_name); // This successfully prints "test.txt"
book_file = SD.open(final_book_name, FILE_WRITE);
if (SD.exists(final_book_name.c_str())) {
  tft.print("Created file");
} else {
  tft.print("Failed to create/replace\nfile!");
}

```

and here's the piece of the code that fails to create a file in a directory:

```
if (!SD.exists(DATA_DIR)) {
  SD.mkdir(DATA_DIR);
}
String final_book_name = upload_book_name + ".txt";
String book_data_path = DATA_DIR;
book_data_path += "/data_" + final_book_name;
if (SD.exists(book_data_path.c_str())) {
  SD.remove(book_data_path.c_str());
}
tft.println(book_data_path); // This successfully prints "DATA/data_test.txt"
File book_data_file = SD.open(book_data_path, FILE_WRITE);
if (SD.exists(book_data_path.c_str())) {
  book_data_file.print(upload_book_font);
  book_data_file.print("|");
  book_data_file.print("0");
  book_data_file.close();
} else{
  tft.print("Failed to create/replace\ndata file!");
  if (SD.exists(final_book_name.c_str())) {
    SD.remove(final_book_name.c_str());
  }
}

```

# Answer
> 1 votes
I found the issue. I'm not creating the directory folder properly. When I checked the SD card from another device, the DATA folder was invalid, and creating it manually works. I'll look for a solution and post an update.

UPDATE: https://forum.arduino.cc/index.php?topic=421131.0 I'll try this tomorrow but it'll probably fix the issue.

# Answer
> 0 votes
As you have given no variable for `DATA_DIR`

```
String book_data_path = DATA_DIR;
book_data_path += "/data_" + final_book_name;

```

so your resulting path looks like

```
DATA_DIR + "/data_" + final_book_name

```

IF `DATA_DIR = "/"` then it would be `"/" + "/data_" + final_book_name`

As tip do not use the string class but char arrays

definition

```
 const char[] DATA_DIR = "/books";
 char book_data_path [128] = {'\0'};
 char final_book_name [13] =  {'\0'}; // IF no LFN support is used its 8.3 !!!
 const char upload_book_name[] = "my_book";
 strcpy (final_book_name, upload_book_name);
 strcat (final_book_name, ".txt");
 Serial.println(final_book_name);

```

If you want long filr namesupport us SDFat library or enable LFB withSD lib (whichneeds about 35% ,ore memory as SDfat (when using long file names).
**EDIT**
As you are using SDFat and I do not know which version/fork there is abug with writing to subdirectories. Please check the following:
To check run the `SdFat\examples\DirectoryFunctions` and watch your serial monitor for the results
SdFile.cpp. At line 782 and 1452, you have (in my version):

```
if (block <= m_vol->cacheBlockNumber()
  && block < (m_vol->cacheBlockNumber() + nb)) {

```

The working code has:

```
if (m_vol->cacheBlockNumber() <= block
  && block < (m_vol->cacheBlockNumber() + nBlock)) {

```

If you have the upper version change it and it should work
**EDIT 2** Work around for buggy SDFat lib
Here is a workaround code

```
const char DATA_DIR [] = "data";
char final_book_name[128] ={'\0'};
char book_data_path [256] ={'\0'};

if (!SD.exists(DATA_DIR)) {
  SD.mkdir(DATA_DIR);
  SD.chdir(DATA_DIR);
}

strcpy (final_book_name, upload_book_name);
 strcat (final_book_name, ".txt";
String book_data_path = DATA_DIR;

strcpy(book_data_path, "data_");
strcat(book_data_path, final_book_name);

if (SD.exists(book_data_path)) {
  SD.remove(book_data_path);
}
SD.mkdir(book_data_path);
SD.chdir(book_data_path);

tft.println(DATA_DIR);
tft.println(book_data_path); // This successfully prints "DATA/data_test.txt"
File book_data_file = SD.open(final_book_name, FILE_WRITE);
if (SD.exists(final_book_name)) {
  book_data_file.print(upload_book_font);
  book_data_file.print("|");
  book_data_file.print("0");
  book_data_file.close();
} else{
  tft.print("Failed to create/replace\ndata file!");
  if (SD.exists(final_book_name)) {
    SD.remove(final_book_name);
  }
}

```

---
Tags: sd-card, sd, stm32
---


# Question
Title: NodeMCU v2 with MH-Z19B CO2 sensor UART read problem
I'm trying to read data from MH-Z19B sensor to NodeMCU v2 board with a simple circuit like this.

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:
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)

```

# Answer
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
> 1 votes

---
Tags: nodemcu, uart
---


title: Is there a test framework for Arduinos?

text:
# Question
Title: Is there a test framework for Arduinos?
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.

# Answer
> 1 votes
> 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.

---
Tags: testing
---


title: Turn RGB blinker via serial

text:
# Question
Title: Turn RGB blinker via serial
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.

# Answer
> 1 votes
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);

```

# Answer
> 1 votes
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);
    }
  }
}

```

---
Tags: serial, programming, serial-data
---


# Question
Title: Problem communicating with GSM module which is a Fona 3G from adafruit
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.

# Answer
> 0 votes
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.

---
Tags: communication, gsm, adafruit, wireless, uart
---


title: Serial.flush() in arduino

text:
# Question
Title: Serial.flush() in arduino
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)

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

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)

# Answer
> 0 votes
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.

---
Tags: arduino-uno
---


title: I2C and softwareserial

text:
# Question
Title: I2C and softwareserial
Attempting to make gps unit with screen. GPS unit communicates over serial (Adafruit Ultimate GPS Breakout) and I can get GPS data through USB to my pc with Adafruit GPS library softwareserial examples. The screen communicates over I2C (Sunfounder OLED-SSD1306 Module) and I can get display with Adafruit SSD1306 examples. However I cannot get both to happen simultaneously. Board is Adafruit Metro Mini 5v 16MHZ. GPS is using pin 8 for TX and pin 9 for RX. Display is using A4 for SDA and A5 for SCL.

If "Adafruit\_GPS GPS(&mySerial);" is not commented the screen will not display anything. If it is commented the screen displays just fine. How do I get both to function simultaneously?

```
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define OLED_RESET     -1
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>
SoftwareSerial mySerial(8, 9);
Adafruit_GPS GPS(&mySerial);

void setup() {
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    for(;;);
  }
  display.display();
  delay(2000);
  display.clearDisplay();
  display.drawPixel(10, 10, SSD1306_WHITE);
  display.display();
  delay(2000);
  testdrawchar();
}

void loop() {
}

void testdrawchar(void) {
  display.clearDisplay();

  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 0);
  display.cp437(true);

  for(int16_t i=0; i<256; i++) {
    if(i == '\n') display.write(' ');
    else          display.write(i);
  }

  display.display();
  delay(2000);
}

```

# Answer
> 1 votes
The problem was indeed running out of memory (as suggested by Juraj). After finding smaller libraries I was able to get it to work together just fine.

---
Tags: i2c, softwareserial, gps
---


title: Arduino Turn on a led with the PCA9865

text:
# Question
Title: Arduino Turn on a led with the PCA9865
I am using the PCA9865 to light a led

**My circuit**

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

**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**

# Answer
> 0 votes
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:

---
Tags: arduino-uno
---


title: Backup an ATMEGA16

text:
# Question
Title: Backup an ATMEGA16
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 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

# Answer
A detailed how to is here its for the ATMega16 but check connections with the circuit diagram.

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 votes

---
Tags: spi, isp, atmega16u2
---


title: Pulse generator with varying width

text:
# Question
Title: Pulse generator with varying width
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?

```
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);
}

```

# Answer
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
> 4 votes

---
Tags: arduino-uno, programming
---


# Question
Title: Problems running Arduino project off a 9V battery
I have been working on an Arduin Uno Rev2 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 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.

# Answer
> 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.

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.
> 2 votes

---
Tags: serial, power, battery
---


# Question
Title: Rechargeable USB "AA" Batteries. Has anyone used them?
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%2Caps%2C242&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

# Answer
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
> 0 votes

---
Tags: arduino-nano, power, battery, ws2812
---


# Question
Title: how to get esp32 ip address ,which is being connected to local network
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?

# Answer
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).
> 1 votes

---
Tags: arduino-uno, esp32, iot
---


# Question
Title: Individually addressing LEDs in a multiplexed matrix
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?

# Answer
> 5 votes
Thanks to KIIV 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);
}

```

---
Tags: arduino-nano, led
---


title: Securing ESP8266 connections

text:
# Question
Title: Securing ESP8266 connections
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

# Answer
> 2 votes
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.

---
Tags: esp8266, web-server, http
---


# Question
Title: Attiny85 SoftwareSerial not working on battery power
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);
}

```

# Answer
> 2 votes
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.

---
Tags: arduino-uno, battery, attiny85
---


# Question
Title: How to achieve smooth motion with a servo motor?
I'm trying to control the MG995 servo motor with an Arduino Uno, but the motion achieved by the motor is kind of erratic. The servo motor is externally powered from a 2200mAh 7.4V 30C LiPo battery with a 7806 voltage regulator which provides a voltage of 6.1V.

The circuit I'm using is as shown below:

When I load the `sweep` example, the servo rotates until a certain angle where it appears to be obstructed and is trying to overcome the obstacle before turning and rotating in the other direction. Here is a video of the motion I'm trying to describe: https://streamable.com/dcr2i

If I connect the motor directly to the battery without the regulator, the motion is smoother than that. I want to use the regulator to protect both my circuit and the motor. How do I achieve the same smooth motion?

# Answer
> 1 votes
According to Jameco:

> Servos are controlled by sending an electrical pulse of variable width, or pulse width modulation (PWM), through the control wire. There is a minimum pulse, a maximum pulse, and a repetition rate.

I'm ignorant of the effect of a voltage regulator on pulse width modulation, but based on your experience, I suggest that it is detrimental.

You can confirm this if you have access to an oscilloscope with which to view the pulses directly from the circuit and then again from the output of the regulator. Correction, view the input to the servo without the regulator and then with the regulator.

According to Roger's Hobby Center, a 2S lipo battery, nominally 7.4v will reach voltages as high as 8.4 volts. This moves the concern of 6v deeper into the question.

Another website, pololu.com references "old style" servos as being designed for 6 volts in the form of 4 batteries at 1.5v, while manufacturers are embracing the newer battery chemistry and producing servos which will operate at levels as high as 9 volts.

Additional research (the data sheets for this model servo) show that it is designed to take 4.8 to 7.2 volts. The full charge voltage of 8.4 will cause the servo to run a bit faster, but I don't believe there will be long term effects, as the voltage will drop into the nominal range in short order.

Another piece of information I gathered somewhat indicates that a regulator will (or should) work, but it has to have the current capacity to handle the servo. I missed that figure in my research. This led to me discovering a caution that your circuits should have a common ground. If you don't have a common ground, your answer may lie there.

# Answer
> 0 votes
Big RC servo like this draw amount of current when rapid moving (maybe greater than stall current) and cause voltage to drop. RC servo sense spindle position by potentiometer which affect by unstable power source. You should use more current regulator like switching type or you can add big capacitor (say 1000uF) at servo power to smooth voltage. I try myself using lab bench PSU and set to 5V 2A and motor still oscillating. I need to go with 5V 5A.

---
Tags: power, servo
---


# Question
Title: The servo sweep library code - "delay" versus "in steps of"
This is a pretty basic question - essentially I want to know the difference between adjusting the basic sweep code (from the library) in terms of the "delay" instruction and the "pos += 1" (in steps of 1 degree) instruction.

For my project I want my servo to move 60 degrees at the same frequency as a heart beating relatively fast (lets say two beats a second). I.e., the servo moves from zero to 60 degrees twice in one second. Should I adjust the 'delay' or the 'position' instruction from the library? What's the difference? Does it matter which one I adjust as long as it does what I need it to?

Thanks for your time!

# Answer
> 0 votes
Changing the delay and leaving the increment to one generally gives a "smoother" movement. In fact, if you want for instance to move (roughly) five times faster than the example you can either move the delay to 3ms or increment the position by 5. This is what happens at the position request:

```
Time   0  3  6  9 12 15 18 21 24 27 30 33 ...
Delay  0  1  2  3  4  5  6  7  8  9 10 11 ...
Incr.  0  0  0  0  0  5  5  5  5  5 10 10 ...

```

Now, usually I try to use the delay approach as much as I can; the limitations on that approach are that it becomes more CPU consuming if you should also perform other actions between two movements (which is not your case, since you are using delays).

In order to perform four 60° movements in one second you should wait roughly 4ms between calls.

In any case, even if the single increment is the best solution, as long as you perform one movement every 10-20ms you won't be able to see any differences, so even increasing the position by 3 every 12ms or by 5 every 20ms is fine. If you start hearing a "pulsed" noise or see the motor going "jerkily" reduce the increments and the delay.

Note: You can also use multiple increments in order to have "fractional" delays. For instance, if you want to have one increment every 3.5ms, instead of using delayMicroseconds you can perform two increments every 7ms.

# Answer
> 0 votes
Servo send out command pulse about 50 Hz. that mean no point to update servo position more frequent than that. Servo.write() give resolution of 1 degree. if you need more resolution you can use servo.writeMicroseconds() For my approach I calculate position trajectory as function of time and update servo position in while loop using millis() as time base. Anyway I finish it and implement to library called accServo https://github.com/Menginventor/accServo

---
Tags: servo
---


title: My Servo Won't Sweep Smoothly

text:
# Question
Title: My Servo Won't Sweep Smoothly
So I've tried this a few times and I always get the same issue. When I try to run the sweep example the servo goes round 180 degrees but only in steps. Anyone know a way to fix this?

The servo I'm using is a **Tower Pro Micro Servo 9G SG90**

```
// Sweep
// by BARRAGAN <http://barraganstudio.com>
// This example code is in the public domain.

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
                // a maximum of eight servo objects can be created

int pos = 0;    // variable to store the servo position

void setup()
{
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()
{
  for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 degrees
  {                                  // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees
  {
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

```

Video: http://vidd.me/A40

# Answer
In electronics, as usual in situations where a cricuit is misbehaving and we don't understand why, a solution that generally works is to add a **decoupling cap** between `+5V` and `GND`.

In your case, I would put at least **220uF**; that would ensure two things:

* the voltage used to control the servo never drops
* the voltage brought to Arduino by the USB does not drop either (which would have very bad impact on the Arduino, probably resetting it)

Electrolytic caps are a **must-have** for every electronics hobbyist (and professional as well, of course).

You can read more about decoupling capacitors on Wikipedia.

**Edit:**

According to @gwideman comment, it seems that using a decoupling capacitance **above 10uF** in a USB 2.0 device would violate USB specs and ***may damage*** the USB host controller on the computer.

I was not aware of this limitation but I have already used decoupling capacitance up to 100uF in my circuits and never got any issue with my USB computer port.

It might be due to extra electronics on the Arduino board that would "isolate" USB power from Arduino +5V anf d GND pins, I don't know (**that should probably be the topic of a specific question**); or maybe I have just been lucky all this time...
> 2 votes

# Answer
I've experienced same behavior with this type of servos. In my case it was easier to spot since Arduino frequently rebooted when servo was approaching the boundaries of the swing - so it was clear it was consuming too much power, and USB port was unable to deliver that.

Cheap dedicated 9V 1A AC/DC converter usually solves the problem. But if you can't wait for one to get delivered, get an iPad USB charger (nowadays everyone has it or has a neighbor/friend who has one). It is rated 10W, and it doesn't suffer from voltage drops even under high loads. Power your setup from it, and if you'd see it moves smoothly, you will have your answer.
> 1 votes

# Answer
It looks like your sketch runs in slow motion.

Check if you wrote delay(150) or have an additional delay in your loop. Check twice and - just to make sure - upload the corrected sketch again.

**Edit:** If possible, test with another servo and even test with another Arduino board.
> 0 votes

# Answer
give a 9v supply +ve terminal to Vin and -ve ground. since the arduino board cannot supply enough power to the servo, this will provide this worked for me and workin just fine
> 0 votes

# Answer
I tested your code, nothing wrong with it. Maybe it is power supply issue. 1. Don't use USB to power servo, it can make current spike when it move rapidly. 2. Use proper supply for servo. High current and use large capacitor to deal with current spike.
> 0 votes

# Answer
The program is faulty. 1) No servo can react to a command in 15 milliseconds. Delay should be more like 500 milliseconds (.5 seconds). 2) The for loops are not designed to work together. The 1st loop feeds a value of 181to the second loop which is designed to start with a value of 180. The 2nd loop feeds a value of -1 back to the first loop, which is designed to start with a value of 0.
> -1 votes

---
Tags: arduino-uno, servo
---


# Question
Title: can we use Software serial and timer one at the same time or this software use also timer one?
i am using timer1 and software serial for gps data i need to see if we have a problem with connection . So i made a timer1 that's start before the loop that will wait the gps sending and after 3s if we didn't receive data we will exit the loop of waiting and going to make diffrent thing .

# Answer
According to Answer software serial only you pinchange interrupt and CPU delay loop. which means it not effect any timer but it might freeze system while transmission.
> 1 votes

---
Tags: softwareserial, timers, tinygps
---


# Question
Title: Where can I find a better pinout diagram for "Arduino Ethernet" board?
I'm looking for a complete pinout of the Arduino Ethernet R3. I've found one here which is low quality, and seems not complete (where are the digital I/O pins?).

BTW, it was not a good idea for Arduino to name this board "Arduino Ethernet", as this is pretty useless for searching online :-(

# Answer
That's a better one from :

https://pinoutguide.com/images/arduino/ethernet.png

This one also presents the Arduino Ethernet R3 board and has the extra I2C pins (SCK=A5,SDA=A4) next to the AREF pin.
> 2 votes

# Answer
The formal Arduino.cc website mentions, somewhat obscurely, that the Arduino Ethernet is pin compatible with Arduino Uno:

> The Revision 3 of the board introduces the standardized 1.0 pinout

Except for pins 10-13:

> Pins 10, 11, 12 and 13 are reserved for interfacing with the Ethernet module and should not be used otherwise. This reduces the number of available pins to 9, with 4 available as PWM outputs.

The other difference is the onboard LED is connected to pin 9 rather than the Uno's pin 13:

> On most other arduino boards, this LED is found on pin 13. It is on pin 9 on the Ethernet board because pin 13 is used as part of the SPI connection.

You can use any Arduino Uno pinout diagram as a reference, the one you have found seems to be pretty elaborated.
> 3 votes

---
Tags: pins, ethernet
---


# Question
Title: I'm trying to control a servo with a push of a button but its not working HELP
I'm new to Arduino and I'm following this tutorial: https://www.youtube.com/watch?v=T2HMJiy9b\_I but the problem is the servo just keeps moving back and forwards on it own and the button is doing nothing when pressed please help.

Code:

```
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
#define servoPin 3 //~
#define pushButtonPin 2

int angle =90;    // initial angle  for servo
int angleStep =5;
const int minAngle = 50;
const int maxAngle = 110;

int buttonPushed =0;

void setup() {
  // Servo button demo by Robojax.com
  Serial.begin(9600);          //  setup serial
  myservo.attach(servoPin);  // attaches the servo on pin 3 to the servo object
  pinMode(pushButtonPin,INPUT_PULLUP);
   Serial.println("Robojax Servo Button ");
}

void loop() {
  if(digitalRead(pushButtonPin) == LOW){
    buttonPushed = 1;
  }
   if( buttonPushed ){
  // change the angle for next time through the loop:
  angle = angle + angleStep;

    // reverse the direction of the moving at the ends of the angle:
    if (angle <= minAngle || angle >= maxAngle) {
      angleStep = -angleStep;
       buttonPushed = 0;
    }
    myservo.write(angle); // move the servo to desired angle
      Serial.print("Moved to: ");
      Serial.print(angle);   // print the angle
      Serial.println(" degree");
  delay(100); // waits for the servo to get there
   }

}

```

# Answer
This condition below is never met because a boolean comparison is implied :

```
if( buttonPushed ){

```

and buttonPushed is declared as :

```
int buttonPushed =0;

```

A proper comparison should be OK :

```
if( buttonPushed == 1)
{
   // Do something
}

```

Also the buttons need proper debouncing or the push event will have undetectable results :

https://dduino.blogspot.com/2012/03/arduino-button-debouncing.html
> -1 votes

---
Tags: servo, button
---


# Question
Title: Adafruit Metro Mini FTDI chip overheating
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?

# Answer
> 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.
> 1 votes

# Answer
The 3.3V output of the FTDI chip might be shorted to Gnd, or overloaded by your circuit. Start by checking that.
> 1 votes

---
Tags: adafruit, ftdi
---


# Question
Title: MEGA 2560: Simple program - One analogWrite turns off the other
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.  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() {

}

```

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() {

}

```

**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.

# Answer
> 5 votes
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.
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.

---
Tags: arduino-mega, arduino-ide, analogwrite, avr-toolchain
---


# Question
Title: strcat gives error when I try to add a char to a char array
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\]
> 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

# Answer
> 1 votes
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.

---
Tags: c++
---


title: An array of existing arrays

text:
# Question
Title: An array of existing arrays
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?

# Answer
> 1 votes
Try this:

```
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

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

```

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

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

```

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

# Answer
> 0 votes
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

```

---
Tags: arduino-nano, array, pointer
---


# Question
Title: Receive socket when in loop arduino (Interupt a while loop with a socket)
I'm currently working on an arduino project. Were the arduino is communicating with a NodeJS server via web sockets.

The socket connection is working fine and has no problems. But the problem I currently have is that I want to be able interupt an infinite while loop with a socket emit from the NodeJS server.

I found a page that had a solution for this problem but only with a button attached to the arduino.

Link to page (Interrupt with button)

This is the loop I want to be able to interrupt with a socket:

```
bool loopRunning = true;

void rainbow(int wait) {
while(loopRunning == true) {

      for(long firstPixelHue = 0; firstPixelHue < 3*65536; firstPixelHue += 256) {
        for(int i=0; i<strip.numPixels(); i++) {
          int pixelHue = firstPixelHue + (i * 65536L / strip.numPixels());
          strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue)));
        }
        strip.show();
        delay(wait);
      }
    }
}

```

I want to set loopRunning to false when I recieve a socket emit.

Anyone have any ides how I can implement this?

Page to the socket functionality that I use

# Answer
There are two ways to handle events: **interrupts** (hardware triggered) and **polling** (software triggered). Interrupts are much more efficient but also more difficult to use. SocketIoClient uses **polling.**

The necessary part of polling is... polling. That is, many times per second, you (or your library) needs to check if anything interesting is happening.

With this library, you have to call `SocketIoClient::loop()` many times a second. That's why `SocketIoClient::loop()` exists. So it needs to be added to your outer `for` loop.

(If your `delay(wait)` takes too long, you may need to break it up into a series of several shorter ones, but I think you can get away with it in this case.)

Then all you need to do is use `SocketIoClient::on()` to perform an action when an event happens. There is an example in the documentation. You will need to make loopRunning into a global variable.
> 1 votes

# Answer
The problem is the while loop trapping execution. When you have a small section of your loop that you want to stick in, you can do it two ways. You can do what you did with a while loop, that keeps execution stuck inside the while loop with nothing else happening. Or you can let the loop function be the loop and use flags and if statements to decide what's running.

Imagine this code:

```
void loop() {
  if(loopRunning){
     // do the stuff in your while loop
  }
  else {
     // all the other stuff in loop that you don't want running during that
  }
  // all the stuff you want to run regardless, like listening to your socket.
}

```

When you do it like that you still get to have the stuff you were going to while loop to happen on it's own without the rest of loop, but you can also have some stuff that runs both ways. That logic can be extended in all kinds of ways. Maybe you want that part to always run but the rest of loop to be skipped when loopRunning is false.

```
void loop(){
   //  all the stuff that should run all the time (like your socket)
   if(!loopRunning) {
       // all the stuff you would put into a while(!loopRunning) code
       // but wouldn't be able to catch the socket.
   }
}

```
> 0 votes

---
Tags: interrupt, nodemcu, neopixel, loop
---