# Question
Title: Controlling output frequency of 3 Phase SPWM Inverter
I am now on a 3 Phase SPWM inverter project, and i got this code from this article. It works perfectly on simulation. But the problem is, i can't make the output frequency variable. I intend to vary the frequency at range 0 to 100 Hz and use it to control the speed of 3 phase induction motor. Could anyone help me, please? Any advice or maybe you got a code that works perfectly in controlling spwm inverter frequency. Here is the code of 3 phase spwm inverter. Oh, i am using Arduino Mega by the way.

```
            int i=0;
            int j=0;
            int k=0;
            int x=0;
            int y=0;
            int z=0;
            int OK=0;
            int OK1=0;
            int OK2=0
            int OK3=0;
            int OK4=0;
            int sinPWM[]={1,2,5,7,10,12,15,17,19,22,24,27,30,32,34,37,39,42,
            44,47,49,52,54,57,59,61,64,66,69,71,73,76,78,80,83,85,88,90,92,94,97,99,
            101,103,106,108,110,113,115,117,119,121,124,126,128,130,132,134,136,138,140,142,144,146,
            148,150,152,154,156,158,160,162,164,166,168,169,171,173,175,177,178,180,182,184,185,187,188,190,192,193,
            195,196,198,199,201,202,204,205,207,208,209,211,212,213,215,216,217,219,220,221,222,223,224,225,226,227,
            228,229,230,231,232,233,234,235,236,237,237,238,239,240,240,241,242,242,243,243,244,244,245,245,246,246,
            247,247,247,248,248,248,248,249,249,249,249,249,255,255,255,255,249,249,249,249,249,248,
            248,248,248,247,247,247,246,246,245,245,244,244,243,243,242,242,241,240,240,239,238,237,237,236,235,234,
            233,232,231,230,229,228,227,226,225,224,223,222,221,220,219,217,216,215,213,212,211,209,208,207,205,204,
            202,201,199,198,196,195,193,192,190,188,187,185,184,182,180,178,177,175,173,171,169,168,166,164,162,160,
            158,156,154,152,150,148,146,144,142,140,138,136,134,132,130,128,126,124,121,119,117,115,113,110,108,106,
            103,101,99,97,94,92,90,88,85,83,80,78,76,73,71,69,66,64,61,59,57,54,52,49,47,44,42,39,37,34,32,30,
            27,24,22,19,17,15,12,10,7,5,2,1};

            int potinput = A1;
            int potfreq = A2;
            float potinputval;
            float potfreqval;
            float A;
            float F;

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

            pinMode(4, OUTPUT);
            pinMode(13,OUTPUT);
            pinMode(9,OUTPUT);
            pinMode(10,OUTPUT);
            pinMode(2,OUTPUT);
            pinMode(5,OUTPUT);

            cli();// stop interrupts
            TCCR0A=0;//reset the value
            TCCR0B=0;//reset the value
            TCNT0=0;//reset the value
            //0b allow me to write bits in binary
            TCCR0A=0b10100001;//phase correct pwm mode
            TCCR0B=0b00000001; //no prescaler

            TCCR2A=0;//reset the value
            TCCR2B=0;//reset the value
            TCNT2=0;//reset the value
            //0b allow me to write bits in binary
            TCCR2A=0b10100001;//phase correct pwm mode
            TCCR2B=0b00000001; //no prescaler

            TCCR3A=0;//reset the value
            TCCR3B=0;//reset the value
            TCNT3=0;//reset the value
            //0b allow me to write bits in binary
            TCCR3A=0b10100001;//phase correct pwm mode
            TCCR3B=0b00000001; //no prescaler
            TCCR1A=0;//reset the value
            TCCR1B=0;//reset the value
            TCNT1=0;//reset the value
            OCR1A=509;// compare match value
            TCCR1B=0b00001001; //WGM12 bit is 1 for CTC mode and no prescaler

            TIMSK1 |=(1 << OCIE1A);// enable interrupts

            sei();//stop interrupts
            }
            ISR(TIMER1_COMPA_vect){// interrupt when timer 1 match with OCR1A value
            if(i>313 && OK==0){// final value from vector for pin 13
            i=0;// go to first value of vector
            OK=1;//enable pin 4
            }
            if(i>313 && OK==1){// final value from vector for pin 4
            i=0;//go to firs value of vector
            OK=0;//enable pin 13
            }
            x = round(A*sinPWM[i]); // x take the value from vector corresponding to position i(i is zero indexed)
            i=i+1;// go to the next position
            if(OK==0){
            OCR0B=0;//make pin 4 0
            OCR0A=x;//enable pin 13 to corresponding duty cycle
            }
            if(OK==1){
            OCR0A=0;//make pin 13 0
            OCR0B=x;//enable pin 4 to corresponding duty cycle
            }

            if ((i==209) || OK1==1){//if i equal with 209 enable second signal
            OK1=1;//mantain if function
            if(j>313 && OK2==0){// final value from vector for pin 10
            j=0;// go to first value of vector
            OK2=1;//enable pin 9
            }
            if(j>313 && OK2==1){// final value from vector for pin 9
            j=0;//go to firs value of vector
            OK2=0;//enable pin 10
            }
            y = round(A*sinPWM[j]);// y take the value from vector corresponding to position j(j is zero indexed)
            j=j+1;// go to the next position
            if(OK2==0){
            OCR2B=0;//make pin 9 0
            OCR2A=y;//enable pin 10 to corresponding duty cycle
            }
            if(OK2==1){
            OCR2A=0;//make pin 10 0
            OCR2B=y;//enable pin 9 to corresponding duty cycle
            }
            }
            if ((j==209) || OK3==1){//if j equal with 209 enable third signal
            OK3=1;//mantain if function
            if(k>313 && OK4==0){// final value from vector for pin 5
            k=0;// go to first value of vector
            OK4=1;//enable pin 2
            }
            if(k>313 && OK4==1){// final value from vector for pin 2
            k=0;//go to firs value of vector
            OK4=0;//enable pin 5
            }
            z=round(A*sinPWM[k]);// z take the value from vector corresponding to position k(k is zero indexed)
            k=k+1;// go to the next position
            if(OK4==0){
            OCR3B=0;//make pin 2 0
            OCR3A=z;//enable pin 5 to corresponding duty cycle
            }
            if(OK4==1){
            OCR3A=0;//make pin 5 0
            OCR3B=z;//enable pin 2 to corresponding duty cycle
        }
        }
        }
        void loop() {

          potinputval = analogRead(potinput);
          A = potinputval/1023;

          potfreqval = analogRead(potfreq);
          F = map(potfreqval,1023,0,0,50);}

```

# Answer
In this sketch the PWM values, matching a sampled sine curve, are stored in integer array sinPWM\[\]. The values from sinPWM (1 - 255) are used unmodified (via intermediate variables x, y and z) to set the various timing registers (OCR0A/B, OCR2A/B and OCR3A/B) which control the pulse width modulation. In this way the amplitude(s) of the generated sine wave(s) will be constant.

If you want to control the speed of the motor you have to multiply the values from sinPWM with a factor between 0 and 1. The most logical place is to do that when the values from sinPWM are transferred to the intermediate variables x, y and z. Example: x=round(0.8 * sinPWM\[i\]). The factor, 0.8 in this example, you can of course replace by a variable which value is derived from an analogRead() of a pin connected to a potmeter or some sensor. But make sure to convert it to a value in the range 0-1 before you use it in the calculation.
> 1 votes

---
Tags: arduino-mega
---


# Question
Title: Can't replace SoftwareSerial by Serial1 on Mega board
This sketch runs well with SoftwareSerial define and the monitor displays device modbus values. But now, i want to replace SoftwareSerial by Serial1 and i have no data.

This is the sketch with SoftwareSerial:

```
#include <SoftwareSerial.h>
#define SSerialRX        10  //Serial Receive pin
#define SSerialTX        11  //Serial Transmit pin
#define SSerialTxControl 40   //RS485 Direction control
#define RS485Transmit    HIGH
#define RS485Receive     LOW

SoftwareSerial RS485Serial(SSerialRX, SSerialTX); // RX, TX
byte byteSend;

void setup()
{
  Serial.begin(9600);
  pinMode(SSerialTxControl, OUTPUT);
  digitalWrite(SSerialTxControl, RS485Transmit);  // Init Transceiver
  RS485Serial.begin(9600);
}
void loop()
{
  delay(500);
  if (RS485Serial.available())
  { for(int i=0; i<7; i++)
    {
    byteSend = RS485Serial.read();   // Read the byte

    Serial.print(byteSend, HEX);
    Serial.print(" ");
    }
  }
  digitalWrite(SSerialTxControl, RS485Transmit);  // Init Transceiver
  byte request[] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x01, 0x84, 0x0A};
  RS485Serial.write(request, sizeof(request));

  digitalWrite(SSerialTxControl, RS485Receive);
  Serial.println(" ");
}

```

And the sketch i tried with Serial1 (pin 19(Rx) and 18(Tx)):

```
#define SSerialTxControl 40   //RS485 Direction control
#define RS485Transmit    HIGH
#define RS485Receive     LOW

byte byteSend;

void setup()
{
  Serial.begin(9600);
  pinMode(SSerialTxControl, OUTPUT);
  digitalWrite(SSerialTxControl, RS485Transmit);  // Init Transceiver
  Serial1.begin(9600);
}
void loop()
{
  delay(500);
  if (Serial1.available())
  { for(int i=0; i<7; i++)
    {
    byteSend = Serial1.read();   // Read the byte

    Serial.print(byteSend, HEX);
    Serial.print(" ");
    }
  }
  digitalWrite(SSerialTxControl, RS485Transmit);  // Init Transceiver
  byte request[] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x01, 0x84, 0x0A};
  Serial1.write(request, sizeof(request));

  digitalWrite(SSerialTxControl, RS485Receive);
  Serial.println(" ");
}

```

Can you help me to find my mistake ?

# Answer
> 2 votes
> what is the best way to solve it, using Serial1?

With either serial device, you need to collect characters until you have an entire message. If every message will be a fixed number of bytes, you can wait until the return value of the Serial::available() call indicates it has that many characters, then collect them into a buffer and process them. But this assumes you'll never get a badly-formed message. If you do, the incoming bytes will get out of sync with your program. A better way is to collect bytes into your buffer (but do nothing with them) until you have a complete message (by byte-count, newline character, or however you need to recognize that it is complete) or your buffer is about to overflow, and then either process them, or if your buffer filled and the contents doesn't look like a valid message, discard it and try to re-synchronize with the source. That may mean reading and ignoring bytes until you get a newline, and dealing with the fact you got a garbled message, or telling your source to restart or reset. The exact method (or whether you even want to bother detecting bad messages) depends on the particular situation. Will someone die if you fail? Will something catch fire, burn parts, lose weeks worth of good data, ... ? Or is this an experiment whose consequence of failure are zero or at least not worth any effort to detect it?

---
Tags: serial, arduino-mega, softwareserial
---


# Question
Title: How do i fade a colorwipe from off to on in 1 color?
So I want to make the same effect as a colorwipe (like going around in a circle turning leds on till they all turn on) except that instead of going from off to 100% brightness immediately I need it to look more natural by making it fade from off to on gradually to a single color and the LEDS should stay on after the fade on is complete. This is my current code and i cant figure out how to make it fade. everything ive found on google is massively complex to do a simple thing. is it really that complex to accomplish this?

```
#include <Adafruit_NeoPixel.h>
#define PIN 6
#define NUM_LEDS 24
Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_GRBW + NEO_KHZ800);

void setup() {
  strip.setBrightness(2);
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
}

void loop() {
  colorWipe(strip.Color(255, 255, 255, 255), 70); //white

}

// Fill the dots one after the other with a color
void colorWipe(uint32_t c, uint8_t wait) {
  for(uint16_t i=0; i<strip.numPixels(); i++) {
    strip.setPixelColor(i, c);
    strip.show();
    delay(50);
  }
}

```

# Answer
> 1 votes
Note that the "wait" variable is not actually used in your colorwipe function.

The colorwipe function seems to turn them all on in succession. The only thing you need to do is add fading to it.

