# Question
Title: How to send float numbers from python3 with struct to arduino
I have searched several questions and through google but could not find a solution. I am simply trying to send a float number from python3 with struct to arduino or if there is any other ways other than processing a char array at the arduino side because it is very slow in my opinion..

My arduino code:

```
void setup() {
  // initialize the serial communication:
  Serial.begin(9600);
}

void loop() {

  unsigned long t = millis();
  float x = analogRead(A3);
  float y = analogRead(A2);
  float c = Serial.read();
  Serial.println(c);
  //Serial.print(t/1000.0);
  //Serial.print(" , ");
  //Serial.print(x);
  //Serial.print(" , ");
  //Serial.println(y);

  // wait a bit for the analog-to-digital converter to stabilize after the last
  // reading:
  //delayMicroseconds(200);
  //delay(2);
  delay(250);
}

```

My python3 code :

```
import serial

import struct

arduino = serial.Serial('/dev/ttyACM0', 9600)
data = arduino.write(struct.pack('f', 111.32))
while True:
#    arduino.write(b"123")
    data = arduino.write(struct.pack('f', 111.32))

```

Getting the serial output as :

```
163.00
222.00
66.00
215.00
163.00
222.00
66.00
215.00
163.00
222.00
66.00
215.00
163.00

```

How can i solve my problem ?

EDIT : I changed the arduino code according to the answer the new arduino code is

```
float f;
void setup(){
  Serial.begin(9600);
}

void loop(){
  while(Serial.available() >= 3){

    f = Serial.read() << 24;
    f = ((unsigned long) f) | (Serial.read() << 16);
    f = ((unsigned long) f) | (Serial.read() << 8);
    f = ((unsigned long) f) | Serial.read();
    Serial.println(f);
  }
  Serial.println(f);
}

```

However, the output is now as such:

```
ovf
ovf
ovf
ovf
ovf
ovf
ovf
4294941184.00
4294941184.00
4294941184.00
4294941184.00
4294941184.00
4294941184.00
4294941184.00

```

# Answer
> 0 votes
I found a better way dealing with the conversion from char to float (note that you yourself have to add the `setup()` function for initiating Serial):

```
float f;
byte *fdata = (byte *) &f;
int num = 0;

void loop()
{
  if(Serial.available()){
    char c = Serial.read();
    if(c == 'B'){
      fdata[3] = c;
      num = 1;
    } else if(num == 1){
      fdata[2] = c;
      num++;
    } else if(num == 2){
      fdata[1] = c;
      num++;
    } else if(num == 3){
      fdata[0] = c;
      num = 0;
      Serial.write(fdata, 4);
      Serial.println(f);
    }
  }
}

```

First we are defining our float variable `f` and then a pointer of type `byte` named `fdata`. We are setting this pointer to point to our float variable. Now you can treat this pointer as an array. Since the type of the pointer is `byte`, we can access the first byte of `f` with typing `fdata[0]`. The other bytes can be accessed through `fdata[1]`, `fdata[2]` and `fdata[3]`.

In the loop example we are checking, if there is any byte in the buffer and read it. If it is the value of the character 'B' (which I used as a trigger, that your float starts, since the float number `111.32` starts with this value) we copy it to the last (most significant) byte of the array (aka float variable `f`). One after another we are doing the same with the other bytes.

When we received the last of the 4 bytes, we write the value back to Serial, once as pure byte data and once as ASCII encoded string.

In Python you can use the code, you already used:

```
arduino.write(struct.pack('>f',111.32))

```

You can read the output of the above sketch back with

```
arduino.readline()

```

PS: From my tries I guess the previous problem with getting `ovf` was, that the byte order was reversed (which simply would have been solved by using `<f` for the struct in python). But I personally like this way better, because it uses less casting.

# Answer
> 0 votes
There is no way around dealing with serial bytewise, since the communication over serial relies on bytes as a unit. You can write the received bytes directly to the float variable. That is faster, than save them to a char array first:

```
float f = Serial.read() << 24;
f = ((unsigned long) f) | (Serial.read() << 16);
f = ((unsigned long) f) | (Serial.read() << 8);
f = ((unsigned long) f) | Serial.read();

```

With this the bytes of the float value have to be send with the order from most significant to least significant. I don't know, how the data is formatted, if you send a struct over python. The casting to `unsigned long` is important here to do the bitwise OR (`unsigned long` and `float` have both 4 bytes). (I tried it and it works for me)

Also be aware, that you shouldn't read from Serial, when there is no received byte in the buffer. You can check this with `Serial.available()`. If there is no new byte in the buffer the `Serial.read()` function returns an integer with value `-1`

EDIT: The code above works, if you transmit the data directly as byte. In your comment you wrote, that you want to write `arduino.write(b"111.32")` in python. Here you are transmitting an ASCII string representation of the float number `111.32`. This is not as fast as transmitting byte data (since you may need way more bytes for one float than 4). In this case you can use either `Serial.parseFloat()` to get the float from the serial buffer (but ensure, that all bytes for this number have been received with `Serial.available()`) or you can save the bytes to a string and using `String.toFloat()` to get the float out of it.

Since you wanted to do it the fast way, you should transmit the numbers as byte data. To do this in python, have a look at the answer of this question. It explains the python code for it (be sure, that you get the ordering of the bytes the same in python and Arduino).

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


title: other interrupts in rc channel reader

text:
# Question
Title: other interrupts in rc channel reader
I have the sketch from James Waldby (Read RC receiver channels using Interrupt instead of PulseIn) working beautifully. I want to use a switch on my TX to start and stop a sequence of lights (emulating guns firing on a ship model). But first, I need the delayed flash routine to work. I have tried a loop counting millis() differences to separate the sequences, but the delays don't delay.

```
 void loop(){
  rc_read_values();//Mr. Waldby's interrupt routine
  currentMillis = millis();
  previousMillis = currentMillis;
  if(fireGun ==1){
    interval = 3000;
  }else{
    interval = 1500;
  }
  interval = 3000;
  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

//if(fireGun ==1){
  analogWrite(led, 255);
  delay(50);
/* a real gun flash doesn't cut right off; it fades away.
  This sequence simulates that  */
  while(brightness > 0){

    // change the brightness for next time through the loop:
    brightness = brightness - fadeAmount;
    analogWrite(led, brightness);
    delay( 7);
  }
  brightness = 80;
}

```

The intention here is to flash the led every 3 seconds. The flash loop works fine, but the 3 second delay doesn't.

The delay routine works ok in a sketch by itself.

Any thoughts about what I might be doing wrong?

# Answer
> 1 votes
> ```
>   currentMillis = millis();
>   previousMillis = currentMillis;
>
> ```

So currentMillis and previousMillis will always be exactly the same, right?

> ```
>   if (currentMillis - previousMillis >= interval) {
>
> ```

