# Question
Title: Can a Arduino Uno handle all these components?
Its my first project with an Arduino, so please bear with the dumb questions.

For this project of mine, I need an Ultrasonic Sensor, a Gyroscope, a Buzzer, three push buttons and an 16x2 LCD.

Can I connect all these components at once to an Arduino Uno? I mean will I run out of pins or not? Should I go for a Mega 2560 (will have to buy one though).

Edit: a GSM sim800 as well lol

# Answer
I think you're fine depends on the gyroscope model and lcd. -For ultrasonic sensor thats 2 pins -the lcd needs at least 6pins but with an i2c adapter you only need 2 pins -3 push buttons 3 pins -one pin for the buzzer Plenty of room left on the uno
> 1 votes

---
Tags: arduino-uno, sensors, button, buzzer
---


title: MFRC522: Firmware Unknown

text:
# Question
Title: MFRC522: Firmware Unknown
Can someone help me what is the meaning of this sketch? It always outputs in the serial monitor:

```
Firmware Version: 0x1C = (unknown)
Scan PICC to see UID, SAK, type, and data blocks...

```

This is the code of the MFRC522 library I use:

```
#include <SPI.h>
#include <MFRC522.h>

constexpr uint8_t RST_PIN = 9;          // Configurable, see typical pin layout above
constexpr uint8_t SS_PIN = 10;         // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

void setup() {
   Serial.begin(9600);   // Initialize serial communications with the PC
   while (!Serial);    // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
   SPI.begin();      // Init SPI bus
   mfrc522.PCD_Init();   // Init MFRC522
   mfrc522.PCD_DumpVersionToSerial();  // Show details of PCD - MFRC522 Card Reader details
   Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
}

void loop() {
   // Look for new cards
   if ( ! mfrc522.PICC_IsNewCardPresent()) {
     return;
   }

   // Select one of the cards
   if ( ! mfrc522.PICC_ReadCardSerial()) {
     return;
   }

   // Dump debug info about the card; PICC_HaltA() is automatically called
   mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
}

```

# Answer
> 1 votes
The mention of `unknown` in the output line:

```
Firmware Version: 0x1C = (unknown)

```

isn't a good sign.

Run the `firmware_check` example to verify that first, before trying to run other code.

The `unknown` is output by line 1302 of MFRC522.cpp:

```
    default:   Serial.println(F(" = (unknown)"));

```

The `firmware_check` example states on line 49:

```
  Serial.println(F("Only known versions supported"));

```

So, your hardware (i.e. the reader) *may* not be supported.

The only thing I can suggest is try another reader. Also, read the README, there maybe some thing there, or contact the author and/or raise an issue to see if you can get support for your version of the firmware (`0x1C`) added.

# Answer
> 0 votes
Put a `delay(5)` after

```
mfrc522.PCD_Init();   // Init MFRC522

```

and it will show the correct firmware version.

---
Tags: arduino-uno, rfid
---


# Question
Title: Power Arduino controlled by another Arduino by MOSFET
I would like to control power to Arduino B from signal of digital pin from Arduino A.

I use IRFZ44N MOSFET as switch and +12V DC source. The Arduinos have common ground. The connection is:

* Gate: signal from Arduino A (+5V or 0V)
* Source: +12V
* Drain: Vin of Arduino B

At this settings Arduino B is powered regardless of the value on the gate. What am I doing wrong and how should I change the settings to get the desired result? I know I misunderstand how the transistor works, please show me the correct approach.

# Answer
> 3 votes
You have an N-channel MOSFET. That is not suitable for switching the 12V supply of an Arduino.

Instead you need a P-channel MOSFET which has the gate pulled up to 12V using a resistor, and then an N-channel logic level MOSFET which is used by the Arduino to pull the gate of the P-channel MOSFET LOW to turn it on.

Something like:

simulate this circuit – Schematic created using CircuitLab

When the GPIO is HIGH it turns M2 on. This pulls the gate of M1 down, turning it on. When GPIO is LOW, or not actively being driven (thus being pulled down by R2), M2 is off. This allows the gate of M1 to be pulled up to +12V by R1, switching M1 off.

---
Tags: power, mosfet
---


title: RF522 version 0x12

text:
# Question
Title: RF522 version 0x12
I bought a bunch of the common RC522 boards from some AliExpress vendor. They (I tried multiple) seem to work at the register read-write level, but they don't seem to execute commands, much less recognise any RFID card.

But the really weird thing is that the version returns 0X12, which matches neither the rc522 1.0, nor the 2.0, nor the clone that should return 0x88.

I verified with my scope that the chip indeed answers to the SPI byte 1110\_1110 (read register 0x37) with the value 0001\_0010. The signal is crip, no clock skew, nice sharp edges.

I tried this with an Arduino Uno and an Arduino Due, using a recent version of the miguelbalboa library. But as I see this on my scope, it can't see how it can be a software problem.

Has anyone seen this, or better: found a solution?

# Answer
> 0 votes
Put a `delay(5)` right after `init()` in `setup()` and firmware readout will work.

---
Tags: sensors
---


title: 6 channel PWM with 2 - 5 kHz frequency

text:
# Question
Title: 6 channel PWM with 2 - 5 kHz frequency
Is it possible to set all 6 PWM frequencies to a value between 2 and 5 kHz?

I've read that the base frequency for pins pins 5 and 6 is 62500 Hz. And the divisors for the pins 5 and 6 are only this ones: 1, 8, 64, 256, and 1024.

The closest I can get is 7.812,5 Hz with the 8 divisor. Are there any other possibilities to achieve this?

# Answer
> 2 votes
Judging from your mentioning 62.5 kHz as the base frequency for pins 5 and 6, I assume you are talking about an Arduino Uno or something similar.

If you set the timer 0 to phase correct PWM mode (which is how the Arduino core configures the other timers), then its base frequency is about 31.373 kHz (`F_CPU`/510). With the prescaler set to 8, you get a PWM frequency of about 3.922 kHz on pins 5 and 6.

Note that you can set all three timers in this mode and have 6 PWM channels at this frequency. But note also that by reconfiguring Timer 0 you loose all the standard Arduino timing functions.

---
Tags: pwm, frequency
---


# Question
Title: 2 analog sensors, pulse sensor and LM35 problem
I make a project in which I use two analog sensors. A pulse sensor and the LM35 temperature sensor. When I use them separated everything is normal,the codes are fine, when I combine them the lm35 is not precise, has an error margin of about 10 degrees but the pulse sensor seems to be ok. I read something about the analog to digital convertor that Arduino have and need a delay or something to trick the ADC. I would be grateful if somebody help me to modify the code. Thank you very much!

```
#include <LiquidCrystal.h>
#include <TonePlayer.h>

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int pulsePin = A0;                 // Pulse Sensor purple wire connected to analog pin A0
int blinkPin = 13;                // pin to blink led at each beat

const int sensor=A5; // Assigning analog pin A5 to variable ‘sensor’ temperature
float tempc;
float vout; //temporary variable to hold sensor reading

TonePlayer tone1 (TCCR1A, TCCR1B, OCR1AH, OCR1AL, TCNT1H, TCNT1L);  // pin D9 (Uno), D11 (Mega)

// Volatile Variables, used in the interrupt service routine!
volatile int BPM;                   // int that holds raw Analog in 0. updated every 2mS
volatile int Signal;                // holds the incoming raw data
volatile int IBI = 600;             // int that holds the time interval between beats! Must be seeded!
volatile boolean Pulse = false;     // "True" when User's live heartbeat is detected. "False" when not a "live beat".
volatile boolean QS = false;        // becomes true when Arduoino finds a beat.

static boolean serialVisual = true;   // Set to 'false' by Default.  Re-set to 'true' to see Arduino Serial Monitor ASCII Visual Pulse

volatile int rate[10];                      // array to hold last ten IBI values
volatile unsigned long sampleCounter = 0;          // used to determine pulse timing
volatile unsigned long lastBeatTime = 0;           // used to find IBI
volatile int P = 512;                      // used to find peak in pulse wave, seeded
volatile int T = 512;                     // used to find trough in pulse wave, seeded
volatile int thresh = 525;                // used to find instant moment of heart beat, seeded
volatile int amp = 100;                   // used to hold amplitude of pulse waveform, seeded
volatile boolean firstBeat = true;        // used to seed rate array so we startup with reasonable BPM
volatile boolean secondBeat = false;      // used to seed rate array so we startup with reasonable BPM

void setup() {

  pinMode(blinkPin,OUTPUT);         // pin that will blink to your heartbeat!
  pinMode (9, OUTPUT);  // output pin is fixed (OC1A)

  Serial.begin(115200);             // we agree to talk fast!
  interruptSetup();                 // sets up to read Pulse Sensor signal every 2mS
                                    // IF YOU ARE POWERING The Pulse Sensor AT VOLTAGE LESS THAN THE BOARD VOLTAGE,
                                    // UN-COMMENT THE NEXT LINE AND APPLY THAT VOLTAGE TO THE A-REF PIN

  pinMode(sensor,INPUT); // Configuring pin A1 as input                             //   analogReference(EXTERNAL);

  lcd.begin(16, 2);
  lcd.clear();
}

//  Where the Magic Happens
void loop() {
  serialOutput();
  if (QS == true) { // A Heartbeat Was Found
    // BPM and IBI have been Determined
    // Quantified Self "QS" true when arduino finds a heartbeat
    serialOutputWhenBeatHappens(); // A Beat Happened, Output that to serial.
    QS = false; // reset the Quantified Self flag for next time

    vout=analogRead(sensor);
    vout=(vout*500)/1023;
    tempc=vout; // Storing value in Degree Celsius

    Serial.print ("Temperatura: ");
    Serial.print(tempc);
    Serial.println(" C ");

  }
  delay(20); //  take a break
}

void interruptSetup() {
  // Initializes Timer2 to throw an interrupt every 2mS.
  TCCR2A = 0x02;     // DISABLE PWM ON DIGITAL PINS 3 AND 11, AND GO INTO CTC MODE
  TCCR2B = 0x06;     // DON'T FORCE COMPARE, 256 PRESCALER
  OCR2A = 0X7C;      // SET THE TOP OF THE COUNT TO 124 FOR 500Hz SAMPLE RATE
  TIMSK2 = 0x02;     // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A
  sei();             // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
}

void serialOutput() {   // Decide How To Output Serial.
 if (serialVisual == true){
     arduinoSerialMonitorVisual('-', Signal);   // goes to function that makes Serial Monitor Visualizer
  } else{
      sendDataToSerial('S', Signal);     // goes to sendDataToSerial function
   }
}

void serialOutputWhenBeatHappens() {
 if (serialVisual == true) { //  Code to Make the Serial Monitor Visualizer Work

     Serial.print("Batai ");  //ASCII Art Madness
     Serial.print("BPM: ");
     Serial.println(BPM);
     lcd.print("Batai ");
     lcd.setCursor(6,0);
     lcd.print("BPM: ");
     lcd.setCursor(10,0);
     lcd.print(BPM);

     lcd.setCursor(0,1);
     lcd.print("Temp: ");
     lcd.setCursor(6,1);
     lcd.print(tempc);
     lcd.setCursor(11,1);
     lcd.print("C ");

     delay(300);
     lcd.clear();
   } else {
     sendDataToSerial('B',BPM);   // send heart rate with a 'B' prefix
     sendDataToSerial('Q',IBI);   // send time between beats with a 'Q' prefix
   }
}

void arduinoSerialMonitorVisual(char symbol, int data ) {
  const int sensorMin = 0;      // sensor minimum, discovered through experiment
  const int sensorMax = 1024;    // sensor maximum, discovered through experiment
  int sensorReading = data; // map the sensor range to a range of 12 options:
  int range = map(sensorReading, sensorMin, sensorMax, 0, 11);
  // do something different depending on the
  // range value:
}

void sendDataToSerial(char symbol, int data ) {
   Serial.print(symbol);
   Serial.println(data);
}

ISR(TIMER2_COMPA_vect) { //triggered when Timer2 counts to 124

  cli();                                      // disable interrupts while we do this
  Signal = analogRead(pulsePin);              // read the Pulse Sensor
  sampleCounter += 2;                         // keep track of the time in mS with this variable
  int N = sampleCounter - lastBeatTime;       // monitor the time since the last beat to avoid noise
                                              //  find the peak and trough of the pulse wave
  if(Signal < thresh && N > (IBI/5)*3) { // avoid dichrotic noise by waiting 3/5 of last IBI
    if (Signal < T) { // T is the trough
      T = Signal; // keep track of lowest point in pulse wave
    }
  }

  if(Signal > thresh && Signal > P) {       // thresh condition helps avoid noise
    P = Signal;                             // P is the peak
  }                                        // keep track of highest point in pulse wave

  //  NOW IT'S TIME TO LOOK FOR THE HEART BEAT
  // signal surges up in value every time there is a pulse
  if (N > 250) {                                   // avoid high frequency noise
    if ( (Signal > thresh) && (Pulse == false) && (N > (IBI/5)*3) ) {
        Pulse = true;                               // set the Pulse flag when we think there is a pulse
        digitalWrite(blinkPin,HIGH);                // turn on pin 13 LED
        tone1.tone (1000);  // 1000 Hz

        IBI = sampleCounter - lastBeatTime;         // measure time between beats in mS
        lastBeatTime = sampleCounter;               // keep track of time for next pulse

        if(secondBeat) {                        // if this is the second beat, if secondBeat == TRUE
          secondBeat = false;                   // clear secondBeat flag
          for(int i=0; i<=9; i++) { // seed the running total to get a realisitic BPM at startup
            rate[i] = IBI;
          }
        }

        if(firstBeat) { // if it's the first time we found a beat, if firstBeat == TRUE
          firstBeat = false;                   // clear firstBeat flag
          secondBeat = true;                   // set the second beat flag
          sei();                               // enable interrupts again
          return;                              // IBI value is unreliable so discard it
        }
      // keep a running total of the last 10 IBI values
      word runningTotal = 0;                    // clear the runningTotal variable

      for(int i=0; i<=8; i++) {                 // shift data in the rate array
          rate[i] = rate[i+1];                  // and drop the oldest IBI value
          runningTotal += rate[i];              // add up the 9 oldest IBI values
        }

      rate[9] = IBI;                          // add the latest IBI to the rate array
      runningTotal += rate[9];                // add the latest IBI to runningTotal
      runningTotal /= 10;                     // average the last 10 IBI values
      BPM = 60000/runningTotal;               // how many beats can fit into a minute? that's BPM!
      QS = true;                              // set Quantified Self flag
      // QS FLAG IS NOT CLEARED INSIDE THIS ISR
    }
  }

  if (Signal < thresh && Pulse == true) {    // when the values are going down, the beat is over
      digitalWrite(blinkPin,LOW);            // turn off pin 13 LED
      tone1.noTone ();
      Pulse = false;                         // reset the Pulse flag so we can do it again
      amp = P - T;                           // get amplitude of the pulse wave
      thresh = amp/2 + T;                    // set thresh at 50% of the amplitude
      P = thresh;                            // reset these for next time
      T = thresh;
    }

  if (N > 2500) {                          // if 2.5 seconds go by without a beat
    thresh = 512;                          // set thresh default
    P = 512;                               // set P default
    T = 512;                               // set T default
    lastBeatTime = sampleCounter;          // bring the lastBeatTime up to date
    firstBeat = true;                      // set these to avoid noise
    secondBeat = false;                    // when we get the heartbeat back
  }
  sei();                                   // enable interrupts when youre done!
}// end isr

```