```
for(uint16_t i=0; i<strip.numPixels(); i++) {
    for(uint8_t brightness=0; brightness<maxBrightness; brightness++){
       strip.setPixelColor(i, strip.Color(brightness, brightness, brightness, brightness );
       strip.show();
       delay(wait);
  }

```

# Answer
> 0 votes
See my answer here.

Code from that answer:

```
/*
 *
 * NeoPixels demo - fades colours (in array) up and down
 *
 */

#include <SPI.h>
#include <NeoPixels_SPI.h>

const unsigned int PIXELS = 8; // Number of pixels in the string

void setup()
  {
  ledsetup();
  } // end of setup

float patterns [] [3] = {
  { 1, 0, 0 },  // red
  { 0, 1, 0 },  // green
  { 0, 0, 1 },  // blue
  { 1, 1, 0 },  // yellow
  { 1, 0, 1 },  // magenta
  { 0, 1, 1 },  // cyan
  { 1, 1, 1 },  // white
  { 160.0 / 256, 82.0 / 256, 45.0 / 256 },  // sienna
  { 46.0 / 256, 139.0 / 256, 87.0 / 256 },  // sea green

};

// number of items in an array
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))

void loop()
  {

  for (byte i = 0; i < ARRAY_SIZE (patterns); i++)
    {
    // fade up
    for (byte m = 0; m < 100; m++)
      {
      showColor (PIXELS, patterns [i] [0] * m, patterns [i] [1] * m, patterns [i] [2] * m);
      delay (10);
      } // end of for

    // fade down
    for (byte m = 100; m > 0; m--)
      {
      showColor (PIXELS, patterns [i] [0] * m, patterns [i] [1] * m, patterns [i] [2] * m);
      delay (10);
      } // end of for
    } // end of for each array item

  } // end of loop

```

---
Tags: arduino-uno, c++
---


# Question
Title: 32u4 using internal clock on custom PCB - loading sketch
I have a custom PCB with a 32u4 running fine with an 8MHz external oscillator. I burned the bootloader and loaded my sketch with an UNO using Arduino as ISP.

I have no USB on my PCB nor do I need precise timing, so I wanted to see if I could simplify things by removing the external oscillator and caps.

Reading the 32u4 datasheet it states "The device is shipped with Low Power Crystal Oscillator (8.0 - 16MHz) enabled and with the fuse CKDIV8 programmed".

With that, can I simply hook my PCB (assuming a factory fresh 32u4) via ISP to the UNO as before and in IDE just use Sketch \> Upload Using Programmer? Basically not burning any bootloader at all.

Also, in IDE I have been choosing the Sparkfun ProMicro 3.3v, 8MHz board. Can I still use that selection?

# Answer
> 1 votes
Yes you can reprogram your 32U4 chips via the ISP, they do not have to be fresh chip. If you set your Fuses to `-U lfuse:w:0xE2:m -U hfuse:w:0xD8:m -U efuse:w:0xCB:m` using AVRDUDE you will have an 8mhz internal RC oscillator set and you do not have to have the external crystal.

You can play with these settings at http://www.engbedded.com/fusecalc/.

I recommend learning the command line AVRDUDE commands this way you have more control over what you are doing to your chip.

I use this all the time, and if you need to do more than one quickly I typically make a batch file that does the Fuse Burn and hex at the same time.

this is for a attiny167 but you get the idea: `.\avrdude\avrdude -C".\avrdude\avrdude.conf" -v -pattiny167 -cstk500v2 -PCOM3 -Ulfuse:w:0xE2:m -Uhfuse:w:0xDF:m -Uefuse:w:0xFF:m -Uflash:w:1060X01-001.hex:i`

# Answer
> 0 votes
I just received some 32u4RC chips and confirmed: If you are building a custom PC and want to use the 32u4 chip and use the chip's internal clock for your project, simply purchase the 32u4RC version of the chip. Your sketch can be loaded onto the chip via SPI without the need to set any fuses with avrdude.

---
Tags: bootloader, atmega32u4
---


title: Problem sending SMS from a GSM SIM900

text:
# Question
Title: Problem sending SMS from a GSM SIM900
I have a laser security system project with a GSM SIM900 and a few sensors. I'm using an Arduino Mega 2560, and everything is working normally, except the GSM is not sending an SMS to the phone and I don't know why!

this is my code:

```
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
#include <SoftwareSerial.h>

SoftwareSerial sim900(0,1);
String  TextForSMS;

int dataldr =0;
int sensorldr = A0;
int ldrState = LOW;
int ldrthres = 900;

int pir = A1;
int pirState = LOW;
int val = 0;

int gas = A8;
int sensorgasThres = 400;

#define Password_Length 8
#define PINNUMBER ""

int signalPin = 2;
int led1 = 12;
int led2 = 11;
int led3 = 10;
int led4 = 9;
int led5 = 8;
int led6 = 7;
int laser =6;

char Data[Password_Length];
char Master[Password_Length] = "123A456";
byte data_count = 0, master_count = 0;
bool Pass_is_good;
char customKey;

const byte ROWS = 4;
const byte COLS = 4;

char hexaKeys[ROWS][COLS] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};

byte rowPins[ROWS] = {30,31,32, 33};
byte colPins[COLS] = {34, 35, 36, 37};

Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

LiquidCrystal_I2C lcd(0x3F, 20, 4);

void setup(){

  lcd.init();
  lcd.backlight();

  pinMode(signalPin, OUTPUT);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  pinMode(led5, OUTPUT);
  pinMode(led6, OUTPUT);
  pinMode(laser, OUTPUT);

  pinMode(gas, INPUT);
  pinMode(pir, INPUT);
  pinMode(sensorldr,INPUT);

 randomSeed(analogRead(0));
  Serial.begin(9600);
  sim900.begin (9600);
  Serial.println(" loggin time completed");
delay(5000);

}

void loop(){

     digitalWrite(laser, HIGH);
     digitalWrite(led1, HIGH);

     lcd.setCursor(0,0);
     lcd.print("Enter Password:");

   char customKey = customKeypad.getKey();

  if (customKey){

    Data[data_count] = customKey;
    lcd.setCursor(data_count,1);
    lcd.print(Data[data_count]);
    data_count++;
    }

  if(data_count == Password_Length-1){
    lcd.clear();

    if(!strcmp(Data, Master)){

      lcd.print("Correct");
      digitalWrite(led3, HIGH);
      tone(signalPin, 150,200);
      delay(5000);
      digitalWrite(signalPin, LOW);
      digitalWrite(led3, LOW);
      digitalWrite(laser, LOW);
      ldrState = LOW;
      delay(5000);
      digitalWrite(laser, HIGH);
      ldrState = HIGH;

      }
    else{
            lcd.print("Incorrect");
            digitalWrite(led4, HIGH);
            digitalWrite(signalPin, HIGH);

      delay(2000);

            digitalWrite(led4, LOW);
           digitalWrite(signalPin, LOW);
 TextForSMS="\nIntruder password wrong";
  sendSMS(TextForSMS);
 lcd.setCursor(10,2);
  lcd.print("sms2sent");      }

    lcd.clear();
    clearData();
  }

  int   dataldr =analogRead(sensorldr);
     lcd.setCursor(0,3);
     lcd.print("Laser:");
     lcd.setCursor(7,3);
     lcd.print(dataldr);

  if(dataldr<ldrthres){
    digitalWrite(signalPin, HIGH);
    digitalWrite(led2, HIGH);
  TextForSMS="\nIntruder detected";
  sendSMS(TextForSMS);
  lcd.setCursor(10,2);
  lcd.print("sms1sent");

  }
  else
  {
    digitalWrite(led2, LOW);
    noTone(signalPin);

  }
  delay(100);

 int analogSensor = analogRead(gas);
  lcd.setCursor(0,2);
  lcd.print("Gas:");
  lcd.setCursor(4,2);
  lcd.print(analogSensor);
  // Checks if it has reached the threshold value
  if (analogSensor > sensorgasThres)
  {
            digitalWrite(led5, HIGH);
            digitalWrite(signalPin, HIGH);

     TextForSMS="\nIntruder GAS";
  sendSMS(TextForSMS);
  lcd.setCursor(10,2);
  lcd.print("sms3sent");
  }
  else
  {
    digitalWrite(led5, LOW);
    noTone(signalPin);
  }
  delay(100);

  val = digitalRead(pir);
  if (val == HIGH) {
    digitalWrite(led6, HIGH);

    if (pirState == LOW) {
           Serial.println("Motion detected!");
           pirState = HIGH;
    }
  } else {
    digitalWrite(led6, HIGH);
 delay (5000);
    if (pirState == LOW){
           Serial.println("Motion ended!");
      pirState = LOW;
    }
  }

}

void clearData(){
  while(data_count !=0){
    Data[data_count--] = 0;
  }
  return;
}

void sendSMS (String message){
    sim900.print("AT+CMGF=1");
    delay(1000);

  sim900.println("AT+CMGS=\"+380633965886\"\r ");
      delay(1000);
sim900.println(message);
    delay(1000);
sim900.println((char)26);
    delay(1000);
sim900.println();
    delay(1000);

  }

```

Also on Github:

https://github.com/shiyaroo/gsm-sim900/blob/master/laser\_security\_system\__gsm.ino

# Answer
> 2 votes
It’s *not* a good approach to put delay function between AT commands.

You have to parse SIM900 responses and check if module replies with OK.

If you don’t receive responses from module, could be different problems:

1. wrong baudrate
2. connection or power supply problem
3. SIM card problem (out of cash, sim lock with pin, etc..)

here you can find a useful guide: https://randomnerdtutorials.com/sim900-gsm-gprs-shield-arduino/

---
Tags: arduino-mega, gsm
---


# Question
Title: Dynamically create functions for AccelStepper that use Adafrut_StepperMotor.oneStep methods?
In the Adafruit\_MotorShieldV2Library\>Accel\_MultiStepper example, AccelSteppers are initialized using the following *static* forwardstep1 and backwardstep1:

```
#include <Wire.h>
#include <AccelStepper.h>
#include <Adafruit_MotorShield.h>

//First, get an Adafruit_MotorShield
Adafruit_MotorShield AFMStop(0x60); // Default address, no jumpers

//Then, get a stepper motor from it
Adafruit_StepperMotor *myStepper1 = AFMStop.getStepper(200, 1);

//Then, create callbacks for the AccelStepper's constructor
void forwardstep1() {
    myStepper1->onestep(FORWARD, SINGLE);
}
void backwardstep1() {
    myStepper1->onestep(BACKWARD, SINGLE);
}

//Finally, create the stepper motor
AccelStepper stepper1(forwardstep1, backwardstep1);

```

I intend to then use these AccelSteppers as members in a MultiStepper, which I'm skipping here because it shouldn't be relevant.

I want to make a function that automates this process. Ideally it would work something like this:

```
typedef void(*mover)();
AccelStepper makeStepper(Adafruit_StepperMotor myStepper){
    // create functions of type mover
    mover forward = []{myStepper->onestep(FORWARD, DOUBLE);};
    mover back = []{myStep->onestep(BACKWARD, DOUBLE);};
    return AccelStepper step(forward, back);
}

```
* What I've tried:
    + Obviously the above solution. This doesn't work because myStepper isn't captured, but if you capture it it's not a mover object and can't be passed to AccelStepper.
    + Using an object's function. This doesn't work because object functions have the implicit first parameter this. See this for more info
    + Making the parameter myStepper static after it's passed in. This doesn't work because it gets over-written on every call to the function.
    + Using std::forward. This would probably work, but I don't think std::forward is defined in ArduinoSTL because I keep getting the error `'forward' is not a member of 'std'`. See the code below:
        - Note, In an attempt to make this work, I upgraded the following folders to `-std=gnu++17` on my ubuntu machine, resulting in `__cplusplus == 201500`:
            * ~/.local/share/umake/ide/arduino/hardware/arduino/avr/platform.txt
            * ~/.local/share/umake/ide/arduino/hardware/hardware/platform.txt

### std::forward attempt