So if `0 >= interval` (which it won't be) do something?

Therefore your fading code will never be executed.

---
Tags: interrupt
---


# Question
Title: How to create a device with buttons that records when they are pressed
I want to build a very simple device, which has a bunch of buttons for switching "settings" and LED lights to show which "setting" it is on. I also want it to record the times of the transitions between settings so that I can later connect it to a computer through USB and retrieve the timestamps of the setting changes, i.e. when the buttons were pressed.

What is the best way to do this? Is it with Arduino or some other way? If it is with Arduino, what would I need to buy, and what would I need to read?

# Answer
Arduino is ideal for it. Buy Arduino or Genuino UNO with Starter Kit. Starter kits contain buttons, LEDs, resistors, breadboard and example projects brochure.

link: Getting Started with Arduino
> 2 votes

# Answer
All is reasonably easy.

* Buttons: use separate buttons, or think about a small 4x4 matrix keypad.
* LED: WS8212 etc or use your own separate LEDs (very cheap)
* Record times: store them on a SD card
* USB: It is possible to send texts via USART which can connect via USB; also you can consider putting the SD card directly in your computer.
> 2 votes

---
Tags: led, usb, timers
---


title: Keypad password check issue

text:
# Question
Title: Keypad password check issue
I am working on a school project, basically I have to create a lock system that opens a fictive gate when the correct code is entered. We have been asked to simulate our system before actually building it. So, I made the following circuit in Proteus(Labcenter Electronics' simulation software):

Here's what my system should do: A variable contains the correct code and the user must type a code on the keypad, and if it is correct, a green LED turns on and the LCD screen displays "Acces Granted!" if the code is wrong, the screen will display "Access refused!". It's a basic system, but I'm trying to make it as simple/short as possible(I have to explain it in an oral presentation, so the simpler the better) and for some reason, I can't get my code to work. Ideally, I'd like to have the LCD display a * for each character typed, liked on a real security system, but I haven't managed to do that either. I've been working on it for hours, trying different variants and etc.. but nothing seems to work the way I want to. BTW, my circuit works perfectly fine and the initialisation part of my code is therefore correct as well. Can anyone help me figure out what's wrong with my code and how I can make it better?

Here's my code so far:

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

//define LED pins
#define redLED 11
#define greenLED 10

String codeSerrure = "87362";   //correct code that opens the imaginative gate
String enteredCode = "";
int keyPressed;

const byte rows = 4;
const byte cols = 3;

char touches_digicode [rows] [cols] = {

  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

byte rowPins [rows] = {25, 26, 27, 28};
byte colPins [cols] = {24, 23, 22};

Keypad leDigicode = Keypad( makeKeymap(touches_digicode), rowPins, colPins, rows, cols);
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

void setup(){
  lcd.begin(16, 2);
  pinMode(redLED, OUTPUT);
  pinMode(greenLED, OUTPUT);
  digitalWrite(redLED, HIGH);
}

void loop(){
  lcd.setCursor(0,0);
  lcd.print(" Entrez le code");

  keyPressed = leDigicode.getKey();
  enteredCode += String(keyPressed);
  if(enteredCode.length() >= 5){
    if(enteredCode == codeSerrure){
      digitalWrite(greenLED, HIGH);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("  Acces autorise!");
      delay(4000);
      digitalWrite(greenLED, LOW);
      digitalWrite(redLED, HIGH);
      enteredCode = "";
    }
    else{
      digitalWrite(redLED, HIGH);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("  Acces refuse!");
      delay(4000);
      enteredCode = "";
    }
  }
  if(keyPressed == "#"){
    lcd.clear();
    enteredCode = "";
  }
}

```

The problem is that when I run this code in the simulation software, the LCD displays "Acces refuse!" and the red LED is on. No matter what keys I press (on the keypad) nothing happens. So the problem is that my code jumps straight to the else statement, inferring that the password typed is wrong (although no password was actually typed). I think the error is in here:

```
keyPressed = leDigicode.getKey();
  enteredCode += String(keyPressed);
  if(enteredCode.length() >= 5){
    if(enteredCode == codeSerrure){

```

Btw, forgive the french words, I am french. Also, I forgot to say, the # key should, clear the entered code. Any explanations, code samples or links would help.

# Answer
The `getKey()` Funktion returns the define `NO_KEY` if no key was pressed, which is set in Keys.h as the NULL char (char with the value 0). In every loop cycle you are adding one character with value 0 to your string. But all functions, that handle strings, will stop, when they find a character with value 0 (it is the delimiter of C strings). Also a string with many NULL chars in it will not be matched to a string only consisting oft digits.

So you should check the return value of getKey for the NO\_KEY define:

```
if(keyPressed != NO_KEY){
  enteredCode += String(keyPressed);
}

```

This avoids adding NULL chars to your string.
> 1 votes

# Answer
After reading all of your comments, I made some changes to my code and I was able to figure out a few other things that weren't working before. I think, because of the way I had coded my password checking function it made all the rest more complicated. I have also implemented the erase key feature, so a press of the * or # keys, erase the entered code. I still need to implement the feature that displays a * on the lcd each time the user presses a key, but I a not sure of what way to do this. Anyways, here's my working code if you're interested:

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

//define LED pins
#define redLED 11
#define greenLED 10

String codeSerrure = "87362";
String enteredCode = "";
char keyPressed;

const byte rows = 4;
const byte cols = 3;

char touches_digicode [rows] [cols] = {

  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

byte rowPins [rows] = {25, 26, 27, 28};
byte colPins [cols] = {24, 23, 22};

Keypad leDigicode = Keypad( makeKeymap(touches_digicode), rowPins, colPins, rows, cols);
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

void setup(){
  lcd.begin(16, 2);
  pinMode(redLED, OUTPUT);
  pinMode(greenLED, OUTPUT);
  digitalWrite(redLED, HIGH);
}

void loop(){
  lcd.setCursor(0,0);
  lcd.print(" Entrez le code");

  keyPressed = leDigicode.getKey();
  if(keyPressed != NO_KEY){
    if(keyPressed == 0x23 || keyPressed == 0x2A){
      lcd.clear();
      enteredCode = "";
    }
    else{
      enteredCode += String(keyPressed);
    }
  }

  if(enteredCode == codeSerrure){
      digitalWrite(greenLED, HIGH);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("  Acces autorise!");
      delay(4000);
      digitalWrite(greenLED, LOW);
      digitalWrite(redLED, HIGH);
      enteredCode = "";
      lcd.clear();
  }
  else if(enteredCode.length() >= 5){
      digitalWrite(redLED, HIGH);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("  Acces refuse!");
      delay(4000);
      enteredCode = "";
      lcd.clear();
  }
}

```

Thank you to everyone for the help (I'm a noobie)! I'm aware that my code is problably not the best way to do what I'm trying to do, so any suggestions and upgrades to the code you could give me are very welcome. Thanks again!

**The final version of my code with all the features working can be found in this thread, for those interested.**
> 0 votes

---
Tags: arduino-mega, lcd, string, code-review, keyboard
---


# Question
Title: What options do I have to get 5v on my current project?
I'm very new to arduino and have started work on my first project, a simple little web server. I'm using a NodeMCU with an sd card module and screen. The issue is that in order to power my sd card module, I need to input 5V which the MCU doesn't provide.

In order to work around this I'm simply using an arduino nano as a power supply to pass into the vin input on the mcu.

What options do I have to exclude the need for the nano? Is there a simple module I can buy that acts as a power supply for 5v?

Any help would be great, thanks!

# Answer
SD cards require 3.3V. Usually, to connect them to an Arduino running at 5V you need to get a level converter. However in your case it sounds like you are making work for yourself:

```
3.3V <--> 5V <--> 3.3V

```

> in order to power my sd card module, I need to input 5V

**Which** SD card module? Maybe you don't need a "module".
> 1 votes

# Answer
The others write that the card needs 3.3V. Your module need 5V. This means that between the input of the module and the sd card is something. it can be a voltage regulator or something like a voltage dropper (resistor in series with diodes). You can search for it on your module. If you are sure you found it you can solder a bridge around it. After this you can give 3.3V to this module.

I think this must work.
> 0 votes

# Answer
To supplement; if you don’t have a level converter on hand, have a look at this diagram: http://homediyelectronics.com/projects/arduino/seriallevelconverter/

Just test it on a breadboard, and if Vcc, Rx and Tx are within 10% of 3.3V, solder it to a bit of perfboard. Haven’t needed to build one myself, since these come in tiny SMD packages which cost almost nothing: https://rover.ebay.com/rover/0/0/0?mpre=https%3A%2F%2Fwww.ebay.com%2Fulk%2Fitm%2F202151474158

... Are you sure your SD module isn’t 5V tolerant? All mine step down 5V to ~3.3V.
> 0 votes

---
Tags: power, arduino-nano, voltage-level, nodemcu
---


# Question
Title: Selecting different arrays using a list of pointers
I have different arrays of different sizes, and a list of pointers to the addresses of each array. How do I select each array using the list of pointers, and access it's elements. On Teensy 3.2 board.

```
int * arr_list[3];
const int arr_sizes[3] = {3,4,5};  // array of the array sizes
const int ar1[3] = {12,2,8};       // arrays of  different sizes
const int ar2[4] = {41,3,6,47};
const int ar3[5] = {9,32,1,5,7};

void map_arrays(){          // list of pointers with the addresses of the
                            // arrays
arr_list[0] = (int*) &ar1;
arr_list[1] = (int*) &ar2;
arr_list[2] = (int*) &ar3;
};

int arr_number = 1;          // select array
int a = arr_sizes[arr_number];    // the size of the selected array
int *b = arr_list[arr_number];
int test = 0;

void setup() {

Serial.begin(57600);  //serial monitor

}

void loop() {

for (int i=0; i<a; i++) {     // for the selected arr_number iterate and
test = b[i];                  // return the index elements

}

Serial.println("size =");
Serial.println(a);
Serial.println();
delay(1000);
Serial.println("index =");
Serial.println(test);
Serial.println();
delay(500);

 }

```

# Answer
> 0 votes
You have it right, only fix initialization of test variables:

1. you do not call map\_arrays() in setup()
2. you assign uninitialized arr\_list item to b

> ```
> const int* arr_list[3];
> const int arr_sizes[3] = { 3, 4, 5 };  // array of the array sizes
> const int ar1[3] = { 12, 2, 8 };       // arrays of  different sizes
> const int ar2[4] = { 41, 3, 6, 47 };
> const int ar3[5] = { 9, 32, 1, 5, 7 };
>
> void map_arrays() {          // list of pointers with the addresses of the
> // arrays
>   arr_list[0] = ar1;
>   arr_list[1] = ar2;
>   arr_list[2] = ar3;
> }
>
> int arr_number = 1;          // select array
> int a = arr_sizes[arr_number];    // the size of the selected array
> const int *b;
> int test = 0;
>
> void setup() {
>
>   Serial.begin(57600);  //serial monitor
>
>   map_arrays();
>
>   b = arr_list[arr_number];
>
>   for (int i = 0; i < a; i++) {     // for the selected arr_number iterate and
>     test = b[i];                 // return the index elements
>     Serial.println(test);
>   }
>
>   Serial.println("size =");
>   Serial.println(a);
>   Serial.println();
>   delay(1000);
>   Serial.println("index =");
>   Serial.println(test);
>   Serial.println();
>   delay(500);
>
> }
>
> void loop() {
> }
>
> ```

---
Tags: array, teensy, pointer
---


# Question
Title: parse intel hex into SPI commands for arduino ICSP AVR
I'm attempting to use the arduino as an ICSP AVR to flash hundreds of ATMEGA's 90USB162. I'm having some difficulties when trying to do the actual flashing of the chip. I've go all the wires done properly and I'm able to read the signature. My source is an Intel hex file and I'm reading it properly as I'm able to see each by as it is read from the arduino's memory. Where I'm getting lost is the documentation states that I need to set the low byte first before I set the high byte for the same memory address. Using the following as an example (underscores to break the data up) could someone help me descern what my SPI transaction bytes would look like?

```
:_20_0000_00_16C100003CC100003AC1000038C1000036C1000034C1000032C1000030C10000_48

```

I know the colon is the start code, 20 is the hex value of number of data bytes, 0000 is the address, 00 is the record type, the next 32 bytes is my data followed by the checksum.

I thought that I would loop over the data portion and increment the address every other byte

```
uint16_t addr = 0;

while (recordtype != endOfFile)
{
  auto data[] = parseData();

  for(uint8_t index = 0; index < 32;)
  {
    SPITask.Send(0x40, 0x00, addr, data[index++]);//send low byte
    SPITask.Send(0x48, 0x00, addr, data[index++]);//send high byte
    SPITask.Send(0x4C, addr, addr, 0x00);//commit new bytes to address
    addr++;
  }
}

```

I don't think this is right and some examples i'm loosely following comment that they are changing the address byte into a word, which makes some sense based on the command layouts of the data sheet (page 260) 90USB162 Data sheet. Can anyone please provide some guidance in how to break up this data into high and low bytes.

# Answer
I have some code that does exactly what you want on GitHub.

Amongst other processors, it supports the At90USB162 chip. The code reads from an SD card in Intel hex format and writes to the chip at the press of a switch. This effectively is what you are trying to do.

Arduino forum moderator "Crossroads" (who has recently also joined Stack Exchange) has made a board to do the programming, hold the SD card, and have some status LEDs:

Here is my code to write to the flash:

```
// execute one programming instruction ... b1 is command, b2, b3, b4 are arguments
//  processor may return a result on the 4th transfer, this is returned.
byte program (const byte b1, const byte b2 = 0, const byte b3 = 0, const byte b4 = 0)
  {
  noInterrupts ();
  BB_SPITransfer (b1);
  BB_SPITransfer (b2);
  BB_SPITransfer (b3);
  byte b = BB_SPITransfer (b4);
  interrupts ();
  return b;
  } // end of program

// write a byte to the flash memory buffer (ready for committing)
void writeFlash (unsigned long addr, const byte data)
  {
  byte high = (addr & 1) ? 0x08 : 0;  // set if high byte wanted
  addr >>= 1;  // turn into word address
  program (loadProgramMemory | high, 0, lowByte (addr), data);
  } // end of writeFlash

```

---

Your loop looks a bit strange, the page size (before you need to commit) is 128 bytes (64 bytes), not 2 bytes.

See the datasheet:
> 1 votes

---
Tags: avr, icsp
---


# Question
Title: Controlling 4 motors using the Arduino Uno
I've decided to make a quadcopter but since I'm a rookie, i decided against doing it from scratch. I'm planning to order this kit, first understand the dynamics and then try and make a quadcopter on my own using the components in it. My first question are

* Can I control the 4 motors using 2 H-bridges (L293D)?
* Are ESC's necessary if I use the PWM pins?

Thanks in advance!

# Answer
> Can I control the 4 motors using 2 H-bridges (L293D)?

Yes. Two per chip.

> Are ESC's necessary if I use the PWM pins?

There is one thing you must understand first: there are two kinds of DC motor - Brushed and Brushless.

The Brushed motor is the "normal" kind - you apply power to it and it spins. These you control with the likes of an L293D and use PWM to control the speed.

Brushless motors are the kind you have in hard drives and the like. They consist of a number of coils that get turned on and off at the right time to pull a magnet around in a circle (to put it crudely). These require special timing and control to get the coils energised at the right time and in the right way. This is what an ESC is for.

Brushless motors are smaller and lighter for the same power than brushed ones. They also have a longer life. Because of this they are generally preferred to brushed motors on quadcopters.

Brushed motors have a very high starting torque, don't require complex control logic and use less energy when not running full speed.

If you use brushless motors, which ideally you should (though I can't tell what kind of motors those are in that kit) then you must either use an ESC or build your own ESC using an Arduino and multiple motor driver circuits. Simplest to use an ESC.

If you don't use brushless motors then an ESC is not what you want to use - just the L293D chips and PWM.
> 2 votes

# Answer
I fully agree with the answer of Majenko but I think something is missing in the explanation.
When you say "I want to control a motor" then it is not yet clear what is needed. There are the following options
1) on/off in one direction (forward).
2) on/off in 2 directions (forward and backwards).
3) on/off in on direction with speed control.
4) on/off in two directions with speed control.

For a brushed dc motor this can be achieved with.
1) a single pole single throw relay (this is similar to a on of switch)
2) a single pole single throw relay and a double pole double throw relays (this is a on off switch and a switch to change the wires to the motor)
3) a mosfet (this is similar to a single pole single throw switch that can go on/off very fast)
4) a H bridge. That is 4 mosfets that are controlled in a certain way.