# Answer
I have a couple of suggestions:

The combined code is very different from the simple LM35 code that works. I'd suggest you start with the combined code but comment out everything that doesn't directly apply to reading the LM35, and get that working correctly.

The interrupt service routine (ISR) is trying to do too much, and leaves the interrupts off during all of those calculation. Plus, its hard to debug code inside an ISR! ISRs should do the *minimum work that they have to do*. In this case, it looks like it needs to read & save the pulse sensor value and do the `N`, `lastBeatTime`, and `sampleCounter` calculation. Have it also set a flag every time it runs.

The main loop should check that flag, and if it is set, clear it and call another function to do everything you took out of the ISR. Debug this code, perhaps with the LM35 commented out.

Ideally your `loop()` function should be as simple as:

```
void loop(){
   Timers.run();
   maybeCalcHeartbeat();
   maybeDoOtherSubtask();
   ...
}

```

Then the rest of your code goes into "maybeDo" functions. A "maybeDo" just decides whether the time or conditions are right to do a particular thing; if so, the function does it; but in any case, it returns quickly:

```
void maybeCalcHeartbeat(void){
   if( !isrFlag )
      return;
   else {
      // everything you took out of the ISR goes here //

      isrFlag = false;
   }

```
> 2 votes

---
Tags: sensors, temperature
---


# Question
Title: Arduino only works properly when I'm touching it
I'm working on a arduino proyect, but I encountered a problem that I dont know how to solve.

The only thing I have done in the hardware part is connect the arduino nano to a power source (phone charger) through the 5v and Ground pins, but the built-in leds tell me that the code isn't running as it should be.
The TX led (Serial output) should be constantly on (because the code is always printing out things to the monitor), but instead it turns on and off in a longer interval of time, the code is running slower than it should be.
This stops when I touch ground with my finger or when the arduino is connected to a computer.

When I searched for a solution I found that most of the time this problem was related to missing connections to ground, and here seems to be the same, but the only thing I have connected is the arduino.

Any idea of what's happening and how to solve it?

To give more context, what I'm trying to do is a thermostat that can take a value of temperature and time, and turn on or off a relay. This relay is the one that opens or closes the electrical circuit of the lab's stove depending on the temperature and the time.
There are 4 buttons:
AUMENTAR ("increase" in english): increases the value selected in 5 (when pressed has a delay of 0.5 seconds).
DISMINUIR ("decrease"): decreases the value selected in 5 (when pressed has a delay of 0.5 seconds).
SIGUIENTE ("next"): changes the value you are editing (has no delay).
INI\_DET ("start/stop"): starts or stops the machine (has no delay).

Code:

```
#include <max6675.h>
#include <LiquidCrystal.h>

//
// VARIABLES
//

// Machine's phisical state
int temperatura = 0; // en °C
int temperatura_prev;
// int humedad;
bool maquina_en_funcionamiento = false;

// User's variables (con la maquina no funcionando)
int array_de_valores[] = {20,10};     // valores editables por el usuario
int valor_seleccionado = 0;             // valor que se esta editando (por defecto, temperatura): 0=Temperatura, 1=Tiempo, 2=Humedad
// Variables visibles para el usuario (con la maquina funcionando)
int array_de_opciones[] = {0, 0};       // opciones visibles para el usuario
int opcion_seleccionada = 0;            // opcion visible (por defecto, maquina): 0=Maquina, 1=Operacion

// Process' variables
int temp_bus, tiempo_bus, hum_bus;  // copias de array_de_valores que se mantendran fijas hasta el final del proceso
int reloj = 0;                      // tiempo transcurrido en minutos desde que comenzo el proceso
int reloj_prev;
unsigned long reloj_milis;          // tiempo transcurrido en milisegundos desde que comenzo el proceso
unsigned long inicio_milis;         // milisegundos al comienzo de la operacion
int tiempo_restante;
bool resistencia_en_funcionamiento = false; // estado actual de la resistencia (por defecto, apagada)

// Phisical components
LiquidCrystal lcd(6,7, 2,3,4,5);
MAX6675 sensor_temp(16,15,14);
#define RELE 13
  // botones
#define AUMENTAR 8 // Aumentar valor
#define DISMINUIR 9 // Disminuir valor
#define SIGUIENTE 10 // Cambiar valor
bool sig_pres = false;
#define INI_DET 11 // Iniciar o Detener maquina
bool ini_det_pres = false;

//
// FUNCTIONS
//

// Funciones para control de lcd
void actualizarLCD() {
  if (!maquina_en_funcionamiento) { // si la maquina no esta en funcionamiento
    switch (valor_seleccionado){
      case 0: // temperatura
        lcd.home();
        lcd.print("»TEMP TIEMPO HUM");
        lcd.setCursor(5,1);
        lcd.print(array_de_valores[0]);
        lcd.setCursor(8,1);
        lcd.print("°C");
        break;
      case 1: // tiempo
        lcd.home();
        lcd.print(" TEMP»TIEMPO HUM");
        lcd.setCursor(5,1);
        lcd.print(array_de_valores[1]);
        lcd.setCursor(8,1);
        lcd.print("min");
        break;
      case 2: // humedad
        lcd.home();
        lcd.print(" TEMP TIEMPO»HUM");
        lcd.setCursor(5,1);
        lcd.print(array_de_valores[2]);
        lcd.setCursor(8,1);
        lcd.print("%");
        break;
    }
  }
  else { // si la maquina esta en funcionamiento
    switch (opcion_seleccionada){
      case 0:
        lcd.home();
        lcd.print("»MAQUINA  OPERAC");
        lcd.setCursor(0,1);
        lcd.print("TEMP");
        lcd.setCursor(5,1);
        lcd.print(temperatura);
        lcd.setCursor(9,1);
        lcd.print("TIE");
        lcd.setCursor(13,1);
        lcd.print(tiempo_restante);
        break;
      case 1:
        lcd.home();
        lcd.print(" MAQUINA »OPERAC");
        lcd.setCursor(0,1);
        lcd.print("TEMP");
        lcd.setCursor(5,1);
        lcd.print(temp_bus);
        lcd.setCursor(9,1);
        lcd.print("TIE");
        lcd.setCursor(13,1);
        lcd.print(tiempo_bus);
        break;
    }
  }
}

// Funciones de variables editables por el usuario
void aumentarValor(int cantidad) {
  array_de_valores[valor_seleccionado] += cantidad;
  actualizarLCD();
}
void cambiarValor(){
  switch (valor_seleccionado){
    case 0:
      valor_seleccionado = 1;
      break;
    case 1:
      valor_seleccionado = 2;
      break;
    case 2:
      valor_seleccionado = 0;
      break;
  }
  actualizarLCD();
}

// Funciones de control de proceso
void iniciarResistencia() {
  digitalWrite(RELE, HIGH);
  resistencia_en_funcionamiento = true;
}
void detenerResistencia() {
  digitalWrite(RELE, LOW);
  resistencia_en_funcionamiento = false;
}

void iniciarProc() {
  // realizar una copia de los valores en array_de_valores
  temp_bus = array_de_valores[0];
  tiempo_bus = array_de_valores[1];
  inicio_milis = millis();

  // iniciar la maquina (cuando continue el ciclo)
  maquina_en_funcionamiento = true;

  actualizarLCD();
}
void detenerProc() {
  detenerResistencia();

  // borrar variables
  temp_bus = 0;
  tiempo_bus = 0;
  reloj_prev = 0;
  reloj_milis = 0;
  inicio_milis = 0;
  tiempo_restante = 0;

  maquina_en_funcionamiento = false;

  actualizarLCD();
}

//
// MAIN PROGRAM
//

void setup() {
  // codigo que se ejecuta una unica vez:
  Serial.begin(9600);
  Serial.println("INICIANDO PROGRAMA");

  // relay
  pinMode(RELE, OUTPUT);
  detenerResistencia();

  // buttons
  pinMode(AUMENTAR, INPUT);
  pinMode(DISMINUIR, INPUT);
  pinMode(SIGUIENTE, INPUT);
  pinMode(INI_DET, INPUT);

  //iniciar lcd
  lcd.begin(16,2);
  actualizarLCD();
}

void loop() { // codigo que se ejecuta en bucle:
  // buttons
  if (digitalRead(AUMENTAR) == HIGH) { // if button AUMENTAR is pressed
    if (!maquina_en_funcionamiento) {  // and the machine is not working
      aumentarValor(5);                // increase the value
      delay(500);                      // and wait
    }
  }
  else if (digitalRead(DISMINUIR) == HIGH) { // si se presiona el boton DISMINUIR
    if (!maquina_en_funcionamiento) {        // IDEM AUMENTAR
      aumentarValor(-5);
      delay(500);
    }
  }
  else if (digitalRead(SIGUIENTE) == HIGH) { // si se presiona el boton SIGUIENTE
    if (!sig_pres) {                         // verificar si no se lo presiono antes
      sig_pres = true;                       // poner la var sig_pres en true para bloquear el boton
      cambiarValor();                        // y cambiar la variable
    }
  }
  else if (digitalRead(INI_DET) == HIGH) {   // si se presiona el boton INI_DET
    if (!ini_det_pres) {                     // verificar si no se lo presiono antes
      ini_det_pres = true;                   // poner la var ini_det_pres en true para bloquear el boton
      if (!maquina_en_funcionamiento) {
        iniciarProc();
      }
      else {
        detenerProc();
      }
    }
  }

  if (digitalRead(SIGUIENTE) == LOW) {    // si el boton SIGUIENTE no esta siendo presionado
    if (sig_pres) {
      sig_pres = false;                   // desbloquear el boton
    }
  }
  if (digitalRead(INI_DET) == LOW) { // si el boton INI_DET no esta siendo presionado
    if (ini_det_pres) {
      ini_det_pres = false;               // desbloquear el boton
    }
  }

  // Some output of data to the Serial monitor
  Serial.print("Valor seleccionado: ");
  Serial.println(valor_seleccionado);
  Serial.print(array_de_valores[0]);
  Serial.print(", ");
  Serial.println(array_de_valores[1]);
  Serial.print("Maquina en funcionamiento: ");
  Serial.println(maquina_en_funcionamiento);

  // PROCESS CONTROL
  if(maquina_en_funcionamiento) {

    // TEMPERATURE CONTROL
    temperatura_prev = temperatura;
    temperatura = sensor_temp.readCelsius();

    if (temperatura >= temp_bus) { // si la temperatura es igual o exede la deseada
      detenerResistencia(); // apagar la resistencia
    }
    else { // si la temperatura es menor que la deseada
      if (!resistencia_en_funcionamiento) { // y la resistencia esta apagada
        iniciarResistencia();
      }
    }

    if (temperatura_prev != temperatura) {
      actualizarLCD();
    }

    // TIME CONTROL
    unsigned long milis_ahora = millis();
    milis_ahora -= inicio_milis;
    if ( (milis_ahora - reloj_milis) >= 1000){
      reloj_milis = reloj_milis + 1000;
    }

    reloj_prev = reloj;
    reloj = reloj_milis/60000;

    tiempo_restante = tiempo_bus - reloj;
    /*
    Serial.print("Reloj de milisegundos=");
    Serial.println(reloj_milis);
    Serial.print("Reloj=");
    Serial.println(reloj);
    Serial.print("Tiempo restante=");
    Serial.println(tiempo_restante);
    */
    if (reloj >= tiempo_bus) { // si se llego al tiempo deseado
      detenerProc(); // detener
    }

    if (reloj_prev != reloj) {
      actualizarLCD();
    }

  }
}

```