```
#include <ArduinoSTL.h>
using namespace std;
#include <iostream>
#include <functional>
#include <utility>

typedef void(*mover)();

template <classF>
mover lambda_to_ptr(F&& f){
    static F fn = std::forward<F>(f);
    return []{ return fn();};
}
AccelStepper makeStepper(Adafruit_StepperMotor myStepper){
    // create functions of type mover
    mover forward = []{myStepper->onestep(FORWARD, DOUBLE);};
    mover back = []{myStep->onestep(BACKWARD, DOUBLE);};
    return AccelStepper step(lambda_to_prt(forward), lambda_to_ptr(back));
}

```

p.s. Of course, I could always change the functions in the library, but this is (almost) always a bad idea.

# Answer
> 1 votes
I ended up just inheriting AccelStepper, and extending the AccelStepper::AccelStepper ( uint8\_t interface = AccelStepper::FULL4WIRE,uint8\_t pin1 = 2,uint8\_t pin2 = 3, uint8\_t pin3 = 4, uint8\_t pin4 = 5, bool enable = true ) constructor to add my own Adafruit\_StepperMotor instance variable and using it in an overridden step0 (which is the only function those callbacks were used in).

```
class MyAccelStepper: public AccelStepper
{
   public:
       MyAccelStepper(Adafruit_StepperMotor *myStepper):AccelStepper(0,0,0,0,0,false)
       {
         //MyStepper(0, 0, 0, 0, 0, false);
         _myStepper = myStepper;
       }
   protected:
       void step0(long step){
          (void)(step);
          if(speed() > 0){
            _myStepper->onestep(FORWARD, DOUBLE);
          }else{
            _myStepper->onestep(BACKWARD, DOUBLE);
          }
       }
    private:
       Adafruit_StepperMotor *_myStepper;
};

```

---
Tags: arduino-uno, arduino-motor-shield, stl
---


# Question
Title: Invalid conversion from 'const char' to 'uint8_t*'
I am just a newbie, don't know how to solve this issue

```
void loop()
{
  UdpSend("Test", "192.168.0.240", 4210);
}

void UdpSend(const char* message, uint8_t * ipaddress, int port){
      Serial.println("Send message: ");
      Udp.beginPacket(ipaddress, port);
      Udp.write(message);
      Udp.endPacket();
}

```

Arduino IDE can't compile.

The error message: ***invalid conversion from 'const char*' to 'uint8\_t\* {aka unsigned char\*}' \[-fpermissive\]\***

Trying to change with this code:

```
void UdpSend(uint8_t * message, uint8_t * ipaddress, int port){
      Serial.println("Send message: ");
      Udp.beginPacket(ipaddress, port);
      Udp.write(message);
      Udp.endPacket();
}

```

Also doesn't work, the error message: ***invalid conversion from 'const char*' to 'uint8\_t\* {aka unsigned char\*}' \[-fpermissive\]\***

Please help...

# Answer
In ESP32 Arduino package the WiFiUdp.h doesn't pull in all Print class `write` functions. As consequence the WiFiUdp class doesn't know `write(const char *str)`.

Use `Udp.print(message);` if message is a zero-terminated char array

or `Udp.write(message, size);` if message is a byte array
> 3 votes

# Answer
Not sure why you're using `uint8_t` at all

The Udp.beginPacket function signature is

```
int WiFiUDP::beginPacket(const char *host, uint16_t port)

```

No hint of uint8\_t there

and .write is either

```
WiFiUDP::write(uint8_t byte)
WiFiUDP::write(const uint8_t *buffer, size_t size)
WiFiUDP::write(const char *str)
WiFiUDP::write(const char *buffer, size_t size)

```

So, your other attempt to use `write((uint8_t *))` is also wrong

Try this:

```
void loop()
{
  UdpSend("Test", "192.168.0.240", 4210);
}

void UdpSend(const char* message, const char * ipaddress, int port){
      Serial.println("Send message: ");
      Udp.beginPacket(ipaddress, port);
      Udp.write(message);
      Udp.endPacket();
}

```
> 2 votes

---
Tags: arduino-ide
---


# Question
Title: Is there a relationship between RSSI and Power? If so, how are they connected and does it have a formula to extract one from the other?
I have searched on Google but to no avail. Perhaps you guys can help.

-Aj

# Answer
> Is there a relationship between RSSI and Power?

Yes

> If so, how are they connected and does it have a formula to extract one from the other?

RSSI is in relation to the square-root of the power. See below references for the actual formula.

Holiday extra: RSSI for an RF433 module can be estimated by the time from end of transmission and noise. This is the time for the AGC circuit to increase gain from the received signal to the noise level. Please see Cosa RF433 library for an example.

References:

1. https://en.wikipedia.org/wiki/Received\_signal\_strength\_indication
2. https://en.wikipedia.org/wiki/Signal\_strength\_in\_telecommunications
> 0 votes

---
Tags: power, xbee
---


title: uBlox Neo 6M GPS module not responding

text:
# Question
Title: uBlox Neo 6M GPS module not responding
I started recently working with a uBlox Neo 6M GPS module (data sheet http://www.u-blox.com/images/downloads/Product\_Docs/NEO-6\_DataSheet\_%28GPS.G6-HW-09005%29.pdf). I connected it to an Arduino Uno as shown:

GPS Arduino VCC-- 3.3V RX -- D11 TX -- D10 GND-- GND

I tried this example code from TinyGps++ (of course, changing the pins and the gpsbaud to 9600, which is the gps' default).

```
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
/*
   This sample sketch demonstrates the normal use of a TinyGPS++ (TinyGPSPlus) object.
   It requires the use of SoftwareSerial, and assumes that you have a
   4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
*/
static const int RXPin = 10, TXPin = 11;
static const uint32_t GPSBaud = 9600;

// The TinyGPS++ object
TinyGPSPlus gps;

// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

void setup() {
  Serial.begin(115200);
  ss.begin(GPSBaud);
  Serial.println(F("DeviceExample.ino"));
  Serial.println(F("A simple demonstration of TinyGPS++ with an attached GPS module"));
  Serial.print(F("Testing TinyGPS++ library v. ")); Serial.println(TinyGPSPlus::libraryVersion());
  Serial.println(F("by Mikal Hart"));
  Serial.println();
}

void loop() {
  // This sketch displays information every time a new sentence is correctly encoded.
  while (ss.available() > 0)
    if (gps.encode(ss.read()))
      displayInfo();
  if (millis() > 5000 && gps.charsProcessed() < 10) {
    Serial.println(F("No GPS detected: check wiring."));
    while(true);
  }
}

void displayInfo() {
  Serial.print(F("Location: "));
  if (gps.location.isValid()) {
    Serial.print(gps.location.lat(), 6);
    Serial.print(F(","));
    Serial.print(gps.location.lng(), 6);
  } else {
    Serial.print(F("INVALID"));
  }

  Serial.print(F("  Date/Time: "));
  if (gps.date.isValid()) {
    Serial.print(gps.date.month());
    Serial.print(F("/"));
    Serial.print(gps.date.day());
    Serial.print(F("/"));
    Serial.print(gps.date.year());
  } else {
    Serial.print(F("INVALID"));
  }

  Serial.print(F(" "));
  if (gps.time.isValid()) {
    if (gps.time.hour() < 10) Serial.print(F("0"));
    Serial.print(gps.time.hour());
    Serial.print(F(":"));
    if (gps.time.minute() < 10) Serial.print(F("0"));
    Serial.print(gps.time.minute());
    Serial.print(F(":"));
    if (gps.time.second() < 10) Serial.print(F("0"));
    Serial.print(gps.time.second());
    Serial.print(F("."));
    if (gps.time.centisecond() < 10) Serial.print(F("0"));
    Serial.print(gps.time.centisecond());
  } else {
    Serial.print(F("INVALID"));
  }
  Serial.println();
}

```

However, I do not get the GPS LED to blink, as well as my Arduino's RX LED, so the module is not transmitting any data. This is the output from the code:

```
A simple demonstration of TinyGPS++ with an attached GPS module
    Testing TinyGPS++ library v. 0.92
    by Mikal Hart

    Location: INVALID  Date/Time: 0/0/2000 00:00:00.00
    Location: INVALID  Date/Time: 0/0/2000 00:00:00.00

```

Thanks!

# Answer
The Neo 6M takes a bit of time to fix when first powered on. If your board is fitted with a small battery it will most probably be flat and will take an hour or two to charge up. It is there to provide charge to the EEPROM and the onboard RTC.

Also check that the leads on the battery are not shorting.

You do not get a valid data sentence out of the GPS until the RTC can sync time.

The Error message that you got from Mike Hart routine first says that there is not enough data to do a FIX and second the Date Time is not syncing.
> 7 votes

# Answer
After 2 days of troubleshooting I found the solution

1. Use 3.3 volt external supply
2. Use voltage dividers to make 3.3 volt compatible to module
3. go outside(open space)

That's it
> 2 votes

# Answer
Try to connect your GPS module with an FTDI cable directly to the Serial-Port of your computer (and read it with screen or any other terminal program). Once that works, proceed with the Arduino. And check what your GPS-module not blinking does mean. Usually it says there is no 'fix', which means it does not see enough satellites. The output you showed would fit into that theory. Which would mean everything is ok, except your module is not seeing the sky...
> 1 votes

# Answer
1) Try outside or near the window. because the signal may not reach inside a house.

2)Check the connection.

3) Print the number of satellites connection to know the device is connectied by

```
Serial.println(gps.satellites.value());

```

Good luck!!!
> 1 votes

---
Tags: arduino-uno, tinygps, gps
---


title: Global or local

text:
# Question
Title: Global or local
I'm new to Arduino and embedded, but understand that it is often better to use global instead of local variables (such as here or here).

I have this simple code (from here):

```
//Libraries
#include <DHT.h>;

//Constants
#define DHTPIN 2     // what pin we're connected to
#define DHTTYPE DHT22   // DHT 22  (AM2302)
DHT dht(DHTPIN, DHTTYPE); //// Initialize DHT sensor for normal 16mhz Arduino

//Variables
float hum;  //Stores humidity value
float temp; //Stores temperature value

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

}

void loop()
{
    //Read data and store it to variables hum and temp
    hum = dht.readHumidity();
    temp= dht.readTemperature();
    //Print temp and humidity values to serial monitor
    Serial.print("Humidity: ");
    Serial.print(hum);
    Serial.print(" %, Temp: ");
    Serial.print(temp);
    Serial.println(" Celsius");
    delay(2000); //Delay 2 sec.
}

```

My ancient C programmer training (Unix servers) says I must move variables hum and temp to loop(), or is it better on Arduino to leave them as globals?

# Answer
> 9 votes
No. If you have the choice, locals are usually better, because they minimize the risk of name collision, and they help make the program clearer by keeping the variable definition close to the place where it is used. In your example, `hum` and `temp` should be locals, as there is no good reason to make them globals.

However, sometimes you don't have the choice. If a variable is used in both `setup()` and `loop()`, then it needs to be global. This is the case of `dht` in your example.

Sometimes a variable is used in many functions. Even if you can make it local, by passing it around through function parameters, doing so doesn't make the program more readable. In that case you may also prefer to keep it global.

Sometimes a variable that is used in only one function needs to be statically allocated in order to preserve its value across calls to the function. In this case the variable could be a `static` local. However, since the `static` keyword is somewhat obscure for beginner programmers, Arduino tutorials tend to use globals whenever static storage is needed. You are not required to follow this practice, although you may want to if you are writing for an audience of novices.

In any case, the take away of your first two links is *not* that you should prefer globals: it's that sometimes there is a good reason for making a variable global, and *that's fine*.

# Answer
> 2 votes
The general rule of good practice is to minimize the scope of a variable to necessary minimum. Write the code to be readable and maintainable, don't do premature optimization.

The variables hum and temp should be defined only in loop(). The compiler can optimize it by putting them to global space or using MCU registers only, to avoid repeated creation on stack.

# Answer
> 0 votes
Not an answer, but I thought some of you may be interested in the C coding standards of *some* projects in the 1990s (based on the EDS standards, if I remember correctly).

A summary of the rules is:

* No goto
* No global variables
* All functions (including main) to return an integer which is either SUCCESS or FAILURE
* All variables declared at start of function
* All variables declared on a separate line
* No "in-line" initialising of variables
* All variables initialised, usually to zero, including mallocs
* No in-line if's
* Probably more things that I can't remember

An example program:

```
#include <stdio.h>
#include <stdlib.h>

#define SUCCESS 0
#define FAILURE !SUCCESS

int log_error(char *msg) {
  int rv;

  rv = SUCCESS;

  fprintf(stderr, "%s\n", msg);

  return(rv);
}

int function2(void) {
  int rv;

  rv = SUCCESS;

  return(rv);
}

int function1(void) {
  int rv;
  int i;
  char *mem;

  rv = FAILURE;
  i = 0;
  mem = 0;

  if(NULL == (mem = malloc(400))) {
    log_error("Malloc error");
  } else {
    for(i=0; i<400; i++) {
      mem[i] = 0;
    }
    if(SUCCESS != (rv = function2())) {
      log_error("function2");
    } else {
      rv = SUCCESS;
      free(mem);
    }
  }
  return(rv);
}

int main(int argc, char **argv) {
  int rv;

  rv = FAILURE;

  if(SUCCESS != (rv = function1())) {
    log_error("function1 error");
  }

  return(rv);
}

```

Bit different to the way K&R wrote UNIX, and perhaps not too relevant to embedded? I'm not sure which I prefer, I guess both styles have their place depending on the makeup of a team :)

---
Tags: arduino-uno, variables
---


# Question
Title: Can't extract basic data using ThingspeakHTTP
I don't know anything about HTML, but I want to extract the % probability of the Northern lights being visible from this webpage http://aurorawatch.ca/. I entered this into the URL field, and selected HTML version 1.

When I inspect the text element I want and copy the Xpath I get the following:

"/html/body/div/div\[5\]/table/tbody/tr/td/div/table\[2\]/tbody/tr\[2\]/td/div/table/tbody/tr/td\[2\]/span"

and enter this into the "parse string" field of the ThingSpeak API app, but get the following error:

"Error parsing document, try a different parse string."

Most people who get this error seem to be getting data that doesn't load with the original page, so I think I must be missing something.

If there is a better solution for pulling this number to my ESP8266 than creating a thingspeak API, I would love to hear it too!

# Answer
> 0 votes
You should use this page, since the other is the front page of the site and more likely to be dynamic:

The XPath is also slightly different. The first `tbody` in the reported path doesn't actually exist. You should also add `/text()` to the end of the path to just return the textual content of the node:

* `/html/body/div[1]/div[5]/table[2]/tr[3]/td/table/tbody/tr/td[2]/span/text()`

---
Tags: esp8266, nodemcu, http, iot, thingspeak
---


# Question
Title: How can I distinguish values sent from Arduino
Having in my visual basic app something like:

```
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        *whatever* value = serialPort1.Read*whatever*();
    }

```

Suppose my Arduino sends in every loop, the value read by a photoresistor. Suppose my Arduino also sends a 0 if certain led is LOW or a 1 if certain led is HIGH. Finally suppose my Arduino also sends a value that is equal to the number of times the loop has been executed.

In the 25th execution, lets suppose my Arduino sends something like:

```
Serial.write(LED_state) // 0 or 1 for LOW or HIGH
Serial.write(photoresistor_value) //lets suppose 25
Serial.write(loop_number) //25

```

Question: if all the values are sent using Serial.write or Serial.print, and all values are ints, how can I distinguish in my app if the value 25 received belongs to the photoresistor or to the loop? Is there any way to send something like (key, value) from Arduino so I can distinguish between the ints received so I can assign them correctly to my app variables?

# Answer
> Is there any way to send something like (key, value)

Sure:

```
Serial.print("LED state: ");
Serial.println(LED_state);

```

You will have to modify your VB code to parse that.
> 1 votes

---
Tags: arduino-uno, serial
---


# Question
Title: Generating and reading a PWM signal at the same time on Arduino Uno R3?
The code below should generate a PWM signal on digital pin 3. But know I want to see if it is even working. I was thinking about a Event triggering method like ISR. But somehow it does not work. I guess a ISR needs to a Input Pin, e.g. it would work, when I would've a PWM signal coming from somewhere.

Is it even possible to generate a PWM signal and read it to see some results on the serial monitor?

edited code:

```
byte const PWM_PIN = 3;

volatile unsigned long pwm_value = 0;
volatile unsigned long prev_time = 0;

void setup() {
  pinMode(PWM_PIN, OUTPUT);
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(PWM_PIN), rising, RISING);
}

void loop() {
  digitalWrite(PWM_PIN, HIGH);
  delay(400);
  digitalWrite(PWM_PIN, LOW);
  delay(1600);
}

void rising() {
  attachInterrupt(digitalPinToInterrupt(PWM_PIN), falling, FALLING);
  prev_time = millis();
}

void falling() {
  attachInterrupt(digitalPinToInterrupt(PWM_PIN), rising, RISING);
  pwm_value = millis()-prev_time;
  Serial.println(pwm_value);
}

```

# Answer
> 1 votes
You are declaring the variables `prev_time` and `pwm_value` as `int`, which has (on a standard Arduino) 16 bits. Since you use the signed variant, you get a range of values from -32768 to 32767. But `micros()` is returning an `unsigned long`, which has 4 bytes (32 bits) and is not signed. With `int` there are only 32.767 ms (since it represents microseconds here), without letting the variable overflow. Even the full range would give you only about 65 ms. It simply cannot hold a value like 1000000. If you assign this value to an `int`, it will directly overflow (which - I think - would give you the value modulo 2^16), effectively loosing big parts of the information. You cannot get meaningful results with this in such a high time scale.

When measuring time (with `millis()` or `micros()`) you should always be sure to use `unsigned long` as type to prevent these problems.

---

Apart from the variable type, why do you use `micros()` here? You are measuring times in the hundreds of milliseconds, so why not use `millis()`? This would keep the values lower.

# Answer
> 0 votes
1. You aren’t generating a correct PWM, because Serial.println introduces a delay. The right way for generating PWM is to use **analogWrite** function.
2. You **can’t** use attachInterrupt function for detecting rising and falling edge of an **output pin**.
3. In order to detect the rising and falling edge of a PWM signal, you have to use the **timer interrupt** of PWM module. For doing this, You have to write/read directly ATmega registers without using Arduino libraries. What version of Arduino are you using?

---
Tags: arduino-uno, pwm
---


# Question
Title: Arduino Uno will not connect to MAC computer running Sierra
I purchased an Arduino Uno. I am trying to set it up, but when I got to the "port" on my MAC, there is no option to select anything related to my board. The only connections the port tab allows me to connect to is the bluetooth incoming port, which is not correct because it gives me errors when I try to set up the UNO to block on and off for 1 second. I know this is the legit Arduino Uno, so why is the bluetooth not connecting?

# Answer
> 0 votes
I assume you have installed Arduino IDE on your mac and connecting board to mac using USB cable. Many time it happens due to driver or OS reason. Just plug the Arduino to another USB port and it should work.

---
Tags: arduino-uno, mac-os
---


# Question
Title: Unable to set LCD contrast using DAC pin on ESP32
I have followed the instructions at https://www.arduino.cc/en/Tutorial/HelloWorld and have my LCD displaying some text. I've also connected the LED back light (LCD pins 15&16).

I wanted to replace the potentiometer used to set the contrast, with a connection to the DAC pin. It needs to be about 0.8V.

When I connect the contrast pin from the LCD to my DAC pin on my ESP32 board, it doesn't work, the contrast is too high. Using a volt meter, it measures about 2.5V.

If I disconnect the LCD contrast pin from my DAC pin, the voltage measured is 0.8V.

Any ideas or examples on how to control the LCD contrast using a DAC pin?

I wondered if I need to add a resistor or something.

# Answer
The DAC in the ESP32 is ok for sourcing current but not so good at sinking current, and that is what you need.

A amplifier set up as a voltage follower would work.
> 1 votes

---
Tags: lcd, esp32
---


# Question
Title: Error with Sparkfun MP3 Shield and Arduino Due playing music files
The code worked on my Ardino Uno. I plugged it up the exact same way and am now getting an error.

Here is the error I get when I try to upload my code to the due:

```
Arduino: 1.8.5 (Windows 10), Board: "Arduino Due (Programming Port)"

C:\Program Files (x86)\Arduino\libraries\SFEMP3Shield\SFEMP3Shield.cpp: In static member function 'static void SFEMP3Shield::refill()':

C:\Program Files (x86)\Arduino\libraries\SFEMP3Shield\SFEMP3Shield.cpp:1984:7: error: 'sei' was not declared in this scope

   sei();

       ^

C:\Program Files (x86)\Arduino\libraries\SFEMP3Shield\SFEMP3Shield.cpp:2006:9: error: 'cli' was not declared in this scope

     cli(); // allow transfer to occur with out interruption.

         ^

C:\Program Files (x86)\Arduino\libraries\SFEMP3Shield\SFEMP3Shield.cpp: In member function 'void SFEMP3Shield::SendSingleMIDInote()':

C:\Program Files (x86)\Arduino\libraries\SFEMP3Shield\SFEMP3Shield.cpp:2053:7: error: 'cli' was not declared in this scope

   cli(); // allow transfer to occur with out interruption.

       ^

C:\Program Files (x86)\Arduino\libraries\SFEMP3Shield\SFEMP3Shield.cpp:2067:7: error: 'sei' was not declared in this scope

   sei();  // renable interrupts for other processes

       ^

exit status 1
Error compiling for board Arduino Due (Programming Port).

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

```

Here is my code:

```
#include <SPI.h>
#include <SdFat.h>
#include <SdFatUtil.h>
#include <SFEMP3Shield.h>

SdFat sd;
SFEMP3Shield MP3player;

const uint8_t volume = 10; // MP3 Player volume 0=max, 255=lowest (off)
//10 for normal 50 for testing

const uint16_t monoMode = 1;

void setup() {
  initSD();
  initMP3Player();
}

void loop() {
  if(!MP3player.isPlaying()){
    MP3player.playTrack(1);
  }
}

void initSD() {
  if(!sd.begin(SD_SEL, SPI_HALF_SPEED))
    sd.initErrorHalt();
  if(!sd.chdir("/"))
    sd.errorHalt("sd.chdir");
}

void initMP3Player() {
  uint8_t result = MP3player.begin();
  MP3player.setVolume(volume, volume);
  MP3player.setMonoMode(monoMode);
}

```

# Answer
The library is written for the Uno, not the Due. It relies on two instructions that are only available in the AVR compiler.

Newer versions of the core provide a pair of macros, `interrupts()` and `noInterrupts()` that should be used in place of `sei()` and `cli()` respectively, which should be provided by the Due's core as well to make it cross-platform. However that library has never been updated to work with those macros.

You *could* replace the `sei()` and `cli()` calls in the library with `interrupts()` and `noInterrupts()`, however that may not make it work, since it was written with the Uno and other AVR based chips in mind.
> 1 votes

---
Tags: arduino-due, shields
---


# Question
Title: How to assign two or more variables incoming from app
I'm really new to Arduino and have some doubts about how Arduino reads data. Lets suppose I have 3 variables `a,b,c`. I need these variables in my Arduino to make whatever. Since all variables are read using `Serial.read()` how can I distinguish between them in my Arduino?

Example:

`Variable a: 2` `Variable b: 3` `Variable c: 4`

Arduino example code:

```
void loop() {
int a = Serial.read();
int b = Serial.read();
int c = Serial.read();

if(a == '0'){
digitalWrite(yellowLed, HIGH);
}

if(b == '0'){
digitalWrite(blueLed, HIGH);
}

if(c == '0'){
digitalWrite(redLed, HIGH);
}

```

In every loop, my Arduino does `serial.read()` 3 times, if I only send value b from my app, since `int a = Serial.read()` executes first, will my b value be assigned to a? If yes, how can I avoid that problem and force the correct assignment? Aditionally, in every loop, if `Serial.read()` doesnt read anything, will my values be changed to null or zero?