Now here comes the trick: H bridges often come in 2 half H-bridges. And with a half H-bridge you can control a motor at level 3.

In other words ... with a chip that has 4 half H bridges (an as such 2 H- bridges) you can control 4 brushed DC motors at the level 3 (forward speed controlled) or 2 brushed DC motors at the level 2 (back and forward speed controlled).
> 0 votes

# Answer
You also need to consider the current needed by your motors (they are DC brushed indeed) and the power/energy you will lose in your driver.

If you use a 3.7V power supply like provided, and the L293D "eats" 1.2V out of it, you lose nearly one third of your energy. See https://electronics.stackexchange.com/questions/108686/what-h-bridge-drivers-are-preferred-for-applications-controlling-a-low-voltage-m for an very interesting review of drivers.

If I can believe that, it looks like DRV883x is the only reasonable choice. It even allows you to use one cell (3.7V) for the logic and 2 cells (7.4V) or more for the motors. But don't do that with the motors you've got, you'd probably burn them.

Unfortunately the other ST or Allegro devices also covered in the article all need more voltage to work.

Regarding the Arduino, a UNO can't be recommended, too heavy, 5V only, power hungry etc. It won't fly. I'd recommend you use a pro mini 3V3 with some LDO power supply such as the TPS73633. Be careful that most LDO regulators (like 1117) have a too high dropout voltage to be used with a 3.7V input, more than 1V.

I'm not affiliated with TI at all, it just happens that when looking for "the right chip for the right job", I keep having to eliminate the others because of data sheet numbers.

On the SW part however, it becomes difficult to find SW for the 328P. Most addicts have moved to 32-bit CPUs. But that's another debate.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Can I use a 3.3v GPIO to control an opto-isolated 5v relay board?
I am working on a DIY home automation project using a Wemos D1 Mini as the controller, and I ordered some 4-channel 5v-triggered relay boards. The ESP8266 that Wemos D1 Mini's are built on has GPIO output voltage of 3.3v, ostensibly too low to trigger the relays.

I've read a Reddit post that was saying that as long as you use a separate 5v power suppy for the relay board, 3.3v should be enough to trigger the relays. Is that accurate, or do I need to use a transistor or something to provide the relay board inputs with 5v?

# Answer
> 2 votes
Yes, the Reddit post's approach is likely to work ok, as long as you correctly follow the cautions in it: • connect the VCC pin of the relay board to a 5V source, • connect together the Arduino ground, the relay ground, and the 5v-source ground.

Here is a typical relay-module circuit diagram (for one channel):

(Note, this diagram is from a home automation blog; for more discussion and similar diagrams, see eg 4-relay-shield-diagram at yourduino.com and stripboard-shield-relay-sm at startingelectronics.org.)

As you can see in the diagram, the Arduino pin that connects to JP2-2 will not be exposed to voltages. (The base of an NPN transistor effectively is at the junction of two back-to-back diodes.)

When the Arduino or ESP pin at JP2-2 is at about 0 V (ie, when the Arduino pin is off) IBE=0; that is, no Q2 base-emitter current will flow; thus, Q2 will be off, so that both of LED1 and relay U1 will remain off.

When the Arduino or ESP pin at JP2-2 is at about 3.3 V (ie, when the Arduino pin is on) IBE is about 2.5 mA, which should be enough to reduce VCE to about 1 V, leaving 4 V across the relay coil, or enough to turn it on.

Note, the 2.5 mA figure for this circuit is calculated as follows: IBE = (3.3-VBE)/1000 - VBE/10000 = (3.3-0.7)/1000 - 0.7/10000 = .00260 - .00007 = .00253 A = 2.53 mA. Note that the alternate circuit diagrams linked above don't have a 10KΩ resistor like that in the diagram above, so instead of about 2.5 mA would have about 2.6 mA drive.

If for some reason you don't have quite enough base drive – in which case you might be able to hear a slight click from the relay, even if it doesn't switch – you could increase the "5 V" line into the LED and relay to say 5.5 V or 6 V. As noted before, the back-to-back diodes structure of the NPN transistor will isolate that voltage from your Arduino or ESP.

# Answer
> 0 votes
Short answer : it will probably work.

If your relay board is opto-isolated, there is a small potential risk that 3V3 may not be enough to lit the optocoupler sufficiently, you will have to test it.

The reddit board is not using optical separation but only a transistor, like on the schematic of the answer above,. In that case, 3V3 is always enough to saturate the transistor. Anything above around 1V5 would probably do, but this can vary according to the resistors, relay consumption and transistor gain.

There is an extensive discussion of this topic at https://www.forward.com.au/pfod/HomeAutomation/OnOffAddRelay/index.html#Mods3v3

---
Tags: esp8266, voltage-level, relay
---


title: Arduino Reaction LED game

text:
# Question
Title: Arduino Reaction LED game
I have this code and it is a reaction light game. When you press the button on pin 11 it starts the game and the lights should osculate back and forth. The main goal is to press the button when it hits the middle led and the osculating will slow down. I cannot get the leds to turn on help?

```
    int ledPin;
    int direction;
    int isChanging;
    unsigned long lastChange;

void setup() {
   //set pins 2 to 10 to be output
  // and LEDs off
   int pin;
    for (pin = 2; pin <= 10; pin++) {
       pinMode(pin, OUTPUT);
       digitalWrite(pin, LOW);
    }
     //set pin 11 to be input
     pinMode(11, INPUT);

     ledPin = 2;
     direction = 1;
     lastChange = millis();
  }

 void loop() {
    if (isChanging) {
    if (millis() - lastChange > 500) {
        //turn off old LED
        digitalWrite(ledPin, LOW);
        //reset time
        lastChange = millis();
        //change the led
        ledPin = ledPin + direction;
        if (ledPin > 10) {
          direction = -1;
        ledPin = 9;
      } else (ledPin < 2); {
        direction = +1;
        ledPin = 3;
     }

       //turn on new LED
        digitalWrite(ledPin, HIGH);
     }
       //check for button
       if (digitalRead(11)) {
        isChanging = 0;
     }
     }
    else {
       //wait for them to let go of the button
       while (digitalRead(11)) {
     }
       //wait for it to be pressed again
       while (!digitalRead(11)) {
     }
       //wait for them to let go of the button
       while (digitalRead(11)) {
     }
    }
   }`

```

# Answer
> 1 votes
Your are not explicitly initializing the variable `isChanging`, so the compiler sets it to `0`. This means, that your code will directly go to the last else statement and cannot at any time reach the LED code, because you are not changing the variable in the else statement.

But I don't really understand, why you were using this variable in the first place. Try to use purely non-blocking code. For checking the button you can do something like this:

```
boolean button_pressed = false;
unsigned long button_timestamp = 0;

void loop(){
  ...
  if(!button_pressed && digitalRead(11)){
    button_pressed = true;
    button_timestamp = millis();
  }
  if(button_pressed && millis() - button_timestamp > 50){
    if(digitalRead(11)){ // real button press
      button_pressed = false;
      // check, if the middle LED is ON and act accordingly
      // or, if the game hasn't started yet, start it
    } else { // just a bounce of the button, not a real button press
      button_pressed = false;
    }
  }

  // LED CODE
  if (millis() - lastChange > 500) {
    ...
  }
}

```

Note, that this code will not wait for the button to be released, but reacting, when the button was held down for 50ms. You can change this value, to a one, that is more fitting your used button, but it is a good start point.

Also in your LED code, you have to replace the 500 in the millis statement with a variable, since you want to change the speed.

For handling starting the game with the same button, you can use a state variable, which contains a value of means "Game Stopped" or "Game Started".

---
Tags: led
---


title: arduino didn't working properly

text:
# Question
Title: arduino didn't working properly
arduino didn't working properly. When i using a alarm program on pin 6 and a blinking led on pin 2 alarm sound beeps once and then goes down but when using only alarm program it works perfectly. I see that arduino can handle one pin perfectly but when it comes to use two pins together it can't handle properly

```
float sinVal;
int toneVal;
void setup(){
                pinMode(7, OUTPUT);
                pinMode(2, OUTPUT);
}
void loop(){
                for(int x=0; x<180; x++)
                                { //convert angle of sinusoidal to radian measure
                                sinVal = (sin(x*(3.1412/180)));
                                //generate sound of different frequencies by sinusoidal value
                                toneVal = 2000+(int(sinVal*1000));
                                //Set a frequency for Pin-out 8
                                tone(7, toneVal);
                                delay(2); }
                digitalWrite(2, HIGH);
                delay(100);
                digitalWrite(2, LOW);
                delay(200);
}