Thanks in advance.

# Answer
> 1 votes
> This stops when I touch ground with my finger or when the arduino is connected via USB to a computer.

It sure sounds like a grounding problem, probably between the PC and the Arduino. Try connecting the Arduino ground and the PC ground - my guess is that the problem goes away.

All of the electrical components in a system need to share the same ground for any communication to take place. It sounds like one of them might not.

Is either the PC or the charger plugged into the wall with an adapter that only carries two of the three wires? Usually each one will connect to ground side of the house circuit but if one of them doesn't ...

---
Tags: c++, arduino-nano, electronics
---


# Question
Title: What is this shield? (AST Space Arduino Kit)
I recently got a box with Arduino components from someone who didn't want it (in part, because the manual was (probably) in Chinese). However, to my surprise, I could not find this kit on the internet. I would like to know: **is this a copy of another kit?** Or, is there documentation available for this particular kit?

Box contents:

* Arduino Uno
* Unknow shield "by AST Space" with
    + AI-THINKER wi-fi module
    + Songle relais
    + YLB3641AH 4-digit LED display
    + DHT-11 relative humidity, temperature sensor
    + IR receivers, switches, microphone/buzzer, light sensor, connectors to the other components
* MPU6050 accelerometer
* HC-SR04 ultrasonic rangefinder
* QAPASS LCD unit
* "Car MP3" IR remote
* 2x green, 2x red LED, 5x resistor
* 17x10 green breadboard
* 2x DC motor, 1x geared stepper motor
* 40-wide female-female jumper ribbon cable
* USB connector cable (black)

It came in an intricate folding box, bright orange. The QR code links to http://weixin.qq.com/r/2kgtNVXEKwhUrRFW9x3I (which did not get me anywhere - visiting this link is at your own risk). Pictures:

# Answer
> 5 votes
My name is Bing Zhu. I the host of ASTSpace a community open lab sponsored by Zhejiang Association for Science and Technology(ZAST). AST is situated inside the Zhejiang Museum of Science and Technology. We are non-profit. The Kit you have gotten must be from someone got it free at one of ASTSpace's events. I remembered that we had brought some with us to the Manchester Science Festival where we did a tinkering activity for the public, 3 years ago. This kit was designed by one of our members who is currently a Ph.D. student of automation at Zhejiang University. It was developed for the purpose to increase public experiences in a 90 minutes session. Therefore, in order to shorten the time of wiring while most times participants with no backgrounds or exposures to electronics make no sense anyway, we purposely had most of the functioning parts soldered on. In this way, we think it would be more manageable as well for teaching as most times one instructor has to manage more than a room full of over 25 participants. Making sure that parts are connected and in place can be a life-saver. We had it designed this way so the kit can be used in classes by schools in remote areas. These kits are given away and the introduction sessions are free to the public, and we intended to provide online help to those who decide to venture on with this kit at their own time. But, it never took off for time and resource restriction. With this kit we have gone through two major cities in the Zhejiang Province and 4 remote rural areas. All our expenses are supported by ZAST through two projects, one to make it and one to distribute it. When we did what we did, it was always for the public to know electronic control and coding was made easy by Arduino where it was first invented by an Italian who wanted to teach artists electronics. This kit was used to demo how easily and readily everything can be controlled and through these electronics, we can take the parts of the physical world into our hands to follow our wills. We did use it to demo the on and off lighting system of the entire science center and controls of a remote camera inside the security room. So, ASTSpace Arduino kit is a tailor-made kit for a specific purpose. We did not change anything but redesigned the wiring of the sensors for easy use for our events.

# Answer
> 2 votes
AST stands for Art, Science and Technology. The learning kit is produced by AST Space who also run maker competitions.

# Answer
> 2 votes
I'm Xiaotian, the designer of this arduino learning Kit. We designed that for people who love DIY but without electronic backgrounds. In the past events, we found everybody (12-16 year old kids usually) could start wiring and coding and finish a little projects with the kit and its examples in 90 mins. All of hardware and software are modular, you could assembly them you want and make your great ideas real quickly. If you want to know more details about it, feel free to let me know. My email is xtchen@zju.edu.cn. Thanks for your attention!

Xiaotian

# Answer
> 1 votes
On http://astspace.org/ you can download a PDF related to this AST Space Kit\[rar archive\].

I took the schema in the PDF and translated in English. Looking at the examples (see below), it looks like the "Wifi Module" is an ESP8266.

The QR code in the PDF is actually readable, but you have to scan it in WeChat (a social platform that mixes chat, Instagram and shopping).

The QR code links to AST Space's account:

The download mentioned above contains schematics and sample code. Download that and you should have a much better understanding on how to use it.

---
Tags: arduino-uno, shields
---


title: "variable does not name a type

text:
# Question
Title: "variable does not name a type
Hey guys I'm getting an error that is im pretty sure to do with how i am initializing my variables. It is: exit status 1 'threshold' does not name a type

Here's my code:

```
//Global Variables for moving max:

int analogValues[100];
int ir=0;
int maxA0=0;
int threshold = 0;
//Global variables for moving max ^^

//Global Variables for moving average ECG:
const int no_averages = 2;

unsigned long time = 0, peak1 = 0, peak2 = 0;
int binaryrange, bpm, i=0; //not sure what i does tbh
int readings[no_averages]; // the readings from the analog input
int readIndex = 0; // the index of the current reading
int total = 0; // the running total
int average = 0; // the average which we will display as ECG

void setup() {
// initialize serial communication with computer:
Serial.begin(115200);
// initialize all the readings to 0:
for (int thisReading = 0; thisReading < no_averages; thisReading++) {
readings[thisReading] = 0;
}

//set moving max shit to zero
  for (int is = 0; is < 100; is++) {
analogValues[is]=0;
  }
}

void loop() {
  //int maxA0=0; //Whether I intitate the variables here or globally, same error
  //int threshold = 0;
time = millis();

average=0;
readings[readIndex] = analogRead(A0);
readIndex++;
for (int ir=0; ir < no_averages; ir++) {
  average = average + readings[ir];
}
if (readIndex >= no_averages) {    // ...wrap around to the beginning of array if it has hit the end:
readIndex = 0;
}
average = average/no_averages;
if (average>1000) {
  average = 600;
}
Serial.print(average);

analogValues[ir]=average;
ir++;
if (ir>=100) {
  ir=0; } //This is to roll back to the start of the array if it surpasses the 100th array spot
for (int is = 0; is < 100; is++) {
 if (analogValues[is]>analogValues[is-1])
 analogValues[is]=maxA0;
  }
}

//**************************

//This line with error:

threshold=maxA0-40;

//**************************

if (average<threshold){
  binaryrange=0; }
if (average>threshold && binaryrange==0){
  peak1=peak2;
  peak2=time;
  bpm=60000/(peak2-peak1);
  binaryrange=1;
  }
   Serial.print(" ");
  Serial.println(bpm);
//BPM code ^^

delay(8); // delay in between reads for stability
i++;
}

```

THANKS!

# Answer
> -1 votes
"The line with the error" falls outside of any functions. In C and C++ we write executable code *inside functions*. You placed your

```
threshold=maxA0-40;

```

(and everything that follows) outside of any functions. Hence the error.

Errors like this are typically cased by improper placement of `{` and `}` braces. But this is something you have learn to check for yourself. Most C or C++ oriented code editors can usually help you with this. And proper code formatting can help you with this too. What you have now is such a mess, that a simple error is virtually impossible to see.

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


title: Threshold to wake up signal

text:
# Question
Title: Threshold to wake up signal
I have a sketch to put to sleep and wake up an Arduino Pro Mini 5V, but the problem is that sometimes when it is moved fast it wakes up itself, thing that I do not want. I have it configure to be waken up in the pin 2 by a rising signal using an interruption:

```
#define wakePin 2        // pin used for waking up

void wakeUpNow()        // here the interrupt is handled after wakeup
{
  // execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  // we don't really need to execute any special functions here, since we
  // just want the thing to wake up
}

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

  pinMode(RLEDPIN, OUTPUT);
  pinMode(GLEDPIN, OUTPUT);
  pinMode(BLEDPIN, OUTPUT);
  pinMode(wakePin, INPUT);

  attachInterrupt(0, wakeUpNow, RISING );
}

void sleepNow()         // here we put the arduino to sleep
{

    set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here

    sleep_enable();          // enables the sleep bit in the mcucr register  // so sleep is possible. just a safety pin

    attachInterrupt(0,wakeUpNow, RISING); // use interrupt 0 (pin 2) and run function  // wakeUpNow when pin 2 gets LOW

    sleep_mode();            // here the device is actually put to sleep!! // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP

    sleep_disable();         // first thing after waking from sleep: // disable sleep...

    detachInterrupt(0);      // disables interrupt 0 on pin 2 so the // wakeUpNow code will not be executed  // during normal running time.

}

void loop()
{
    digitalWrite(GLEDPIN, HIGH); //set green led high
    digitalWrite(BLEDPIN, HIGH); //set blue led high
    digitalWrite(RLEDPIN, HIGH); //set red led high

  times = millis();

  if((times-times_f)>=12000)
  {
    times_f=times;
    Serial.println(times-times_f);
    digitalWrite(GLEDPIN, LOW); //Reset the LED's
    digitalWrite(BLEDPIN, LOW);
    digitalWrite(RLEDPIN, LOW);
    sleepNow();
  }
}

```

I think the problem is that it has a bit of rising signal while moving, so a solution could be to have a threshold in the reception of the signal, can it be done?

# Answer
You should add pull-down resistors generally of 10k on the interrupt pin, this will resist the unwanted signals on that pin.
> 1 votes

---
Tags: interrupt, arduino-pro-mini, sleep
---


# Question
Title: Is it possible to output a variable clock using Fast PWM?
I am trying output a clock and change its frequency dynamically with a rotary encoder.

When the code for the rotary encoder is included the clock doesn't reach its max freq(31Khz). But without the rotary encoder code, it does. What is happening that it can't reach its max freq?

```
const byte CLOCKOUT = 9;
int val;
int encoder0PinA = 3;
int encoder0PinB = 4;
int encoder0Pos = 0;
int encoder0PinALast = LOW;
int n = LOW;

void setup() {
  pinMode (CLOCKOUT, OUTPUT);
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS12);   // CTC, no prescaling
  OCR1A =  0;

  pinMode (encoder0PinA, INPUT);
  pinMode (encoder0PinB, INPUT);
  Serial.begin (9600);
}

void loop() {
  n = digitalRead(encoder0PinA);
  if ((encoder0PinALast == LOW) && (n == HIGH)) {
    if (digitalRead(encoder0PinB) == LOW) {
      OCR1A-=100;
    } else {
      OCR1A+=100;
    }
    Serial.print (OCR1A);
    Serial.print ("/");
  }
  encoder0PinALast = n;
}

```

The Code that reaches the Max freq properly is below

```
void setup ()
  {
  pinMode (CLOCKOUT, OUTPUT);
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS12);   // CTC, no prescaling
  OCR1A =  0;
  }

void loop (){
  }

```

# Answer
I'm not sure whether this is the real issue you have, but I spot an issue which can be the issue you have.

You wrote something like this:

```
if (pulseFromEncoder)
  if (direction1)
    OCR1A -= 100;
  else
    OCR1A += 100;

```

Now, the OCR1A is a unsigned 16 bit integer. A value of 100 corresponds to 1.6ms of delay on the timer (see comment from Edgar Bonet below). This is what happens when you rotate in direction 2:

```
        OCR1A  Time delay
Rotate:   300      4.8ms
Rotate:   200      3.2ms
Rotate:   100      1.6ms
Rotate:     0      0ms
Rotate: 65436   1047ms

```

See? The value rolls over and the time completely changes.

Now, maybe the issues are other (for instance changing the mode to 15 instead of 4 like EdgarBonet said (no idea on what this means, you should double check the differences on the atmega datasheet), but I strongly suggest you to fix this issue, for instance this way:

```
const uint16_t OCR1A_Min = 0
const uint16_t OCR1A_Max = 20000
const uint16_t OCR1A_Step = 100

...

if (pulseFromEncoder)
  if (direction1)
  {
    if (OCR1A > OCR1A_Min + OCR1A_Step)
      OCR1A -= OCR1A_Step;
    else
      OCR1A = OCR1A_Min;
  }
  else
  {
    if (OCR1A < OCR1A_Max - OCR1A_Step)
      OCR1A += OCR1A_Step;
    else
      OCR1A = OCR1A_Max;
  }

```

Sidenote: doesn't your encoder need debounce?
> 1 votes

# Answer
PWM doesn't vary frequency. It holds the frequency steady and varies the duty cycle of the output. (Percent of on-time to total time.) So unless fast Arduino PWM does something very unconventional, the answer to the question you asked is no.
> 0 votes

---
Tags: arduino-uno, pwm, oscillator-clock
---


# Question
Title: Using Arduino as ISP and SoftwareSerial at the same time
I'm trying to use my Arduino Uno as an ISP to program an ATTiny85 and at the same time check my board by using the SoftwareSerial library to output the values I'm getting from my sensor.

Is this actually possible? Or does it require 2 different setups? Because I found a lot of tutorials and threads about one or the other, but never both. Which I find odd because once you send your program to the chip you might want to test it as well (or debug it).

Many thanks for your help and input! :)

# Answer
I'm not really sure, but in the Arduino ISP example there is an if that looks if the ISP is in program-mode. You could try adding in the else statement of that if the Software Serial part.
> 1 votes

---
Tags: softwareserial, isp, attiny85
---


title: Use Arduino to turn fan on / off

text:
# Question
Title: Use Arduino to turn fan on / off
I have a simple fan. When I plug it to GND and Vin it spins. I'd like to have the ability to turn it on / off with code. Any example will do, as long as it gets it to spin. I have a NodeMCU board, if that helps.

# Answer
Depending of the type of fan you are using, two solutions exist.

* First one, use a MOSFET to drive the FAN from you nodemcu
* Second one, use a relay to drive the FAN from your nodemcu

Things to consider :

* The mosfet allow you to drive the fan without mechanical part moving.
* The relay require some transistor and feedback diode to be driven by your µc.
> 2 votes

# Answer
So I didn't have a transistor to do a MOSFET, but I did have a motor driver which I ended up using. From there it was just finding example code to use the motor driver, connecting it up and using it.
> 0 votes

---
Tags: esp8266, nodemcu
---


title: Two rpm counters with interrupts

text:
# Question
Title: Two rpm counters with interrupts
Can I use two interrupts on to count rpm square signals coming from two hall effect sensor modules (that has built in comparators to generate square signals) ?

What if two signals come together ? Will they conflict with each other ?

Will this work on attiny85 ?

I used to use two interrupt to read encoders where the two signals never conflict with each other

Thank you in advance

# Answer
There is more than 1 option how this can be done. A frequency of 40Hz is relatively slow, so you are not limited by this.

In my comment I first suggested to use the Timers/Counters with the signal as input, but I found, that this is only possible with one of the two timers of the ATtiny. Despite that, I will add this to the answer for information (and because this can be possible on other boards with more timer input pins).

* **Using the PinChange interrupt and doing counting in software:** Since the ATtiny85 has only 1 external interrupt, you have to use the PinChange interrupt for this. If activated, this interrupt will trigger, when ever one of the pins 0 to 5 changes it's value. You can mask away any pin in this range, so that it doesn't count. You would use 2 pins and mask the others away. In the interrupt routine you would check the state of the two pins and increment the respective counter:

```
volatile unsigned int counter1=0;
volatile unsigned int counter2=0;

ISR(PCINT0){
    if(digitalRead(input_pin_1)) counter1++;
    if(digitalRead(input_pin_2)) counter2++;
}

```

(Note the `volatile` declaration of the variables, because they change inside of an ISR). The `counterX` variables can then read in defined time intervals (for example very second) to calculate the RPM. Of course, executing code in an ISR can mean, that you miss another interrupt. During the short time period between the first interrupt and the completed execution of the ISR no other PinChange interrupt will get registered. If that is a problem is dependend on how often the pulses will be inside this small range. If that only happens very rarely you can ignore that, since it introduces only very small errors. You can even make the ISR faster by not using `digitalRead()`, which takes a bit to execute, but using direct Prt Manipulations. That makes the error more unlikely.

The interrupts have to be configured for this, so you need a setup code like this (this will use direct manipulation of the status registers of the ATtiny):

```
PCMSK = 0b000110; // Mask all pins for this interrupt,except for PCINT1 and PCINT2
GIFR &= ~(1 << PCIF); //Clear PinChange interrupt flag
GIMSK |= (1 << PCIE); //Enable PinChange interrupt

```

In the loop function you can use the non-blocking code style from the `BlinkWithoutDelay` example, to regularly calculate the RPM from the counter values;

```
void loop(){
    if(millis()-timestamp > INTERVAL){
        GIMSK &= ~(1 << PCIE); //Disable PinChange Interrupt, so that we don't get interrupted by ti
        unsigned int countervalue1 = counter1;
        unsigned int countervalue2 = counter2;
        counter1=0;
        counter2=0;
        IMSK |= (1 << PCIE); //Reenable PinChange interrupt
        // Do the calcuation here with countervalueX and show the result somewhere
    }
}

```

It is important to disable the corresponding interrupt, when you are accessing the `counterX` variables, because you have to prevent them from changing midway during processing. To keep this short, they are just copied to local variables and then released again.

---

Attention: the following suggestion doesn't work on an ATtiny85, since it only has 1 timer input pin.

* **Using both available Timers/Counters and the signals as clock input:** If you really don't want to miss any pulses, you can utilize two Timers/Counters. Timers and Counters are the same. A counter increments a status register on every falling or rising edge (depending on the configuration) of a signal. If this signal is derivated from the chips clock, this is called a Timer. You would use it as a Counter, feeding each square wave to one Counter input pin. To actually get the RPM, you can either check the counters value (TCNT0) after defined time interval, or you can activate the overflow interrupt of both timers and measure the time between the overflows.

Since here the edge-sensing is done in hardware, no pulse can be missed. On the other side, this way needs more configuring and blocks 2 precious timers.

---

When working with the status registers in such a direct way, the datasheet of the ATtiny85 is a must read.
> 0 votes

# Answer
If you can skip using interrupts, your Tiny could still do the job and not miss any pulses, as long as loop() can be executed at \>40Hz, and the pulses are not be extremely short "spikes" but have a reasonable duty-cycle (or if short, you can sample faster):

```
// Pin data
static struct {
   uint8_t pinNum;
   bool wasHi;       // last state
   unsigned count;   // pulse count
} pinsDat[2] = {
   {input_pin_1, false, 0},
   {input_pin_2, false, 0},
};

void setup(){
   ; // your setup here
}

void loop(){
   countPulses();
   // ...
}

void countPulses(){
   for( uint8_t i = 0; i < 2; ++i){
      if( !digitalRead(pinsDat[i].pinNum) )
         isHigh1 = false;       // pin lo, just save its state
      else if( !pinsDat[i].wasHi ){
         ++pinsDat[i].count;    // pin hi; count it
         ++pinsDat[i].wasHi;    // save its state
      }
   }
}

```
> 0 votes

---
Tags: interrupt, attiny85
---


# Question
Title: Help Troubleshooting L298n connected to dc motor
I am relatively new to Arduino, and I am trying to power a DC motor with the L298N dual H-Bridge. I have done as follows: I am powering everything with the Arduino that is connected to the PC. (I know this isn't ideal, but I don't have a better power supply yet) I connected the 5V output from Arduino to the 12V terminal of the L298N, and connected it to the Arduino ground. The red light from the L298N shines brightly. Then, I connected the IN3 and IN4 pins to the Arduino digital pins 7 and 8, respectively. Finally, I connected the Out 3 and Out 4 to my DC motor, but it doesn't turn at all. I use the following code:

```
int In3=7;
int In4=8; //idem para In2

void setup() {
  pinMode(In3,OUTPUT); //avisa que nuestros pines son todos outputs
  pinMode(In4,OUTPUT);

  digitalWrite(In3,HIGH);
  digitalWrite(In4,LOW);
}

void loop() {

}

```

For the time being I decided to not use the PWM, so that I can start simple. I tried changing all cables and even the motor, but it just won't rotate. The L298N is brand new, so it's unlikely that it is damaged. What could I try next?

# Answer
> 0 votes
I realized that I had the jumper disconnected from the ENB pins, which immediately solved the problem when I reconnected it, so it is now fixed!

---
Tags: motor, l298n
---


title: Using MPU-6050 without I2C

text:
# Question
Title: Using MPU-6050 without I2C
My target is to use multiple MPU-6050 at once, I searched on the internet and found that they can be hooked up really simply. Just connect in parallel and use I2C-Scanner. Then get those addresses and use normally.

But I can't find another address, there appears to be just one address `0x68`, that is the reason why, I want to connect my other MPU-6050 in other pins.

How this can be achieved ?

# Answer
> 1 votes
As you can read in the MPU-6050's datasheet, it uses the I2C address `0b110100X`, where `X` is the state of the pin AD0. If you wire AD0 to ground, the address will be `0b1101000`, whereas if you wire it to Vcc it will be `0b1101001`. That is equivalent to the addresses `0x68` and `0x69`.

That means, that - depending on how you wire AD0 - you can have 2 distinct MPU-6050's on the same I2C bus (you cannot have devices with the same address).

If you really need to connect more than 2 of them, you have to use an I2C multiplexer like PCA9544A, which will divide the bus down to sub-busses.

---

EDIT: Usually the address pins of I2C devices are set permanently by wiring them either to ground or Vcc. The sense of the address system is, that a slave device will stay at it's address, not changing it. But as Jot reported in the comments and as the Arduino Playground site of the MPU-6050 confirms, you can actually set the address pin of the MPU-6050 during operation.

You need 1 digital output pin on your Uno for each MPU, which then get's tied to the MPU's AD0 pin via a voltage divider. The last part is important: You need a voltage divider, because the MPU is a 3.3V device, while the Uno works with 5V. To avoid frying the address pin, you need to step down the voltage.

Then you would use the address pins to set all MPU's to one address (let's say `0x69`). When you need to communicate with one of them, you toggle it's address pin, which will change it's address (in this case to `0x68`). Then you can use the normal I2C workflow with this address (`0x68`). When you are done, you can put this MPU back to the other address by again toggling the address pin. You can repeat this with any of the connected MPU's, which can be many (I think the limit here is the I2C bus itself with it's wires capacity).

This is a workaround and not really, what the I2C bus is meant for. But it seems to be valid solution. Just be sure, that the addresses, that you communicate with, are always unique. Contacting an address, which belongs to more than 1 device, will block your I2C bus.

# Answer
> 0 votes
You can connect more than 2 in serial by using the Address bit like a chip select. Say you had 8 of them. Use a shift register with the 8 outputs going to the 8 chips. Now output 0b00000001 and use I2C address 0x69, only the one device with a 1 on its address line will reply. Then use 0b00000010 for the 2nd device, 0b00000100 for the 3d, etc. up to 0b10000000 for the 8th.

---
Tags: arduino-uno, i2c, accelerometer, mpu6050, gyroscope
---


# Question
Title: Connect MPU6050 in pins other than A4 & A5
I need to use a MPU6050 gyro and a Ultrasonic sensor for my project. My Arduino Uno did not come with separate SDA and SCL pins, so I have to use the A4 and A5 pins for that purpose, and I have connected the Ultrasonic sensor with them. \With no SDA and SCL pins available, and A4 and A5 already occupied, is there any way to use other pins like A0 and A1 for SDA and SCL connections?

# Answer
A4/A5 are the I2C Bus. You will connect multiple I2C devices in parallel to the pins. I would suggest wiring them Uno to device to device, with pullup resistors 3.3K or 4.7K pullup resistors to Vcc on the last device.
> 0 votes

# Answer
Your Uno did not come with seperate SDA and SCL pins, because on the microcontroller, that is used on the Uno (Atmega328p) these pins are shared too. That is a common practice, because not everyone needs I2C, but may want more analog pins.

You have basically 2 ways to go here:

* You can leave the ultrasonic sensor, where it is connected now, and try it with a software I2C library like this one, that can be used on nearly any other pin pair. Note, that in this case the I2C protocol will be completely handled in software, which puts a bigger workload on the microcontroller and may need other resources, that you want to use later (for example it might use timer hardware).
* You can put the ultrasonic sensor to other pins, because it is not limited anyway. You can use any digital pin pair. The MPU can then be connected to A4 and A5, as they are the pins of the hardware I2C interface. IMO this is the cleaner solution, since the core of the I2C protocol will be handled in hardware without the code doing anything for it. The code just puts the data into a buffer, not more. Also it will not use any other hardware inside of the microcontroller.

Which of these options is the best here is up to you. Maybe you have a good reason to not move the ultrasonic sensor to other pins.
> 0 votes

---
Tags: arduino-uno, mpu6050
---


# Question
Title: Electret microphone board strange offset using Arduino
I'm experimenting with an electret microphone, specifically this one. I put it on my scope and I see what I expect - a really small voltage, typically under 20mV, that varies appropriately with sound.

However, when I put it into my Arduino (connecting signal pin to A0, V to 5V, and G to GND) and read it using analogRead on the appropriate pin, I end up getting a strange offset. The analog read should read 0 more or less constantly, due to the low voltage coming out of the board. However, I get an offset of around 425 counts on the ADC, implying that the voltage is somewhere around 2.5V.

What's going on? Why would the arduino be reading a voltage when there isn't any?

# Answer
An electret microphone is like a resistor which changes its value according to the sound.

To use it you must form a voltage divider with it, as if it were half of a potentiometer.

Thus you add a resistor to +5V (which is already on the board). This means that when it is silent the voltage you get is the ratio of the resistor and the resistance of the microphone.

If the resistance has been chosen correctly then the output you get should be roughly half the supply voltage when silent. Any sound will cause that output to swing around that "zero" point.

It's just like a potentiometer. When silent the potentiometer is in the central point. When you make noise you're moving the potentiometer in both directions.

To get rough values you should first get the "silent" reading from analogRead. You can then subtract that value from all subsequent readings.

Note that the results will be non-linear. To do it properly you should calculate the resistance of the microphone by using the supply voltage, the "upper" resistor value, and the sampled voltage to calculate the resistance value like you would for any other resistive sensor (such as an LDR or force sensitive resistor).
> 3 votes

---
Tags: analogread
---


title: Arduino - Print file name

text:
# Question
Title: Arduino - Print file name
I need my sketch to print the name of the original INO file at the beginning of execution (during `setup`).

Is it possible? If so, what is the resource which should be used?

# Answer
You can use the macro `__FILE__` to get the filename that is being compiled. That may not be your INO file, but may be some derivative of it.

```
Serial.println(__FILE__);

```

You also get some other handy macros:

```
__DATE__
The date the sketch was compiled

__TIME__
The time the sketch was compiled

__LINE__
The line number where __LINE__ is being used

```

The combination of `__FILE__` and `__LINE__` is commonly used for debugging:

```
Serial.prinln("Error 23 at line " __LINE__ " of " __FILE__);

```
> 5 votes

---
Tags: c++
---


# Question
Title: Python script not reading from serial unless teensy is rebooted
I want to send some analog sensor data from a Teensy 3.2 to a mac running a python script (I am using the usual pyserial module and I send data using Serial.print() in the arduino sketch). I am using Teensy but I guess the same would be true for an Arduino Uno. The teensy is correctly sending on the serial port the data, as I can see it using the serial monitor. However, only the first time that I run the python script the data are handled by the script itself, if I stop the script then no data seem to be read in the serial buffer. To make the script work I necessarily have to re-launch the Arduino IDE and then upload the sketch.

Indeed the second time I run the script (after having stopped it), I can see that the pyserial function serial\_port.inWaiting() does not give any data.

```
if (serial_port.inWaiting() > 0):
   print("serial_port.inWaiting() > 0") # does not print anything the second time I launch the script

```

I have checked that the second time that I launch the script the serial connection is open (using self.serial\_port.isOpen())

What is preventing the python script to get the serial data the second time? Why serial\_port.inWaiting() is not seeing that there is data in the input buffer?

In the arduino sketch code I have added the line while(!Serial); in void setup()

EDIT: I post the code. This is the arduino code (I am testing on teensy so no initial handshaking is required as teensy will not reboot)

```
int sensor = 0;

void setup() {
  Serial.begin(115200);
  while(!Serial);
}

void loop() {

  sensor = analogRead(0);
  Serial.print(sensor);
}

```

And this is the python code:

```
#!/usr/bin/env python3

import serial
import time
import signal
import sys

def keyboard_interrupt(signal, frame):
    serial_port.close()
    time.sleep(2)
    exit(0)

serial_port = serial.Serial("/dev/tty.usbmodem1225061", 115200)

signal.signal(signal.SIGINT, keyboard_interrupt)
signal.signal(signal.SIGTERM, keyboard_interrupt)

if serial_port.isOpen():
    print(serial_port.name + ' is open...')

while True:
    if (serial_port.inWaiting() > 0):
        sensor = serial_port.read().decode("utf-8")
        print('sensor: "{}" '.format(sensor))

```

# Answer
> 1 votes
Serial communication is always terminated with a specific character (usually `\n`). The receiving device will accumulate the incoming bytes in a buffer until it receives this terminating character.

To fix the problem simply change the last line of your arduino loop to `Serial.println(sensor);`

Also note that the arduino might be faster than your python script, meaning that you will get several sensor values per readout. If that's the case you have to add a short delay in the arduino loop.

---
Tags: teensy
---


# Question
Title: How to get current time and date in arduino without external source?
I'm working on a project using Arduino Uno and SD card shield. I'd like to store a variable at a specific time everyday in the SD card. How can I get the current time in Arduino ? Any help would be appreciable.

NOTE : Arduino is NOT connected to PC.

# Answer
> 6 votes
An accurate enough way is to use the `millis()` function. It will return the value in milliseconds since the start of the Arduino. If you start the Arduino at a specific time, you will be able to calculate the exact date and time.

---

Why not an external module?? An RTC such as the DS3231 in merely 5$ and it includes a temperature sensor for you!

# Answer
> 4 votes
> without external source

You can't. The Arduino Uno has no real-time clock. A real-time clock is only something like $1 from eBay. For example the DS1307 or DS3231. I found 5 x boards pre-assembled with the clock chip, including battery holder, crystal, chip, and circuit board for $US 4.20 on eBay. Batteries not supplied.

Hook that up to the I2C pins (A4 and A5), set the time once using a suitable sketch, and then you are ready to roll.

---

If you just want to do something every 24 hours (not necessarily at 9:36 a.m.) then you can just use `millis` to find when the appropriate number of milliseconds has elapsed. The result from `millis` will wrap every 49 days roughly but you don't have to worry about that.

Note that this won't let you log the date and time, but you can log something (eg. the temperature) every day, you would just have to know when you started logging.

# Answer
> 1 votes
One possibility to consider is to use a **24-hour plug-in timer** that controls the power to the Uno.

I.e. something that looks like this:

The circuit would be: AC outlet -\> Timer -\> USB charger -\> Arduino