# Answer
This is a classic problem that is solved either by uniquely identifying each value or by agreeing on a pre-defined sequence of data. However, it can be said that many solutions exist for this problem & that these are only 2 examples.

In the first case, the sender and receiver need to agree that all data will be sent in pairs. A pair of bytes, for example, where the first identifies the data and the second is the data. In this case the order of data does not matter. And much more of one type of data can be sent than another. This is good to use when the data rate is irregular and does not need to be fast. Stock prices for example.

In the second case, the sender and receiver need to agree that all data will be sent in the same sequence even if there is no data to be sent. Such a scheme may employ a special synchronizing bit to identify the beginning of a sequence of data. Usually, when there is no data to be sent, a zero is sent. But if zeros are significant, then special null characters will have to be agreed upon. This is good when the data rate is regular and needs to be fast. Digitized audio for example.
> 0 votes

---
Tags: arduino-uno, serial
---


title: Doubt in choosing the right DC motor?

text:
# Question
Title: Doubt in choosing the right DC motor?
Take this motor as an example - https://www.robotshop.com/en/12v-100rpm-583-oz-in-brushed-dc-motor.html

it has torque of 42kg.cm

I know all the calculation to find the payload of dc motor from here - https://www.quora.com/How-do-I-calculate-how-much-weight-can-DC-motor-carry

My main concern is the output power. Power formula is:-

power = voltage x Stall Current = 12 x 2A = 24W

But the specification says that the power is 5W. Which value should I use in my calculation?

# Answer
> 0 votes
With a current rating of `0.68 A` at `12 V` you get the *normal* power requirement of `8.6 W` for a `7Kg.cm` torque.

If, for any reason, you stall the motor, your driver must be capable to output `2.2 A` or `26.5 W` to avoid a permanent damage.

---
Tags: motor, mechanical
---


# Question
Title: Confused between SPI and I2C for SSD1306 OLED
I recently got myself an SSD1306 OLED display:

I haven't been able to successfully wire it to an Arduino (Mega 2560) however. I have been reading up on I2C and SPI and checked some libraries from Adafruit and U8G2.

However, I'm confused, since most of the Internet is talking about a similar OLED display with GND - VDD - SCL - SDA labelled pins, where mine has SCK instead of SCL.

Now, the number of pins make me believe I need to interface with I2C, but the SCK label points to SPI, right?

One person seemed to have the same problem as me, but the solution he got (pull-up resistors) didn't do the trick for me, I'm afraid.

So, my question remains: how to wire this OLED display to the Mega 2560?

Much appreciated if someone could point me to the right direction.

Thanks!

# Answer
SCK and SCL are the same thing.

* Serial ClocK
* Serial CLock

They seem to be interchangeable. The fact you have SDA (Serial DAta) as opposed to separate SDI / SDO or MOSI / MISO pins means it's I2C.

Wire it like you would any other I2C device.
> 7 votes

# Answer
I have what appears to be the same display (GM009605 v4) and while both SCL and SCK both stand for Serial Clock many development boards have different SCK and SCL pins that you'd need to interface. On a Wemos d1 mini for example I have this display plugged into SDA =\> D2 & SCK =\> D5 where as if it was SCL it would to to D1.