```

# Answer
> 0 votes
with this wiring setting pin 2 HIGH shorts pin 2 to ground and Arduino dies. you must use a resistor in series with LED. and better use one with the speaker too.

# Answer
> -1 votes
I'm not sure but its your power supply. I suggest to used another power supply on your arduino. Use 9V battery and connect it to Vin(+) and GND(-) and test if there is an improvement.

---
Tags: arduino-nano
---


# Question
Title: Connecting Arduino Mega + SIM800L to a car battery
I need to make a car tracker powered from a car battery. The problem is the SIM800L needs to be powered with 3.8v to 4.2v, and at 2A preferably. I want to connect the car battery to my Mega first then the Mega powers the SIM800L.

So:

Car battery \> Mega \> SIM800L

What do I need to achieve this?

This is the SIM800L model:

# Answer
With this setup you are overstressing the onboard regulator, while wasting a lot of power (not suggested on a battery setup, even if the battery is quite big).

First of all, the power. You have a MEGA, which runs at 5V/few mA, and a SIM800L, which runs at 4V/2A. I suggest you to have two power supplies. On ebay you can find cheap XL4015 converters rated at 5A. You connect IN+ to the +12V, IN- to the ground, then set the first one to output 5V, while the other to 4V. If you want to have the most correct powering scheme connect the 5V to the USB port, otherwise connect it to the +5V pins (note that you will exclude the fuse).

Then there is another problem: the UART levels. As a first approximation you can hope that the arduino reads the correct levels, so you'll just have to lower the TX voltage from 5V to 3.3V. You can do this by using a voltage divider with a 4.7k resistor between arduino TX and SIM RX and a 10k resistor between SIM RX and ground (see, for instance, how they did it in this image).
> 1 votes

# Answer
> I want to connect the car battery

The Mega has an NCP1117 linear voltage regulator onboard. This is qualified for automotive use, however the max. output current at 12V input voltage is only 1A, which is too less to supply your SIM800.
Next thing you should consider: The car voltage is not stable. Voltage peaks up to 40V can occur, especially when starting the engine. This will stress your components, and destroy them in worst case.
I would use two DC/DC converters with high enough input voltage and adjust one to 7V output (for the Arduino), the other one to 4V (for the SIM) and connect the ground lines together.

For voltage level matching between Arduino and SIM Uart see page 32 of SIM800 hardware manual.
> 1 votes

---
Tags: arduino-mega
---


title: Write to EEPROM before shutdown

text:
# Question
Title: Write to EEPROM before shutdown
I'm currently designing a battery operated device that has to write data to an EEPROM before shutting down, or in regular intervals to save data. Would it damage the EEPROM if it had to shut down while it is being written to?

The first possible case is when it is transmitting the data over I2C. That shouldn't affect it much. But if it gets powered down while it is actually writing the byte to its memory, I don't know whether it would save it correctly or corrupt it.

# Answer
> 2 votes
According to the datasheet, an EEPROM write takes 3.3mS. If power drops below the level needed to complete the write, the data will be corrupted.

---
Tags: eeprom
---


title: Can't re-write Arduino Pro Mini

text:
# Question
Title: Can't re-write Arduino Pro Mini
I am just getting started with arduino, but I am having an issue with some 3.3V, 8Mhz Arduino Pro Minis. I am using a SparkFun FT232RL USB to Serial breakout (https://www.sparkfun.com/products/12731) to communicate with the board, using Windows 7 and the Arduino IDE.

The Pro Minis were blank when I got them, I am able to upload a single program (Blink), which runs successfully, but I am unable to upload subsequent programs. I get the error:

```
avrdude: stk500_recv(): programmer is not responding

```

Any idea what might be going on?

# Answer
> 0 votes
Connect the DTR pin from the FT232 to the Promini as well, that will allow the software autoreset to work. Promini has a 0.1uF cap between the DTR pin and Reset already.

---
Tags: serial, arduino-pro-mini
---


# Question
Title: SoftwareSerial runs out of "text" space on ATtiny
I have an ATtiny and am trying to send a very large byte array stored in a separate `.h` file over SoftwareSerial:

```
for (int i=0; i<numElements; i++) {
    softSerial.println(myList[i]);
}

```

I imagine it will very slow, which is fine, but I'm getting a cryptic error when compiling:

```
Firmware.ino.elf section `.data' will not fit in region `text'

```

It seems that this is due to the `println()` command running out of memory for some reason – if I comment out the `println()` command everything works fine. How to fix this?

# Answer
Your sketch doesn't fit into program memory of the ATtiny. If you comment out the `println` of the array, the compiler evaluates that the array is not used and doesn't attach it to the program. Then the program fits into memory.

**EDIT**
Chad suggests some good alternatives below, if you need to store more data than flash or `PROGMEM` will allow.
> 3 votes

# Answer
There is not enough room in program memory for 140KB. ATiny only has 8KB for the whole program. So there is no way to fix this with your current hardware.

Options-

add a storage device (SD card, sram module, others....) where you can store the data, and then read it in small chunks and send it out

possibly use a arduino mega. It has 256KB of program space. you will still have to make sure you are not trying to store the whole byte array in an array since that would get stored in sram (which there is still only 8KB) but it could again to written in chunks to avoid this problem.
> 3 votes

# Answer
The ATTiny only has a limited amount of RAM. A lot less that flash-memory.

Using a normal array, the entire contents of the array are placed into RAM (during initialization). Which is very limited.

I'd suggest, looking into PROGMEM. This is a way to read the data directly from the flash-memory.
> 1 votes

---
Tags: softwareserial, attiny, memory
---


# Question
Title: Has pt.h library been removed from arduino?
I'm trying to get a program to use protothreading and I've got an error at the include statement for the pt.h library stating that there is no such file or directory. This is how it's written in the program:

```
#include <pt.h>

```

# Answer
`pt.h` has never, and will never, be part of the Arduino core distribution. It is a completely separate third party library that you have to install yourself.

I think the library you want is this one.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: expected primary expression before ')' token
```
#define ANALOG_IN 0

void setup() {

  Serial.begin(19200);

  analogReference(INTERNAL);

}

void loop() {

  int val = analogRead(ANALOG_IN);

  Serial.print(0xff, byte);

  Serial.print( (val >> 8) & 0xff, byte);

  Serial.print( val & 0xff, byte);

}

```

This is my code and I'm getting this error for all 3 Serial.print commands. Please help.

# Answer
> 1 votes
Why are you putting `byte` there? That isn't in the Serial.print reference page.

This compiles OK:

```
#define ANALOG_IN 0

void setup() {
  Serial.begin(19200);
  analogReference(INTERNAL);
}

void loop() {
  int val = analogRead(ANALOG_IN);
  Serial.print(0xff);
  Serial.print( (val >> 8) & 0xff);
  Serial.print( val & 0xff);
}

```

---
Tags: arduino-uno, serial, programming, arduino-ide
---


# Question
Title: How to know the external interrupt origin from the ISR
I'd like to know if there is any way to know what is the origin of an external interrupt by programming inside the ISR.

I know I can use a different ISR for each external interrupt and that works but I'm thinking if it's possible to use the same ISR for all external interrupts

If you check the origin pin and trigger condition inside ISR it's not a reliable way to do.

Is there any memory record which store the external interrupt activation?

This is a general question for any AVR microcontroller.

# Answer
> Is there any memory record which store the external interrupt activation?

There is, but I do not think it will be easy to exploit.

At low level, each interrupt is handled by a different ISR. So you will have `INT0_vect` handling external interrupt 0 and `INT1_vect` handling interrupt 1. These ISRs are all defined by the Arduino core library. In your case, they will both call the same handler that you defined. Thus, the information about which ISR fired is now on the stack: it is the return address of your function.

The reason this information will not be easy to use is that you do not know how far it is from the stack pointer. It depends on how much stuff your own handler pushed onto the stack. You could disassemble it and count, but then your code will be fragile, as the smallest change in the handler (or compiler version) may change this count.

An easier approach may be to define your own `INT0_vect` and `INT1_vect`, overriding those from the Arduino core. These new ISRs will both call your handler, but they will pass it an argument to tell which interrupt fired.

Or you can register a different handler for each interrupt, each calling a common function. But this adds an extra level of function calls.
> 1 votes

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


# Question
Title: remove weird chars from char array ESP32
When I'm converting a string to a char array there are always some weird chars at the end. I have to do it manualy because the convertTochar function crashes my ESP.

```
  String sssid = module.getCssid(); //String is stored in the eeporm
  char cssid[sssid.length()];
  Serial.println(sssid.length()); //prints correct length of 6
  //convert do ssid
  for( int i = 0; i<sizeof(cssid);i++){
    cssid[i] = sssid[i];
  }
  Serial.println(cssid); //prints myssid⸮?⸮2⸮?
enter code here

```

If I'm printing the value directly fromm eeprom there are no wired characters. Also the max eeprom size for the string is 10 bytes...

Why are these characters at the end of string?

# Answer
You forgot to add one more character to the array to place a \0 (0 value byte) in. This denotes the end of a string. If you forget this, the string will continue until it finds the first 0 byte, which will probably be after the original string copy. This can be dangerous, because it might be in memory that is not containing useful data, and those weird character can be many if there is not a 0 soon or at all.

Note that the 6 bytes you get are the bytes EXCLUDING this 0 byte, so you need to allocate 7 bytes to store a string of length 6.

Instead of the for loop you can use the strcpy function which copies a function including the 0 string.

See description:

Description

The C library function char \*strcpy(char \*dest, const char \*src) copies the string pointed to, by src to dest.

Declaration

Following is the declaration for strcpy() function. char \*strcpy(char \*dest, const char \*src)

Parameters

dest − This is the pointer to the destination array where the content is to be copied.

src − This is the string to be copied.

Return Value

This returns a pointer to the destination string dest.

Example

The following example shows the usage of strcpy() function.

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

int main () {
   char src[40];
   char dest[100];

   memset(dest, '\0', sizeof(dest));
   strcpy(src, "This is tutorialspoint.com");
   strcpy(dest, src);

   printf("Final copied string : %s\n", dest);

   return(0);
}

```
> 2 votes

---
Tags: string, esp32
---


# Question
Title: Use LoLin V3 pins starting with 'S' in Arduino
I have this LoLin NodeMcu V3 board:

What are the pins S3, S2, S1, SC, S0, SK? Can I use them as GPIO in Arduino?

Thank you for your help!

# Answer
These pins have 2 functions: They are the connections to an SD card and/or to its internal flash chip. The ESP8266 has the feature of when you set GPIO15 HIGH during bootup, it will load the program from SD card and execute it. See here for reference. On the normal board, these pins are however connected to an internal flash chip.

Signal name meanings:

* SK: Serial Clock
* SC: SPI Chip Select
* S0 to S3: Data lines (Quad-I/O mode).

This picture found here explains the pins:

But as @Majenko already said, only the chip documentation matters, which is here:

Now to answer the actual question: Can you use these pins for arbitrary purposes? That depends. On the board they are all internally connected to a Quad-SPI flash chip. If you re-assign these pins to GPIO pins during normal operation in Quad-SPI mode, the chip hang up as the you just cut off one of the important lines to flash chip. **However**, if you really want you can modify your chip and cut two connections from the flash chip. Quad-SPI uses 4 data lines, but you can also operate the chip in Dual-SPI with 2 data lines (refer to here).

That means that you are able to cut 2 of the 4 data lines, GPIO9 (SPI\_HD, S2 on the board) and GPIO10 (SPI\_WP, S3 on the board) on the PCB from the ESP8266 to the flash chip and then use these two GPIO pins arbitrarily. This is to avoid interference with the flash chip when you are driving random signals to it while the lines are still physically conencted to the flash chip. You will ofcourse need to tell your flash tool (`esptool.py`) to use Dual-SPI mode for all subsequent firmwares. See here for that.

All other Flash GPIO pins can not be re-purposed, these conenctions (such as SCLK, MISO, MOSI, CS) are always needed for the flash chip.

GPIO15, which is D8 on the board, is easier to repurpose: You just need to make sure it's LOW during startup as to not trigger the SD card bootup by using a pulldown resistor. After flash bootup you can re-purpose it for input and output. This is already done on the board for you and you just need to use `pinMode` to set it as INPUT or OUTPUT. This is also described in here.