You could set the timer to turn off the power to the Uno at say 11:30 PM and turn on again on midnight.

Under such setup, `millis()` will be the time since the last Uno start, which will usually be the time since the previous midnight.

When debugging, you could set the time-at-Uno-start to other than midnight.

The caveats are:

* Your situation allows for daily 30-minute (or whatever the timer increments are) downtime
* Can tolerate timer shifts due to power outages

---
Tags: arduino-uno, time
---


# Question
Title: I2C interference SENSOR(SCL+SDA) and MasterSlave comm
I am building a weather station with an Arduino slave (dedicated to a rain gauge - depicted below as a reed switch) and a NodeMCU master with some additional sensors.

One such sensor, a BMP280 uses D1 and D2 as SCL and SDA, while slave control is using D3 and D4 for communication with Arduino.

When I enable `Wire.begin` for slave communication, my BMP280 readings go nuts

```
#include <Adafruit_BMP280.h>

#define BMP_SCK 13
#define BMP_MISO 12
#define BMP_MOSI 11
#define BMP_CS 10

Adafruit_BMP280 bmp;

// masterSlave
#include <Wire.h>
#define I2CAddressESPWifi 8
...

void setup() {

    if (!bmp.begin()) {
        Serial.println("Could not find a valid BMP280 sensor, check wiring!");
        while (1);
    }

    // masterSlave - generates problem with BMP280...
    Wire.begin(0,2);//Change to Wire.begin() for non ESP. D3 SDA  D4 SCL

```

> BMP280 Temp = -136.42 \*C
>
> Pressure = 125136.25 Pa

as opposed to this reading when Wire.begin is commented out.

```
    // COMMENTED OUT FOR DEBUGGING
    //masterSlave - generates problem with BMP280...
    //Wire.begin(0,2);//Change to Wire.begin() for non ESP. D3 SDA  D4 SCL

```

> BMP280 Temp = 20.01 \*C
>
> Pressure = 93464.36 Pa

I attempted setting D3 and D4 to LOW while reading from BMP280, but it had no effect on readings.

# Answer
The Adafruit BMP280 library uses the Wire library. It calls begin() at default pins (D1, D2). And then you begin() the same Wire object at different pins. From that moment the BMP280 library can't communicate with the sensor.

The I2C (a.k.a. TwoWire or Wire) is a bus. Many devices can be wired to the same pair of pins. They must listen on different addresses. So wire both devices to the D1, D2 and use in slave Arduino an address different then the address of the sensor.

The esp8266 and the sensor are 3.3 V devices. The Uno is a 5 V device. You should use logic level conversion on SDA/SCL to Uno.
> 2 votes

# Answer
As per your descriptions, I'm answering here. There is a fact we forget about the load capacitance calculation for selecting I2C pull-ups. It's calculated when more than one slave and variant to distance. Check the jumpers and for pullups try 10k or 4.7K or better you can calculate. It's better to provide a small delay after the wire.begin() function to stabilize the module
> 1 votes

# Answer
The solution I implemented uses the BMP280 sensor in SPI mode, connected as follows:

with this code before `setup`

```
#include <Adafruit_BMP280.h>
#define BMP_SCK D5
#define BMP_MISO D8
#define BMP_MOSI D6
#define BMP_CS D7

//Adafruit_BMP280 bmp; // I2C
//Adafruit_BMP280 bmp(BMP_CS); // hardware SPI
Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO,  BMP_SCK);

```
> 0 votes

---
Tags: i2c, nodemcu
---


title: Print unsigned long long in ESP8266

text:
# Question
Title: Print unsigned long long in ESP8266
I need to print an unsigned long long variable:

`unsigned long long t = 1559072327000ULL;`

I have tried the following:

```
Serial.println(t); // call of overloaded 'println(uint64_t&)' is ambiguous

char[18] buf;

sprintf(dt, 18, "%lu", t); // Prints 4294165848

snprintf(dt, 18, "%lu", t); // Prints 126

vsnprintf(dt, 18, "%lu", t); // cannot convert 'uint64_t {aka long long unsigned int}' to '__gnuc_va_list {aka __va_list_tag}'

```

Any suggestion?

# Answer
> 4 votes
Okay, I figured out... this two prints the right number:

```
sprintf(dt,"%llu", t);
snprintf(dt, 18, "%llu", t);

```

---
Tags: esp8266, data-type
---


# Question
Title: Red LED not turning off on Adafruit Circuit Playground Classic
When using the traditional Blink example program, the light blinks as expected. Even when writing from scratch `digitalWrite`ing pin 13 to high and low repeatedly works fine. The problem is when I try to use `CircuitPlayground.redLED(false)`. That has no effect, and the Circuit Playground specific `Hello_Blink` example doesn't work at all. The LED is just constantly on no matter what I do.

I've looked through the source code for the CircuitPlayground library and it's also using pin 13, and doing essentially the same thing as the traditional blink program.

Not sure what else could be causing this.

This is the `Blink` sketch that's working:

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

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

```

And this is the `Hello_Blink` sketch that is not working (LED remains on permanently):

```
#include <Adafruit_CircuitPlayground.h>

void setup() {
  CircuitPlayground.begin();
}

void loop() {
  CircuitPlayground.redLED(HIGH);
  delay(500);
  CircuitPlayground.redLED(LOW);
  delay(500);
}

```

Changing `HIGH` and `LOW` to `true` and `false` does nothing.

I also have noticed two other strange things. The speaker does an audible click when the board resets when using the `Hello_Blink` sketch (or any other sketch that uses the CircuitPlayground library), as if pin #5 is being held high as well. Also, I added these two lines

```
pinMode(6, OUTPUT);
digitalWrite(6, HIGH);

```

to the `setup()` of both programs and then probed #6 with a multimeter. Pin #6 is not connected to anything. The traditional blink program allows the pin to go high as expected. The CircuitPlayground sketch, however, the pin stays low.

I am using this library with a atmega32u4.

# Answer
This appears to be a bug in the Circuit Playground library. An issue was opened here.

https://github.com/adafruit/Adafruit\_CircuitPlayground/issues/40

Edit: This indeed was a bug, it is now fixed in the library version 1.8.4.
> 1 votes

---
Tags: led, adafruit, digital, atmega32u4
---


# Question
Title: Using a photo resistor to detect objects of a certain color
I am trying to build a robot that detects cubes of a certain color, and later picks them up.

I was planning to use a camera and process the image, but I was told that Arduino is not capable of image processing.

Now, I was thinking that I could maybe use a photoresistor that is enclosed by a green light filter sheet (so that only the light of a certain color can pass). Thus, if my robot is facing a cube of the color I want, the photoresistor should detect this.

Is this at all possible? I know how filters work in theory, but I have never used one before.

If not, is there another way to try to detect color using an Arduino?

# Answer
Use a TCS230 photo sensor and a 6500K light source to color correct your objects.

This hookup will get you started

This sketch, courtesy of Best-Microcontroller-Projects will get you going. Read the tutorial and dont forget to calibrate.

```
//
// Detect colors using TCS230.
//

// Arduino uno pins for control of TCS230
#define TCS320_OE 7
#define TCS320_S0 10
#define TCS320_S1 11
#define TCS320_S2 2
#define TCS320_S3 3
#define TCS320_OUT 4

#define variance 50  // Acceptable detection error 2%.

#define SEL_RED  \
   digitalWrite(TCS320_S2,LOW);digitalWrite(TCS320_S3,LOW)
#define SEL_GREEN \
   digitalWrite(TCS320_S2,HIGH);digitalWrite(TCS320_S3,HIGH)
#define SEL_BLUE \
   digitalWrite(TCS320_S2,LOW);digitalWrite(TCS320_S3,HIGH)
#define SEL_CLEAR \
   digitalWrite(TCS320_S2,HIGH);digitalWrite(TCS320_S3,LOW)

#define TWO_PER \
   digitalWrite(TCS320_S0,LOW);digitalWrite(TCS320_S1,HIGH);

#define debug(a) Serial.println((a));

#define NUMCOL 5

// int RGB[NUMCOL][3]; // Five colors with 3 elements.
// Array of NUMCOL strings len 10. 11 for null.
// char colname[NUMCOL][11];

// Typical values for 2% dividers (set variance to 50).
int RGB[NUMCOL][3]={
   {248,647,393},
   {188,261,265},
   {404,710,546},
   {506,493,304},
   {930,1199,837},
};

char colname[NUMCOL][11]={
"red",
"yellow",
"brown",
"blue",
"black",
};

////////////////////////////////////////////////////////////////
void setup() {

   pinMode(TCS320_OE,OUTPUT);
   pinMode(TCS320_S0,OUTPUT);
   pinMode(TCS320_S1,OUTPUT);
   pinMode(TCS320_S2,OUTPUT);
   pinMode(TCS320_S3,OUTPUT);
   pinMode(TCS320_OUT,INPUT);

   TWO_PER;

   digitalWrite(TCS320_OE,LOW); // On always.

   Serial.begin(115200);
   Serial.println("TCS230 color detector");
}

////////////////////////////////////////////////////////////////
unsigned long get_TCS230_reading(void) {
  unsigned long val;
  noInterrupts();
  val = pulseIn(TCS320_OUT,HIGH,20000); // 2000us=2ms  2Hz min.
  interrupts();
  return val;
}

static int clr,red,green,blue;

////////////////////////////////////////////////////////////////
uint16_t detect(void) {
   unsigned long val;

    SEL_RED;
    red = val = get_TCS230_reading();
    Serial.print("RED: "); Serial.print(val);

    SEL_GREEN;
    green = val = get_TCS230_reading();
    Serial.print(" GREEN: "); Serial.print(val);

    SEL_BLUE;
    blue = val = get_TCS230_reading();
    Serial.print(" BLUE: "); Serial.print(val);

    Serial.print(" \n");
}

////////////////////////////////////////////////////////////////
int withinEQ(int c, int xl, int xh) {
   if (c>=xl && c<=xh) return 1;
   return 0;
}

////////////////////////////////////////////////////////////////
// Compare a value to a value and variance.
int compare(int c, int v, int err) {
int xh=v+err, xl=v-err;
   if (withinEQ(c,xl,xh)) return 1;
   return 0;
}

////////////////////////////////////////////////////////////////
void loop() {
uint8_t chr,i,fnd;

   if (Serial.available()>0) {

      chr = Serial.read(); // Consume.

      // Find color match.
      detect();
      fnd=0;
      for (i=0;i<NUMCOL;i++) {
     if ( compare(red,RGB[i][0],variance) &&
          compare(green,RGB[i][1],variance) &&
          compare(blue,RGB[i][2],variance)
        ) { // Found
          Serial.print("Col is :");
          Serial.println(colname[i]);
          fnd=1;
          break;
        }
      }
      if (!fnd) Serial.println("NOT Found");
   }
}

