# Question
Title: Using TXD1/RXD1 on ATmega1280 for USB communication
I have a few MakerBot Mightyboards running off ATmega1280 chips that can no longer use their standard USB port to connect to a computer (to make a long story short, there's a little inductor that blew up between the USB port and the 8u2 chip and it is essentially impossible to replace). I have noticed, however, that they have headers for the RXD1 (PD2) and TXD1 (PD3) pins on the 1280 as seen in this picture:

Would it be possible to hook up an external 8u2 (or similar) chip programmed as a USB to serial converter (something like this) and use it as if it were the normal USB port (e.g. for uploading firmware)?

(I wanted to add atmega1280 as a tag, but it doesn't seem to exist)

# Answer
> 1 votes
Not directly, no.

The USB interface connects to TX0 and RX0 - you have access to TX1 and RX1. The bootloader is set to look at TX0 and RX0.

You would have to compile and install a new version of the bootloader that is set to use TX1 and RX1.

---
Tags: serial, usb
---


# Question
Title: Serial Monitor appears unreadable characters
Hello

My serial monitor keep showing these unreadable characters. Anyone know what is going on? Many thanks!

---

# Answer
> 3 votes
It can have many reasons, but the most likely are:

* You set the baudrate wrong
* You set the stop/start bits wrong
* You send wrong data
* The cable is bad

It helps if you show your sketch(es), for sender/receiver and possibly your circuit.

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


# Question
Title: When does the pulsein() function start counting?
I have an Arduino Pro mini 3.3V, 8 mHz and I want to use the pulsein() function for a low-going pulse. My question: Does the timer start when the function senses a LOW on the input pin, or when the function senses a high-to-low transition, or either?

Code snippet:

```
pinMode(3,INPUT); // Signal input to Arduino from pin 2 on LM339  - D3
int pwindow = 6000; // Maximum timeout value for pulsewidth
long pcounterA = 0; // Unfiltered Pulse Width of Channel 1
pcounterA = pulseIn(3,LOW,pwindow);
Serial.print(pcounterA);

```

Thanks for any help. JT

# Answer
> 3 votes
According the official Arduino Reference: PulseIn

Fragment:

> Reads a pulse (either HIGH or LOW) on a pin. For example, if value is HIGH, pulseIn() waits for the pin to go HIGH, starts timing, then waits for the pin to go LOW and stops timing. Returns the length of the pulse in microseconds. Gives up and returns 0 if no pulse starts within a specified time out.

---
Tags: pulsein
---


# Question
Title: Arduino IDE: How to get PROGMEM const length?
I have defined a byte array as a constant in the Atmel's flash memory:

```
const uint8_t eye [] PROGMEM = {
  0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
  0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff
};

```

How can I (repeatedly) read the length of this constant in the program? All the available functions in avr/pgmspace.h do not deliver the proper length, no matter how I use them. I tried strlen(eye), strlen\_P(eye), strLen\_PF(eye) and also sizeof(eye). I'm new to C, so I'm not sure about the whole pointer stuff.

# Answer
> 3 votes
Probably the best way would be to define below it

```
const int eye_len = sizeof(eye)/sizeof(eye[0]);

```

If the linker does link time optimization, or if you only use it within the same file (and declare it static), it shouldn’t cost any memory, otherwise it will take up two bytes of ram.

---
Tags: programming, progmem, strlen
---


title: Making profit from Arduino

text:
# Question
Title: Making profit from Arduino
I have been experimenting with Arduino for a couple of months, and, riding on the back of my 16 years as a high school science teacher (I am now back at university as a student), I can see a few potential improvements for existing science experiments in the high school teaching lab. My question is this: can I make packages based on Arduino and legally sell them to schools for a small profit? Since I’m no longer a teacher, I wouldn’t be using them myself, so I’d have to at least recoup my costs.

# Answer
> 2 votes
The Arduino itself is open, and you can use it to make commercial products.

Note however, that for commercial products, a lot of additional requirements may be needed (regulations, safety, certifications), especially since it will be used in public places among (many) other people. You don't want students to be injured/die because of a badly designed device.

Not that I think you might not capable, but it might be something to keep in mind, that your project is maybe more than just creating some software and adding some packages and sell them.

---
Tags: arduino-builder
---


title: Working with long strings

text:
# Question
Title: Working with long strings
So I need some tips on working with long strings with the arduino. I have a barcode scanner working. This barcode scanner reads a persons driver license. the result is a lengthy character string of varying length that's 300+. Using substring doesn't work when looking for a certain section of the string and indexOf results in a -1 in most spots. Is there anyway getting around this? Right now I have the data just stored in a string variable.

Thanks.

# Answer
Since the Arduino Uno only has a few KB, 300 bytes is a considerable amount.

My advice:

* Define a fixed char\[300\] array, where 300 is the max amount of characters you want to support.
* Use the C (string.h) library as Majenko already suggests.

The last thing you want is that the string will be copied somehow, using up double the amount of data, or triple. It's hard to see what's going on under water, by casting or even by implicit casting a copy can be made, so 600/900 bytes are used.

For the default library, searching should work for strings longer than 256 characters. You can even write them yourself, for example if you can make it more efficient if you know something about the characters (e.g. if you can skip some because you know some patterns exist or don't exist).

Update after your comment below.

What you can try:

* Try (if existing) an example sample for the barcode scanner to see if the hardware is ok. If not possible try to make a minimal sketch.
* Double check the wiring (although it seems easy).
* Try different wires (maybe a jumper wire is malfunctioning).
* Try another sketch using serial, but without the barcode scanner (to verify RX/TX is not broken on the Arduino).
> 2 votes

# Answer
So when printing my string variable, I get the full, uninterrupted string displayed to me. I decided to index through my string with a for loop and come to find out, I had many null characters included in the string itself. I did a check to make sure that the character isn't a NULL character before appending it to my string upon creation, and that seemed to do the trick. indexOf is working now.

Reason I decided to index through my string is because I tried to string.toCharArray(buff, DL.length()); and despite the length, I would only get one character pushed into buff.

Thanks for all the tips guys!
> 0 votes

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


# Question
Title: Coding Arduino's samples/period and cycles/sample configurations for input signal
Am I able to code the Arduino so that I can change cycles/sample of an input waveform and a number of samples/period configurations? I would like to modify these parameters in order to be able to store a high-frequency sinusoid but taking into account Arduino's 16MHz clock. For examples, I have a 40,000kHz sine wave. I would like to sample it at 10 samples/period and having 10 cycles/sample. As a result, I need a (40,000kHz * 10samples/period * 10 cycles/sample = 4MHz clock, which Arduino can supply). Compared to a more standard 128 samples/period and 256 cycles/sample, which would require a 1.3GHz clock.

# Answer
The limitation is in the ADC which by default takes 104 µs to make a sample. Now you can speed up the ADC, sacrificing accuracy, but even then you can probably practically only reach a sampling time of 13 µs. Plus you would have the issue of where to put these 400,000 samples in the 2KB of RAM you have.

To sample at 400,000 times a second you would need to sample every 2.5 µs, which you can see is way shorter than 13 µs.

Plus, you not only need space to put these 400,000 samples, but it would take time to store them.

For more information see my page about the ADC which has a lot of details about sampling times, frequencies, accuracy, etc.
> 0 votes

---
Tags: arduino-uno, communication, hardware, signal-processing, software
---


title: How to declare a Dynamic Array?

text:
# Question
Title: How to declare a Dynamic Array?
I want to define an unknown size for an array. However, I know that this cannot be done on the arduino. So what other methods do you suggest? I tried using vectors by downloading the library ArduinoSTL, but it doesnt work. (It only prints Serial.println(Signal); once, referring to the code in the pastebin link below)

Here's my code with vectors:

```
#include <ArduinoSTL.h>
#define sensor1 A0

using namespace std;

int Signal;
int Threshold = 550;

vector<int> startTime;
vector<int> endTime;
unsigned long measureTime;

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

void loop()
{
  //Serial.println(analogRead(sensor1));
  int i = 0;
  measureTime = millis();

  while ((millis() - measureTime) < 10000)
  {
    Signal = analogRead(sensor1);
    Serial.println(Signal);
    if (Signal < Threshold)
    {
      startTime.at(i) = millis();
      Serial.println("1");
    }
    if (Signal > Threshold)
    {
      endTime.at(i) = millis();
      Serial.println("2");
    }
    i++;
  }
}

```

# Answer
The `vector` is empty after its default constructor. And nothing was ever added into it in your code. So you can't use anything like idexing by `vect[index]` or method `vect.at(index)`. And as there are no exceptions available, who knows what it does after the out of range call.

You should consider ring buffer instead, using dynamic memory is tricky on such constrained platforms. Even using Arduino's String class is often source of memory fragmentation and out of memory type errors.
> 1 votes

---
Tags: c++, array, vector, stl
---


# Question
Title: had dice code but lost it during recovery
I had the dice code, but reset and forgot to back the code up, now I need help creating the code again, I can't get the select button to proceed to the loop when pressed here's what I have so far:

```
#include <LiquidCrystal.h>
// select the pins used on the LCD panel
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

//used for later
String line2 = "Press Select to roll"; // Scrolling line

// define some values used by the panel and buttons
int lcd_key     = 0;
int adc_key_in  = 0;
#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5

// read the buttons
int read_LCD_buttons()
{
 adc_key_in = analogRead(0);      // read the value from the sensor

 // For V1.0 comment the other threshold and use the one below:

 if (adc_key_in > 1000) return btnNONE; // We make this the 1st option for speed reasons since it will be the most likely result
 // For V1.1 us this threshold
 if (adc_key_in < 50)   return btnRIGHT;
 if (adc_key_in < 195)  return btnUP;
 if (adc_key_in < 380)  return btnDOWN;
 if (adc_key_in < 555)  return btnLEFT;
 if (adc_key_in < 790)  return btnSELECT;

 return btnNONE;  // when all others fail, return this...
}

void setup() {
 randomSeed(analogRead(1));
 lcd.begin(16, 2);              // start the library
 lcd.setCursor(3,0);
 lcd.print ("Catan Dice");
 lcd.setCursor(0,1);
 lcd.print("Press Select to roll");
}

void loop() {
//local varables
int buttonState = read_LCD_buttons(); // read the button pad
int lastButtonState = btnNONE; // previous state of the button

//Dice
int DiceOne = random(1,7);
int DiceTwo = random(1,7);

  if (buttonState != lastButtonState) {
  // if the state has changed, increment the counter
  if (buttonState == HIGH) {
  // if the current state is HIGH then the button went from off to on:

if (btnState == btnSELECT)
  lcd.setCursor (0,4);
  lcd.print(DiceOne);

  }

}
lastButtonState = buttonState;

}

```

can anyone help me plz

# Answer
> 1 votes
You know that LCD shield buttons are usually multiplexed to the analog pin A0? If I've googled correct schematics, this applies to this one too. Therefore no pin change interrupts nor external interrupts can be used.

Maybe analog comparator module with correct threshold.

---
Tags: arduino-uno
---


# Question
Title: How can I handle micros() double rollover?
I know that I can handle a single rollover with subtraction:

```
if (micros() - lastTime > period) {
  lastTime = micros();
  ...
}

```

But how it can be handled if this is not `true` or it is not checked for more than 70 minutes (without using uint64\_t)?

# Answer
If you want to measure times longer than 70 minutes with `micros()`, you *will have to* use `uint64_t`, and there is nothing wrong with that.

> The code needs to run with as little interruptions as possible \[...\]

You don't need to do the 64-bit arithmetic within the ISR. You could very well implement an interrupt-driven 32-bit version, and then extend it to 64 bits in non-interrupt context. Example:

```
// Your ISR-based implementation.
uint32_t micros32();

// Extend to 64 bits.
uint64_t micros64() {
    static uint64_t time64;
    time64 += micros() - (uint32_t) time64;
    return time64;
}

```

This should work as long as you call `micros64()` often enough. Presumably, you will have something like `if (micros64() - lastTime > period) { ... }` within your loop, so this should be no issue as long as you never block your loop.

Actually, you can push this idea even further. If you can guarantee that `micros64()` will be called at least once every 65.5 ms, then you could have your ISR increment only a 16-bit counter.
> 3 votes

---
Tags: time
---


# Question
Title: SIM800L GSM Module, no network signal RSSI
I am using a GSM 800L module to send SMS messages. When I test the module with Arduino, it shows a 0 : -115dbm signal strength.

So basically there is no signal. SIM800L is a quad-band GSM/GPRS module that works on frequencies GSM850MHz, EGSM900MHz, DSC1800Mhz, and PCS1900MHz.

My SIM card carrier uses the frequency bands GSM 900, GSM 1800 for 2G-capablities.

What might be the possible reasons my GSM module doesn't work properly with my SIM card? I have tried different locations, still no signal.

The code I use for testing is provided by Adafruit-Fona.

# Answer
The Problem was that I used 5 V Dc to power the module , it worked but in order to function I must use lithium battery. ( its mentioned in the manual)
> 0 votes

---
Tags: arduino-uno, programming, gsm, communication
---


title: Delete line from text file

text:
# Question
Title: Delete line from text file
In order to make an algorithm work, I'd like to delete the first line of a text file. I'm having a hard time finding an example for that though. I was thinking that there should be the possibility to delete up to a \n. Could you point me to a solution? Oh, I'm using a standard Arduino Uno

Thank you

# Answer
What you can do is:

* opening a file (to read)
* opening a new file (to write)
* since a line can be long (more than arduino's memory), it's best to read it character by character, thus:
* use a boolean to denote when to start removing a line (set to e.g. Remove = TRUE)
* For every character you read:
    + If Remove is TRUE, don't write to the output file, otherwise write it
    + If the character is \n or \r (check how line ends are), set the boolean to False (e.g. continue writing)
* Remove file to read
* Rename written file
> 1 votes

---
Tags: serial, sd
---


# Question
Title: Problem while interfacing LCD screen with Arduino
I tried to interface an LCD screen with my Arduino but I have a problem - Nothing is being displayed on my LCD screen:

Here is the code:

```
#include<LiquidCrystal.h>

LiquidCrystal lcd(7, 8, 9, 10, 11, 12);  // sets the interfacing pins

void setup()
{
 lcd.begin(16, 2);  // initializes the 16x2 LCD
}

void loop()
{
  lcd.setCursor(0,0);           //sets the cursor at row 0 column 0
  lcd.print("16x2 LCD MODULE"); // prints 16x2 LCD MODULE
  lcd.setCursor(2,1);           //sets the cursor at row 1 column 2
  lcd.print("HELLO WORLD");     // prints HELLO WORLD
}

```

# Answer
In the `setup()` you have to state what pin the Vo (display contrast pin) on the LCD is connected to. Before the

```
lcd.begin(16,2)

```

try

```
analogWrite(pin Vo is connected to, contrast you want to set the screen to);

```

An example would be:

```
analogWrite(6,80);

```
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Output 20x20 Image to Arduino serial monitor
I am working on an Arduino project where I need to display a black and white (no gray) image to the serial monitor. It doesn't need to be high resolution, so something like 20x20 would work. I will be using this several times a second to make video of a sort, but it doesn't need to be a very high fps (4 or 5 would work). Currently I am just using unicode blocks and printing them (at a baud rate of 500,000) to the serial monitor, but it ends up having a very bad screen tear sort of effect. Is there any way to do this better, or at the very least make the serial monitor print everything at once instead of each character individually?

Thanks!

# Answer
The Arduino IDE's serial monitor is, to put it bluntly, awful.

Switch to a proper ANSI compatible serial terminal emulator (Tera Term, Putty, Minicom, whatever) and use ANSI control sequences to manipulate the screen.

The simplest ones to use are:

```
Serial.print("\e[2J"); // Clear the screen
Serial.print("\e[1;1H"); // Move the cursor to coordinate (1,1)

```

Use the first one to clear the screen in setup(), then use the second one at the start of the loop to move to the top-left corner of the screen (1,1 is top left - the coordinates are given as Y;X not X;Y and start from 1 not 0).

Print your 20 lines of 20 characters as either space (nothing) or your chosen "pixel" character. The spaces overwrite the existing characters to help reduce flicker (clearing the screen every time would be just awful).

The way serial works (sending one character at a time sequentially) there is no such thing as "All at once". The above is the best you can get without writing your own program to interpret incoming serial data representing an image frame and displaying it.
> 2 votes

# Answer
> Is there any way to do this better, or at the very least make the serial monitor print everything at once instead of each character individually?

No, serial isn't the right technology for that. By its very definition, it transmits data one bit at a time, one byte after the other. What you're after is to transmit the data in parallel. You're already making the closest approximation to parallel you can using serial - transmitting the data at the highest rate you can to minimize the skew. The longer the time between frames and the shorter the time to transmit one frame, the better your result will be. But you may have reached the limit for 5fps with the available serial hardware.
> 0 votes

---
Tags: serial
---


# Question
Title: Graphing force sensor data routed through HX711?
I'm using the code off of the sparkfun website HX711 hookup guide (https://learn.sparkfun.com/tutorials/load-cell-amplifier-hx711-breakout-hookup-guide#arduino-code) to attempt to create a scale.

Currently I have output data of weight in the serial monitor - is there an easy way to then graph this data with regards to time? I've spent an hour fooling around with Processing and googling, but haven't had any luck.

Thanks!

# Answer
Include the Time library in your sketch, then print the time and your sensor output as a comma separated list. Your output to the serial monitor can then be written to .csv file using PuTTY, which you will need to download in order to collect data (I used online tutorials to figure out writing to a file with PuTTY). Once in a .csv, you can open the file in Excel to graph the data.
> 1 votes

---
Tags: arduino-uno, processing-lang
---


# Question
Title: My Arduino keeps telling me the button is being pushed
My code is simple simple for the button.

There is no reason why this shouldn't work... I think. I honestly have no clue what's wrong.

Output:

Code:

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

#define SS_PIN 53
#define RST_PIN 5
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.

int led = 13;
int led2 = 12;

Bounce debouncer1 = Bounce();

// constants won't change. They're used here to set pin numbers:
const int buttonPin = 2;     // the number of the pushbutton pin
// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

int buzzer = 10;

Servo LockServo;

int ServoPos = 0;

void setup()
{
  debouncer1.attach(buttonPin);
  debouncer1.interval(5); // interval in ms

  pinMode(buzzer, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP); // Push Button as INPUT wiith pullup
  buttonState = digitalRead(buttonPin);
  LockServo.attach(9);  // attaches the servo on pin 9 to the servo object
  Serial.begin(9600);   // Initiate a serial communication
  SPI.begin();      // Initiate  SPI bus
  mfrc522.PCD_Init();   // Initiate MFRC522
  Serial.println("Approximate your card to the reader...");
  Serial.println();
  pinMode(led, OUTPUT);
}

void loop()
{
  debouncer1.update();
  buttonState = debouncer1.read();
  if (buttonState == HIGH) {
    Serial.println("Button Pushed");
    // turn LED on:
    digitalWrite(led, HIGH);
    ServoPos = 0;
    LockServo.write(ServoPos);
  }
  else {
    digitalWrite(led, LOW);
    ServoPos = 180;
    LockServo.write(ServoPos);
  }

  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent())
  {
    return;
  }
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial())
  {
    return;
  }
  //Show UID on serial monitor
  Serial.print("UID tag :");
  String content= "";
  byte letter;
  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
     Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     Serial.print(mfrc522.uid.uidByte[i], HEX);
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();
  if (content.substring(1) == "20 96 2E A5") //change here the UID of the card/cards that you want to give access
  {
    Serial.println("Authorized access");
    Serial.println();
    digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
    ServoPos = 0;
    LockServo.write(ServoPos);
    tone(buzzer, 20000);
    delay(500);
    noTone(buzzer);

    tone(buzzer, 15000);
    delay(500);
    noTone(buzzer);
    delay(15);
    delay(3000);
    digitalWrite(led, LOW);
    delay(3000);
    ServoPos = 180;
    LockServo.write(ServoPos);
  }
  else {
    Serial.println(" Access denied");
    tone(buzzer, 10000);
    delay(500);
    noTone(buzzer);

    tone(buzzer, 30000);
    delay(500);
    noTone(buzzer);
    digitalWrite(led2, HIGH);
    delay(3000);
    noTone(buzzer);
    digitalWrite(led2, LOW);
  }
}

```

# Answer
When using a pull-up mode on an input pin, that means that when nothing is connected, the pin floats up to `HIGH`. The connected button should have one side connected to your input pin, and the other to `GND`, so that when you press the button, the input pin is pulled to `GND` (that is, `LOW`).

So your comparison to trigger on a button press should be `if (buttonState == LOW)`
> 3 votes

---
Tags: arduino-mega, button
---


title: Debouncing Multiple Buttons

text:
# Question
Title: Debouncing Multiple Buttons
I'm creating a binary calculator with my Arduino. This will take two different binary numbers and add them together. I am focusing right now on the Byte One Input screen. For this, I can use two buttons, the left to change to selected bit to either 0 or 1 when pressed, and the right button to move to the next bit, or when at the end, to move to the next screen. I am having difficulty with the debouncing of the buttons.

Right now, the debouncing is not working and the position changes from 1 to 8 or 16 instead of to the second bit when I hit the right button.

Any help would be great!

**Fixed Code: See accepted answer below.**

```
       #include <LiquidCrystal.h>
/*(RS, E, D4, D5, D6, D7)*/
LiquidCrystal lcd(12,11,5,4,3,2);
#include <Button.h>

int page = 0;
int binary[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int con = 80;
char btn_push;
int pos = 0;

const int button1Pin = 8;
const int button2Pin = 9;
int button1State = HIGH;
int button2State = HIGH;
int lastButton1State = HIGH;
int lastButton2State = HIGH;

unsigned long debounceDelay = 50;

//****************************************************************setup*****************************************
void setup() {
  pinMode(button1Pin, INPUT_PULLUP);
  pinMode(button2Pin, INPUT_PULLUP);

  Serial.begin(9600);
  analogWrite(6,con);
  mylcd.begin();
  lcd.print("Welcome");
}

//************************************************************loop************************************************

void loop() {

  int reading1 = digitalRead(button1Pin);
  int reading2 = digitalRead(button2Pin);

  if (reading1 == lastButton1State &&
      reading2 == lastButton2State)
    return;  // do nothing if no change

  delay (debounceDelay);  // debounce

  // re-read so we can catch both buttons down at once
  reading1 = digitalRead(button1Pin);
  reading2 = digitalRead(button2Pin);

  // save for next time
  lastButton1State = reading1;
  lastButton2State = reading2;

  if (reading1 == LOW && reading2 == HIGH)     // first one down
    btn_push = 'D';
  else if (reading1 == HIGH && reading2 == LOW)  // second one down
    btn_push = 'U';
  else if (reading1 == LOW && reading2 == LOW)  // both
    btn_push = 'S';
  else
    return;  // nothing interesting

 Serial.print("btn_push = ");
 Serial.println(btn_push);

    // page select
    switch (page) {

    case 0:
      page0();
      break;
    case 1:
      page1();
      break;
    case 2:
      page2();
      break;
    case 3:
      page3();
      break;
    case 4:
      page4();
      break;
    }

}

// The rest is the same, excluding the functions that are no longer needed

```

# Answer
> 1 votes
Your first problem is here:

```
char ReadKeypad(){
  if(button1.isPressed() && !button2.isPressed()){
    return 'D';
  }
  else if(button2.isPressed() && !button1.isPressed()){
    return 'U';
  }
  else if (!button1.isPressed() && !button2.isPressed()){
    return 'N';
  }
  else if (button1.isPressed() && button2.isPressed()){
    return 'S';
  }
}

```

The compiler gives a warning, which you should pay attention to:

```
In function 'char ReadKeypad()':
warning: control reaches end of non-void function [-Wreturn-type]
 }
 ^

```

The warning basically is that if no button is pressed you are returning an undefined value. It would be better to add to the end:

```
return 0;  // no button pressed

```

---

Then later on in `page1` function:

```
  for (int i; i<16; i++){
    lcd.print(binary[i]);
  }

```

Another compiler warning:

```
In function 'void page1()':
warning: 'i' may be used uninitialized in this function [-Wmaybe-uninitialized]
       for (int i; i<16; i++){

```

You haven't initialized `i` so it could have any value. That should read:

```
  for (int i = 0; i<16; i++){
    lcd.print(binary[i]);
  }

```

Ditto further down.

---

If I add some debugging here:

```
void MainmenuBtn(){
  btn_push = ReadKeypad();
  Serial.print ("btn_push = ");
  Serial.println (btn_push);
 // WaitBtnRelease();
}

```

And then press a button, I see:

```
btn_push = D
btn_push = D
btn_push = D
btn_push = D
btn_push = D
btn_push = D
btn_push = D
btn_push = D
btn_push = D
btn_push = D
btn_push = D
btn_push = D

```

So that is registering as **many** presses, not just one. You should test for "has the button state changed?". That is:

* Is the button closed now?
* Was it closed before?
* If the two are different, then the button has just been pressed.

---

Adding debugging prints is **very helpful** in general when things aren't going to plan.

If you had added those extra prints to your MainmenuBtn function you would immediately have seen that it looked like the button was pressed hundreds of times (until you let go) rather than once.

> the position changes from 1 to 8 or 16 instead of to the second bit when I hit the right button

Exactly. Since it is treating a button press as a multiple press you would expect exactly that to happen. Effectively you have built in a very fast auto-repeat (unintentionally).

---

### Edited to add:

Your code is so confusing I've rewritten the state change stuff.

```
#include <LiquidCrystal.h>
/*(RS, E, D4, D5, D6, D7)*/
LiquidCrystal lcd(12,11,5,4,3,2);
#include <Button.h>

int page = 0;
int binary[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int con = 80;
char btn_push;
int pos = 0;

const int button1Pin = 8;
const int button2Pin = 9;
int button1State = HIGH;
int button2State = HIGH;
int lastButton1State = HIGH;
int lastButton2State = HIGH;

unsigned long debounceDelay = 50;

//****************************************************************setup*****************************************
void setup() {
  pinMode(button1Pin, INPUT_PULLUP);
  pinMode(button2Pin, INPUT_PULLUP);

  Serial.begin(9600);
  analogWrite(6,con);
  mylcd.begin();
  lcd.print("Welcome");
}

//************************************************************loop************************************************

void loop() {

  int reading1 = digitalRead(button1Pin);
  int reading2 = digitalRead(button2Pin);

  if (reading1 == lastButton1State &&
      reading2 == lastButton2State)
    return;  // do nothing if no change

  delay (debounceDelay);  // debounce

  // re-read so we can catch both buttons down at once
  reading1 = digitalRead(button1Pin);
  reading2 = digitalRead(button2Pin);

  // save for next time
  lastButton1State = reading1;
  lastButton2State = reading2;

  if (reading1 == LOW && reading2 == HIGH)     // first one down
    btn_push = 'D';
  else if (reading1 == HIGH && reading2 == LOW)  // second one down
    btn_push = 'U';
  else if (reading1 == LOW && reading2 == LOW)  // both
    btn_push = 'S';
  else
    return;  // nothing interesting

 Serial.print("btn_push = ");
 Serial.println(btn_push);

    // page select
    switch (page) {

    case 0:
      page0();
      break;
    case 1:
      page1();
      break;
    case 2:
      page2();
      break;
    case 3:
      page3();
      break;
    case 4:
      page4();
      break;
    }

}

// The rest is the same, excluding the functions that are no longer needed

```

I made the buttons INPUT\_PULLUP so that they normally read HIGH if not pressed, thus LOW means pressed (therefore the switches should be wired from the digital pin on one side to Gnd on the other side).

It still isn't perfect but that should give you something to play with. Add some more debugging prints to see what is going on in the other functions.

# Answer
> 0 votes
The button stays down long enough for you to cycle through more than once, first setting binary\[i\] to 1 then to 0, etc. you need to add some logic to say “this is the first time I’ve seen this button state”

# Answer
> -1 votes
As an alternative to using two inputs, consider using a single analogue input with several momentary buttons - each with differing resistor values in series - this will let you avoid debouncing altogether. Just 5/3V3-\>resistor-\>btn-\>analogInput.

At worst, you will need to smoothe out jitter on analog reads. Have a look at https://www.codeproject.com/Tips/709109/ADKeyboard-Library-for-Arduino

---
Tags: arduino-uno, lcd, button, debounce
---


# Question
Title: Slowly decreasing the speed on a steppermotor over time
I am currently working on an elevator for my examsproject in school. It's a quite simple simulation of a lifesize elevator. I'm currently using a steppermotor for the elevatorchair and it's set with a certain speed.

However, in a real elevator, the speed would slowly decrease as it's progressing towards it's destination for a more pleasant ride for the passengers. I'd like to make the same simulation. I was thinking of using the millis to periodically increase the delays over time, but I don't know whether alternative methods could be used for better results.

# Answer
> 1 votes
millis() sound like a good way to go.

Check the estimated time until arrival (stopping), and in steps (you define yourself) you changen the (PWM) speed of the stepper motor.

Note, also for accelerating you can use the same step schema but reversed.

There are other ways, but I think those will be too complicated, like setting a (hardware) timer for the next speed change. Changing the speed in ms-accuracy will be more than enough.

Do not use delay, since you still want to be responsive for pressed buttons, and (safety) sensors.

---
Tags: arduino-uno, stepper, millis
---


# Question
Title: Control solenoid valve with arduino running on battery
I built a simple setup according to this tutorial using a 9v battery (in the meantime replaced it with a 120A battery): https://www.bc-robotics.com/tutorials/controlling-a-solenoid-valve-with-arduino/

Also i attached a humiditiy sensor to measure the soil-humidity. My plan is: 2 times a day (evening and morning before sunrise) wake up arduino and check humidity, if it is below a certain %, open the 12v-valve, wich i operate at 9v (like the one in the tutorial).

I read a lot about how to reduce power on the arduino and found this tutorial for the pro mini, wich seems a LOT easier than to modify the standard arduino uno: https://www.whizzy.org/2015/06/howto-very-low-power-usage-on-pro-mini-v2-arduino-clone/

Now, my question is: would a pro mini v2 work as well for controlling the valve? On the uno, i have the vin-pin wich provides the 9v for the valve, on the pro mini instead, as far as i understood, i need to use that pin (named RAW pin there) as power supply for the arduino... but how would i get out the 9v from the arduino like i did on the uno? Is there any possibility at all?

Thanks in advance!

# Answer
Vin and the barrel jack are the same power input on Uno.

RAW is the label for Vin on Mini Pro.

You can connect the `+` of the battery to power rail of the breadboard and from there to Vin/RAW pin of Arduino and to the solenoid powering contact.
> 0 votes

---
Tags: arduino-uno, power, arduino-pro-mini
---


# Question
Title: How does the build process in Arduino IDE work for ESP8266
How does the build process for esp8266 work in arduino IDE. Arduino ide uses avr-gcc to compile programs For atmel micro controllers. Does it uses same for compiling programs for esp8266?

# Answer
> Does it uses same for compiling programs for esp8266 ?.

No. It uses `xtensa-lx106-elf-gcc`. The compiler has to match the architecture.

Most of the build "process" (as in the actions that are taken) is the same, but executables specific to the EXP8266's XTensa core are used. There's also a few extra things in there, like building the (optional) SPIFFS image, etc.
> 2 votes

---
Tags: esp8266, ide, avr-gcc
---


# Question
Title: What's a good alternative to an Arduino Nano that can be used with Neopixels?
I'm doing an arduino project in school which requires neopixels, but the Arduino's too big. Is there an arduino I can use that's compatible with neopixels? Thanks!

# Answer
**ESP8266** mini is the best and cheaper alternative 2$5 on Ali express. Then 100% compatible with arduino toolchain/IDE + very impressive community/github library!
> 2 votes

# Answer
There are Arduino ProMinis (they have the same specs as the nano) also there's an arduino digispark tiny 85 (they have lower specs than the nano) and at the end there are just microcontrollers that can be soldered on a PCB that is enough small for you (they have a big range of specs) Here is a comparison to the nano
> 1 votes

# Answer
It's not really an Arduino, however there is an STM32 which you can program almost identical to an Arduino (using the Arduino IDE). It's the STM32F103C8T6.
> 1 votes

---
Tags: arduino-uno, neopixel
---


title: MKR1000 - Connecting to Pubnub

text:
# Question
Title: MKR1000 - Connecting to Pubnub
I don't know if it's a stupid question but I need some help.
I am trying to follow this tutorial and I want to connect my arduino to PubNub. In the tutorial it says that I have to 'open PubNub.h and switch the comments for the Ethernet and WiFi lines' with some code provided there. But, when I open the file PubNub.h the only thing in there is this:

```
/* -*- c-file-style:"stroustrup"; indent-tabs-mode: nil -*- */
#include "PubNubDefs.h"

class PubNub PubNub;

```

I'm quite new to this so I don't know much. I hope someone can help. Thank you in advance!

# Answer
It appears the tutorial is now outdated and the PubNum library does not need the changes described in the tutorial.

The PubNub library has an example titled PubNubWifi101 which shows the client type being set with a `#define` before including the PubNub headers:

```
#include <WiFi101.h>
#define PubNub_BASE_CLIENT WiFiClient
#include <PubNub.h>

```

I don't have a MKR1000 to test with, but I was able to compile the example from the tutorial by adding that single `#define` after the `#include <WiFi101.h>`.
> 1 votes

---
Tags: mkr1000
---


title: Two batteries sharing ground?

text:
# Question
Title: Two batteries sharing ground?
I need to power my arduino and 2 DC motors requiring 6V each, I want to power the DC motors with a 6V battery through the vM pin on an h-bridge and use a 9V battery to power the Arduino itself.

On my breadboard I have a dedicated power line and ground line on each side, is it okay to share the ground between both batteries and consequently share grounds for any servo motors or sensors i connect?

# Answer
> 12 votes
Not only *can* you share the grounds - sharing the grounds is *required* for there to be any form of meaningful circuit for signals to get around the place.

To copy-and-paste a blog post I wrote some time back:

---

A lot of the time on the Arduino forums we get questions regarding wiring things together. One common format is:

> I want to connect my 12V powered LED strip to my Arduino but I can’t get it to communicate. I have checked all the connections and they seem fine. I have a 12V power supply for the LEDs and the Arduino is powered from the computer.

And 9 times out of 10 the first question we have to ask in return is:

> Have you connected the grounds together?

And guess what the reply to that usually is? Yep:

> No, do I need to? And isn’t that dangerous, connecting a 12V ground to the 5V Arduino ground?

That in itself shows a fundamental lack of knowledge about what “ground” actually is. So let’s start by clearing that up:

Ground, technically, is just a name given to a point in your circuit. That point is a point chosen by you against which all other voltages in the circuit are measured. Often it is the point of lowest potential, such as the – side of a battery, or the – connection of a power supply. Or it may have been chosen for you, such as the ground signal from the USB connection to your computer.

The 5V pin of the Arduino isn’t actually 5V – it is 5V with respect to the ground pin. Equally, you could rename the 5V pin to Ground, and what was the ground pin then becomes -5V with respect to \[the new\] ground.

So ground has to be a single point in your circuit against which all voltages “make sense”.

Let’s take a look at the typical circuit from the original question. An Arduino connected to some 12V device (such as some 12V LEDs):

Here you can see the Arduino connected to, for example, a 5V USB charger. It could be a battery, or it could be the USB port on your computer. It doesn't matter. Connected to that is a 12V device which then has its own 12V power supply. Now. Where is ground in that circuit?

The 5V pin of the Arduino is 5V with respect to the ground pin of the Arduino. So seen from the Arduino’s point of view ground is, in the image above, the bottom line of the Arduino’s power circuit (charger -). However, the 12V of the external circuit is 12V with respect to the – side of the 12V PSU. So seen from the point of view of the 12V device the ground is the lower side of the 12V circuit – the “PSU -” connection.

That doesn’t sound too bad, does it? Each device’s power is correct with respect to the power supply it is running off. As far as that goes, sure. However take a look at the data signal going from the Arduino to the 12V device. What voltage is that at?

Well, seen from the Arduino’s point of view, with respect to its ground, since it is generating the signal, it is a 5V signal. But, what about what the 12V device sees? What voltage is that signal with respect to the 12V circuit ground?

Given that voltages aren’t absolute – they are only relative to a reference point within the same circuit, it is impossible to know what the voltage is there.

There’s something more fundamental at play here though which can help you to understand it even better. In the image above there are two red arrows in loops. That is the flow of the current around the circuit (shown as conventional current flow). The key phrase there is around the circuit. Current has to flow out of a supply, through a circuit, and back to the supply from where it came.

In the circuit above the current can flow out of the 5V, through the Arduino, and back to the 5V again because there is a complete loop there. Likewise there is a loop from the 12V supply, through the 12V device, and back to the 12V supply again. But there is no such loop for the signal from the Arduino to the 12V device. If we think of the Arduino’s output pin as a small power supply there really should be some way for the current to get out of the Arduino, through whatever it is connected to, and then back to the Arduino again. There is no way for that to happen in this circuit.

So you connect the grounds. As soon as you do that a lot of things start to happen. Let’s do that now and see how the circuit looks:

The grounds are now linked by the green wire at the bottom. Immediately we can now see a loop has appeared where the current from the IO pin can flow through the 12V device, out of the ground connection of the device, along the green wire, and back up through the ground connection of the Arduino.

In actuality the loop is a branch from the 5V power loop. Current goes from 5V into the Arduino where it splits, some to run the Arduino and some out of the IO pin. From there it goes through the 12V device, down to ground, then joins the current flowing out of the ground of the Arduino to go back to the 5V supply. It’s useful to think in terms of discrete loops though so you can get a better idea of how the ground fits into things.

Also, now, since the ground of the 5V section and the ground of the 12V section are one and the same (in a schematic all points along a line are the same point) any signals generated from the 5V side are recognisable by the 12V side as 5V since the reference point (ground) is the same for every point in the circuit.

But isn’t it dangerous?

Absolutely not. Not only is it not dangerous, it’s safer than not connecting grounds together. Since now the whole circuit has a single baseline voltage to reference everything from 12V is 12V and 5V is 5V. Without that link the voltage difference between ground on the 5V side and 12V on the 12V side could potentially be many hundreds of volts (especially when the distances between the two points is great). For fully isolated systems, such as battery powered devices, that is not a problem. For anything using power supplies though it can be quite dangerous. And that leads me on to my next point – a slight variation on the question:

I built a circuit with a 12V device powered from a power supply which is controlled by my Arduino. It all works well. But as soon as I run the Arduino from a battery instead of my computer it stops working.

This is a classic case where the grounds haven’t been connected together by the user, but there exists another path linking the grounds together. This is most often the earth connection of the computer and the earth connection of the power supply being linked together through the house wiring:

As you can see the current loop still exists, it just takes a longer route. As soon as you remove the Arduino from your computer and power it from batteries – or a power supply that has no connection to earth – the lower part of that loop disappears completely and you are back to the original circuit with only 2 loops. And it stops working.

Connect the grounds together manually, though, and you reinstate that portion of the loop, making it all work again.

So there you have it. If you have multiple power supplies in your project, whatever they may be (except in special circumstances) you must connect the grounds together for it to work. If it works without connecting the grounds together then you are inadvertently relying on some pre-existing ground connections to do the job for you, and that is likely to fail if your setup ever changes.

---
Tags: arduino-nano, motor, voltage-level, battery, h-bridge
---


# Question
Title: Can I use 1 clock module for multiple Arduinos?
I want to connect an RTC to a master Arduino, send the time data to a slave Arduino through I2C, then connect an LCD to the slave and print it out.

can it be done? A think it would mean that the slave Arduino is a master for the LCD a the same time and it would mess up my code. Any input would be highly appreciated.

# Answer
The LCD is connected over SPI. The MCU can be an I2C slave and the SPI master. There is no conflict.
> 1 votes

# Answer
From what I understood. I think you are trying to pass time to 2 ardruinos using one RTC. m.a. = master arduino s.a. = slave arduino

```
                            RTC
                            /\ (i2c)
                        m.a.  s.a.-------------(LCD)
                         L______|(spi)

```

No you cannot but you can read time in master and then relay it to slave using your own protocol (i.e. "Apr 4 21:20:16 IST 2018") and let it print to LCD.

```
      RTC ------ m.a. ======= s.a. ++++ (lcd)
            i2c          spi
        (read reg.)  (pass string)

```

Humble NOTE:- If possible draw some digram while you are explaining circuit. It will be far easy to understand and answer than explaining circuit. may be draw on paper and upload to igmur/drive and add link in question or upload it here. My ascii digrams may not be best but I think they pass message clearly.
> 1 votes

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


# Question
Title: Problem in bootloading 328p using Arduino as ISP. Please help me in figuring out the problem.I have uploaded the verbose below
Arduino: 1.8.3 (Windows 10), Board: "Arduino/Genuino Uno"

```
C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -cstk500v1 -PCOM8 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDE:m -Ulfuse:w:0xFF:m

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM8
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

Error while burning bootloader.

```

# Answer
there is great community called avrfreaks.net great with anything with AVR.

There is thread going with exactly same issue. follow it.

one quick thing try different 328p chip if it works mostly this one is bricked. still want o experiment try changing crystal, fuse-bit , ISP , external clock generator.
> 0 votes

---
Tags: arduino-uno, atmega328, bootloader, electronics
---


title: Arduino MKR1000 as Access Point

text:
# Question
Title: Arduino MKR1000 as Access Point
I want to turn my Arduino MKR1000 into an Access Point. My code is the following:

```
#include <SPI.h>
#include <WiFi101.h>
#define PubNub_BASE_CLIENT WiFiClient
#include <PubNub.h>

WiFiServer server(80);
char ssid[] = "MKR1000";
int status = WL_IDLE_STATUS;

void setup() {
  delay(1000);
  Serial.begin(9600);
  Serial.print("Creating access point named: ");
  Serial.println(ssid);
  if (WiFi.beginAP(ssid) != WL_CONNECTED) {
    Serial.println("Creating access point failed");
    while (true);
  }
  server.begin();
  printStatus();
}

void loop() {

}

void printStatus() {
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
  Serial.print("To connect, join the network and open a browser to http://");
  Serial.println(ip);
}

```

After uploading this, in the serial monitor I get this:

```
Creating access point named: MKR1000
Creating access point failed

```

I'm new to this so I really don't know what's the problem. I hope someone knows what's going on.
Thank you in advance.

# Answer
I found this reference for `Wifi.beginAP()` in the Wifi101 library, which I hope is the correct one - apologies if it's not.

It says that `beginAP()` returns either `WL_AP_LISTENING` or `WL_CONNECT_FAILED`, so checking for `WL_CONNECTED` is not sensible.

Try this:

```
if (WiFi.beginAP(ssid) != WL_AP_LISTENING) {
  Serial.println("Creating access point failed");
  while (true);
}

```
> 0 votes

---
Tags: mkr1000
---


# Question
Title: How can I hack my intercom system to buzz people in remotely?
How would you go about activating this button remotely?

This board is from the intercom in my apartment. The button when pressed unlocks the building door. I've just ordered the MKR IoT bundle (https://store.arduino.cc/arduino-iot-mkr1000-bundle). My plan is to learn the basics and figure out how to activate this button remotely.

# Answer
3 possible solutions:

1. Connect the 2 contact for the button to a relay and control that relay from the arduino (example) But the kit you have doesn't include a relay.
2. Use a transistor to trigger the switch -- I would not recommend this option as your first project. It would be easy to damage the intercom and/or your arduino.
3. Use the servo in the kit to physically press the button. You will need to figure out the mechanical linkages but you don't need to attach wires to the intercom.

For a beginner project I would probably go with the third option.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Interaction between Analog Pins when measuring a DC voltage- a common issue?
Just set up a replacement "Piduino" - a RPi3 connected by USB to an Arduino Uno. The previous one was the victim of a Diet Big Gulp - spilled on the voltage divider breadboard. Whoops. The tiny breadboard with the voltage divider began to rust inside so it got really difficult to keep it working correctly.

This is for the plot named "Indoor 12V Lighting System" at https://www.SDsolarBlog.com/montage

I built a new Uno/breadboard from scratch and swapped it in with the breadboard stuck onto the plastic case. All nice and tidy.

But the analog inputs were really strange. It would read really close, but then minor changes to the software would produce wildly varying results.

Imagine my surprise when this morning I discovered that I had plugged the divider's analog input to A4 instead of to A1 where it belonged.

Now that it has been fixed all is well. As long as the correct pin is being used in the `digitalRead` it seems not to matter, perhaps.

Here is the plot from before then after I moved the input to the correct location:

The actual voltage was falling from 12.7 down to 12.5, and after moving the pin it settled down to the correct reading. Then I turned on the charger while the sun is up. It is tracking the voltmeters perfectly now.

Clearly, the problem was that I was reading the wrong pin. My fault, obviously. But it got me wondering just how much they affect each other.

So my question is about why I was getting any readings at all? I would have hoped that the analog inputs were truly separate from each other. Instead, it appears as if there is crosstalk of some kind.

Is this a common issue?

---

**New information**

I see that it has been pointed out that this was discussed in this Q&A:

Should all unused analog input ports be tied to ground for accurate A2D measurements?

But since that does not call it an imperative, just "one of the problems with using analog" I would have assumed that this is not common, so perhaps there is an implied answer there.

It would be a project all by itself to use half the small breadboard to distribute ground to all the other analog pins. And I've never seen this referenced in any of the documentation. Nor is there a tag for crosstalk.

So my question still stands: Is this common when measuring a DC voltage?

# Answer
This is normal and expected behaviour. There are a number of factors that influence it, and it will help to understand the basic internals of the ADC.

In simple terms the front-end of the ADC looks like this:

simulate this circuit – Schematic created using CircuitLab

The MUX selects which pin (A0-A5) is being sampled. Switch SW1 connects the *Sample And Hold* capacitor C1 to that selected input, which then charges (or discharges) to the same voltage as the input.

After the acquisition period switch SW1 switches position and the ADC circuit is connected to the capacitor. Over a period of clock cycles the ADC works out what the voltage across the capacitor is and stores the result in the ADCH and ADCL registers.

Now - on a pin that has nothing connected to it, what voltage will be across that capacitor when SW1 is switched to charge it? Well, this is where your strange results come from:

1. Any charge already in the capacitor will *still be there* (which is why it can be good to connect the unused ADC pins to ground through a resistor, to remove that charge).
2. Signals, either in wires, IC pins, or the silicon circuitry in the chip itself, will be capacitively coupled with what is next to it.

That last one is the most critical for your results. Capacitive coupling.

Place two wires next to each other and they will, through capacitance, try and get the same charge on them. Under most circumstances that attempt to influence the charge is completely swamped out by what is being send down the wire. But, when there is *nothing* being sent down the wire that charge becomes noticable. A1 will attempt to "float" to the same level as A0, because they're next to each other. A2 will try and float to the same level as A1, A3 to A2, etc.

If you put a signal in to A0 and plot all 6 inputs you will see each has a progressively lower amplitude copy of the signal. It's hopping, capacitively, between the pins. And all because there's nothing to stop it.

If you think "Ah, but it's DC. DC doesn't go through capacitors", then you're wrong. Wrong in thinking it's DC. There's a lot of mistaken assumptions about the labels "AC" and "DC".

DC is not what you have. Yes, there is a "DC component" to what you have (which is manifest as the average of the voltage over time), but there is a large AC component as well. That AC component is what you are graphing in the form of your changing battery voltage.

Voltage is far more complex than just DC or AC. What you think of as AC is actually a waveform with a fundamental frequency (e.g., 60Hz) and zero "DC offset". Add a DC offset to the signal and it's still AC, but compared to the "lower" end of whatever adds the DC offset, it's just the waveform is "shifted up".

Pure DC, and what doesn't pass through a capacitor, has no signal components. There is only 0Hz and nothing else. Pure DC is almost impossible to create without highly specialized equipment. All voltages in normal life vary, and that variance is the AC component of the signal.
> 1 votes

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


# Question
Title: Interacting with a video game - Keyboard & LUFA
I have an Uno and Leonardo that I am trying to have it interact with the GTA V video game. Using the Keyboard library, it works within the OS. But it ocassionally works within the GTA V process. It seems that the transfer speed may be too slow, as the game sometimes registers the key press and does the assigned command. For instance, I can have a pushbutton that when pressed, it activates **Keyboard.Write('J')**. While in GTA V, I can rapidly press the pushbutton for 3 seconds and the game will only detect one **J** within that time frame and do the assigned game command. Yet, if I rearrange the code to be momentary to where the pushbutton is active, it'll constantly send **Keyboard.Write('J')**, this will work for commands that are momentary ingame, like the vehicle horn.
Below is the code I used for my Uno. It works fine within programs.

```
/*
  Keyboard Message test

  For the Arduino Leonardo and Micro.

  Sends a text string when a button is pressed.

  The circuit:
  - pushbutton attached from pin 4 to +5V
  - 10 kilohm resistor attached from pin 4 to ground

  created 24 Oct 2011
  modified 27 Mar 2012
  by Tom Igoe
  modified 11 Nov 2013
  by Scott Fitzgerald

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/KeyboardMessage
*/

#include "Keyboard.h"

const int buttonPin = 4;          // input pin for pushbutton
int previousButtonState = HIGH;   // for checking the state of a pushButton
int counter = 0;                  // button push counter

void setup() {
  // make the pushButton pin an input:
  pinMode(buttonPin, INPUT);
  // initialize control over the keyboard:
  Keyboard.begin();
}

void loop() {
  // read the pushbutton:
  int buttonState = digitalRead(buttonPin);
  // if the button state has changed,
  if ((buttonState != previousButtonState)
      // and it's currently pressed:
      && (buttonState == HIGH)) {
    // increment the button counter
    counter++;
    // type out a message
    Keyboard.write('J');
    //Keyboard.print("You pressed the button ");
    //Keyboard.print(counter);
    //Keyboard.println(" times.");
  }
  // save the current button state for comparison next time:
  previousButtonState = buttonState;
}

```

I also tried this same test using LUFA but the same issues were encountered.
I believe it has to do with the game, not my code. Does anyone have a clue of why this might be?

# Answer
> 1 votes
It is quite common for games to be quite slow at reading the keyboard.

The Leonardo's `Keyboard.write()` command is quite rapid. The OS can pick it up with its interrupt driven buffering, but games tend not to use that buffering so they can get more realtime key control.

The trick here is actually to slow down the Leonardo's sending, by not using `Keyboard.write()`. Instead you need to `press` the key, wait a moment, then `release` the key:

```
Keyboard.press('j');
delay(1);
Keyboard.release('j');

```

Increase the delay until it becomes reliable. It's hard to say what the delay should be.

---
Tags: keyboard
---


title: Sampling and serial transfer

text:
# Question
Title: Sampling and serial transfer
I am trying to get a sampling rate of over 10k Samples per second as well as send each sample over a serial line. Taking a sample and putting it on the serial line each time took too long. I am using Processing 3.3.6 for datalogging into a csv file. I am unable to achieve more than 6k samples per second even at lower prescaler value and high baudrate. What am I doing wrong? Here is my arduino code.

```
int val[2000];
void setup()
{
  Serial.begin(250000);

  //ADCSRA = 0;             // clear ADCSRA register
  //ADCSRB = 0;             // clear ADCSRB register
  ADCSRA &= ~(bit (ADPS0) | bit (ADPS1) | bit (ADPS2)); // clear prescaler bits
  //ADCSRA |= bit (ADPS0);                               //   2
  ADCSRA |= bit (ADPS1);                               //   4
  //ADCSRA |= bit (ADPS0) | bit (ADPS1);                 //   8
  //ADCSRA |= bit (ADPS2);                               //  16
  //ADCSRA |= bit (ADPS0) | bit (ADPS2);                 //  32
  //ADCSRA |= bit (ADPS1) | bit (ADPS2);                 //  64
  //ADCSRA |= bit (ADPS0) | bit (ADPS1) | bit (ADPS2);   // 128
  //pinMode(A0, INPUT);

}

void loop()
{
  for(int i=0; i<2000; i++) {
    val[i] = analogRead(A0);
  }
  for(int i=0;i<2000;i++){
    Serial.print(val[i]);
    Serial.print('x');
  }

}

```

P.S I am new to arduino.

--edit1\>\> I am using Arduino Mega 2560.

# Answer
> 1 votes
Probably the serial port is too slow:

Assuming 250 kbits/s, is (including 3 start/stop bits, maybe 2 in your case) in about 250000 (bits/s) / 11 (bits/byte)= about 22 KBytes/s Assuming each sample has 3 or 4 digits and an 'x' is added (which is 5 characters), 22 (KBytes/s) / 5 (digits/sample) = about 5-6 Ksamples/s you can transfer, which is what you experienced.

So you have to increase the speed for the serial port.

---
Tags: serial, processing-lang, analog-sampling
---


title: Improper sampling of wave

text:
# Question
Title: Improper sampling of wave
I am using Arduino Mega 2560 to sample and serially send a square wave. I am using Processing 3.3.6 for logging the data to .csv file. I am receiving about 6k samples at the moment. When I try sampling a square wave, min= 0V, max=3V at 200Hz, the number of samples at the two amplitudes(at 0 and 3V) are not at all close by. What could be going wrong?

This is my Processing code:

```
//import the required libraries
import processing.serial.*;

Serial mySerial;
Table table;
String filename;

void setup()
{ //print(0);
  //set mySerial to listen on COM port 4 at 1000000 baud
  mySerial = new Serial(this, "COM4", 1000000);

  table = new Table();
  //add a column header "Data" for the collected data
  table.addColumn("Data");
  //add a column header "Time" and "Date" for a timestamp to each data entry
  table.addColumn("Time");
  table.addColumn("Date");
}

void draw()
{ print(1);
  //variables called each time a new data entry is received
  int d = day();
  int m = month();
  int y = year();
  int h = hour();
  int min = minute();
  int s = second();
  //int s_prev=0;
  char d1 = 'a';

  if(mySerial.available() > 0)
  { //print(2);

    //set the value recieved as a String
    String value = mySerial.readString();
    //check to make sure there is a value
    if(value != null)
    {
      String[] parts = value.split("x"); //returns an array with the 2 parts

      //print(parts);
      //print('\n');
      for(int i=0;i<parts.length;i++)
      {

        String Part = parts[i];
        TableRow newRow = table.addRow();
        //place the new row and value under the "Data" column
        newRow.setString("Data", Part);
        //place the new row and time under the "Time" column
        newRow.setString("Time", str(h) + ":" + str(min) + ":" + str(s));
        //place the new row and date under the "Date" column
        newRow.setString("Date", str(s + 100));// + "/" + str(m) + "/" + str(y));
      }
    }
  }
print(4);}

void keyPressed()
{ print(5);
  //variables used for the filename timestamp
  int d = day();
  int m = month();
  int h = hour();
  int min = minute();
  int s = second();
  //variable as string under the data folder set as (mm-dd--hh-min-s.csv)
  filename = "data/" + str(m) + "-" + str(d) + "--" + str(h) + "-" + str(min) + "-" + str(s) + ".csv";
  //save as a table in csv format(data/table - data folder name table)
  saveTable(table, filename);
  exit();
}

```

This is my arduino code:

```
int val[2000];
void setup()
{
  Serial.begin(250000);

  //ADCSRA = 0;             // clear ADCSRA register
  //ADCSRB = 0;             // clear ADCSRB register
  ADCSRA &= ~(bit (ADPS0) | bit (ADPS1) | bit (ADPS2)); // clear prescaler bits
  //ADCSRA |= bit (ADPS0);                               //   2
  ADCSRA |= bit (ADPS1);                               //   4
  //ADCSRA |= bit (ADPS0) | bit (ADPS1);                 //   8
  //ADCSRA |= bit (ADPS2);                               //  16
  //ADCSRA |= bit (ADPS0) | bit (ADPS2);                 //  32
  //ADCSRA |= bit (ADPS1) | bit (ADPS2);                 //  64
  //ADCSRA |= bit (ADPS0) | bit (ADPS1) | bit (ADPS2);   // 128
  //pinMode(A0, INPUT);

}

void loop()
{
  for(int i=0; i<2000; i++) {
    val[i] = analogRead(A0);
  }
  for(int i=0;i<2000;i++){
    Serial.print(val[i]);
    Serial.print('x');
  }

}

```

# Answer
> 0 votes
You are doing 2000 samples really close together in rapid succession with no concept of time between them, then you are spending a considerable amount of time sending that data through serial.

That's not how you sample signals.

Instead, you need to set up some kind of time-based periodic sampling system, either through a timer interrupt or some other facility provided by the ADC (read the datasheet to see what interrupts the ADC can generate and what sample trigger sources there are) which runs completely asynchronously. Then when (and only when) a sample set has been captured do you send that data through serial.

If your sampling takes longer than your sending through serial (unlikely) and you have the memory for it you can set up two buffers and "ping-pong" between them so you are sampling at the same time as sending. Otherwise, all you will be able to do is capture a short window of data and then send it afterwards, so you get short bursts of samples.

---
Tags: serial, processing-lang, analog-sampling
---


# Question
Title: Two power source for Arduino and a relay
In my work, I have an ESP-8266, Arduino-Uno and a Relay. ESP 8266 and Uno is connected. Relay's data signal is take from arduino's 12th pin. ESP is powered from Uno.

If I use two different power sources for Uno and Relay, Relay does not response for the signal from Uno. (Both have a same common ground)

If relay is powered from Uno, then after load control (power on and off) ESP-8266 goes down.

# Answer
> 2 votes
The uno can't provide enough power to power an ESP8266 **reliably**. I suggest you power it from a separate source.

When ever you use separate power supplies for a circuit you need to "tie the grounds together", connect them. Otherwise the circuits don't use the same definition of zero.

# Answer
> 1 votes
Use a relay driver IC like ULN2003 to drive relay. Here is a sample circuit diagram :

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


# Question
Title: Arduino Uno vs Arduino Micro timers → pins
**Where do I find the pins relative to timers of each individual Arduino microcontroller?**

As I like Arduino's I already have various samples of them. The one I mostly use is the Uno and Micro for now... I'm planning to also get a Mega and others. Most simple things work on all devices, but if you start with complex code to fasten up things, every device is a little different. A problem I could not solve for days now is the relation between pins and timers.

I cannot find any information about the Arduino Micro. I also don't know exactly what the proper keywords are that I need to find the relation between timers and pins.

**Example:** A PWM driver multiplexing

As I for now just got some stuff from my local dealer I have no access to shift registers, PWM drivers and other proper integrated circuits.

So I used the Arduino as a PWM driver for 8 RGB or 24 (3\*8) white LEDs. The code works on Arduino Uno. But as the **Arduino Micro has no *Timer2***, `TCCR2B`, I cannot use the same code on the Arduino Micro.

Even if I understand the code (I wrote a lot in other languages...), some of the Atmel chip specific parameters are not clear.

This function sets the prescaler of the timer:

```
void setPwmFrequency(int pin, int divisor){

  byte mode;
  if(pin==5||pin==6||pin==9||pin==10){
    switch(divisor){
      case 1:mode=0x01;break;
      case 8:mode=0x02;break;
      case 64:mode=0x03;break;
      case 256:mode=0x04;break;
      case 1024:mode=0x05;break;
      default:return;
    }
    if(pin==5||pin==6){
      TCCR0B=TCCR0B&0b11111000|mode;
    } else{
      TCCR1B=TCCR1B&0b11111000|mode;
    }
  }else if(pin==3||pin==11){
    switch(divisor){
      case 1:mode=0x01;break;
      case 8:mode=0x02;break;
      case 32:mode=0x03;break;
      case 64:mode=0x04;break;
      case 128:mode=0x05;break;
      case 256:mode=0x06;break;
      case 1024:mode=0x7;break;
      default:return;
    }
    TCCR2B=TCCR2B&0b11111000|mode;
  }
}

```

First of all, I probably don't even need this function as soon I know what frequency I want, and so I probably need only two lines to set my three (RGB) pins.

```
//Arduino Uno timer setup for pin 9, 10, and 11
TCCR1B=TCCR1B&0b11111000|0x01; // Pin 9,10
TCCR2B=TCCR2B&0b11111000|0x01; // Pin 11

```
1. Correct, I need to set `TCCR1B` only one time?
2. What does the `0b11111000` refer to?

In the setup function there is also this line:

```
TIMSK2 = 1<<TOIE2;

```
3. What does this do?

While the above three questions are not so important until it works, **I need to understand how I can convert those timers to work with Arduino Micro**, but also later with other Arduino boards.

---

**On Arduino Micro**

There is no timer 2

Do pin 9, 10, and 12 have the same timer?

```
??????=??????&0b11111000|0x01;

```

Also if I understand correctly the Arduino Micro has:

1. A higher PWM range 1024 vs 255 (UNO)??
2. A much higher frequency available in on Timer4 only for pin 13

**So is there somewhere a table describing the differences between all Arduino timers?**

**Full working (on Arduino Uno) code.**

```
unsigned char Prescaler=0;
unsigned char CurrentLED=0;
unsigned char LEDValues[8][3];
unsigned char ports[8]={
  0b00000100,
  0b00001000,
  0b00010000,
  0b00100000,
  0b01000000,
  0b10000000,
  0b00000001,
  0b00010000
};//PINS 2,3,4,5,6,7,8,12

#define PrescalerOverflowValue 4

ISR(TIMER2_OVF_vect){
  if(Prescaler<PrescalerOverflowValue){
    Prescaler++;
  }else {
    Prescaler=0;
    Multiplex();
  }
}

void Multiplex(void){
  PORTD&=0b00000011;
  PORTB&=0b11101110;
  analogWrite(9,255-LEDValues[CurrentLED][0]);
  analogWrite(10,255-LEDValues[CurrentLED][1]);
  analogWrite(11,255-LEDValues[CurrentLED][2]);
  CurrentLED<6?(PORTD|=ports[CurrentLED]):(PORTB|=ports[CurrentLED]);
  CurrentLED++;
  if(CurrentLED>7)CurrentLED=0;
}
void setPwmFrequency(int pin, int divisor){
  byte mode;
  if(pin==5||pin==6||pin==9||pin==10){
    switch(divisor){
      case 1:mode=0x01;break;
      case 8:mode=0x02;break;
      case 64:mode=0x03;break;
      case 256:mode=0x04;break;
      case 1024:mode=0x05;break;
      default:return;
    }
    if(pin==5||pin==6){
      TCCR0B=TCCR0B&0b11111000|mode;
    }else{
      TCCR1B=TCCR1B&0b11111000|mode;
    }
  }else if(pin==3||pin==11){
    switch(divisor){
      case 1:mode=0x01;break;
      case 8:mode=0x02;break;
      case 32:mode=0x03;break;
      case 64:mode=0x04;break;
      case 128:mode=0x05;break;
      case 256:mode=0x06;break;
      case 1024:mode=0x7;break;
      default:return;
    }
    TCCR2B=TCCR2B&0b11111000|mode;
  }
}

void setup(void){

  pinMode(2,OUTPUT);//1
  pinMode(3,OUTPUT);//2
  pinMode(4,OUTPUT);//3
  pinMode(5,OUTPUT);//4
  pinMode(6,OUTPUT);//5
  pinMode(7,OUTPUT);//6
  pinMode(8,OUTPUT);//7
  pinMode(12,OUTPUT);//8
  pinMode(9,OUTPUT);//red
  pinMode(10,OUTPUT);//green
  pinMode(11,OUTPUT);//blue
  setPwmFrequency(9,8);
  setPwmFrequency(10,8);
  setPwmFrequency(11,8);
  TIMSK2=1<<TOIE2;
}

void loop(void){
  for(int i=0;i<8;i++){
    //LEDValues[i][0]; // Red
    //LEDValues[i][1]; // Green
    //LEDValues[i][2]; // Blue
  }
}

```

# Answer
> 7 votes
> I cannot find any information about the arduino micro. I also don't know exactly what the proper keywords are that i need to find the relation between timers and pins.

Now we know the processor, the datasheet tells you about the timers, and the schematic tells you which ATmega32U4 pins are connected to which pins on the Micro board.

---

> But as the Arduino Micro has no Timer2 TCCR2B i cannot use the same code on the Arduino micro.

True. But it has Timer 1, Timer 3 and Timer 4. You just need to adjust the registers a bit.

---

> Correct, I need to set TCCR1B only one time?

Yes you can do that. Personally I normally stop the timer and then set the parameters in case setting them when it is running has a different effect. eg

```
TCCR1A = 0;  // stop timer 1
TCCR1B = 0;
TCCR1C = 0;

```

---

> ```
>    TCCR1B=TCCR1B&0b11111000|0x01; //pin 9,10
>
> ```
>
> What do the 0b1111000 refer to?

In this case the first part `TCCR1B & 0b11111000` clears the low-order 3 bits (the rest are ANDed in with 1 so they stay the same as before).

Then it sets the lower-order bit. In this particular case you are setting up a prescaler of 1 times the clock rate.

---

> ```
>    TIMSK2=1<<TOIE2;
>
> ```
>
> what does this ?

TIMSK2 is a timer register.

By shifting 1 left "TOIE2" bits it sets that bit (ie., TOIE2 in TIMSK2).

In other words, it enables the overflow interrupt for Timer 2.

---

> On Arduino Micro There is no timer 2 Pin 9,10,12 have the same timer ?

Look at the reference schematic. Yes it looks like it.

As you can see from that pin 30 (on the chip) is labelled `OC4B` which means it is the "output compare timer 4: B output". That pin has the net name "IO10\*" which I presume means it is connected to board pin 10 (pin 30 on the chip).

---

> Also if I understand correctly the Arduino micro has:
>
> 1. a higher PWM range 1024 vs 255 (UNO)??
> 2. a much higher frequency available in on timer4 only for pin 13

No, the Uno has Timer 1 which is 16 bits (up to 65536). The Micro has Timer 4 which is 10 bits and therefore can count up to 1024.

Anyway, the frequency is a function of the clock speed. On either chip, by using a prescaler of 1, and counting up to 1, you can get an 8 MHz frequency (one up, one down from 16 MHz).

The higher number of bits in the timer, the *finer the resolution* \- that is you can adjust the frequency in finer steps, and you can adjust the PWM duty cycle in finer steps.

**However** with Timer 4 on the Micro you can, apparently, clock it with 6 times the clock rate (96 MHz) which is used for the USB part of the chip. Setting appropriate bits (I haven't done this personally) you could get that higher frequency.

You can apparently get 96 MHz, 64 MHz or 48 MHz clock frequencies on Timer 4 (as well as the normal ones).

---

*Added in response to comments*

> Pin 12 on the chip has 2 timers, OC0A & OC1C??

Yes, from the datasheet:

> The Output Compare unit 1C and Output Compare unit 2 shares the PB7 port pin for output. The outputs of the Output Compare units (OC1C and OC0A) overrides the normal PORTB7 Register when one of them is enabled (i.e., when COMnx1:0 is not equal to zero). When both OC1C and OC0A are enabled at the same time, the modulator is automatically enabled.

---

> What timer do i need to use for let's say pin 9,10,12 on arduino micro?

Looks like Timer 4.

---

> in arduino ide i can only write analogWrite(255)

That is changing the PWM duty cycle for the timers configured in their default way.

Have a look in wiring.c:

```
// timers 1 and 2 are used for phase-correct hardware pwm
// this is better for motors as it ensures an even waveform
// note, however, that fast pwm mode can achieve a frequency of up
// 8 MHz (with a 16 MHz clock) at 50% duty cycle

```

analogWrite changes the duty cycle, not the frequency.

---

> You can apparently get 96 MHz... so at the end arduino micro can go faster on timer 4

I'm not sure what you mean by "go faster" here.

---

> but I actually did not solve the problem. I hope you give me a hint to how to make it work.

It isn't clear really what you want to happen.

* What devices are you driving?
* Why do you need high frequencies?
* What is the underlying problem?

---

### Reference

* Timers and counters \- mainly about the Atmega328P, however a lot of it applies to the other chips as well.

# Answer
> 0 votes
You can check `pins_arduino.h` file as well.

```
// ATMEL ATMEGA32U4 / ARDUINO LEONARDO
//
// D0               PD2                 RXD1/INT2
// D1               PD3                 TXD1/INT3
// D2               PD1     SDA         SDA/INT1
// D3#              PD0     PWM8/SCL    OC0B/SCL/INT0
// D4       A6      PD4                 ADC8
// D5#              PC6     ???         OC3A/#OC4A
// D6#      A7      PD7     FastPWM     #OC4D/ADC10
// D7               PE6                 INT6/AIN0
//
// D8       A8      PB4                 ADC11/PCINT4
// D9#      A9      PB5     PWM16       OC1A/#OC4B/ADC12/PCINT5
// D10#     A10     PB6     PWM16       OC1B/0c4B/ADC13/PCINT6
// D11#             PB7     PWM8/16     0C0A/OC1C/#RTS/PCINT7
// D12      A11     PD6                 T1/#OC4D/ADC9
// D13#             PC7     PWM10       CLK0/OC4A
//
// A0       D18     PF7                 ADC7
// A1       D19     PF6                 ADC6
// A2       D20     PF5                 ADC5
// A3       D21     PF4                 ADC4
// A4       D22     PF1                 ADC1
// A5       D23     PF0                 ADC0
//
// New pins D14..D17 to map SPI port to digital pins
//
// MISO     D14     PB3                 MISO,PCINT3
// SCK      D15     PB1                 SCK,PCINT1
// MOSI     D16     PB2                 MOSI,PCINT2
// SS       D17     PB0                 RXLED,SS/PCINT0
//
// TXLED    D30     PD5                 XCK1
// RXLED    D17     PB0
// HWB              PE2                 HWB

```

There is an array inside the same file with name `digital_pin_to_timer_PGM` that list the timers also.

```
const uint8_t PROGMEM digital_pin_to_timer_PGM[] = {
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    TIMER0B,        /* 3 */
    NOT_ON_TIMER,
    TIMER4A,        /* 5 */
    TIMER4D,        /* 6 */
    NOT_ON_TIMER,

    NOT_ON_TIMER,
    TIMER1A,        /* 9 */
    TIMER1B,        /* 10 */
    TIMER0A,        /* 11 */

    NOT_ON_TIMER,
    TIMER4A,        /* 13 */

    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,

    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
};

```

---
Tags: arduino-uno, timers, arduino-micro
---


# Question
Title: Digital Band pass filter arduino 1100-1300 Hz
For a project I need to design an digital band pass filter. I started of with this in Matlab:

```
wch=1100*2*pi;
wcl=1300*2*pi;

sys=tf([1/wch 0],[1/(wch*wcl) 1/wch+1/wcl 1])
sysd=c2d(sys,9615,'tustin')

so I got this values:

3.01e-08 z^2 - 3.01e-08/(z^2 + 2 z + 1)

```

Then I rewrote it to:

```
y[k] = 3.01*10^-8*u[k]-3.01*10^-8*u[k-2] -y[k-2]-2y[k-1]

```

and so I put hoped that this arduino script should do the Job:

```
#include <TimerOne.h>

float out;

float second_filt(float x0) {
  static float y1=0;  // y[n-1]
  static float y2=0;  // y[n-2]
  static float x1=0;  // x[n-1]
  static float x2=0;  // x[n-2]
  float y0 = 3.01*10^(-8)*x0-3.01*10^(-8)*x2-2*y1-1*y2 ;

  // Shift values
  y2 = y1;  // Shift y[n-1] to y[n-2]
  y1 = y0;  // Shift y[n] to y[n-1]
  x2 = x1;  // Shift x[n-1] to x[n-2]
  x1 = x0;  // Shift x[n] to x[n-1]
  return y0;
}

void setup() {
  Timer1.initialize(32); //Initialize timer with a period of 32 us
  Timer1.pwm(9,0); // Use pin 9 for PWM
}

void loop() {
  if (isTime()) {
    out=second_filt(analogRead(0));
    Timer1.setPwmDuty(9,out); //Sets the duty cycle to the analog value on pin 0
  }
}

bool isTime(){ //Checks if 300 us elapsed since the last call
  static unsigned long t0=0;
  static unsigned long t1=0;

  t1 = micros();

  bool res = (t1-t0)>300;

  if (res) {
    t0 = t1;
  }
  return res;
}

```

Now I don't know what the error: 'invalid operands of types 'double' and 'double' to binary 'operator^' means and I am not sure if this is actually gonna work. Pleas help me out I have been busy with this for days.

# Answer
> 3 votes
You cannot use ^ as mathematical power symbol in C. Ini C it means the exclusive-or bit operation (hence the error showing it is a bit operation).

For the mathematical power function, you should use the math C library. See library explanation. To include it, use:

```
#include <math.h>

```

The power function has the following prototype:

```
double pow(double x, double y)
Returns x raised to the power of y.

```

However if you only need to write a float/double in exponential format, you can use

```
3.01e-8

```

# Answer
> 1 votes
You have more than one problem here...

> `3.01e-08 z^2 - 3.01e-08/(z^2 + 2 z + 1)`

I don't quite understand your Mathlab code, but there is something wrong with this transfer function. The denominator can be rewritten as (z + 1)2. Thus there is a double pole at z = −1, i.e. at the Nyquist frequency. An infinite gain at Nyquist is not what you expect from a bandpass filter.

> `y[k] = 3.01*10^-8*u[k] - 3.01*10^-8*u[k-2] - y[k-2] - 2y[k-1]`

This is implementing the transfer function 3.01 × 10−8 (z2 − 1)/(z2 \+ 2 z + 1), which is **not** the same as the one written above: mind the parentheses.

> `float y0 = 3.01*10^(-8)*x0-3.01*10^(-8)*x2-2*y1-1*y2;`

As explained in Michel Keijzers’ answer, the constant should be written `3.01e-8`. Also, you can save one multiplication by writing it as

```
float y0 = 3.01e-8*(x0 - x2) - 2*y1 - y2;

```

> `if (isTime()) { out=second_filt(analogRead(0)); ... }`

You cannot expect to get a uniform sampling time with `analogRead()`, as your timing will depend on how long your program takes to get trough the loop, which is data dependent and affected by interrupts.

> sysd=c2d(sys,9615,'tustin')

I assume 9615 is the expected sampling rate, which translates to 104 µs between samples. This is the time it takes for the ADC to perform one reading. You cannot achieve this rate if you do computations *in between* the readings.

Here your best option is to configure the ADC in *free-running mode*. In this mode it will take one sample every 104 µs, and you will achieve the desired sampling rate. You should also do the filtering *in parallel* with the readings, and have the CPU and the ADC work concurrently instead of sequentially. For implementing this, you will first have to read the datasheet of the ATmega328P powering your Uno.

---
Tags: arduino-uno, programming, c, digital
---


# Question
Title: Is there alternative to arduino IDE program ESP8266 and ESP32 with arduino toolchain?
I use ESP8266 and ESP32 with arduino toolchain rather than pure arduino hardware. Arduino IDE is standard and proven but what are the other IDE and advantage/disadvantage ?

# Answer
> 4 votes
Not an exhaustive list. Most **advantages** will be subjective.

* UECIDE \- Wide variety of boards, not only Arduino, better editor and serial monitor, plug-in based modules.
* PlatformIO (Available as plugin for Atom editor, MS Visual Studio and Eclipse IDE) - Automatic library updating, one `ini` file that defines project settings and external libraries, making projects portable to other users without having to download all external libraries.
* Arduino IDE for Visual Studio \- For those who like VS?
* Arduino Makefiles \- More like old-school command-line coding, Linux-style development. Not an IDE.
* Eclipse \- Another quite popular IDE outside Arduino world.
* Atmel/Microchip Studio 7 \- Provided by the manufacturer of the AVR chips. "Arduino" sketches may not compile without changes to make them more like standard C++.

# Answer
> 2 votes
For example, Eclipse IDE with Sloeber plugin is much better than Arduino IDE. You have all the features of Eclipse (coloring, error highlighting, auto-complete, open declaration ('drill down' to libraries), ...\*). And every project has own settings (board settings, port, programmer ...). And the Arduino IDE buttons Upload, Verify, Session Monitor are there and the Arduino toolchain too.

\*... projects management, version control, TODO lists, outline, ...

---
Tags: arduino-uno, esp8266, ide, esp32
---


title: MEGA I2C and interrupts on 0,1

text:
# Question
Title: MEGA I2C and interrupts on 0,1
Looking at the pinout for the Arduino MEGA:

I see that Pins 20 and 21 can be both SDA and SCL or Interrupts 0 and 1.

If I'm using an Adafruit I2C 16x2 RGB LCD Shield connected to the SDA and SCL pins by the USB Jack, is there anything I can do in my code to still use INT0 and INT1 off Pins 20 and 21 for a different purpose?

# Answer
> 2 votes
No, there is nothing you can do.

Both the SCL pins and both the SDA pins are physically connected together by copper tracks. They are in effect the same pin. If you use I2C you can't use INT0 or INT1. You have INT2 and INT3 though (pins 18 and 19), as well as Pin Change Interrupts on a large number of other pins.

---
Tags: arduino-mega, i2c, interrupt
---


# Question
Title: What is the use of 1k resistor shown in the picture and why it is used? Please check Arduino Uno Schematics for more info
Can anyone tell me why 1k resistor is used on pin 13 of ATmega16U2 in arduino uno schematics. I have also seen a 100k resistor used in this position?

Link for schematics - https://www.arduino.cc/en/uploads/Main/Arduino\_Uno\_Rev3-schematic.pdf

# Answer
> 3 votes
Its a pulldown resistor!

Comment there says "USB Boot Enable" so safe assumption that it's an digital pin.

They're handy because they mean if there is no input to whether that pin is headed, the voltage at the pin will be 0 instead of floating.

The value doesn't matter too much, "When in doubt 10k it out" is a pretty well known saying around electronics people, meaning just use a 10k Ohm resistor and you'll be fine.

# Answer
> 0 votes
Pin 13 of the USB interface chip is connected to RESET line of the ATMEGA328 MCU. I would guess (also from "USB boot En" label) that pressing/issuing board reset gives the USB interface an interrupt (INT7), such that USB bootloader gets activated and the ATMEGA328 can start loading firmware code over USB. The resistor is a pull-down resistor ensuring LOW signal, and its value shouldn't matter much. However, there is a capacitor (C5) which provides a short pulse to the interrupt line. This is not the best way to form a digital signal and initiate an interrupt, but the RC should be long enough, so I would expect that if 100k is used, the cap can be much smaller than 100n as in 1k case.

---
Tags: arduino-uno
---


# Question
Title: C++ Adding Two 16 bit binary numbers together
I am trying to add two 16 digit binary numbers together. Each binary number will have been entered by the user and saved as: `int binaryOne[16] and int binaryTwo[16]`. Originally,

```
int binaryOne[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int binaryTwo[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

```

are the values declared. Then, the user has the option to change these values using buttons that I implement before the Solution() function. So, once the used gets to the Solution() function, the numbers may be stored as:

```
int binaryOne[16] = {0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1};
int binaryTwo[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};

```

This is what I have so far:

```
void Solution() {
  /*
    Rule of binary addition:
    0 + 0 = 0
    1 + 0 = 1
    0 + 1 = 1
    1 + 1 = 1 and carry = 1
   */
   lcd.clear();
   lcd.setCursor(0,0);
   lcd.print("Solution");
   lcd.setCursor(0,2);

    int a[16] = binaryOne[16];
    int b[16] = binaryTwo[16];
    int i = 0;
    int remainder = 0;
    int sum[32];

    while(a[16] != 0 || b[16] != 0){
      sum[i++] = (a[16] % 10 + b[16] % 10 + remainder) % 2;
      remainder = (a[16] % 10 + b[16] % 10 + remainder) / 2;
      a[16] = a[16] /10;
      b[16] = b[16] / 10;
    }
    if(remainder != 0){
      sum[i++] = remainder;
    }
    i--;
    while(i>=0){
      lcd.print("%d", sum[i--]);
   }
   return 0;
}

```

I believe I am doing something wrong with calling the arrays since I am renaming them to a\[16\] and b\[16\] within this function. I'm also curious, since I only have 16 bits of space on the screen, what if the user enters a binary number such as 1111111111111111 + 1000000000000000 and therefor there is going to be a carry on that first digit? Would it be best just to have an error message?

# Answer
> 2 votes
You're making a mountain out of a molehill.

You're trying to manually manipulate binary digits in an array, but C can already manipulate binary digits. Everything is binary already - you just need to represent it as such.

All you need to do is convert the contents of your array into an actual number, then do simple mathematics on that number. One of the simplest ways of doing that is to shift the bits into a variable:

For instance:

```
int binaryOne[16] = {0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1};
int binaryTwo[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};

uint16_t binOne = 0;
uint16_t binTwo = 0;

for (int i = 0; i < 16; i++) {
    binOne <<= 1;
    binOne |= binaryOne[i];
    binTwo <<= 1;
    binTwo |= binaryTwo[i];
}

```

Now you can add them together, since they're just numbers:

```
uint32_t result = binOne + binTwo;

```

And you can output it as binary:

```
Serial.println(result, BIN);

```

If you want to convert back into an array again (why?!) you can just do the opposite as before:

```
bool resultBin[32];

for (int i = 0; i < 32; i++) {
    resultBin[i] = (result & (1 << (31-i))) ? 1 : 0;
}

```

# Answer
> 2 votes
A few issues here:

1. The way you “rename” the arrays is wrong, and furthermore there is no point in doing such renaming.
2. There is no reason to divide by 10 (ten, in decimal) within your code: as everything you do is binary, the number *ten* has nothing to do with what are trying to accomplish.
3. While doing the addition, you forgot to *loop* over the bits.
4. You shouldn't `return 0` in a function of type `void`. In fact, you shouldn't return any value.

Fixing those issues should give you something similar to this:

```
void Solution() {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Solution");
    lcd.setCursor(0, 2);

    // Compute the sum.
    int sum[16];
    int remainder = 0;
    for (int i = 0; i < 16; i++) {
        int s = binaryOne[i] + binaryTwo[i] + remainder;
        sum[i] = s % 2;
        remainder = s / 2;
    }

    // Print it.
    for (int i = 15; i >= 0; i--) {
        lcd.print("%d", sum[i]);
    }
}

```

Note that there is no point in computing a 32-bit result if you can only print 16 bits: just accept that the computation is done modulo 216, just like a 16-bit ALU would do, or the `unsigned int` data type in the Arduino.

Of course, the whole idea of doing the computation one bit at a time is highly inefficient. See Majenko's answer for a more idiomatic and efficient way of managing numbers bit-wise in C and C++.

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


# Question
Title: NodeMCU not responding AT after blink app
I've just bought NodeMCU LoLin ESP8266, I tried to send AT commands (after spending days on ESP8266-01) and everything was okay. Than I've uploaded the Blink example to the board, after that moment it's not responding to any command.

I tried to update firmware, it's updating successfully but nothing has changed. By the way blink app is not working also...

# Answer
> 3 votes
If you replaced AT firmware in esp8266 with Blink and you want it back, download the AT firmware from Espressif download page and flash it with the Espressif Flash Download Tool (Windows) or with esptool.py.

---
Tags: arduino-mega, esp8266, wifi, nodemcu
---


# Question
Title: Arduino GSM Shield NET and STATUS led turn off after a few seconds
```
#include <GSM.h>

// PIN Number
#define PINNUMBER ""

// initialize the library instance
GSM gsmAccess;     // include a 'true' parameter to enable debugging
GSMScanner scannerNetworks;
GSMModem modemTest;

// Save data variables
String IMEI = "";

// serial monitor result messages
String errortext = "ERROR";

void setup() {
  // initialize serial communications and wait for port to open:
  Serial.begin(9600);

  Serial.println("GSM networks scanner");
  scannerNetworks.begin();

  // connection state
  boolean notConnected = true;

  // Start GSM shield
  // If your SIM has PIN, pass it as a parameter of begin() in quotes
  while (notConnected) {
    if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
      notConnected = false;
    } else {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  // get modem parameters
  // IMEI, modem unique identifier
  Serial.print("Modem IMEI: ");
  IMEI = modemTest.getIMEI();
  IMEI.replace("\n", "");
  if (IMEI != NULL) {
    Serial.println(IMEI);
  }
}

void loop() {
  // scan for existing networks, displays a list of networks
  Serial.println("Scanning available networks. May take some seconds.");
  Serial.println(scannerNetworks.readNetworks());

  // currently connected carrier
  Serial.print("Current carrier: ");
  Serial.println(scannerNetworks.getCurrentCarrier());

  // returns strength and ber
  // signal strength in 0-31 scale. 31 means power > 51dBm
  // BER is the Bit Error Rate. 0-7 scale. 99=not detectable
  Serial.print("Signal Strength: ");
  Serial.print(scannerNetworks.getSignalStrength());
  Serial.println(" [0-31]");
}

```

Results: When I run the program, I can see the "GSM networks scanner" message appear on my serial monitor, but it does not display anything else after that. Also, the NET and STATUS LEDs turn off after some few seconds when the program starts running. I already made the minor adjustments necessary for the Arduino Mega, and the power supply is temporarily from the USB port of my laptop connected to the Arduino Mega. I am using a SIM card that has been activated.

I think my program stops at this stage:

```
  // connection state
  boolean notConnected = true;

  // Start GSM shield
  // If your SIM has PIN, pass it as a parameter of begin() in quotes
  while (notConnected) {
    if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
      notConnected = false;
    } else {
      Serial.println("Not connected");
      delay(1000);
    }
  }

```

P.S. when I run the program without inserting a SIM card, the NET and STATUS LEDs keep on working (NET is blinking, while STATUS remains ON)

I tried this program as well https://www.arduino.cc/en/Guide/ArduinoGSMShield#toc9 and it has the same problem (i.e. stops at the same stage as the previous program)

# Answer
> 2 votes
SOLUTION: To solve my GSM shield issue, I connected a 9 V battery to my Arduino as a supply instead of using my Laptop's USB cable (and I also tried a 12 V supply as well). Thankfully, it did work. In the case that that it does not work (after uploading the program), click on the 'restart' button found on the GSM shield. You can find the type of sources that I used to supply my Arduino & GSM shield in the image posted below. IT IS IMPORTANT TO MENTION THAT THE FOLLOWING PROGRAM WAS IMPLEMENTED TO CHECK IF THE GSM SHIELD IS WORKING (I tried the "GSM Networks Scanner" program that I have mentioned in my question initially, but it did not work and it was not necessary anyways. So, I used the 'GSM SMS' code directly and it worked fine)

This is the code that worked out with me:

```
#include <GSM.h>

#define PINNUMBER ""

// initialize the library instance
GSM gsmAccess; // include a 'true' parameter for debug enabled
GSM_SMS sms;

// char array of the telephone number to send SMS
// change the number 1-212-555-1212 to a number
// you have access to
char remoteNumber[20]= "Replace this text with a mobile number instead";

// char array of the message
char txtMsg[200]="Hello World";

void setup()
{
  // initialize serial communications
  Serial.begin(9600);

  Serial.println("SMS Messages Sender");

  // connection state
  boolean notConnected = true;

  // Start GSM shield
  // If your SIM has PIN, pass it as a parameter of begin() in quotes
  while(notConnected)
  {
    if(gsmAccess.begin(PINNUMBER)==GSM_READY)
      notConnected = false;
    else
    {
      Serial.println("Not connected");
      delay(1000);
    }
  }
  Serial.println("GSM initialized");
  sendSMS();
}

void loop()
{
// nothing to see here
}

void sendSMS(){

  Serial.print("Message to mobile number: ");
  Serial.println(remoteNumber);

  // sms text
  Serial.println("SENDING");
  Serial.println();
  Serial.println("Message:");
  Serial.println(txtMsg);

  // send the message
  sms.beginSMS(remoteNumber);
  sms.print(txtMsg);
  sms.endSMS();
  Serial.println("\nCOMPLETE!\n");
}

```

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