Obviously that's a lot of trouble to get 2 GPIO pins. If you just want more GPIO, you will find an I²C GPIO port expander such as the MCP23017 much more suitable for that -- 16 more GPIOs at the cost of 2 GPIO pins (the I2C bus). If you're already using the I2C bus in a project then you don't even loose additional GPIOs, it's just one more device on the bus.
> 5 votes

# Answer
My guess is those are the SDIO pins. They're meant for use with an SD card - 4 data pins, a clock pin, and a select pin.

To find out what more you can do with them you should ignore the fact that it's a "LoLin" and instead just look for documentation on the ESP8266 or ESP32 (whatever it is on there) that powers that board.
> 1 votes

---
Tags: arduino-ide, pins
---


# Question
Title: If an I2C connection is lost for a short period of time will it work if the connection is live again?
I'm using an ESP8266 with the Arduino library to read from a sensor(MPU9250 specifically). The readings are done via I2C but I'm using a library that abstracts these methods.

The wires are not soldered together so temporary disconnections are possible and after these disconnects the sensor readings freeze. I'm new to the world of I2C so my questions are:

* Do I have to re-init the connection after it disconnects or is there a way to continue on re-connection immediately?
* Is there a way to prevent this to happen (for example to stop reading when there's no connection) or should I just solder together the pins?

# Answer
When an I2C master starts a transmission or a request from a slave, it sends the slaves address and then check for an acknowledgement (ACK) from the slave (SDA LOW, when the clock has a HIGH pulse). When no slave is connected, or there is no slave with this address, then there isn't any circuit to pull SDA to LOW on the clock pulse, that is generated by the master. This is interpreted as No acknowledgement (NACK) and the transmission/request fails and should exit. So a disconnection between the transmission should not freeze your code (though I don't know what your library is doing exactly).

A quick google search gives me, that the esp8266 does not have hardware I2C, so your library does a pure software I2C. There are many pitfalls, which can block the I2C bus (especially, if one the lines is hold LOW by one of the involving circuits). Your library may or may not implement the correct I2C protocoll.

So to clearly answer your questions:

1. You don't have to reinit connection. Your master transmission fails, if there is no slave, and should give you an error as return value. But be sure, that there isn't happening anything on the SDA or SCL lines, when it starts up again after reconnection. Master or slave can interpret voltage spikes as signal.
2. If the library is implemented correctly, it will exit, when there is no ACK from the slave.

Look into the documentation of your library how it handles these events. And check the state of SDA and SCL, when a block occures. You can refer to this site for further information about I2C. It also gives some advice if your bus is blocked.
> 1 votes

---
Tags: esp8266, i2c
---


# Question
Title: Arduino: using digital pins to emulate USB device
Is there any "easy" way to emulate USB keyboard or gamepad using digital pins on Arduino Mega? I looked at Uno-Joy/Mega-Joy, but I dont find firmware changes appealing.

# Answer
> 1 votes
There is (or was) an implementation of software-only USB for the Arduino. I think it was called V-USB, though I am having trouble finding it now.

I think it may be this library though nothing has happened with that for a number of years.

Personally, I wouldn't recommend it, though, and would suggest using a board with a real USB interface, such as the Arduino Leonardo, chipKIT Lenny, or Teensy 3.x.

---
Tags: arduino-mega, usb
---


# Question
Title: Arduino - Finite State Machine does not start in the initial state
I'm building a state machine using 6 flip-flopsD, and an G input coming from an infrared sensor. This circuit should count from 0-35. The problem is that it always starts in state 111111. That is, after it passes through Flip-flop D A, B, C, D, E, F = 1;

Here's my code:

```
#include "flipflopD.h"

boolean a1,b1,c1,d1,e1,g1;//display 1
boolean a2,b2,c2,d2,e2,f2,g2;//display 2
boolean Aa=false;
boolean Bb=false;
boolean Cc=false;
boolean Dd=false;
boolean Ee=false;
boolean Ff=false;
boolean A=false;
boolean B=false;
boolean C=false;
boolean D=false;
boolean E=false;
boolean F=false;
boolean G=false;//receiver

void setup() {

    //DISPLAYS
    pinMode(A0, OUTPUT);
    pinMode(2, OUTPUT);
    pinMode(3, OUTPUT);
    pinMode(4, OUTPUT);
    pinMode(5, OUTPUT);
    pinMode(6, OUTPUT);
    pinMode(7, OUTPUT);
    pinMode(8, OUTPUT);
    pinMode(9, OUTPUT);
    pinMode(10, OUTPUT);
    pinMode(11, OUTPUT);
    pinMode(12, OUTPUT);
    pinMode(13, OUTPUT);

    pinMode(A2, INPUT);// IR RECEIVER
}

void loop() {
    //  Counter
    G = digitalRead(A2);
    Aa = flipflopD((A||!B||!C||!D && !A||B||C||D||E||F||G), A, G);
    Bb = flipflopD((!A||B||!C||G && !A||B||F||!G && !A||B||E||!F && !A||B||D||!E && !A||B||C||!D && !A||!B||C||D||E||F||G), B, G);
    Cc = flipflopD((!A||C||!D && !A||C||!E && !A||C||!F && !A||C||!G && !A||!C||D||E||F||G), C,G);
    Dd = flipflopD((!A||D||!E && !A||D||!F && !A||D||!G && !A||!B||!C||D && !A||!D||E||F||G && !A||!B||C||!E||!F||!G), D, G);
    Ee = flipflopD((!A||E||!F && !A||E||!G && !A||!E||F||G && A||!B||!C||!D||E && !B||!C||!D||!E||F||G), E, G);
    Ff = flipflopD((!A||!F||G && !A||F||!G && !B||!C||!D||!F||G && !B||!C||!D||F||!G && A||!B||!C||!D||E||G), F, G);

    A=Aa;
    B=Bb;
    C=Cc;
    D=Dd;
    E=Ee;
    F=Ff;

    //   ABCDEF TO 7 Segments
    a1 = !A||B||D && !A||B||C & A||!B||!C||!D;
    b1 = !A||B && !A||C||E && !A||C||D && A||!B||!C||!D;
    c1 = !A||!B||C||E && !A||!B||C||D && !A||C||D||E && !A||B||!C||!D + A||!B||!C||!D;
    d1 = !A||B||D && !A||B||C && A||!B||!C||!D;
    e1 = !A||B||!C||D && !A||B||D||!E && !A||B||C||!D;
    g1 = !A||B||D && !A||B||C & A||!B||!C||!D;

    a2 = (!A||!C||E  &&  !A||!B||!D||!F  &&  !A||!B||D||F && !A||!B||C||!E && !A||C||D||!E && !A||B||!C||!F && !A||B||!D||F && !A||B||E||!F && !B||!C||!D||E||F && A||!B||!C||!D||!E);
    b2 = (!A||B||D && !B||!C||!D||!E && !B||!C||!D||!F && !A||!B||!E||!F && !A||!C||!D||F && !A||!C||!D||E && !A||!C||E||F && !A||!D||E||F && !A||!B||C||!E && !A||!B||C||!F && !A||C||!E||!F);
    c2 = (!A||F && !A||!D||!E && !A||C||E && !A||B||!D && !A||B||!E && !B||!C||!D||F && !A||!B||!C||D && A||!B||!C||!D||E);
    d2 = (!A||!B||!C||!D||!F && !A||!B||!C||E||!F && !B||!C||!D||E||F && !A||!C||D||!E||F && !A||!B||C||!D||!E && !A||!B||C||!E||!F && !A||C||!D||!E||!F && !A||!B||C||E||F && !A||C||!D||E||F && !A||C||D||E||!F && !A||B||!C||!E||F && !A||B||!D||E||!F && !A||B||!C||D||!E && !A||B||!C||D||F && !A||B||D||!E||F && A||!B||!C||!D||!E);
    e2 = (!A||!C||!D||!F && !A||!C||E||!F && !A||!D||E||!F && !A||B||D||!F && !B||!C||!D||!E||!F && !A||!B||C||!E||!F);
    f2 = (!A||!C||!E||!F && !A||C||!D||!E && !A||C||E||!F && !A||B||C||!E && !A||!B||!C||D||!E && !A||!B||!C||D||!F && !A||!B||C||D||E && !A||B||!C||!D||E && A||!B||!C||!D||E);
    g2 = (!A||C||!E && !A||!C||!D||E && !A||!C||E||!F && !A||!B||D||!E && !A||!B||C||D && !A||B||!D||!F && !A||B||!C||E && A||!B||!C||!D);

    // OUTPUTS

    //DISPLAY 2
    digitalWrite(A0,a2);
    digitalWrite(2,b2);
    digitalWrite(3,c2);
    digitalWrite(4,d2);
    digitalWrite(5,e2);
    digitalWrite(6,f2);
    digitalWrite(7,g2);

    //DISPLAY 1
    digitalWrite(8,a1);
    digitalWrite(9,b1);
    digitalWrite(10,c1);
    digitalWrite(11,d1);
    digitalWrite(12,e1);
    digitalWrite(13,g1);
}

```

Here's my Flip-FlopD:

```
boolean flipflopD(boolean D, boolean Q, boolean CLK){
  boolean Qo=false;
    if (CLK=true) {
      Qo=D;
    } else {
  Qo=Q;
  }
  return Qo;
}

```

Can someone tell me what's wrong?

# Answer
> 3 votes
One potential error source: In your D-Flip-Flop code, you have

```
boolean flipflopD(boolean D, boolean Q, boolean CLK){
  boolean Qo=false;
    if (CLK=true) {
      Qo=D;
    } else {
  Qo=Q;
  }
  return Qo;
}

```

You probably want to do a comparison with double `==` instead of an assignment with `=` in the line

```
if(CLK=true)

```

This causes the `if` to always evaluate to `true` and set `Qo=D`.

Also, I am not really sure if this is what you want:

```
a1 = !A||B||D && !A||B||C & A||!B||!C||!D;

```

First, you're mixing `&&` (logical-and) with the bitwise `&` here. Next, C++ operator precedence dictates that the `&&`has a higher priority than `||`. This looks like a conjunctive-normal-form of some boolean function, thus I would group the AND terms in parenthesis, like

```
a1 = (!A||B||D) && (!A||B||C) && (A||!B||!C||!D);

```

In the `c1` expression you are also suddenly using the `+` operator in a chain of logical expressions, which looks wrong.

Overall I don't quite get how this should work. If you have an IR receiver connected to A2, from which you read the "CLK" input, it will get some 39kHz input wave when you point a IR remote at it and press a button. And you want that on each CLK rise/fall the Arduino reacts to it by calculating the output for a seven-segment display? Your Arduino Uno/Nano with its 16MHz will take some time to execute each of the statements in the loop, sequentally. So what you're doing is actually sampling the A2 input every now and then -- how often exactly, I don't know, maybe with a few kilohertz. Your Arduino might sample the input at the wrong time or not fast enough to react the way you expect. `digitalRead` and `digitalWrite` are notoriously slow, maybe try direct port access or an interrupt-based approach. Of course, calculating all these AND, OR and NOT expressions will take some processing time, too.

This sort of combinational logic is more suited for an FPGA implementation, not for an Arduino.

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