FWIW I use the Wire.h and SSD1306.h libraries (https://github.com/ThingPulse/esp8266-oled-ssd1306) to interface with the display using the Wemos D1 mini.
> 1 votes

---
Tags: arduino-mega, i2c, spi, display, wires
---


# Question
Title: Trying to save .wav files with new name every loop
I have built a set up with an Arduino UNO hooked up to a switch, so that whenever the switch goes from HIGH to LOW it saves audio to an SD card. I am using the TMRpcm Library. The problem is the current code will only be able to record 1 audio file; I want to the Arduino to run for a long period of time collecting multiple audio files as the switch is turned on and off. I need a way that will allow it so everytime the switch is pushed back down the next file saved will have a different name than the one previously saved (preferably by an increased numeric value eg "1.wav" & "2.wav"). I have tried **audio.startRecording(audiofile+".wav", 16000, A0);** and it makes it so no files save to the SD card accept an empty file simple titled 'WAV'. I have tried using a switch case but it will not allow me to reach a case over 10, without running out of RAM. Currently, my code can save 1 audio file but I want it to reach a point where it can save as many as the SD card can hold, without having to restart the software.

My current code is here. Any help would be greatly appreciated

```
//////////////////////////////////////// SD CARD
#include <SD.h>
#include <SPI.h>
#include <TMRpcm.h>
#define SD_ChipSelectPin 10
TMRpcm audio;
//////////////////////////////////////// SWITCH CASE
int audiofile = 0;     // # of recording
unsigned long i = 0;
bool recmode = 0;      // recording state
//////////////////////////////////////// SWITCH
int inPin = 2;         // input Switch Pin
int state = HIGH;      // the current state switch
int reading;           // the current reading from the switch

void setup() {
  Serial.begin(9600);
  pinMode(A0, INPUT);  // Microphone
  pinMode(inPin, INPUT_PULLUP); // Switch
  //////////////////////////////////////// SD CARD
  SD.begin(SD_ChipSelectPin);
  audio.CSPin = SD_ChipSelectPin;
}

void loop() {

  reading = digitalRead(inPin);
  ////////////////////////////////////////
  while (i < 300000) {
    i++;
  }
  i = 0;
  ////////////////////////////////////////
  if (reading == LOW) {
    if (recmode == 0) {
      recmode = 1;

      Serial.println("Recording");

      audiofile++; // To move case
      audio.startRecording("1.wav", 16000, A0);
    }
  }
  ////////////////////////////////////////
  else if (reading == HIGH) {
    recmode = 0;

    Serial.println("Hung-Up");
    audio.stopRecording("1.wav");
  }
}

```

# Answer
> 1 votes
I would (and do) use `snprintf` to format a string as a filename:

```
// Global scope, or local static
uint32_t myFileNumber = 1;
char filename[12];

// in your function - results in 00000001.WAV
snprintf(filename, 12, "%08d.WAV", myFileNumber);

```

%08d will allow between 00000000.WAV and 99999999.WAV and always with 8 digits. Any more and it will get truncated and corrupted (100000000.WA) but won't cause a buffer overrun. You will have to take precautions that you never have more than 100 million files ;)

---
Tags: arduino-uno, programming, library, sd-card, tmrpcm
---


title: Which LCD Pins, if any, require PWM?

text:
# Question
Title: Which LCD Pins, if any, require PWM?
In the Arduino Tutorial Page named "Hello World" aimed to help people connect a 16x2 LCD Display compatible with Hitachi HD44780 driver to an Arduino Uno. The pins used to connect the Arduino Uno and LCD Module are as follows:

* LCD RS pin to digital pin 12
* LCD Enable pin to digital pin 11
* LCD D4 pin to digital pin 5
* LCD D5 pin to digital pin 4
* LCD D6 pin to digital pin 3
* LCD D7 pin to digital pin 2

Pins 3,5 and 11 are connected to PWM Pins, however, I'm wondering if they actually need these PWM capabilities or does this tutorial just pick random pins and the LCD's D6, D4 and Enable pins doesn't actually need the PWM capabilities available of these pins.

I'm asking this as I'm considering on using an Arduino Mega for my next project and it would be much easier and neater for all the pins of the LCD to go onto the digital pins instead of some being on the digital and others on the PWM pins.

# Answer
Likely all programmable pins on modern embedded processors are able to perform digital I/O. In addition, many can also perform other tasks such as PWM, or Analog to Digital Conversion (ADC). This is true for many of the different processors used on different Arduino boards.

Often, the nice people who write the C++ driver class of programs or Arduino Libraries offer the user the ability to change pin assignments used by the Arduino Libraries when instantiating an instance of the driver. This is true for the LiquidCrystal driver in the tutorial in the question. This can be an advantage as processor's resources are limited. For example, if you need PWM controlled pin to dim LEDs, you can move LCD controlling pins to other non-PWM pins.

The LCD specified in the tutorial linked to in the above question uses a common Hitachi HD44780 interface. Such assemblies only need embedded processor Digital I/O pins for control. Had the LCD no electronic driver, the segments need to be directly driven by very low alternating current (AC). This is difficult for embedded processors. However, it may be possible using enough PWM pins and some clever software & hardware.
> 2 votes

# Answer
PWM is not used on those pins for the LCD operation. You can choose more convenient pins as long as they are general purpose pins. For example, not A/D input only.

(I thought you might appreciate a short clear answer)
> 1 votes

---
Tags: arduino-mega, lcd, pwm
---


# Question
Title: My Arduino freezes if power removed from the HMI
I have an Arduino (Pro Mini) connected to an HMI display over serial. When the user pushes a button on the HMI screen, it activates a relay attached to one of the digital pins on the Arduino.

For safety reasons, if the Arduino loses communications with the HMI, I want it to turn off the relay. So, when the button has been pushed, it triggers a polling sequence to verify that the button is still being pushed (I'm not relying on the button release event, again for safety).

The following code works perfectly if I disconnect either of the signal lines (tx or rx) or ground from the HMI. If I disconnect the +5 volts, however, the Arduino freezes completely, and therefore never shuts down the relay.

What could be causing this, and what can I do to overcome the problem?

The code is as follows, however, it works as expected if the data lines or ground are severed.

```
int getNumber(const char *reqString)
{
  sendString(reqString);

  long startTime = currentMillis;
  long waitTimer = currentMillis - startTime;

  bool responded = false;
  int endcount = 0;
  byte inbyte;
  byte bytebuffer[80];
  int bytecount = 0;

  while (waitTimer < 100 && !responded)
  {

      if (HMI.available())
      {
        inbyte = HMI.read();

        if (inbyte == 0xFF)
        {
          endcount++;
          if (endcount == 3)
          {
            responded = true;
            endcount = 0;
          }
        }
        else
        {
          endcount = 0;
        }

        bytebuffer[bytecount] = inbyte;
        bytecount++;
      }

      // Update the wait Timer.
      waitTimer = millis() - startTime;
  }

  // If we received a response, return the first data byte. If not, return 0
  if (responded)
   {
     Serial.println("Received response");
     return bytebuffer[1];
   }
   else
   {
 Serial.println("No response");
     return 0;
   }
}

```

# Answer
It seems that Software Serial is waiting for "high" on RX

Only a hardware solution comes to my mind

simulate this circuit – Schematic created using CircuitLab

This way Arduino RX will be released on HMI power loss

Later edit

You can also use the watchdog timer to unfreeze your code when unresponsive. It will reset the Arduino if wdt\_reset() is not called in a given amount of time and you can make the cleaning you need before using Software Serial again. Here is a useful tutorial.
> 1 votes

---
Tags: softwareserial, code-review
---


# Question
Title: Arduino: Reading PPM values from MQ-131 Ozone sensor
I have this sensor MQ131 by sainsmart: https://www.amazon.co.uk/gp/product/B00NL8XIQG/ref=ox\_sc\_act\_title\_1?ie=UTF8&psc=1&smid=A3DRI1TTHCTDIG

All I can read is the analog value which does not reflect the gas concentration. Any Arduino code for that to read the ppm concentration? How long does the sensor needs to be preheated?

# Answer
> 1 votes
First you need t make it burn for 24hrs mini (48 advised). Just plug it and wait. Then for calibration you need a reference atmosphere free of NOx, CL2 and O3. In this reference atmosphere you should get an output value of 0.

I don't know this model you bought exactly, but most of these gas sensors mounted on a PCB have a mini eeprom so the output is the actual PPM concentration. Note that these sensors are not able to tell you how much of which gas is detected, but only a ppm concentration (you then have to guess which one is in the air). If you have several of these gas in the air, you will not be able to tell their concentration with such a sensor.

# Answer
> 0 votes
According to the picture, the sensor is a Winsen MQ131 low concentration (black bakelite version). You can have additional information on the sensor in the datasheet.

Your sensor is mounted on a PCB with some features like converting values (analog to digital), controlling the heater, maybe providing I2C bus... Without any additional information, it's difficult to give guidance on your module (the Amazon link doesn't mention any datasheet for the module).

In order to use your sensor, you can connect it directly on the sensor and pilot it by yourself. You can find some code on GitHub (for inspiration or fork).

---
Tags: arduino-uno, sensors
---


# Question
Title: Using a toggle switch to run part of a sketch
First, I am a beginner for this. I just ordered my first book on coding Arduino and I'm working through some simple applications using a DS3231 (that has a temperature reading), LCD, MicroSD card module, etc. My board is a Uno R3. Currently, I need a sketch to run part of a program which contains a loop to collect data and have this run when a toggle switch is turned on. So, toggle goes on and part of program runs, toggle goes off and this part exits. The reason I need a toggle with constant on/off is the problem with G forces and vibration. I momentary push button input will not be reliable. Ultimately, all the components will be in a amateur high-power rocket to run a roll control program. If you can help, I greatly appreciate your assistance.

# Answer
> 3 votes
There are different ways to accomplish the same thing.

The condition is a flag, or a read port.

```
if(digitalRead(inPin))
     {
     // Your first code here.
     }
else
     {
     // second code
     }

```

Switch contacts will bounce when opening or closing. You may want to consider that. Usually it is stable within 10 milliseconds. Depending on what you are doing it may or may not be relevant.

# Answer
> 0 votes
You need a few things. At the top of your sketch, before setup()

```
byte togglePin = x; // from 2 to 19 with an Uno. Wire to connect pin to Gnd when closed.

```

In setup()

```
 pinMode (togglePin, INPUT_PULLUP);

```

In loop()

```
if (digitalRead(togglePin) == LOW){
// switch closed, do something - or stop doing something
// maybe set a flag too, like
toggleState = 0;
}
else {
// switch, stop doing something - or start doing something
toggleState = 1;
}

```

The flag can be used elsewhere in your code

```
if (someOtherCondition && toggleState == 0){
// run a timer or motor or something
}
if (someOtherCondition && toggleState == 1){
// turn off timer or motor or something
}

```

---
Tags: switch
---


# Question
Title: How can I upload .hex files to a Pro Micro using Linux?
I have a hand-wired keyboard that uses a Pro Micro board, with an ATmega32u4 chip. I can't seem to flash firmware on it. The commands I've been trying are variations of:

```
avrdude -p m32U4 -P /dev/ttyACM0 -c avr109 -U flash:w:atreus62.hex

```

The errors I've been getting begin:

```
Writing | #######avrdude: error: programmer did not respond to command: set addr
####avrdude: error: programmer did not respond to command: set addr
avrdude: error: programmer did not respond to command: write block
 ***failed;
 ***failed;
 ***failed;
 ***failed;

```

And end:

```
#avrdude: error: programmer did not respond to command: set addr
avrdude: error: programmer did not respond to command: set addr
avrdude: error: programmer did not respond to command: set addr
#avrdude: error: programmer did not respond to command: set addr
avrdude: error: programmer did not respond to command: set addr
avrdude: error: programmer did not respond to command: set addr
# | 100% 0.16s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0000
         0x0d != 0x0c
avrdude: verification error; content mismatch
avrdude: error: programmer did not respond to command: leave prog mode
avrdude: error: programmer did not respond to command: exit bootloader

```

I'm on Arch Linux. Any ideas?

# Answer
> 2 votes
There's two stages to uploading a hex file to a USB-based Arduino - and you're only doing the second stage.

The first stage is to reset the board into the bootloader so it can accept the instructions from the second stage. The IDE normally does that manually for you when you hit the UPLOAD button.

The way these boards are reset is to first open the CDC/ACM port and set the baud rate to 1200, then close the port again. That triggers the code to reset the board into the bootloader.

You can probably do it using the `stty` tool in Linux:

```
$ stty -F /dev/ttyACM0 speed 1200
$ stty -F /dev/ttyACM0 speed 115200
$ avrdude -p m32U4 -P /dev/ttyACM0 -c avr109 -U flash:w:atreus62.hex

```

The second `stty` may not actually be needed, but it's good to reset the baud rate to a normal value ready for uploading. I don't have a board to hand right now to test it though.

# Answer
> 2 votes
I had the same issue, and it was caused by udev, I found the answer here

It's some obscure bug

Tweaking udev rules solved the problem for me, now all is good, here is the procedure: https://learn.adafruit.com/adafruit-arduino-ide-setup/linux-setup#udev-rules

---
Tags: avrdude
---


title: toggling Rx, Tx pins after Serial.begin

text:
# Question
Title: toggling Rx, Tx pins after Serial.begin
What should one expect when the following program runs on Arduino Uno?

```
void setup()
{
    Serial.begin(9600);
    DDRD |= 0b11;
}

void loop()
{
    PORTD |= 0b11;
    delay(100);
    Serial.print("ABCD");
    PORTD &= ~0b11;
    delay(100);
    Serial.print("DEFG\n");
}

```

When Serial.begin() is used, the pins PD0, PD1 might be configured as UART pins. After that if DDR is used, are the pins configured as GPIO, or are they still UART Rx, Tx pins?

# Answer
As always, the answer is in the datasheet:

> * TXD/PCINT17 – Port D, Bit 1
>
> TXD, Transmit Data (Data output pin for the USART). When the USART Transmitter is enabled, this pin is configured as an output **regardless of the value of DDD1.** PCINT17: Pin Change Interrupt source 17. The PD1 pin can serve as an external interrupt source.
>
> * RXD/PCINT16 – Port D, Bit 0
>
> RXD, Receive Data (Data input pin for the USART). When the USART Receiver is enabled this pin is configured as an input **regardless of the value of DDD0.** When the USART forces this pin to be an input, the pull-up can still be controlled by the PORTD0 bit.

As to what trying to set the output level on the TX pin would have, only experimentation can show. It's not defined in the datasheet (because who would do it?)
> 1 votes

---
Tags: pins, uart
---


# Question
Title: Nano damaged. Power LED OK. USB Detected. No Sketch upload. No Program running
seems i damaged one of my Nanos. i have to say i am new to Arduino and have basic electronik skills and i realized after shopping via amazon that the Nanos i have are clones with CH340G. never the less they are working. i was building a light driven open/close circuit for my chickens. using L293D motordriver, LCD, photocell. my sketch was just reading the photocell and outputting it on the LCD. not yet using the L293D in the sketch but assembled it already (without Motors and MV+). The program was running for ~ 2 minutes. i was testing the reading for the photocell and was wondering why at low light the reading was still quite high ~ 600+. then all disappeared from the LCD apart of the background light. as i couldnt get it running i tried to upload Blink again -\> not working

```
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x96 code here
...
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x96
Problem beim Hochladen auf das Board. Hilfestellung dazu unter http://www.arduino.cc/en/Guide/Troubleshooting#upload.

```

after a while i was reading about programmers so i turned another Nano into a ArduinoISP trying to write either Booloader or Sketch via ISP bypassing USB (as i understood the different articles) which gave

```
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x15
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x15

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x14

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x01
avrdude: stk500_initialize(): (a) protocol error, expect=0x14, resp=0x10
avrdude: initialization failed, rc=-1
     Double check connections and try again, or use -F to override
     this check.

avrdude: stk500_disable(): unknown response=0x12
Der ausgewählte serielle Port avrdude: stk500_disable(): unknown response=0x12
 ist nicht vorhanden oder das Board ist nicht angeschlossen

```

then i used Atmega\_Board\_Detector and Atmega\_Board\_Programmer which both seem to work. output of Boarddetector:

```
    Atmega chip detector.
    Written by Nick Gammon.
    Version 1.20
    Compiled on Dec 27 2018 at 15:13:27 with Arduino IDE 10808.
    Attempting to enter ICSP programming mode ...
    Entered programming mode OK.
    Signature = 0x1E 0x95 0x0F
    Processor = ATmega328P
    Flash memory size = 32768 bytes.
    LFuse = 0xFF
    HFuse = 0xDE
    EFuse = 0xFD
    Lock byte = 0xEF
    Clock calibration = 0x9E
    Bootloader in use: Yes
    EEPROM preserved through erase: No
    Watchdog timer always on: No
    Bootloader is 512 bytes starting at 7E00

    Bootloader:

    7E00: 0x11 0x24 0x84 0xB7 0x14 0xBE 0x81 0xFF 0xF0 0xD0 0x85 0xE0 0x80 0x93 0x81 0x00
    7E10: 0x82 0xE0 0x80 0x93 0xC0 0x00 0x88 0xE1 0x80 0x93 0xC1 0x00 0x86 0xE0 0x80 0x93
    7E20: 0xC2 0x00 0x80 0xE1 0x80 0x93 0xC4 0x00 0x8E 0xE0 0xC9 0xD0 0x25 0x9A 0x86 0xE0
    7E30: 0x20 0xE3 0x3C 0xEF 0x91 0xE0 0x30 0x93 0x85 0x00 0x20 0x93 0x84 0x00 0x96 0xBB
    7E40: 0xB0 0x9B 0xFE 0xCF 0x1D 0x9A 0xA8 0x95 0x81 0x50 0xA9 0xF7 0xCC 0x24 0xDD 0x24
    7E50: 0x88 0x24 0x83 0x94 0xB5 0xE0 0xAB 0x2E 0xA1 0xE1 0x9A 0x2E 0xF3 0xE0 0xBF 0x2E
    7E60: 0xA2 0xD0 0x81 0x34 0x61 0xF4 0x9F 0xD0 0x08 0x2F 0xAF 0xD0 0x02 0x38 0x11 0xF0
    7E70: 0x01 0x38 0x11 0xF4 0x84 0xE0 0x01 0xC0 0x83 0xE0 0x8D 0xD0 0x89 0xC0 0x82 0x34
    7E80: 0x11 0xF4 0x84 0xE1 0x03 0xC0 0x85 0x34 0x19 0xF4 0x85 0xE0 0xA6 0xD0 0x80 0xC0
    7E90: 0x85 0x35 0x79 0xF4 0x88 0xD0 0xE8 0x2E 0xFF 0x24 0x85 0xD0 0x08 0x2F 0x10 0xE0
    7EA0: 0x10 0x2F 0x00 0x27 0x0E 0x29 0x1F 0x29 0x00 0x0F 0x11 0x1F 0x8E 0xD0 0x68 0x01
    7EB0: 0x6F 0xC0 0x86 0x35 0x21 0xF4 0x84 0xE0 0x90 0xD0 0x80 0xE0 0xDE 0xCF 0x84 0x36
    7EC0: 0x09 0xF0 0x40 0xC0 0x70 0xD0 0x6F 0xD0 0x08 0x2F 0x6D 0xD0 0x80 0xE0 0xC8 0x16
    7ED0: 0x80 0xE7 0xD8 0x06 0x18 0xF4 0xF6 0x01 0xB7 0xBE 0xE8 0x95 0xC0 0xE0 0xD1 0xE0
    7EE0: 0x62 0xD0 0x89 0x93 0x0C 0x17 0xE1 0xF7 0xF0 0xE0 0xCF 0x16 0xF0 0xE7 0xDF 0x06
    7EF0: 0x18 0xF0 0xF6 0x01 0xB7 0xBE 0xE8 0x95 0x68 0xD0 0x07 0xB6 0x00 0xFC 0xFD 0xCF
    7F00: 0xA6 0x01 0xA0 0xE0 0xB1 0xE0 0x2C 0x91 0x30 0xE0 0x11 0x96 0x8C 0x91 0x11 0x97
    7F10: 0x90 0xE0 0x98 0x2F 0x88 0x27 0x82 0x2B 0x93 0x2B 0x12 0x96 0xFA 0x01 0x0C 0x01
    7F20: 0x87 0xBE 0xE8 0x95 0x11 0x24 0x4E 0x5F 0x5F 0x4F 0xF1 0xE0 0xA0 0x38 0xBF 0x07
    7F30: 0x51 0xF7 0xF6 0x01 0xA7 0xBE 0xE8 0x95 0x07 0xB6 0x00 0xFC 0xFD 0xCF 0x97 0xBE
    7F40: 0xE8 0x95 0x26 0xC0 0x84 0x37 0xB1 0xF4 0x2E 0xD0 0x2D 0xD0 0xF8 0x2E 0x2B 0xD0
    7F50: 0x3C 0xD0 0xF6 0x01 0xEF 0x2C 0x8F 0x01 0x0F 0x5F 0x1F 0x4F 0x84 0x91 0x1B 0xD0
    7F60: 0xEA 0x94 0xF8 0x01 0xC1 0xF7 0x08 0x94 0xC1 0x1C 0xD1 0x1C 0xFA 0x94 0xCF 0x0C
    7F70: 0xD1 0x1C 0x0E 0xC0 0x85 0x37 0x39 0xF4 0x28 0xD0 0x8E 0xE1 0x0C 0xD0 0x85 0xE9
    7F80: 0x0A 0xD0 0x8F 0xE0 0x7A 0xCF 0x81 0x35 0x11 0xF4 0x88 0xE0 0x18 0xD0 0x1D 0xD0
    7F90: 0x80 0xE1 0x01 0xD0 0x65 0xCF 0x98 0x2F 0x80 0x91 0xC0 0x00 0x85 0xFF 0xFC 0xCF
    7FA0: 0x90 0x93 0xC6 0x00 0x08 0x95 0x80 0x91 0xC0 0x00 0x87 0xFF 0xFC 0xCF 0x80 0x91
    7FB0: 0xC0 0x00 0x84 0xFD 0x01 0xC0 0xA8 0x95 0x80 0x91 0xC6 0x00 0x08 0x95 0xE0 0xE6
    7FC0: 0xF0 0xE0 0x98 0xE1 0x90 0x83 0x80 0x83 0x08 0x95 0xED 0xDF 0x80 0x32 0x19 0xF0
    7FD0: 0x88 0xE0 0xF5 0xDF 0xFF 0xCF 0x84 0xE1 0xDE 0xCF 0x1F 0x93 0x18 0x2F 0xE3 0xDF
    7FE0: 0x11 0x50 0xE9 0xF7 0xF2 0xDF 0x1F 0x91 0x08 0x95 0x80 0xE0 0xE8 0xDF 0xEE 0x27
    7FF0: 0xFF 0x27 0x09 0x94 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0x04 0x04

    MD5 sum of bootloader = 0xFB 0xF4 0x9B 0x7B 0x59 0x73 0x7F 0x65 0xE8 0xD0 0xF8 0xA5 0x08 0x12 0xE7 0x9F
    Bootloader name: optiboot_atmega328

    First 256 bytes of program memory:

    00: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    10: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    20: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    30: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    40: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    50: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    60: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    70: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    80: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    90: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    A0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    B0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    C0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    D0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    E0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    F0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF

    Programming mode off.

```

Output of Board Programmer:

```
    Atmega chip programmer.
    Written by Nick Gammon.
    Version 1.38
    Compiled on Dec 27 2018 at 15:15:38 with Arduino IDE 10808.
    Attempting to enter ICSP programming mode ...
    Entered programming mode OK.
    Signature = 0x1E 0x95 0x0F
    Processor = ATmega328P
    Flash memory size = 32768 bytes.
    LFuse = 0xFF
    HFuse = 0xDE
    EFuse = 0xFD
    Lock byte = 0xEF
    Clock calibration = 0x9E
    Type 'L' to use Lilypad (8 MHz) loader, or 'U' for Uno (16 MHz) loader ...
    Using Uno Optiboot 16 MHz loader.
    Bootloader address = 0x7E00
    Bootloader length = 512 bytes.
    Type 'Q' to quit, 'V' to verify, or 'G' to program the chip with the bootloader ...
    Erasing chip ...
    Writing bootloader ...
    Committing page starting at 0x7E00
    Committing page starting at 0x7E80
    Committing page starting at 0x7F00
    Committing page starting at 0x7F80
    Written.
    Verifying ...
    No errors found.
    Writing fuses ...
    LFuse = 0xFF
    HFuse = 0xDE
    EFuse = 0xFD
    Lock byte = 0xEF
    Clock calibration = 0x9E
    Done.
    Programming mode off.
    Type 'C' when ready to continue with another chip ...

```

other observations: when trying to upload a sketch the rx LED blinks where thin a few times but not bright and at the speed it usually does. the L LED blinks at power on a few times.

i have 2 questions:

1. can you see anything in my circuit that could have damaged the NANO?
2. any idea to recover the NANO?

i am more curious on the first question as i don't want to take out another one. the second is more curiosity what can be done on a Nano. and i am clueless why it died as i run all the experiments individually on an UNO

attached pictures and my fight with Fritzing for the schematics.     Many Thanks already

UPDATE: just recognized that also my working NANOs can not be programmed via ArduinoISP Sketch using a Programmer NANO. so as the tools from Nick Gammon. are working https://github.com/nickgammon/arduino\_sketches. i assume my chip is working and it is up to the USB Chip or connection.

UPDATE2: my NANO is fully back in live. what ever happened seems to have corrupted my flash. so after the TIPs from @Majenko with the 10uF Cap between Reset and GND i was able to programm via a "Programmernano". but here is another catch when you first flash bootloader and then right away flash a sketch via programmer as well, this erases again the bootloader. you can check this with the Atmega chip detector. Written by Nick Gammon.

```
    Bootloader is 2048 bytes starting at 7800

    Bootloader:

    7800: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    7810: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    7820: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
    7830: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF

```

So i just flash the Bootloader via ArduinoISP and then connect the NANO directly to USB to flash a sketch

# Answer
> 1 votes
Try replacing the diode as in this link, it worked for me: https://forum.arduino.cc/index.php?topic=166089.0

A short on VCC might damage the diode.

As for the answer to the first question, yes there is a flaw in the design, if the external power is lost the LCD and the L293D will be powered from USB through the above diode.

"Small change" , see Juraj's comment below.

# Answer
> 1 votes
Based on the output from my sketches that you have posted, the CPU chip is fine (Atmega328P). Since you cannot program via the USB port is looks likely that the CH340G is damaged.

A fall-back position is to use another one of the sketches (Atmega\_Hex\_Uploader) in the link you posted, and upload code via the SPI interface. To make this work you need to purchase a micro-SD card interface as described here for around $US 15.

As for why it failed, this should be investigated promptly. Possibly the answer by Dorian will help.

---
Tags: arduino-nano, electronics
---


# Question
Title: Do the libraries of the Arduino Uno work with the Arduino Mega?
I did a project with the Arduino Due and the libraries for the VS1053 MP3 Shield were not compatable with the Due. Are the libraries that work with the Uno compatable with the Arduino Mega?

# Answer
> 2 votes
> Are the libraries that work with the Uno compatable with the Arduino Mega?

Sometimes.

They have a higher chance of being compatible, due to them both using the same AVR core, but since internal peripherals differ slightly there is a chance that, depending on what the library does, it won't work right.

You just have to try it and see.

---
Tags: arduino-uno, arduino-mega
---


title: New code results in audio noise

text:
# Question
Title: New code results in audio noise
I am working on a circuit that can record audio to an SD when a switch is HIGH and stop recording when the switch is LOW. I am using the TMRpcm library. I previously had an issue solved on these two forumsRecording Audio - Film Name Errorand Trying to save .wav files with new name every loop. These solutions solved my problem but have left me with a new one. Currently the audio recorded on the new code (which I have pasted below) results is a very noisy and muffled audio quality; while the audio recorded on the old code (also posted below) is very clear. Could this be a physical issue and if so what should I do about it? Or is it an issue I am missing in the code?

OLD CODE - provides good quality audio

```
//////////////////////////////////////// SD CARD
#include <SD.h>
#include <SPI.h>
#include <TMRpcm.h>
#define SD_ChipSelectPin 10
TMRpcm audio;
//////////////////////////////////////// SWITCH CASE
int audiofile = 0;     // # of recording
unsigned long i = 0;
bool recmode = 0;      // recording state
//////////////////////////////////////// SWITCH
int inPin = 2;         // input Switch Pin
int state = HIGH;      // the current state switch
int reading;           // the current reading from the switch

void setup() {
  Serial.begin(9600);
  pinMode(A0, INPUT);  // Microphone
  pinMode(inPin, INPUT_PULLUP); // Switch
  //////////////////////////////////////// SD CARD
  SD.begin(SD_ChipSelectPin);
  audio.CSPin = SD_ChipSelectPin;
}

void loop() {

  reading = digitalRead(inPin);
  ////////////////////////////////////////
  while (i < 300000) {
    i++;
  }
  i = 0;
  ////////////////////////////////////////
  if (reading == LOW) {
    if (recmode == 0) {
      recmode = 1;

      Serial.println("Recording");

      audiofile++; // To move case
      switch (audiofile) {
        case 1: audio.startRecording("1.wav", 16000, A0); break;
        case 2: audio.startRecording("2.wav", 16000, A0); break;
        case 3: audio.startRecording("3.wav", 16000, A0); break;
        case 4: audio.startRecording("4.wav", 16000, A0); break;
        case 5: audio.startRecording("5.wav", 16000, A0); break;
        case 6: audio.startRecording("6.wav", 16000, A0); break;
        case 7: audio.startRecording("7.wav", 16000, A0); break;
        case 8: audio.startRecording("8.wav", 16000, A0); break;
        case 9: audio.startRecording("9.wav", 16000, A0); break;
        case 10: audio.startRecording("10.wav", 16000, A0); break;
      }
    }
  }
  ////////////////////////////////////////
  else if (reading == HIGH) {
    recmode = 0;

    Serial.println("Hung-Up");
    switch (audiofile) {
      case 1: audio.stopRecording("1.wav"); break;
      case 2: audio.stopRecording("2.wav"); break;
      case 3: audio.stopRecording("3.wav"); break;
      case 4: audio.stopRecording("4.wav"); break;
      case 5: audio.stopRecording("5.wav"); break;
      case 6: audio.stopRecording("6.wav"); break;
      case 7: audio.stopRecording("7.wav"); break;
      case 8: audio.stopRecording("8.wav"); break;
      case 9: audio.stopRecording("9.wav"); break;
      case 10: audio.stopRecording("10.wav"); break;
    }
  }
}

```

NEW CODE - poor quality audio

```
//////////////////////////////////////// SD CARD
#include <SD.h>
#include <SPI.h>
#include <TMRpcm.h>
#define SD_ChipSelectPin 10
TMRpcm audio;
//////////////////////////////////////// SWITCH CASE
unsigned int i = 0;     // # of recording
unsigned long d = 0;
bool recmode = 0;      // recording state
//////////////////////////////////////// SWITCH
int inPin = 2;         // input Switch Pin
int state = HIGH;      // the current state switch
int reading;           // the current reading from the switch

void setup() {
  //Serial.begin(9600);
  pinMode(A0, INPUT);  // Microphone
  pinMode(inPin, INPUT_PULLUP); // Switch
  //////////////////////////////////////// SD CARD
  SD.begin(SD_ChipSelectPin);
  audio.CSPin = SD_ChipSelectPin;
}

void loop() {
  char buffer[50];
  sprintf(buffer, "%i.wav", i++);
  reading = digitalRead(inPin);
  ////////////////////////////////////////
  while (d < 300000) {
    d++;
  }
  d = 0;
  ////////////////////////////////////////
  if (reading == LOW) {
    if (recmode == 0) {
      recmode = 1;

      //Serial.println("Recording");

      audio.startRecording(buffer, 1600, A0);
      //Serial.println(buffer);
    }
  }
  ////////////////////////////////////////
  else if (reading == HIGH) {
    recmode = 0;

    //Serial.println("Hung-Up");

    audio.stopRecording(buffer);
  }
}

```

# Answer
Old code:

```
audio.startRecording("1.wav", 16000, A0);

```

New code:

```
audio.startRecording(buffer, 1600, A0);

```

Spot the typo?
> 2 votes

---
Tags: arduino-uno, programming, library, sketch, code-review
---


# Question
Title: comprehensive list of common library methods that do not work in interrupt service routines
Where is a comprehensive and authoritative list of commonly used library or built-in methods (functions) that do not work properly in Arduino interrupt service routines?

I am aware of the following:

* do not use delay()
* do not use Serial print methods

which are part of Nick Gammon's advice linked here. His TLDR summary is:

> TL;DR :
>
> When writing an Interrupt Service Routine (ISR):
>
> ```
> Keep it short
> Don't use delay ()
> Don't do serial prints
> Make variables shared with the main code volatile
> Variables shared with main code may need to be
>             protected by "critical sections" (see below)
> Don't try to turn interrupts off or on
>
> ```

however, I am looking for, as I said, a list that is more comprehensive and authoritative.

# Answer
> ... that do not work properly in Arduino interrupt service routines ...

A much safer approach would be to ask what **does** work properly in an ISR. Considering that my advice was to "keep it short" that would tend to exclude calling *any* functions except ones which are known to be OK. For example, calling `millis()` or `micros()` to find out the current timer values would be OK (bearing in mind that the figures returned by `millis()` will not increment).

Anything complex enough to be placed in a library would tend to be excluded simply based on that, in my opinion, unless *specifically documented otherwise*.

So, I wouldn't try to write files, do serial output, do I2C output, drive motors, etc.

Really, what an ISR should be doing is one or more of:

* Setting a flag (eg. "key has been pressed")
* Note the time (eg. "Pulse received at this moment")
* Retrieve some value (eg. what number is in a timer register)

Then the main code, not in an ISR, does something lengthier with that data.

The other thing to be concerned about is: *Is a function re-entrant?*

Just as an example, if you are doing `strcpy` in an ISR, is the `strcpy` function coded to be re-entered? (I don't know the answer just now). If it is not re-entrant, and you happen to be doing a `strcpy` in the main code, and the ISR also does a `strcpy` then one of them will be corrupted.

---

In terms of getting a comprehensive list, that would be almost impossible. Some libraries are no longer maintained. Others might be maintained but change from one month to the next, and the change might affect how they work inside an ISR. This is like the question people ask about "which libraries use which timers or pins?". These questions are difficult or impossible to adequately answer.
> 2 votes

# Answer
The basic rule is quite simple, but the list is practically impossible to produce.

The rule is:

* You cannot use anything that relies on an interrupt to function from within an interrupt service routine.

AVR chips only have one interrupt priority. Only one interrupt routine can function at a time. If an interrupt fires whilst an ISR is currently executing that interrupt will be delayed until the ISR finishes. If that ISR relies on a function that itself needs an ISR to fire (such as `millis()`, or serial transmission), then it will never get to finish.

A partial list of things to know:

* You cannot transmit serial more than there is room in the TX buffer for, or it blocks.
* The time generated by `millis()` (which `delay()` relies on) never changes.
* Servo motors cannot be controlled and will *jitter* if an interrupt routine takes too long.
* `tone()` generated sounds will also jitter since the ISR is delayed while another ISR is executing

And basically anything else that uses interrupts.
> 3 votes

---
Tags: interrupt
---


# Question
Title: SIlly PID question using the PID library
I'm new to PID. My goal: control the motor to get it to run a given RPM by a potmeter (which is setpoint). Sensor is optical (detects white line, reflections), counts 100 round in x amount of time. Small calculation gives detected RPM. I'm using an Arduino and the PID library.

Now my question. Let's say I've implemented the PID lib on the arduino. It all calculates and so on, but it gives a PID\_value which I don't understand.

Ex: setpoint = 5000 detected = 4999 received PID value = 40

It's my guess that this (or rather: all) PID-lib I'm using always gives a value between 0 and 255 and I have to map/scale that value to my AC trigger. Could someone point me in the right direction? Thanks!

# Answer
See PID Library - SetOutputLimits() \- you can change the limits.

For a meaningful result you need to make the output do something reasonable to the speed. Since your detected speed is lower than the desired speed, you have found it outputs a positive value, which is good, as far as it goes. But you have to interpret that in the context of what you are currently sending to the motor. If you are using PWM to control the motor you could feed the output (40 in this case) to the motor. If that makes it go even slower hopefully the PID library will compensate.

It's hard to make more suggestions without seeing the code.
> 1 votes

---
Tags: arduino-uno, pid
---


# Question
Title: esp32 spi library, how read a mcp23s08 register
thanks for any help I need to read a gpio expander mcp23s08 set as 8 bits input. my code write correctly (I believe) the setup register using SPI library, with the enclosed example modified. But I do not understand how read a gpio register (0x09) code (with the read out routine wrong:

```
#define GPIO_SEL_pin 14                         // D14 = MCP23S08 GPIO SPI select pin
#define SCLK 18                                 // D18 SPI SCLK
#define MISO 19                                 // D19 SPI MISO
#define MOSI 23                                 // D23 SPI MOSI

#include <SPI.h>

uint8_t keyboard;

static const int spiClk = 1000000; // 1 MHz

//uninitalised pointers to SPI objects
SPIClass * mcp23s08 = NULL;

void setup() {
  Serial.begin(115200);
  pinMode(GPIO_SEL_pin, OUTPUT);                     //MCP23S08 SPI select pin
  digitalWrite(GPIO_SEL_pin, HIGH);                  //pull ss high to disable data transfer
  mcp23s08 = new SPIClass(VSPI);
  mcp23s08->begin(SCLK, MISO, MOSI, GPIO_SEL_pin);   //SCLK, MISO, MOSI, SS
  mcp23s08SetUp();
  delay(1);

}

void loop() {
  keyboard = mcp23s08Read();
  Serial.println (keyboard);
  delay(100);
}

// ================================== routines =================================
void mcp23s08SetUp( void ) {
  uint8_t dev_adr  = 0x40;                          // MCP23S08 address 0; R/W = write
  uint8_t reg_adr  = 0x00;                          // MCP23S08 IODIR register
  uint8_t reg_data = 0xFF;                          // pin configured as input

  digitalWrite(GPIO_SEL_pin, LOW);                 //pull SS slow to prep other end for transfer
// ============================= MCP3S08 pin as input ==============================
  mcp23s08->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
  mcp23s08->transfer(dev_adr);
  mcp23s08->transfer(reg_adr);
  mcp23s08->transfer(reg_data);
  mcp23s08->endTransaction();

  reg_adr  = 0x01;                                 // MCP23S08 IPOL register
  reg_data = 0xFF;                                 // invert input polarity
// ============================= MCP3S08 invert input ==============================
  mcp23s08->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
  mcp23s08->transfer(dev_adr);
  mcp23s08->transfer(reg_adr);
  mcp23s08->transfer(reg_data);
  mcp23s08->endTransaction();

  reg_adr  = 0x06;                                 // MCP23S08 GPPU pull-up register
  reg_data = 0xFF;                                 // set pull-up register
// ============================= MCP3S08 pullup resistor ==============================
  mcp23s08->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
  mcp23s08->transfer(dev_adr);
  mcp23s08->transfer(reg_adr);
  mcp23s08->transfer(reg_data);
  mcp23s08->endTransaction();

  digitalWrite(GPIO_SEL_pin, HIGH);                //pull ss high to signify end of data transfer
}

uint8_t mcp23s08Read ( void ) {
  uint8_t dev_adr  = 0x41;                          // MCP23S08 address 0; R/W = read
  uint8_t reg_adr  = 0x09;                          // MCP23S08 GPIO register
  uint8_t reg_data;                                 // GPIO register
  mcp23s08->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
  mcp23s08->transfer(dev_adr);
  mcp23s08->transfer(reg_adr);
  reg_data = mcp23s08->transfer(0x00);
  mcp23s08->endTransaction();
  return reg_data;
}

```

# Answer
You forgot to toggle SS pin in `mcp23s08Read()` function.

```
 uint8_t mcp23s08Read ( void ) {
      ----> digitalWrite(GPIO_SEL_pin, LOW);                 //pull SS slow to prep other end for transfer
      uint8_t dev_adr  = 0x41;                          // MCP23S08 address 0; R/W = read
      uint8_t reg_adr  = 0x09;                          // MCP23S08 GPIO register
      uint8_t reg_data;                                 // GPIO register
      mcp23s08->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
      mcp23s08->transfer(dev_adr);
      mcp23s08->transfer(reg_adr);
      reg_data = mcp23s08->transfer(0x00);
      mcp23s08->endTransaction();
      ----> digitalWrite(GPIO_SEL_pin, HIGH);                //pull ss high to signify end of data transfer
      return reg_data;
    }

```
> 0 votes

---
Tags: pins, spi, esp32
---


# Question
Title: How to stop Arduino from drawing power through USB
I'm working on an embedded project, where I use arduinos as a "sensor shield" for RaspberryPi (I have model B).

The problem is, that the RaspberryPi's USB port is not powerfull enough to drive WiFi adapter and arduino with sensors. The solution is easy, I will power the sensors externally, not through the RPi.

But I was wondering, **is it possible to power whole Arduino externally (through Vin) and use the USB only for serial communication.**

To clarify, I know how to solve my problem - use some other mean of communication, than USB - GPIO serial, I2C, wireless, etc... I'm just interested if the whole thing will work, with USB cable which has 5V lead cut, for example.

The main issue I can see with this is, that the USB\<-\>Serial chip is powered through USB only, then it will now work.

# Answer
> 8 votes
If you provide power to the Arduino through `Vin` this will disconnect USB power through the MOSFET switch.

# Answer
> 2 votes
There are a couple of alternative solutions to the question that I think are worth mentioning.

1. Use a data only USB cable or manually cut the VCC and GND wires of the cable.
2. Remove the USB poly fuse from the arduino board.
3. Connect external power to one of the input pins to measure the voltage. This measurement can then be used to determine if the external power is connected and is providing sufficient voltage. If it does the USB power should not be use anyways, otherwise an if statement can be used to disable the code that turns devices that draw power. USB power will still be used to power the arduino board itself. It also has a limitation in that because the power supply could provide insufficient current it could draw the remaining required current from USB.

# Answer
> 0 votes
**Just cut the *`VCC`* line (usually *red*) in the USB cable.**

---

There are four wires in a USB cable:

* Ground
* VCC
* Data +
* Data -

You cannot send data along without a reference ground as you need a potential difference. Hence you must keep the ground connected and just snip the power line (red *`VCC`*).

---

Note that this is **not** usually necessary as ***`VIN`* is favoured over *USB* power**.

---
Tags: power, usb
---


# Question
Title: Differences between nodemcu and arduino processer
I have an arduino Uno and nodemcu development board.

I have an OV7076 camera and used with arduino UNO. It worked flawlessly with it and the code used is provided in the \[Instructables tutorial\]\[2\] named as FromComputerNerd.ino.

Now i want to use it with Nodemcu. Whereas Nodemcu have a single Analog input but OV7076 uses two analog inputs \[shown in\]\[2\]. So to get it I am trying to use Multiplexer. I can change the code so that it would adjust for analog pins.

But will the code be compatible with Nodemcu. Since it was written for arduino uno.If not, What changes can be done to make it compatible?

http://www.instructables.com/id/OV7670-Without-FIFO-Very-Simple-Framecapture-With-/

# Answer
> 1 votes
Camera doesn't send data via Analog to Arduino. A5 and A4 are I2C bus beside Analog.

NodeMCU has Software I2C protocol bus too, You can use D1 (GPIO 5) as CLK, and D2 (GPIO 4) as SDA.

see : https://github.com/esp8266/Arduino/blob/master/doc/libraries.rst#i2c-wire-library

# Answer
> 0 votes
I am suggesting you to buy NodeMCU because it is having inbuilt WIFI, you can connect NodeMcu to internet without much effort compare to connecting UNO to internet, and the best thing is NodeMCU is arduino compatible you can do all possible stuff that can be done with UNO. We can also program NodeMCU in 'C' language using Arduino IDE directly

**Hardware comparison**

*NodeMCU*

1. 128KB RAM
2. 4MBytes ROM(flash)
3. micro USB port
4. Small Board Size

*Arduino UNO*

1. 2kB RAM
2. 32 KB ROM
3. USB type B connector
4. Bigger in size than NodeMCU

> Both are having nearly same prices.

---
Tags: arduino-uno, nodemcu
---