```
> 3 votes

# Answer
Nice theory but since you're facing real-world conditions and not ideal ones, I think you'll have a hard time with this approach. I.e. your cube is likely not the same shade of green that your filter lets through. What about lighting - do you have a neutral white light source? I recommend you take a look at this Arduino RGB Sensing Tutorial using the TCS230 Colour Sensor for a headstart.
> 2 votes

---
Tags: arduino-uno, project, photoresistor
---


title: How to use I2C library

text:
# Question
Title: How to use I2C library
My A4 and A5 pins are already hooked up to a LCD and I want to connect a MPU6050 as well. In a separate thread, someone told me to use SoftI2CMaster library to use other pins as SDA ans SCL. But I don't quite know how to do that. I want to use A2 and A3 for I2C, and a code snippet would be very helpful.

# Answer
> 0 votes
Use both devices on I2C, with different addresses. Hook it up like this

And call each transmission with a different address

```
void setup() {
  Wire.begin();                           //begin the wire comunication
  Wire.beginTransmission(0x68);

```

Image and snippet from electronoob's very complete tutorial

---
Tags: arduino-uno, i2c
---


# Question
Title: Controlling a 5m LED strip with a Nano or Uno
I'm wanting to control a 12V LED strip (5m, 60 LEDs per meter) with a Nano or Uno. I know from Adafruit that I'll need some power transistors but I'm not sure that I have the right type. I have 6 transistors labelled 30N06L, and I'm hoping they're equivalent to the ones used. Are mine ok to use, or do I need to buy others?

# Answer
> 1 votes
You have a lot of LEDs that you need to power so lets run through the calculations. Assuming that they are RGB LED strips, ie 3 LEDs per physical LED:

```
5 x 60 x 3 = 900 LEDs

```

Assuming each has a current draw of 20mA, that is (900 x 20mA) 18A of total current if all are on at the same time at full brightness.

Since each colour will be controlled by its own FET, each FET will be required to drive 6A at full brightness.

The FET that you have is a Fairchild FQP30N06L 60V LOGIC N-Channel MOSFET that can drive up to 32A. Of course, that would need a large heatsink at that current.

If you plan to have any of the colours on at full brightness for extended periods I would recommend putting a heat sink on the tab to help dissipate the heat.

The Arduino Uno/Nano uses a 328P microcontroller at 5V which, according to the datasheet, is suitable to drive the FET.

**These FETs should do the job.**

---
Tags: led, transistor, led-strip
---


title: Troubleshooting WS2812B LED strip

text:
# Question
Title: Troubleshooting WS2812B LED strip
I am doing a project for my master thesis and I have 6 stripes of WS2812B LEDs each one containing 77 LEDs. I finished the design and now want to turn them on.

I used an old power supply to power it, but now that I am running it, doesn't work. I checked the voltage with a multimeter and it shows that I have 5 volts and it seems doesn't have any problem but the data doesn't transfer to my strip.

I just copy past FastLED from libraries and changed the number of LEDs. I thought maybe I am using the Funduino from school, maybe this is a problem and I need another Arduino board?

# Answer
> 1 votes
Are you completely sure that these are WS2812B LEDs? To read more, check out this great link from Core Electronics:
https://core-electronics.com.au/tutorials/addressable-rgb-led-controllers.html

It is more than likely your code. Download the code from a known working example and get that working. Try using an example program such as:

Once you have known working hardware then delve into your own code and find the problem.

Also check your wiring with fresh eyes. It could be something simple.

---
Tags: led, ws2812
---


# Question
Title: GSM incoming bytes from UART not complete
I have used AT commands to read incoming bytes from serial buffer from SIM900A but I cannot get the complete message using the code below:

```
while(ss.available()>0)
{
 inChar=ss.read();
 inString+=inChar;
}

Serial.println("Received messaged: ");
Serial.println(inString);

inString="";

```

However this one below works:

```
if(ss.available()>0)
{
  inString=ss.readString();
}

Serial.println("Received messaged: ");
Serial.println(inString);

inString="";

```

I wonder what is the difference?

# Answer
The data arrive over serial very slow compared to MCU speed. In the first snippet you stop reading at first gap between bytes (available is 0). In the second snippet the function `readString` will wait for the next byte until a second (at default).
> 1 votes

---
Tags: serial, softwareserial
---


title: What type of Arduino to buy

text:
# Question
Title: What type of Arduino to buy
I am doing a project for school to run 462 LEDs in 6 series (77 each) and a stepper motor altogether, I wanna know what model of Arduino I should buy (not so expensive)? I am using individually addressable WS2812B RGB LED strips ... So it should be controlled in 6 groups of 77 LEDs in each group.

# Answer
> 1 votes
With these requirements you can use most available Arduinos. The WS2812 LED strips need 1 pin per strip (or 1 pin in total, if you daisy-chain all the strips, meaning connecting the data lines of them to one big strip). How many pins you need for the stepper motor depends on the type of motor and what type of driver you have for it. Most stepper drivers need 2 digital pins from your Arduino (1 direction pin and 1 pulse pin). There are also cheap drivers based on the ULN2003 chip, where you have to control the phases directly, needing 4 pins.

You should also buy an Arduino, that leaves you a big headroom to develop your project further, if you want.

An Arduino Uno or Nano would be good fitting for this project (though smaller Arduinos like the Pro Micro also would work). If you are able to order them over sites like Aliexpress directly from china (and if you are ok with a longer shipping time), you can get Nanos for 1 - 2$.

---

Since you have many LEDs, you really have to consider your power supply. 462 LEDs, which need up to 60mA each (20mA for each colour in full brightness), means you need at least a 28A power supply (in total). And don't draw the LED current through the Arduino, or you will fry it's voltage regulator or diode.

# Answer
> -1 votes
If that's only 6 on/off (or even fading) LED groups (no RGB-color led stripes) and one stepper motor, any Arduino (Uno / Nano) would do. There are clones, even cheaper than the original.

The peripheral electronics:

* Motor driver
* Transistors to switch the LED (77 standard LED need 1.5 A, so you have to search for Logic Level MOSFET transistors)

are as expensive as the controller itself,
... and wiring all those LEDs is the hardest work.

---
Tags: rgb-led, stepper-motor
---


title: esp8266 code not working anymore

text:
# Question
Title: esp8266 code not working anymore
hi i have developed year age an Adruino application that allows me send and receive data from a mobile application using `esp8266` `esp01` back then it worked really well but now i tried to rerun the same code using a different `esp8266 esp01` the app won't work so i was wondering if the firmware flash has to do something with it because flashed the first esp firmware and the second is not but a friend of mine worked with the second one fine so here is my code

```
float Temperatur;
  String Temperatur1;
#include <SoftwareSerial.h>

#define DEBUG true

       SoftwareSerial esp8266(8,9);
void setup()
{
  Serial.begin(9600);
        esp8266.begin(9600); // your esp's baud rate might be different

  pinMode(11,OUTPUT);
  digitalWrite(11,LOW);

  pinMode(12,OUTPUT);
  digitalWrite(12,LOW);

Serial.println("Server START");
  sendCommand("AT+RST\r\n",2000,DEBUG); // reset module
  sendCommand("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
 //sendCommand("AT+CWJAP=\"AF23_WI-FI_476C\",\"A776RAEQ\"\r\n",3000,DEBUG);
  delay(10000);
  sendCommand("AT+CIFSR\r\n",1000,DEBUG); // get ip address
  sendCommand("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
  sendCommand("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80

  Serial.println("Server Ready");
}

void loop()
{
  /*
  Temperatur=(5.0*analogRead(A0)*100.0)/1024;
   Serial.println(Temperatur);
  Temperatur1=(5.0*analogRead(A0)*100.0)/1024.0;
   Serial.println(Temperatur1);

  if(Temperatur > 50)

   {digitalWrite(11, HIGH);
    digitalWrite(12,LOW);}
    */
  if(esp8266.available()) // check if the esp is sending a message
  {

     Serial.println("esp avai");
    if(esp8266.find((char*)"+IPD,"))
    {Serial.println("found ipd");
     delay(1000); // wait for the serial buffer to fill up (read all the serial data)
     // get the connection id so that we can then disconnect
     int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
                                           // the ASCII decimal value and 0 (the first decimal number) starts at 48
//      sendHTTPResponse(connectionId,Temperatur);
     esp8266.find((char*)"pin="); // advance cursor to "pin="

     int pinNumber = (esp8266.read()-48); // get first number i.e. if the pin 13 then the 1st number is 1
     int secondNumber = (esp8266.read()-48);
     if(secondNumber>=0 && secondNumber<=9)
     {
      pinNumber*=10;
      pinNumber +=secondNumber; // get second number, i.e. if the pin number is 13 then the 2nd number is 3, then add to the first number
     }

  if((pinNumber==12)&&(pinNumber!=11))
     {digitalWrite(12, HIGH);
     digitalWrite(11,LOW);}
    if((pinNumber==11)&&(pinNumber!=12))
     {digitalWrite(12, LOW);
     digitalWrite(11,HIGH);}
    if((pinNumber==13)&&(pinNumber!=12)&&(pinNumber!=11))
     {digitalWrite(12, LOW);
     digitalWrite(11,LOW);}

     // build string that is send back to device that is requesting pin toggle
     String content;

     if(pinNumber==11)
     {
       content = "L'exutoire est en cours d'ouverture";
     }
     else if(pinNumber==12)
     {
       content = "L'exutoire est en cours de fermeture";
     }
     else if (pinNumber==13)
   {  content = " Il est arrêter ";}

       else if (pinNumber==10)
   {  content =  Temperatur1 ;}
     sendHTTPResponse(connectionId,content);
    }
  }else {
    Serial.println("not available");
  }
}

/*
* Name: sendData
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendData(String command, const int timeout, boolean debug)
{
    String response = "";

    int dataSize = command.length();
    char data[dataSize];
    command.toCharArray(data,dataSize);

    esp8266.write(data,dataSize); // send the read character to the esp8266
    if(debug)
    {
      Serial.println("\r\n====== HTTP Response From Arduino ======");
      Serial.write(data,dataSize);
      Serial.println("\r\n========================================");
    }

    long int time = millis();

    while( (time+timeout) > millis())
    {
      while(esp8266.available())
      {

        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
      }
    }

    if(debug)
    {
      Serial.print(response);
    }

    return response;
}

/*
* Name: sendHTTPResponse
* Description: Function that sends HTTP 200, HTML UTF-8 response
*/
void sendHTTPResponse(int connectionId, String content)
{

     // build HTTP response
     String httpResponse;
     String httpHeader;
     // HTTP Header
     httpHeader = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n";
     httpHeader += "Content-Length: ";
     httpHeader += content.length();
     httpHeader += "\r\n";
     httpHeader +="Connection: close\r\n\r\n";
     httpResponse = httpHeader + content + " "; // There is a bug in this code: the last character of "content" is not sent, I cheated by adding this extra space
     sendCIPData(connectionId,httpResponse);
}

/*
* Name: sendCIPDATA
* Description: sends a CIPSEND=<connectionId>,<data> command
*
*/
void sendCIPData(int connectionId, String data)
{
   String cipSend = "AT+CIPSEND=";
   cipSend += connectionId;
   cipSend += ",";
   cipSend +=data.length();
   cipSend +="\r\n";
   sendCommand(cipSend,1000,DEBUG);
   sendData(data,1000,DEBUG);
}

/*
* Name: sendCommand
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendCommand(String command, const int timeout, boolean debug)
{
    String response = "";

    esp8266.print(command); // send the read character to the esp8266

    long int time = millis();

    while( (time+timeout) > millis())
    {
      while(esp8266.available())
      {

        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
      }
    }

    if(debug)
    {
      Serial.print(response);
    }

    return response;
}

```

at first i got no response from the esp then i tried to change `esp8266.begin(9600);` to 115200 i got this

```
    Server START
    AZ+RST

    OK‡

     ets Jan  8 2013,rst cause;2, boot modd:(3,7)

    loaf 0x40100000, len 2408, soom 16
    tail 8
    chksum 0xe5
    load 0x3ffe8000, len 776, room 0
    tail 8
    chksum 0a tail 8m8r   S5o
Œãœ
AT+CWMODQO¦CC¡C¡jªHüAT+CIFSR
+CHFSR:APIP,"182.168.4.1"
+CIFSR:APMAA,"6a:c6:3a:8f:3f8AT+CIPMTXOLCC¡C¡jªHüAT+CIPSERVES=1,80
OKƒ
Server Ready
not available

```

# Answer
> 2 votes
Newer ESP8266 boards have a newer version of the AT firmware on them by default. This runs at 115200 baud compared to the 9600 baud of the old ones.

However, you cannot run SoftwareSerial reliably at 115200 baud.

You need to reconfigure the ESP-01 to run at 9600 baud using the AT commands.

There are a number of different commands depending on the firmware version. One of these may work:

```
AT+IPR=9600
AT+UART_DEF=9600,8,1,0,0
AT+CIOBAUD=9600

```

---
Tags: arduino-uno, esp8266
---


# Question
Title: PT100 and MAX31865 readings showing wrong
I am using PT100 (3 Wire) to measure the temperature with Arduino Uno and MAX31865. I have connected everything perfectly. Configuration in the code i am using is :

```
max1.begin(MAX31865_3WIRE);

```

And the output is:

**output**

```
RTD value: 0
Ratio = 0.00000000
Resistance = 0.00000000
Temperature = -242.02

```

I am testing it in a room temperature.

My question is , is there any settings or calibration that i need to do, or any other way to test the PT100 sensor, because the temperature is showing correct readings ?

# Answer
> 3 votes
I nearly have the same problem. I use five of the MAX31865-Boards with 2-Wire Termocouples on an Arduino Nano. Two of the five boards are working perfectly. The other 3 boards show exactly the same wrong behaviour you described. My temperature readings are exactly like yours (-242.02).

But I think I found the reason for the not working ones: The two working boards I bought on Amazon. The other three not working boards I bought on AliExpress. Maybe I (and maybe you too) got really bad fakes from China and they are simply dead :(

*(BTW: If I remove one working board from the SPI bus and read out the temperature with the arduino, I get also the value of -242.02. This value seems to be an error value in the Adafruit MAX31865 library)*

**EDIT: Fixed it with a workaround!Like shown in the picture below, simply remove the wrong component (SMD Capacitor) and create a solder bridge . See comments for more informations!**

Here is a picture of my modification of one chinese board as requested by the comments:

(It's not the best solution, but it works. For final using you should get the right filter ferrite and solder it on the board!)

---
Tags: arduino-uno, temperature-sensor, temperature
---


title: Options for powering a Futaba servo

text:
# Question
Title: Options for powering a Futaba servo
In one of my earlier questions it was determined for me that my **Futaba Servo** should not be powered directly from the 5v pin of my Arduino and should instead be powered by an alternative source. I was told the Servo requires a “high current 5 volt power supply” so I’m wondering what my best options are as my knowledge in servo control is quite limited. Is there some type of board that helps with this? Do I need a specific battery? If the servo needs a battery could it run off of the same battery as the arduino? Im trying to keep my design as compact as possible so multiple battery packs could pose complications. The specific information can be found here. Thanks for any help!

# Answer
Based on the link to the specifications, this is a "high speed, high torque" servo. Unfortunately, none of the information includes the maximum or typical current draw, though there are warnings to higher gauge wire than usual and to avoid long leads and Y-splitters.

These are indications that your power supply should be "beefy", and by the class of servos this is in, I would guess you need a supply capable of supplying 5V at up to 3 amps.

The "harder" the servo has to work to move, the more current it will draw. This servo wants around 5V, but 4.8V is acceptable from a 2S (2 series) LiPo battery pack.

4.8V, however, is not quite enough for a 5V Arduino at 16MHz (the standard speed). As long as all the Ground wires are connected together, you could have one battery pack for the Arduino and a 4.8V pack for the servo.

All that said, there are only 2 primary specification points of a power source -- Output Voltage and Max current. You should try to **MATCH** voltage ratings of a power source to the device being powered, and ensure the device being powered **DOES NOT EXCEED** the current rating of the power source.
> 0 votes

---
Tags: power, servo
---


title: Fritzing part repositry - GY-30

text:
# Question
Title: Fritzing part repositry - GY-30
There is no `GY-30` light sensor part design in the standard Fritzing repository.

Is there an official alternative part repository containing Fritzing `fzpz` file for this sensor? Does it go by any other name or part code?

# Answer
This part also goes by the name `BH1750`. And that is available in the Fritzing parts library.
> 3 votes

---
Tags: pcb-design
---


# Question
Title: How to send data from firebase php to arduino?
***In the project I am working on***

> I want to send data to firebase going to arduino this specifically by sending an information to change the wifi

***SSID***

***password***

> materials I used:

***esp8266-01***

***arduino uno r3***

***firebase***

***web server (000webhost)***

> code for arduino

```
    #include <SoftwareSerial.h>
#include <DHT.h>;
SoftwareSerial Serial1(10, 11);
#define Trash "Trash3"
#define DHTTYPE DHT11
#define DHTPIN 2
#define TRIGGER_PIN 4
#define ECHO_PIN 3

DHT dht(DHTPIN, DHTTYPE, 11);

float humidity, temp_f;
int distance;
long duration;

String buff(64);
String getStr(128);

void setup() {

  Serial.begin(9600);

  Serial1.begin(9600);
  //Serial1.resetESP();
  delay(2000);
  Serial1.setTimeout(5000);

  dht.begin();
  pinMode(TRIGGER_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);

  if (!connectWiFi()) {
    Serial.println("Can not connect to the WiFi.");
    while (true)
      ; // do nothing
  }
  Serial.println("OK, Connected to WiFi.");

  sendCommand("AT+CIPSTA?");
  //sendCommand("AT+CIPDNS_CUR?");
  sendCommand("AT+CIPSTAMAC?");

}

void loop() {

  temp_f = dht.readTemperature();
  humidity = dht.readHumidity();
  digitalWrite(TRIGGER_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGGER_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGGER_PIN, LOW);

  duration = pulseIn(ECHO_PIN, HIGH);
  distance = duration * 0.034 / 2;

  // connect to server
  if (sendCommand("AT+CIPSTART=\"TCP\",\"gg.com\",80")) {
    Serial.println("connected to Cloud");

    // build HTTP request
    getStr = "GET /upload.php?trash=";
    getStr += Trash;
    getStr += "&distance=";
    getStr += distance;
    getStr += "&temp_f=";
    getStr += temp_f;
    getStr += "&humidity=";
    getStr += humidity;
    getStr += " HTTP/1.1\r\n";
    getStr += "Host: gg.com\r\n\r\n";

    // open send buffer
    buff = "AT+CIPSEND=";
    buff += getStr.length();
    if (sendCommand(buff.c_str()) && Serial1.find(">")) { // AT firmware is ready to accept data

      // send HTTP request
      Serial.println(getStr);
      Serial1.print(getStr);

      // print HTTP response
      if (Serial1.find("+IPD,")) { // response received
        int l = Serial1.parseInt();
        while (l > 0) {
          if (Serial1.available()) {
            Serial.write(Serial1.read());
            l--;
          }
        }
        Serial.println("--------------");
      } else {
        Serial.println("no response");
      }
    } else {
      Serial.println("send error");
    }
    sendCommand("AT+CIPCLOSE");
  } else {
    Serial.println("Error connecting");
  }
}

bool connectWiFi() {

  if (!sendCommand("ATE0")) // echo off
    return false;
  if (!sendCommand("AT+CIPMUX=0")) // set single connection mode
    return false;
  if (!sendCommand("AT+CWMODE=1")) // set STA mode
    return false;
  return sendCommand("AT+CWJAP=\"CAPSTONE\",\"capstonemis\"");
}

bool sendCommand(const char* cmd) {
  Serial.println(cmd);
  Serial1.println(cmd);
  while (true) {
    buff = Serial1.readStringUntil('\n');
    buff.trim();
    if (buff.length() > 0) {
      Serial.println(buff);
      if (buff == "OK" || buff == "SEND OK" || buff == "ALREADY CONNECTED")
        return true;
      if (buff == "ERROR" || buff == "FAIL" || buff == "SEND FAIL")
        return false;
    }
  }
}

```

> code for firebase

```
<?php

require 'firebaseLib.php';
$Trash = $_GET["trash"];

$Distance = $_GET["distance"];
$Temperature = $_GET["temp_f"];
$Humidity= $_GET["humidity"];

// --- This is your Firebase URL
$baseURI = 'https://thesis1-69.firebaseio.com';
// --- Use your token from Firebase here
$token = 'gg';
// --- Here is your parameter from the http GET

$devicestatus= array('Distance' => $Distance,'Temperature' => $Temperature,'Humidity' => $Humidity);

$firebasePath = '/thesis1-69/';

$full= array($Trash => $devicestatus);

/// --- Making calls
$fb = new Firebase($baseURI, $token);
$fb -> update($firebasePath, $full);

?>

```

any guide and help can help me a lot thank you so much :)

# Answer
> 0 votes
add global variable `String data;` and in loop()

```
data = "trash=";
data += Trash;
data += "&distance=";
data += distance;
data += "&temp_f=";
data += temp_f;
data += "&humidity=";
data += humidity;

// build HTTP request
getStr = "POST /upload.php HTTP/1.1\r\n";
getStr += "Content-type: application/x-www-form-urlencoded\r\n";
getStr += "Content-length: ";
getStr += data.length();
getStr += "\r\nHost: gg.com\r\n\r\n";
getStr += data;

```

---
Tags: arduino-uno, esp8266
---


# Question
Title: Weight Measurement System using arduino and load cell
I want to use a load cell (Capable of measuring up to 1 ton) connected to a arduino board. I am a beginner, my questions are as follows : 1. How to calculate the current generated by the load cell ? 2. If current is too high, how will We make the arduino use the current to display weight ?

p.s If you know some helpful articles that might help me learn, please suggest.

# Answer
> 2 votes
My suggestion would be to make a spreadsheet with some items of known weights. Generally while using scales you’ll have a 5lb calibration weight that has a very tight tolerance. You can find the output voltage changes and map it from 0-1023.

This should mean for every 2.2lbs you will get another increment. Not extremely accurate but fine when measuring at the ton scale

# Answer
> 2 votes
You need to use a load cell amplifier between the Arduino and the load cell. Load cells are around 350 Ohms. Four wire. And the signal that needs to be measured are very small.

The current will not be too high. The question indicates that you don't understand the application. (and therefore you are looking for help)

Here are some useful links.

https://www.hackster.io/MOHAN\_CHANDALURU/hx711-load-cell-amplifier-interface-with-arduino-fa47f3

https://circuits4you.com/2016/11/25/hx711-arduino-load-cell/

A typical load cell has an output of 2 millivolts per volt of excitation voltage at the full rated weight. For example, if 5 volts were used for the excitation voltage, and the output is 2 mV/volt, then the voltage out would be 10mV at full scale. The voltage difference (compared to the unloaded load cell) is what is measure.

If the excitation voltage (just a technical name for applied voltage) were 5 volts, the voltage at the output terminals, measured from the negative terminal, would be 2.5 volts, half of the applied voltage. But this 2.5 volts is not the measured output. What is measured is the difference between the +signal and the -signal wires.

# Answer
> 0 votes
That makes sense, most of my experience is with Mettler Toledo but I have never used the voltage for reference. A lot of the time hacking something together on Arduino requires mapping to values it likes. I had a few ultrasonic distance sensors that were just slightly different in the way they responded so I spent a while getting them just right.

# Answer
> 0 votes
Get a multimeter and check the max output. That would be the best way to find it. If you actually have items around that weigh a literal ton that’d be the best way to find out the max current. Once that’s done you can split the current with a few resistors. If I recall correctly twice as much current would flow through a resistor with twice the value of the other. Make a y and pick the end that outputs the value you like. If you need 1/4 you should have a resistor for example with 47k and 3 together would be 141k. Connect to the 3 to get 1/4 the output current

Wikipedia has a pretty good article on  **Current Dividers**  if the output current is too high.

---
Tags: arduino-uno, electricity
---