# Question
Title: Getting the voltage of an 18650 battery with an Arduino
I'm using a Arduino Pro Mini (5v) to sense the voltage of an 18650 battery. The battery (that is being sensed)is also used to power the Pro Mini but the MCU is behind a boost-converter which outputs 5.05v. Would I be able sense the right voltage of the battery?

simulate this circuit – Schematic created using CircuitLab

The boost converter has an input voltage ranges to 0.9 to 5 volts and current of 600mA.

# Answer
Yes, if Vin- and Vout- are joined together inside the boost converter or share a common ground on the boost converter circuit board such as this one:
> 1 votes

---
Tags: power, analogread, voltage-level
---


# Question
Title: Did I overheat my Arduino while soldering to perfboard?
So this is the second time that I've had a circuit that worked perfectly on a breadboard, but as soon as I connected it to a perfboard and soldered the joints together, the Arduino stopped working and wouldn't let me upload sketches (though I could see a COM port for it).

I'm using lead-free solder for the first time, and had the temperature at 750 deg Fahrenheit, and I'm thinking that while I had quick joints to connect the Arduino to the perfboard, when bridging two joints with solder, the iron might have been heating the header pin for 4-10 seconds... Is that enough to break the board?

(note - I'm using jumper wires on the other side to connect everything up, and I've already checked the board's connections using a multimeter and they're all as intended, and there are no accidental shorts/bridges)

# Answer
> I would like to clarify that my only question in ENTIRE post was: "Is that enough to break the board?"

The answer to that narrow question is that *heat from soldering with an iron* is extremely unlikely to have done this. IC's are in practice (vs data sheet) quite heat tolerant, and further the pins you are soldering on are not even the pins of the IC or any electronic components, but rather those of the module headers. You'd be more likely to melt the plastic web between those headers pins, but even that won't be a great problem since they are already in place. Or if you were soldering directly on the board, lifting a pad or trace - but you were not doing that.

Your actual problem is something else, *what that might be* is presently unanswerable due to the lack of detail in your question.
> 2 votes

# Answer
Bridging adjacent pins by heating for 10 seconds is not a great way of doing things. You are trying to cross the "solder resist" with solder, so you are basically fighting something.

I normally use some tinned copper wire to cross gaps like that. You should be able to keep the soldering times down to a couple of seconds.

> Did I overheat my Arduino ... ?

We can't really say from where we sit, but maybe.

> I could see a COM port for it

The Pro Mini doesn't have a USB chip, so how are you programming it?

---

> I am using an FTDI breakout board to program the Pro Mini, which then attaches to a USB cable.

Right, well you are seeing the COM port from the FTDI breakout board, not the Arduino as such. You would see that even if there was no Arduino there at all.

---

The soldering on one of your pins (5th from the bottom, on the right) looks a bit dodgy. It might just be the light.

As I said earlier, you possibly overheated the processor chip. I would use the technique I described rather than a 10-second heat.

See my question/answer: Have I bricked my Arduino Uno? Problems with uploading to board \- that describes various tests you can do to check if the processor is still good.
> 0 votes

---
Tags: arduino-pro-mini
---


# Question
Title: How can i check for valid fingerprint and no finger detected?
i am working in arduino fingerprint sensor with adafruit. i am using two leds to check if fingerprint is valid. my problem is that i need three cases instead of two. 1 case: when fingerprint is valid. turn on green led and turn off red led. 2 case: when fingerprint is not valid. turn on red led and turn off green led. i put a finger but was a not valid finger. 3 case: when there is no finger detected, turn off both leds. Is there a way to do that?

i am using adafruit library and fingerprint sensor, with fingerprint.ino and using pin 11 and 12 for output.

# Answer
When there is no finger on the sensor, the function `Adafruit_Fingerprint.getImage()` from the Adafruit Fingerprint library returns the constant `FINGERPRINT_NOFINGER`. You can execute the function in a loop and setting the LED outputs in a `switch` statement according to the return value. Refer to the examples of the Adafruit Fingerprint Sensor Library. There you have directly the code for checking the sensor (since the full check for a valid fingerprint is longer than this one function call, you can use the `getFingerprintIDez()` function from the `fingerprint` example, or a variation of it).
> 1 votes

---
Tags: arduino-uno, adafruit
---


title: Peer to Peer using Ethernet Module

text:
# Question
Title: Peer to Peer using Ethernet Module
I'm beginner here at arduino stuff. i just started learning arduino and i have this small homework where i NEEDED to connect 2 arduino using ethernet shield or module ONLY over a distance of 20 meters.

I don't have my modules yet but i want to atleast study it now while i'm waiting for it. I can't seem to see any tutorials about it nor anyone tried it. How can i do this? i hope you can help me and give some insights, links, etc reference. Thanks :)

EDIT: I had in mind where these arduino will have their own identity, 1st arduino will be receiving only some data coming from 2nd arduino. The 2nd arduino will have sensors and read them then sends them to 1st arduino. Now, i like my 2nd arduino to have a power source coming from the 1st arduino to save power supply installation and since it'll be like a remote arduino. Thus has anyone has experience applying PoE on arduino?

# Answer
> 2 votes
You will need a crossover cable to connect two Ethernet shields peer to peer.

Then you configure the Ethernet library to use static IP address. Use 192.168.1.1 and .2 address. (Or other 192.168.x.x address). Set subnet 255.255.255.0. Gateway should be the IP address of the other Arduino.

---
Tags: ethernet, networking
---


title: How to delay properly inside ISR

text:
# Question
Title: How to delay properly inside ISR
I am currently working on a little code which needs to react fast. Here is what I am trying to accomplish:

Using a sine wave phase detector I am detecting every zero crossing and feeding that pulse into the Arduino.

Using an ISR the Arduino detects this zero crossing pulse using RISING. Once one pulse has been detected AND I have pressed a button, I need there to be a delay of 0 - 10ms before switching on an output.

If I don't use an ISR and set a delay of up to 10ms inside the loop, it won't really be 10ms and it will be some other delay, nothing consistent. (I checked with an oscilloscope).

Only when using an ISR and using delayMicrosenconds() inside the ISR I can delay the output consistently for up to 10 ms everytime.

Now I have read that doing this is wrong...Even though it works perfectly. Which better way could I use?

Thanks!

EDIT: While 100% accuracy may not be possible, it needs to be as precise as possible. More important is the repeatability. Using my method I could reproduce the outcome everytime with an accuracy in the nano seconds range.

# Answer
It's quite simple: You don't.

Instead you use your initial ISR to configure and enable one of the ATMega's Timer peripherals. Set that to the length of your required delay - then the ISR exists.

When the chosen time has passed the timer interrupt triggers, and you use *that* interrupt to turn on your output.
> 4 votes

---
Tags: arduino-uno, interrupt
---


title: Every loop other case

text:
# Question
Title: Every loop other case
I need to achieve that in every loop my Arduino do other thing. Say in first loop do one thing, in second do second thing and in third loop do third thing. And again. And while doing one thing, other things are dead.

Not sure what approach to use. This is just my 50 cents:

```
for(int x=0; x<2; x++)
  {
  switch (x) {
    case 0:
      //do something
      break;
    case 1:
      //do something
      break;
    case 2:
      //do something
      break;
  }
  delay(1);
}

```

I tried this from above but it stuck at case 0

Any point or link to explanation would be nice.

# Answer
> 2 votes
Your implementation is in principle correct. However, tradionally, you don't incrementally loop over all states from 0 to end using a `for` loop. The implementation is more flexible if it allows the state to go to any other state if it needs to. This would be a normal *finite state machine* (FSM).

```
#include <Arduino.h>
/* How many states are possible? */
#define MAX_STATES 2
/* global state variable */
int currentState = 0;

/* prototypes */
void Action1();
void Action2();

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

void AdvanceStateByOne() {
    currentState = (currentState + 1) % MAX_STATES;
}

void loop() {
    //Execute the action dictated by the current state
    switch(currentState) {
        case 0:
            Action1();
            break;
        case 1:
            Action2();
            break;
        default: //Catch for un-implemented states
            break;
    }
    //Go to next state, incrementally.
    //This could also be modified in one of the functions above
    //Loop back to zero state after MAX_STATES using modulo operator
    AdvanceStateByOne();

    //for testing, introduce some delay
    delay(1000);
}

void Action1() {
    Serial.println("Action 1");
}

void Action2() {
    Serial.println("Action 2");
}

```

This prints out "Action 1" and "Action 2" in a loop forever.

Now you could take this further and instead of using pure numbers for your states, you can use an `enum` representation of those to make the code clearer:

```
enum state_t {
    STATE_DO_ACTION_1 = 0,
    STATE_DO_ACTION_2,
    STATES_END
} ;

```

And then act on those accordingly. You can also use the C++ feature of a `enum class` to give you a nice notation like `State::SomeState1`.

# Answer
> -1 votes
> ```
> for(int x=0; x<2; x++)
>   {
>   switch (x) {
>     case 0:
>       //do something
>       break;
>     case 1:
>       //do something
>       break;
>     case 2:
>       //do something
>       break;
>   }
>   delay(1);
> }
>
> ```

You will never do case 2, that's for sure, as you are incrementing to **less than** 2.

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


title: my arduino uno board is not working

text:
# Question
Title: my arduino uno board is not working
at once, when i connect arduino uno to my computer, my computer shuts down, after that i cannot upload programs to my computer,the board is not working but the led is ON. Before this, i upload programs 4 to 5 times continuously. i upload program with no physical connections in arduino except motor shield which is also not connected to anything. i used three boards, all of them got damaged.

my computer's USB port and USB cable is in good codition. i already updated my drivers.

computer spec: dell inspiron 15 3567 windows10 x64 bit

# Answer
> 2 votes
Computer shutting down is often an indication that excess power is being drawn. If you measure between +5 and Gnd on the unpowered board with a meter set for resistance, do you get a reading in the 5Kohm range? Or something much lower? Much lower would be bad.

---
Tags: arduino-uno
---


title: Arduino - Push Button State Problem

text:
# Question
Title: Arduino - Push Button State Problem
My problem is I want the buzzer to stop after a certain amount of time, regardless if it is still pressed or not.

I have tried to implement a boolean statement to the code but to no avail(I'm not very good at this)

Can someone shed some light as to how I do this?

The code already times out after 1000ms when your finger is lifted off the buttin so I got that far but cant get any further.

Here is what I have.

Any other suggestions are also welcome as I know its not the prettiest or best implemented but i was just happy it worked for me.

```
// Setting The Pin Numbers
const int touchsensor = 2;                      // the number of the touchsensor pin
const int buzzer =  4;                          // the number of the LED pin

// variables:
int touchsensorState = 0;                       // variable for reading the
touchsensor status
unsigned long timestamp = 0;
unsigned long timeout = 1000;

void setup() {

  pinMode(buzzer, OUTPUT);                      // initialize the buzzer as an output
  pinMode(touchsensor, INPUT);                  // initialize the touchsensor as an input
 }
void loop() {

   touchsensorState = digitalRead(touchsensor);  // read state of the pushbutton value:

   if (touchsensorState == HIGH) {                 // check if the touch sensor is pressed. If it is, the touchsensorState is HIGH:
     digitalWrite(buzzer, HIGH);                 // buzzer will emit sound:
     timestamp = millis();                       // Timing button press
   }

   if(millis() - timestamp > timeout) {
   digitalWrite(buzzer, LOW);                  // buzzer will not sound:
   }
}

```

# Answer
you will need to implement a edge sensor. Add a `previousTouchsensorState` to the globals and replace the if where you check the sensor state with:

```
if(previousTouchsensorState == LOW && touchsensorState == HIGH) {
     // check if the touch sensor is pressed and wasn't the last time though the loop.
     // If it is, the touchsensorState is HIGH and previousTouchsensorState is LOW:
     digitalWrite(buzzer, HIGH); // buzzer will emit sound:
     timestamp = millis();       // Timing button press
}
previousTouchsensorState  = touchsensorState;

```
> 3 votes

---
Tags: arduino-yun, button, buzzer
---


# Question
Title: WS2812 HELP. Need name of Unkown component
https://i.stack.imgur.com/pbYn6.png

I need to know what the little "thing" that i marked in blue is and how it works.

Thanks.

picture taken here: https://www.sparkfun.com/products/13282

# Answer
It's most likely a decoupling capacitor meant to smooth out the voltage supply to the internal control chip.

This is standard practice to add to any chip. Power cables create a small bit of parasitic inductance in relation to the area between the lines. This inductance can induce voltage spikes when current draw changes significantly. A capacitor shrinks the effective area between the power lines.

This is also why the general advice for decoupling capacitors is to put them as close to the chip as physically possible.
> 2 votes

# Answer
It's a capacitor. Specifically a decoupling capacitor of somewhere around 100nF to 1uF.

It works by storing an electrical charge in two plates with a dielectric between them. That specific type is a Multi-Layer Ceramic Capacitor and looks to be 0603 in size.
> 0 votes

# Answer
It's a capacitor connected between 5V and GND and it smooths out voltage spikes for a cleaner power supply to the chip. A cleaner power supply means the circuitry in the chip can more easily pick out the data signal (i.e., the reference voltage is more constant, so the actual signal appears more stage.)
> 0 votes

---
Tags: arduino-uno, arduino-mega, led, ws2812
---


title: Fade out lightbulb 220V

text:
# Question
Title: Fade out lightbulb 220V
I am trying to make a lightbulb fade to dark and back to light, for which I found the following tutorial online: http://bildr.org/2012/03/rfp30n06le-arduino/
Unfortunately, the tutorial makes use of a 60V light source while my intention is to use the system on 220V. Would it be enough to solve my problem to replace the 60V MOSFET in the system with one of 220V?
What would otherwise be a solution?

Thank you very much for your help!

# Answer
> 3 votes
Absolutely not. Not under any circumstances.

Dimming AC is a considerably harder task, and doing it with 220VAC can be deadly.

To do it you need:

* A zero-crossing detection circuit
* A TRIAC driver circuit
* A suitable TRIAC to do the switching
* Software that will use the zero crossing information to time the switch-on of the TRIAC to a certain point in the waveform.

And most importantly:

**Good knowledge of working with mains electricity - without which you will probably kill yourself or those around you.**

# Answer
> 1 votes
You can buy 220V dimmer modules controllable with 5V PWM from Arduino. Here is one controllable with this PWM digital potentiometer module.

I use Kemo 4000VA regulator module with that M150 digital pot module controlled with Arduino PWM for heater regulation.

---
Tags: arduino-uno, mosfet
---


# Question
Title: Implementing Quasi-Perpetual Battery on Arduino
I am interested in seeing how much "*uptime*" I can achieve with my Arduino device/project. I am brand new to electronics/robotics, and so I wanted to bounce my idea off of this community first and see if I am overlooking anything obvious/major, or if my overall approach is incorrect.

The idea is simple:

Provide my Arduino device with 2+ "rechargeable power sources" (described next) and then provide a mechanism to route power to any viable (non-dead) power source at any time. While one power source is being used to power the Arduino device, the other "idling" power sources are recharging. The intention is to allow the device to keep switching between power sources endlessly, in perpetuity, achieving 100% uptime (perfect "high availability").

As for each "rechargeable power source" I am thinking an energyShield (rechargeable Li-polymer) backed by a solar panel.

I did some preliminary research and was told that if I were to wire these power sources in series with diodes, then the circuit would always by default draw power from the source with the highest voltage. As soon as another source has higher voltage, the circuit begins drawing power from that one, and the "old source" begins recharging.

I'm a noob but not a fool, and I **know** there is no such thing as perpetual energy (hence the title "quasi-perpetual"), and I'm sure factors like sunlight/weather conditions/etc. would affect the efficacy of the solar panels, etc. But I guess my first concern is: am I doin' it right? Are there any caveats/pitfalls or considerations I'm overlooking here?

Assuming I'm more or less correct in my approach, the other concern is how to actually implement power sources and diodes in a series, and how to actually rig that all up and connect it to the Arduino board. Again, I'm a total electronics newbie, so I'm just having a tough time visualizing the precise solution there.

And as for determining the *actual* number of power sources (energyShield + solar panel combo) my device would need, I was just planning on starting with 2, and running the device at max power and monitoring their recharge rates. The more sources I add, the longer the device will operate. Obviously, at some point I'll either reach a point where its uptime is sufficient for my needs, or I'll run out of money. :-)

# Answer
> 4 votes
You're overthinking it. Use one or more solar panels, a harvesting IC with sufficient storage, and the bare MCU and peripherals. Use enough panels and storage to run the MCU and peripherals 24/7, and to also charge the storage during the day.

# Answer
> 0 votes
"I did some preliminary research and was told that if I were to wire these power sources in series with diodes, then the circuit would always by default draw power from the source with the highest voltage."

That is not correct - you need the two sources in parallel with a diode each. Then the higher voltage will become the current source. When the sources are charging, the charge source may become the current source if that voltage is higher than the other stored charge source.

---
Tags: arduino-uno, battery, solar
---


# Question
Title: How do I use digital pin on sensor to analog on arduino uno
I am working on a autonomous fire extinguisher.i have run out of pins.I have the following question in my mind while working on my project

Is it necessary that the DO pin in a flame sensor must be in a PWM digital pin in Arduino.i have this doubt since when I connected it to non PWM pin it didn't worked.

Secondly it is possible for me to use the analog pin in Arduino for the DO pin of the flame sensor or trigger/echo pins of the ultrasonic sensor.

Thanks.

# Answer
> 1 votes
PWM stands for Puls Width Modulation and is only available when the Digital Pin is in OUTPUT mode.

And **YES**, you can connect the flame sensor's D0 to any digital pin on the Arduino.

And yes it is possible to connect the flame sensor's D0 to a analog pin, but why not use the A0 from the flame sensor and connect it toi a analog pin on the Arduino?

# Answer
> 0 votes
You can use the analog pins (A0-A5, but not A6 and A7) also as digital pins. So you can set one of them as digital input, connecting it with the D0 pin of your fire sensor. You can read this pin with `digitalRead(pin)`.

Regarding your problem with PWM: There is no "PWM input" on an Arduino Nano (because PWM hardware in a microcontroller means pulse with modulated output). The example code of your sensor uses an analog input (ADC: Analog Digital Converter) (with usage of `analogRead()`). If you want to use this functionality you have to connect the A0 pin of your sensor to one of A0-A7 and reading it with `analogRead()` to get the fires intensity/distance.

---
Tags: arduino-uno, pins
---


# Question
Title: What is best way to get data from sensors if arduino is slave?
Im working on a project where i have motor controller(arduino nano) being i2c slave. Its job is to get RF24 data and control motor and at same time send data to master about motor... Currently i have 2 ultrasonic sensors for distance sensing and if they are too close it will stop motor. I want to add 2-4 more but it adds a lot of delay because of

```
pulseIn();

```

command. I want to use attiny as sensor reader and just dump current data when requested.

Is it possible for arduino nano to be i2c slave (hardware i2c) and at same time i2c master (software i2c/please library without using timers... im short on them) or there is way to dump data in less than 2ms via serial or some other protocol? SPI is already used for RF24 and i need RF24 to be up all the time.

# Answer
> 0 votes
On simultaneous master/slave: Yes and no. You can initiate the `Wire` library as slave and despite of than using `Wire.beginTransmission()` and it's siblings to send as a master. The library will configure the hardware as master only for the time it needs to send. But there are 2 problems:

1. When you have multiple masters on the same bus, they have to continuously watch the bus, so that they are only starting a transmission, when the bus is free. The `Wire` library doesn't seem to do that.
2. If two masters start their transmission at the same time, the data will be good, as long all transmitted bits are equal. For other cases the I2C protocol has a rule: When 2 masters start a transmission at the same time, the first one to write a `1` to the bus (HIGH value) has to immediately back of to slave mode. (This is because to write a `1` to the data line the pullup resistors are used. When another master tries to write `0` to the bus (LOW value on SDA) he wins against the pullups, effectively writing `0` to the port, and not `1`)

As mentioned on this Github issue there are some workaround, though I haven't tested them myself until now. All in all I2C multi-master may be to complex at this point.

As another option, you can use an extra line, connecting master and slaves (use the internal pullup on the masters side). Any slave can at any time write a `LOW` to this line, triggering the master to request data from all slaves (maybe via external interrupt or pin change interrupt).

Note: I don't know, for what purposes you used all your timers, but maybe there is a way to share one of them with other hardware, so that you don't have to use the blocking `pulseIn()` function. Or maybe you can tweak the timeout value of the function to a fitting value.

---
Tags: arduino-nano, i2c
---


title: How do I do a register read?

text:
# Question
Title: How do I do a register read?
Below is the sketch I'm using with the TI 32-bit adc ADS1262. I've been trying to achieve maximum resolution by setting the MODE2 register gain to 101, which is 32V/V. The default PGA setting is 000 or 1V/V. The line I set the gain is: "PC\_ADS1262.ads1262\_Reg\_Write(MODE2, 5\<\<4 | 2);" I think it is probably set for the 32V/V, but I was wanting to do a register read to make sure where it is actually set at. I do not know how to do the register read, any suggestions? The ADS1262 datasheet page 85 shows a RREG read register command, but I simply do not know how to use it. BTW, with the adc connected to a 10mV voltage the best results I get are 0.00997589244 volts or 0.00997589149 volts. It jumps between those two voltage readings. So the increment is 0.00000000095 volts. That's pretty good precision, but its not 32-bit. ADS1262 datasheet

```
 example.ino
 this example gives differential voltage across the AN0 And AN1 in volts
 Hooking-up with the Arduino
 ----------------------
|ads1262 pin label| Pin Function         |Arduino Connection|
|-----------------|:--------------------:|-----------------:|
| DRDY            | Data ready Output pin|  D6              |
| MISO            | Slave Out            |  D12             |
| MOSI            | Slave In             |  D11             |
| SCLK            | Serial Clock         |  D13             |
| CS              | Chip Select          |  D7              |
| START           | Start Conversion     |  D5              |
| PWDN            | Power Down/Reset     |  D4              |
| DVDD            | Digital VDD          |  +5V             |
| DGND            | Digital Gnd          |  Gnd             |
| AN0-AN9         | Analog Input         |  Analog Input    |
| AINCOM          | Analog input common  |                  |
| AVDD            | Analog VDD           |  -               |
| AGND            | Analog Gnd           |  -               |
-----------------------------------------------------------------
*/
#include <SPI.h>
#include <SoftwareSerial.h>
#include <math.h>
#include <ads1262.h>

#define PGA 32
#define VREF 2.50                 // Internal reference of 2.048V
#define VFSR VREF/PGA
#define FSR (((long int)1<<23)-1)

ads1262 PC_ADS1262;                     // class

float volt_V=0;
float volt_mV=0;
volatile int i;
volatile char SPI_RX_Buff[10];
volatile long ads1262_rx_Data[10];
volatile static int SPI_RX_Buff_Count = 0;
volatile char *SPI_RX_Buff_Ptr;
volatile int Responsebyte = false;
volatile signed long sads1262Count = 0;
volatile signed long uads1262Count=0;
double resolution;

void setup()
{
  // initalize the  data ready and chip select pins:
  pinMode(ADS1262_DRDY_PIN, INPUT);                  //data ready input line
  pinMode(ADS1262_CS_PIN, OUTPUT);                   //chip enable output line
  pinMode(ADS1262_START_PIN, OUTPUT);               // start
  pinMode(ADS1262_PWDN_PIN, OUTPUT);                // Power down output

  Serial.begin(9600);
  //initalize ADS1292 slave
  PC_ADS1262.ads1262_Init();                      // initialise ads1262
  Serial.println("ads1262 Initialised successfully....");

 }

void loop()
{
  volatile int i,data;

 if((digitalRead(ADS1262_DRDY_PIN)) == LOW)               // monitor Data             ready(DRDY pin)
  {
    SPI_RX_Buff_Ptr = PC_ADS1262.ads1262_Read_Data();      // read 6 bytes  conversion register
    Responsebyte = true ;
  }

  if(Responsebyte == true)
  {
    for(i = 0; i <5; i++)
    {
      SPI_RX_Buff[SPI_RX_Buff_Count++] = *(SPI_RX_Buff_Ptr + i);
    }
    Responsebyte = false;
  }

  if(SPI_RX_Buff_Count >= 5)
  {

    ads1262_rx_Data[0]= (unsigned char)SPI_RX_Buff[1];  // read 4 bytes adc count
    ads1262_rx_Data[1]= (unsigned char)SPI_RX_Buff[2];
    ads1262_rx_Data[2]= (unsigned char)SPI_RX_Buff[3];
    ads1262_rx_Data[3]= (unsigned char)SPI_RX_Buff[4];

     uads1262Count = (signed long) (((unsigned long)ads1262_rx_Data[0]<<24)|   ((unsigned long)ads1262_rx_Data[1]<<16)|(ads1262_rx_Data[2]<<8)|ads1262_rx_Data[3]);//get the raw 32-bit adc count out by shifting
     sads1262Count = (signed long) (uads1262Count);      // get signed value
     PC_ADS1262.ads1262_Reg_Write(MODE2, 5<<4 | 2);  //Here is where I set the gain
     resolution = (double)((double)VREF/pow(2,31));       //resolution= Vref/(2^n-1) , Vref=2.5, n=no of bits
    // Serial.print(resolution,15);
     volt_V      = (resolution)*(float)sads1262Count;     // voltage = resolution * adc count
     volt_mV   =   volt_V*1000;                           // voltage in mV
     Serial.print("Readout voltage");
     Serial.print(" : ");
     Serial.print(volt_V,9);
     Serial.print(" V ,");

   }

  SPI_RX_Buff_Count = 0;

}

float mapfloat(float x, float in_min, float in_max, float out_min, float out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

```

# Answer
Here are the important parts of the code I use to READ or WRITE to registers in the ADS1263 chip... I hope this helps you over this hurdle...

```
// The ADS1263 2 byte commands.
// Note the 3 msb are the command, the remaining bits are the starting register address.
// Refer to table 37 on page 85 of the SBAS661B.PDF for details of the ADC command map.
// Read XXXn nnnn register(s) starting at address XXXr rrrr. The first byte 001r rrrr and the second byte 000n nnnn.
// Write XXXn nnnn register(s) starting at address XXXr rrrr. The first byte 010r rrrr and the seconf byte 000n nnnn.
const byte WREG = 0x40; // 0b01000000 ADS1263 Command Write 40h + reg address.
const byte RREG = 0x20; // 0b00100000 ADS1263 Command Read  20h + reg address.
const byte MASK = 0x03; // 0b00000011 mask out the msb's and limit block size from 0 to 3 bytes.

unsigned int ads1263_Read_Reg(byte thisRegister, byte bytesToRead)
{
byte inByte = 0;
unsigned int result = 0;
byte readStatus = 0;
byte readCRC = 0;

... REDACTED
// ADS1263 expects the register address in the lower 5 bits of the byte. So no shifting of the bits is necessary:
// Now combine the address and the command into one byte bit masked to add the read register command.

byte dataToSend = thisRegister | RREG;
byte lengthToRead = byte bytesToRead & MASK; // Enforce a maximum of 3 bytes.

... REDACTED

SPI.transfer(dataToSend);
result = SPI.transfer(0x00);
lengthToRead--;
if (lengthToRad > 0)
    {
    result = result << 8;
    inByte = SPI.transfer(0x00);
    result = result | inByte;
    lengthToRead--;
    }

... REDACTED

Serial.print("Register Data: ");
Serial.println(result, BIN);

... REDACTED
}

```

If you used an array for a read buffer you would not have to enforce a maximum of four bytes at a time reading as unsigned int can only hold four bytes...
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: DHT 11 sensors and i2c LCD to Wemos Wifi not Working
Its my first time make arduino project. I make wemos d1 project using DHT11 temperature sensor and LCD 20x4 with i2c. **The temperature data will display in LCD and sending to the bot telegram.** **For sending to the bot telegram it works, but why the data cannot display to the LCD?** When I tried common charachter like "Hello World!" in the LCD it works. Can you help me? What should I do? Thanks before.

```
#include "DHT.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F,2,1,0,4,5,6,7,3, POSITIVE);
#define DHTPIN D14
#define DHTTYPE DHT11

byte degree[8] = {
  0b00110,
  0b00000,
  0b00000,
  0b00000,
  0b00000,
  0b00000,
  0b00000,
  0b00000
};

DHT dht(D14, DHT11);

void setup() {
  lcd.createChar(0, degree);
  Serial.begin(115200);
  Serial.println("DHT11 test!");
  lcd.begin (20, 4);
  dht.begin();
}

void loop() {
  delay(2000);
  float h = dht.readHumidity();
  float t = dht.readTemperature();

  lcd.setCursor(0, 0);
  lcd.print("Humi : ");
  lcd.print(h);
  lcd.print(" %");

  lcd.setCursor(0, 1);
  lcd.print("Temp : ");
  lcd.print(t);
  lcd.print(" C");
}

```

# Answer
> 1 votes
Constant `D14` is for Wemos D1 and other esp8266 dev boards mapped in arduino core to esp8266 io pin 4. Pin 4 is used as I2C SDA pin. The LCD uses I2C so pin 4 (D14) can't be used for the sensor.

from `pins_arduino.h` for Wemos D1 R1:

```
#define PIN_WIRE_SDA (4)
#define PIN_WIRE_SCL (5)

static const uint8_t D14  = 4;
static const uint8_t D15  = 5;

```

The origin of this confusing esp8266 io pin to Dx constants mapping is the big Wemos D1. There are esp8266 pins mapped to standard Uno pinout.

---
Tags: lcd, temperature-sensor, print
---


# Question
Title: Arduino Nano joystick x2 / potentiometer
will i be able to connect up all these parts to an arduino Nano i noticed i will need to connect to the nanos v5 to the 2 joysticks and potentiometer slider if i share the voltage will it still function as intended  **Parts**

x1 = USB Arduino Nano V3.0 ATMEGA328P CH340G 5V 16M Micro-Controller Arduino

x2 = 3D Analog Joystick for Sony PSP 1000 Consol +5v (possible 10kOhm resistance)

x1 = Electronic slider 10K potentiometer Slider Module for Arduino Voltage: 3.3V or 5V / Resistance: 10K

# Answer
Yes, this should work. The potentiometer slider will source about 5mA and each joystick axis about 50mA. In total this gives you 205mA. Here it is important, that your power source can provide enough current. If you are using an USB port from your computer, this would result in 500mA maximum that can be drawn from the bus. Since this is shared with the Arduino you can externally use about 400mA

For more information about current ratings refer to this question

EDIT: Since your previous resistance values were not correct, I edit my answer.

When all potentiometers have 10kOhm resistance (and this seems to be more likely the right values), each one draws about 5mA from the 5V pin (You can calculate this with Ohm's Law `U = R * I`, which gives you `I = U / R`. So you have to divide the voltage by the resistance.). So you aren't getting anywhere near the problematic currents. These potentiometers are designed this way. They don't want to draw a high amount of power, but only setting a certain voltage to the output pin.
> 0 votes

---
Tags: arduino-nano, potentiometer, joystick
---


# Question
Title: Is checking an if statement every loop/while iteration inefficient?
I have code that changes a bool only time in the setup(), and in my loop() I have

```
if (setupBool) {
// ...
} else {
// ...
}

```

Is checking the bool every loop slower than having a while(true) with the same code?

And what about checking it in every loop in a while(true)?

Is there any reason I shouldn't do those?

# Answer
Of course an if statement cost time, although very little. However, it changes (although once), so if you need to vary depending on the value, you have to use the if statement.

A while(true) also cost a little time (a little bit less), but less than 1 us, same as the if statement. You can do perfectly do an if statement within the while(true), but remember, the loop itself is behaving like a while(true) already.

However, I wouldn't concern at all about optimizing performance, unless:

* You know beforehand you will need the fastest code possible
* You have already performance issues

Always prefer readability/maintainability about performance.
> 3 votes

# Answer
The actual full structure of the loop function is like this:

* while(true)
    + Call loop()
        - if (condition)
            * Run your code
        - else
            * Run your other code
    + Check for serial data

By putting a `while(true)` inside your `if` you:

* Remove the overhead of calling `loop()` every time
* Remove the overhead of checking for serial data (that is what the `SerialEvent` system is all about)
* Remove the overhead of checking the `if` every iteration.

So the executing part of your code now looks like:

* while(true)
    + Run your code.

If your code needs to run in a tight loop it can provide some speed improvements, yes, but at the cost of:

* No SerialEvent processing (normal Serial works, but the SerialEvent system breaks)
* Harder to "get out" of the loop to do something else (although `break` can help with that).
* On ESP8266 boards the watchdog will time out unless you manually `yield()` regularly.

Would I suggest doing it? Well, there are times when it can be beneficial, but those times are few and far between. If you don't *need* to do it then, in general, don't do it.
> 2 votes

---
Tags: programming, sketch
---